Skip to main content
guidesSource-backedReview first Safety Privacy

Claude Process Automation

Automate business and engineering processes with Claude Code: headless `claude -p` runs, GitHub Actions, scheduled routines, and in-session loops, with permission and output-format guidance.

by JSONbored·added 2025-10-27·
HarnessClaude Code
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/headless, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/business-process-automation.mdx
Safety notes
Automated runs can execute Bash and edit/write files. Scope `--allowedTools` and `--permission-mode` tightly; `dontAsk` denies anything outside your allow rules., Routines run with no approval prompts, so limit repositories, connectors, and network access to what each task actually needs.
Privacy notes
Headless and CI runs read your codebase and any piped stdin; GitHub Actions and routines need an `ANTHROPIC_API_KEY` or provider credentials stored as secrets, never hardcoded in workflow files., Routine actions appear under your linked GitHub and connector identities, so commits, PRs, and connector writes are attributed to you.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-10-27

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Install command

Not provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

32/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

2 safety and 2 privacy notes across 4 risk areas. Review closely: credentials & tokens, permissions & scopes, network access.

4 areas
  • SafetyPermissions & scopesAutomated runs can execute Bash and edit/write files. Scope `--allowedTools` and `--permission-mode` tightly; `dontAsk` denies anything outside your allow rules.
  • SafetyNetwork accessRoutines run with no approval prompts, so limit repositories, connectors, and network access to what each task actually needs.
  • PrivacyCredentials & tokensHeadless and CI runs read your codebase and any piped stdin; GitHub Actions and routines need an `ANTHROPIC_API_KEY` or provider credentials stored as secrets, never hardcoded in workflow files.
  • PrivacyGeneralRoutine actions appear under your linked GitHub and connector identities, so commits, PRs, and connector writes are attributed to you.

Safety notes

  • Automated runs can execute Bash and edit/write files. Scope `--allowedTools` and `--permission-mode` tightly; `dontAsk` denies anything outside your allow rules.
  • Routines run with no approval prompts, so limit repositories, connectors, and network access to what each task actually needs.

Privacy notes

  • Headless and CI runs read your codebase and any piped stdin; GitHub Actions and routines need an `ANTHROPIC_API_KEY` or provider credentials stored as secrets, never hardcoded in workflow files.
  • Routine actions appear under your linked GitHub and connector identities, so commits, PRs, and connector writes are attributed to you.

Schema details

Install type
copy
Reading time
7 min
Difficulty score
32
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/headlesshttps://code.claude.com/docs/en/common-workflowshttps://code.claude.com/docs/en/github-actionshttps://code.claude.com/docs/en/routines
Full copyable content
## TL;DR

Claude Code can run unattended, not just interactively. The same agent loop is available non-interactively through `claude -p` (headless mode), inside GitHub Actions, on a schedule via routines or desktop tasks, and as an in-session poll with `/loop`. This guide shows the real commands and configuration, and how to pick the right tool and the right permission scope for each.

**Key points:**

- Headless mode (`claude -p`) reads stdin and writes stdout, so it composes with any shell pipeline, script, or CI step.
- `--output-format json` returns a structured result (with session ID, usage, and `total_cost_usd`) you can parse with `jq`.
- Permissions are the safety boundary: scope `--allowedTools` or pass a `--permission-mode` instead of running wide open.
- Choose where automation runs by where the work lives: CLI session, CI pipeline, your machine, or Anthropic-managed cloud.

## What "process automation" means here

A process worth automating is repeatable, has a clear definition of done, and runs without a human in the loop. With Claude Code that means three building blocks:

1. **A self-contained prompt.** The run is autonomous, so the prompt must state what to do and what success looks like. It cannot ask clarifying questions mid-run.
2. **A scoped permission set.** Decide up front which tools the run may use without prompting.
3. **A trigger.** A pipe in a script, a GitHub event, a cron schedule, or an HTTP call.

The rest of this guide covers each block with verifiable commands from the Claude Code docs.

## Headless mode: `claude -p`

Add `-p` (or `--print`) to any `claude` command to run it non-interactively. It reads stdin and writes stdout like a normal Unix tool, so you can pipe data in and redirect output:

```bash
# Ask a one-off question about the codebase
claude -p "What does the auth module do?"

# Pipe a build log in and write the explanation out
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

# Summarize recent history
git log --oneline -20 | claude -p "summarize these recent commits"
```

For CI and scripts, add `--bare`. Bare mode skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and `CLAUDE.md`, so you get the same result on every machine and only the flags you pass explicitly take effect. In bare mode Claude has access to the Bash, file read, and file edit tools, and Anthropic authentication must come from `ANTHROPIC_API_KEY` (or an `apiKeyHelper` in `--settings`):

```bash
claude --bare -p "Summarize this file" --allowedTools "Read"
```

### Auto-approve only what the task needs

Unattended runs cannot answer permission prompts, so you decide in advance. Use `--allowedTools` to allow specific tools, or set a baseline with `--permission-mode`:

```bash
# Allow exactly the tools a test-fix loop needs
claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"

# Use permission-rule syntax to scope a commit task to git commands only
claude -p "Look at my staged changes and create an appropriate commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
```

`acceptEdits` lets Claude write files without prompting and auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. `dontAsk` denies anything not in your `permissions.allow` rules or the read-only command set, which is useful for locked-down CI. Other shell commands and network requests still need an explicit allow entry, or the run aborts when one is attempted.

### Structured output for scripts

Use `--output-format` to control the response shape: `text` (default), `json` (structured result with session ID and metadata), or `stream-json` (newline-delimited events for real-time streaming). The JSON payload includes `total_cost_usd` so you can track spend per invocation:

```bash
# Parse the text result with jq
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Enforce a schema and read the structured_output field
claude -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'
```

### Use it as a project linter

Because `-p` composes with `package.json` scripts, you can ship Claude as a project-specific check. Piping the diff means Claude does not need Bash permission to read it:

```json
{
  "scripts": {
    "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.\""
  }
}
```

### Chain runs across steps

Use `--continue` to continue the most recent conversation, or capture a session ID and pass it to `--resume` for a specific one. Run both from the same directory: session ID lookup is scoped to the current project directory and its git worktrees.

```bash
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
```

## GitHub Actions: automate on repo events

The Claude Code GitHub Action runs the same agent inside your CI. With an `@claude` mention in a PR or issue, Claude can analyze code, implement features, fix bugs, and open PRs. The quickest setup is to run `/install-github-app` from the terminal, which guides you through installing the GitHub app and adding the `ANTHROPIC_API_KEY` secret. You must be a repository admin.

A minimal workflow that responds to `@claude` mentions in comments:

```yaml
name: Claude Code
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          # Responds to @claude mentions in comments
```

For scheduled or fully automated work, supply a `prompt` and pass CLI flags through `claude_args`. The action auto-detects interactive vs. automation mode based on whether a `prompt` is present:

```yaml
name: Daily Report
on:
  schedule:
    - cron: "0 9 * * *"
jobs:
  report:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Generate a summary of yesterday's commits and open issues"
          claude_args: "--model opus"
```

`claude_args` accepts any Claude Code CLI argument, for example `--max-turns 5`, `--model`, `--mcp-config`, and `--allowedTools`. Always reference the key as `${{ secrets.ANTHROPIC_API_KEY }}` rather than hardcoding it, and set `--max-turns` plus a workflow timeout to bound cost and runtime.

## Scheduling: pick where the work runs

Claude Code offers four ways to run a task automatically. Choose by where the task needs to live and what it must reach.

| Option | Where it runs | Triggers | Best for |
| --- | --- | --- | --- |
| Routines | Anthropic-managed cloud infrastructure | Schedule (cron), API (HTTP POST), GitHub events | Tasks that should run even when your computer is off; combine multiple triggers on one routine |
| Desktop scheduled tasks | Your machine, via the desktop app | Schedule | Tasks needing direct access to local files, tools, or uncommitted changes |
| GitHub Actions | Your CI pipeline | Repo events, cron | Work tied to repo events (opened PRs), or schedules that live alongside workflow config |
| `/loop` | The current CLI session | In-session interval | Quick polling while a session is open |

`/loop` polls within an open session; tasks stop when you start a new conversation, and `--resume` or `--continue` restore unexpired ones. Routines are in research preview and available on Pro, Max, Team, and Enterprise plans with Claude Code on the web enabled; create them at [claude.ai/code/routines](https://claude.ai/code/routines) or from the CLI with `/schedule`.

### Routine triggers in practice

A routine packages a prompt, one or more repositories, an environment, and connectors, then attaches one or more triggers. A schedule trigger has a minimum interval of one hour. An API trigger gives the routine a dedicated `/fire` endpoint you POST to with a bearer token, passing optional `text` for run-specific context such as an alert body:

```bash
curl -X POST https://api.anthropic.com/v1/claude_code/routines/trig_01ABCDEFGHJKLMNOPQRSTUVW/fire \
  -H "Authorization: Bearer sk-ant-oat01-xxxxx" \
  -H "anthropic-beta: experimental-cc-routine-2026-04-01" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"text": "Sentry alert SEN-4521 fired in prod. Stack trace attached."}'
```

A GitHub trigger starts a session on repository events (pull request or release actions) and supports filters such as base branch, labels, draft state, and merged state. By default routines can only push to `claude/`-prefixed branches, which keeps protected branches safe unless you explicitly enable unrestricted branch pushes.

## Worked example: triage and fix CI failures

A realistic engineering process: when a deploy reports an error, get a draft fix instead of starting from a blank terminal. Two ways to wire it up.

In CI, as a follow-up step that pipes the failing log into a scoped headless run:

```bash
cat ci-failure.log | claude --bare -p \
  "Correlate this failure with recent commits and propose a minimal fix. Output only a unified diff." \
  --allowedTools "Read,Bash(git log *),Bash(git diff *)" \
  --output-format json | jq -r '.result' > proposed-fix.diff
```

As an alert-triage routine: your monitoring tool POSTs to the routine's API endpoint when an error threshold is crossed, passing the alert body as `text`. The routine pulls the stack trace, correlates it with recent commits, and opens a draft pull request with a proposed fix and a link back to the alert, so on-call reviews a PR instead of an empty prompt.

## Practical guidance

- **Write prompts for autonomy.** Be explicit about success and what to do with results, for example: "Review open PRs labeled `needs-review`, leave inline comments on any issues, and post a summary in the `#eng-reviews` Slack channel." The task cannot ask follow-up questions.
- **Default to least privilege.** Start from the narrowest `--allowedTools` set, widen only when a run actually needs more, and prefer `dontAsk` for locked-down CI.
- **Pipe data instead of granting Bash.** Piping a diff or log into stdin avoids handing Claude permission to read it.
- **Bound cost and runtime.** Use `--max-turns`, workflow timeouts, and `--output-format json` (which reports `total_cost_usd`) to track and cap spend.
- **Use `--bare` for reproducible runs.** It avoids picking up whatever hooks, MCP servers, or `CLAUDE.md` happen to be configured locally.
- **A green routine status is not a success signal.** It only means the session started and exited without an infrastructure error. Open the run transcript to confirm the task actually completed.

## Prerequisites

- Claude Code installed and authenticated. Headless `--bare` runs and CI need `ANTHROPIC_API_KEY` (or Bedrock/Vertex/Foundry provider credentials); routines need a claude.ai subscription login.
- For GitHub Actions: repository admin access to run `/install-github-app` and add the `ANTHROPIC_API_KEY` secret.
- For routines: a Pro, Max, Team, or Enterprise plan with Claude Code on the web enabled. `jq` is handy for parsing `--output-format json`.

## Troubleshooting

- **A `-p` run aborts when it hits a tool.** A shell command or network request was attempted that is not covered by `--allowedTools` or your permission mode. Add the specific tool/command rule, or pick a permission mode that allows it.
- **CI runs behave differently than local.** Local context (hooks, MCP servers, `CLAUDE.md`) may be leaking in. Add `--bare` so only explicit flags take effect, and pass context with `--mcp-config`, `--settings`, or `--append-system-prompt`.
- **Piped input fails on large files.** Piped stdin is capped at 10MB. Write the content to a file and reference its path in the prompt instead of piping it.
- **Claude does not respond to `@claude` in GitHub.** Verify the GitHub App is installed, workflows are enabled, the `ANTHROPIC_API_KEY` secret is set, and the comment contains `@claude` (not `/claude`).
- **`/schedule` returns "Unknown command".** It requires a claude.ai subscription login. Remove `ANTHROPIC_API_KEY`/`ANTHROPIC_AUTH_TOKEN` from your shell (and any `apiKeyHelper` in `settings.json`), since these take precedence over a claude.ai login. You can always manage routines at [claude.ai/code/routines](https://claude.ai/code/routines).
- **A routine cannot reach your service.** The Default environment uses Trusted network access and blocks arbitrary hosts (`403`, `x-deny-reason: host_not_allowed`). Add the domain under the environment's network access settings, or use an MCP connector, whose traffic is routed through Anthropic's servers.

## Next steps

- [ ] {"task": "Wrap one repeatable check (typo lint, dependency audit) in a `claude -p` script", "description": ""}
- [ ] {"task": "Add `--output-format json` and parse the result with jq in that script", "description": ""}
- [ ] {"task": "Run `/install-github-app` and add a workflow that responds to @claude", "description": ""}
- [ ] {"task": "Pick a scheduling option from the table for one recurring task and set it up", "description": ""}
- [ ] {"task": "Scope every automated run with the narrowest --allowedTools or permission mode", "description": ""}

_See the [headless mode](https://code.claude.com/docs/en/headless), [common workflows](https://code.claude.com/docs/en/common-workflows), [GitHub Actions](https://code.claude.com/docs/en/github-actions), and [routines](https://code.claude.com/docs/en/routines) docs for the full reference._

About this resource

TL;DR

Claude Code can run unattended, not just interactively. The same agent loop is available non-interactively through claude -p (headless mode), inside GitHub Actions, on a schedule via routines or desktop tasks, and as an in-session poll with /loop. This guide shows the real commands and configuration, and how to pick the right tool and the right permission scope for each.

Key points:

  • Headless mode (claude -p) reads stdin and writes stdout, so it composes with any shell pipeline, script, or CI step.
  • --output-format json returns a structured result (with session ID, usage, and total_cost_usd) you can parse with jq.
  • Permissions are the safety boundary: scope --allowedTools or pass a --permission-mode instead of running wide open.
  • Choose where automation runs by where the work lives: CLI session, CI pipeline, your machine, or Anthropic-managed cloud.

What "process automation" means here

A process worth automating is repeatable, has a clear definition of done, and runs without a human in the loop. With Claude Code that means three building blocks:

  1. A self-contained prompt. The run is autonomous, so the prompt must state what to do and what success looks like. It cannot ask clarifying questions mid-run.
  2. A scoped permission set. Decide up front which tools the run may use without prompting.
  3. A trigger. A pipe in a script, a GitHub event, a cron schedule, or an HTTP call.

The rest of this guide covers each block with verifiable commands from the Claude Code docs.

Headless mode: claude -p

Add -p (or --print) to any claude command to run it non-interactively. It reads stdin and writes stdout like a normal Unix tool, so you can pipe data in and redirect output:

# Ask a one-off question about the codebase
claude -p "What does the auth module do?"

# Pipe a build log in and write the explanation out
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

# Summarize recent history
git log --oneline -20 | claude -p "summarize these recent commits"

For CI and scripts, add --bare. Bare mode skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md, so you get the same result on every machine and only the flags you pass explicitly take effect. In bare mode Claude has access to the Bash, file read, and file edit tools, and Anthropic authentication must come from ANTHROPIC_API_KEY (or an apiKeyHelper in --settings):

claude --bare -p "Summarize this file" --allowedTools "Read"

Auto-approve only what the task needs

Unattended runs cannot answer permission prompts, so you decide in advance. Use --allowedTools to allow specific tools, or set a baseline with --permission-mode:

# Allow exactly the tools a test-fix loop needs
claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"

# Use permission-rule syntax to scope a commit task to git commands only
claude -p "Look at my staged changes and create an appropriate commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

acceptEdits lets Claude write files without prompting and auto-approves common filesystem commands such as mkdir, touch, mv, and cp. dontAsk denies anything not in your permissions.allow rules or the read-only command set, which is useful for locked-down CI. Other shell commands and network requests still need an explicit allow entry, or the run aborts when one is attempted.

Structured output for scripts

Use --output-format to control the response shape: text (default), json (structured result with session ID and metadata), or stream-json (newline-delimited events for real-time streaming). The JSON payload includes total_cost_usd so you can track spend per invocation:

# Parse the text result with jq
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Enforce a schema and read the structured_output field
claude -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'

Use it as a project linter

Because -p composes with package.json scripts, you can ship Claude as a project-specific check. Piping the diff means Claude does not need Bash permission to read it:

{
  "scripts": {
    "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.\""
  }
}

Chain runs across steps

Use --continue to continue the most recent conversation, or capture a session ID and pass it to --resume for a specific one. Run both from the same directory: session ID lookup is scoped to the current project directory and its git worktrees.

session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

GitHub Actions: automate on repo events

The Claude Code GitHub Action runs the same agent inside your CI. With an @claude mention in a PR or issue, Claude can analyze code, implement features, fix bugs, and open PRs. The quickest setup is to run /install-github-app from the terminal, which guides you through installing the GitHub app and adding the ANTHROPIC_API_KEY secret. You must be a repository admin.

A minimal workflow that responds to @claude mentions in comments:

name: Claude Code
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          # Responds to @claude mentions in comments

For scheduled or fully automated work, supply a prompt and pass CLI flags through claude_args. The action auto-detects interactive vs. automation mode based on whether a prompt is present:

name: Daily Report
on:
  schedule:
    - cron: "0 9 * * *"
jobs:
  report:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Generate a summary of yesterday's commits and open issues"
          claude_args: "--model opus"

claude_args accepts any Claude Code CLI argument, for example --max-turns 5, --model, --mcp-config, and --allowedTools. Always reference the key as ${{ secrets.ANTHROPIC_API_KEY }} rather than hardcoding it, and set --max-turns plus a workflow timeout to bound cost and runtime.

Scheduling: pick where the work runs

Claude Code offers four ways to run a task automatically. Choose by where the task needs to live and what it must reach.

Option Where it runs Triggers Best for
Routines Anthropic-managed cloud infrastructure Schedule (cron), API (HTTP POST), GitHub events Tasks that should run even when your computer is off; combine multiple triggers on one routine
Desktop scheduled tasks Your machine, via the desktop app Schedule Tasks needing direct access to local files, tools, or uncommitted changes
GitHub Actions Your CI pipeline Repo events, cron Work tied to repo events (opened PRs), or schedules that live alongside workflow config
/loop The current CLI session In-session interval Quick polling while a session is open

/loop polls within an open session; tasks stop when you start a new conversation, and --resume or --continue restore unexpired ones. Routines are in research preview and available on Pro, Max, Team, and Enterprise plans with Claude Code on the web enabled; create them at claude.ai/code/routines or from the CLI with /schedule.

Routine triggers in practice

A routine packages a prompt, one or more repositories, an environment, and connectors, then attaches one or more triggers. A schedule trigger has a minimum interval of one hour. An API trigger gives the routine a dedicated /fire endpoint you POST to with a bearer token, passing optional text for run-specific context such as an alert body:

curl -X POST https://api.anthropic.com/v1/claude_code/routines/trig_01ABCDEFGHJKLMNOPQRSTUVW/fire \
  -H "Authorization: Bearer sk-ant-oat01-xxxxx" \
  -H "anthropic-beta: experimental-cc-routine-2026-04-01" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"text": "Sentry alert SEN-4521 fired in prod. Stack trace attached."}'

A GitHub trigger starts a session on repository events (pull request or release actions) and supports filters such as base branch, labels, draft state, and merged state. By default routines can only push to claude/-prefixed branches, which keeps protected branches safe unless you explicitly enable unrestricted branch pushes.

Worked example: triage and fix CI failures

A realistic engineering process: when a deploy reports an error, get a draft fix instead of starting from a blank terminal. Two ways to wire it up.

In CI, as a follow-up step that pipes the failing log into a scoped headless run:

cat ci-failure.log | claude --bare -p \
  "Correlate this failure with recent commits and propose a minimal fix. Output only a unified diff." \
  --allowedTools "Read,Bash(git log *),Bash(git diff *)" \
  --output-format json | jq -r '.result' > proposed-fix.diff

As an alert-triage routine: your monitoring tool POSTs to the routine's API endpoint when an error threshold is crossed, passing the alert body as text. The routine pulls the stack trace, correlates it with recent commits, and opens a draft pull request with a proposed fix and a link back to the alert, so on-call reviews a PR instead of an empty prompt.

Practical guidance

  • Write prompts for autonomy. Be explicit about success and what to do with results, for example: "Review open PRs labeled needs-review, leave inline comments on any issues, and post a summary in the #eng-reviews Slack channel." The task cannot ask follow-up questions.
  • Default to least privilege. Start from the narrowest --allowedTools set, widen only when a run actually needs more, and prefer dontAsk for locked-down CI.
  • Pipe data instead of granting Bash. Piping a diff or log into stdin avoids handing Claude permission to read it.
  • Bound cost and runtime. Use --max-turns, workflow timeouts, and --output-format json (which reports total_cost_usd) to track and cap spend.
  • Use --bare for reproducible runs. It avoids picking up whatever hooks, MCP servers, or CLAUDE.md happen to be configured locally.
  • A green routine status is not a success signal. It only means the session started and exited without an infrastructure error. Open the run transcript to confirm the task actually completed.

Prerequisites

  • Claude Code installed and authenticated. Headless --bare runs and CI need ANTHROPIC_API_KEY (or Bedrock/Vertex/Foundry provider credentials); routines need a claude.ai subscription login.
  • For GitHub Actions: repository admin access to run /install-github-app and add the ANTHROPIC_API_KEY secret.
  • For routines: a Pro, Max, Team, or Enterprise plan with Claude Code on the web enabled. jq is handy for parsing --output-format json.

Troubleshooting

  • A -p run aborts when it hits a tool. A shell command or network request was attempted that is not covered by --allowedTools or your permission mode. Add the specific tool/command rule, or pick a permission mode that allows it.
  • CI runs behave differently than local. Local context (hooks, MCP servers, CLAUDE.md) may be leaking in. Add --bare so only explicit flags take effect, and pass context with --mcp-config, --settings, or --append-system-prompt.
  • Piped input fails on large files. Piped stdin is capped at 10MB. Write the content to a file and reference its path in the prompt instead of piping it.
  • Claude does not respond to @claude in GitHub. Verify the GitHub App is installed, workflows are enabled, the ANTHROPIC_API_KEY secret is set, and the comment contains @claude (not /claude).
  • /schedule returns "Unknown command". It requires a claude.ai subscription login. Remove ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from your shell (and any apiKeyHelper in settings.json), since these take precedence over a claude.ai login. You can always manage routines at claude.ai/code/routines.
  • A routine cannot reach your service. The Default environment uses Trusted network access and blocks arbitrary hosts (403, x-deny-reason: host_not_allowed). Add the domain under the environment's network access settings, or use an MCP connector, whose traffic is routed through Anthropic's servers.

Next steps

  • {"task": "Wrap one repeatable check (typo lint, dependency audit) in a claude -p script", "description": ""}
  • {"task": "Add --output-format json and parse the result with jq in that script", "description": ""}
  • {"task": "Run /install-github-app and add a workflow that responds to @claude", "description": ""}
  • {"task": "Pick a scheduling option from the table for one recurring task and set it up", "description": ""}
  • {"task": "Scope every automated run with the narrowest --allowedTools or permission mode", "description": ""}

See the headless mode, common workflows, GitHub Actions, and routines docs for the full reference.

Source citations

Add this badge to your README

Show that Claude Process Automation is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/business-process-automation.svg)](https://heyclau.de/entry/guides/business-process-automation)

How it compares

Claude Process Automation side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

Automate business and engineering processes with Claude Code: headless `claude -p` runs, GitHub Actions, scheduled routines, and in-session loops, with permission and output-format guidance.

Open dossier

Use Claude Code routines for recurring maintenance: schedule triggers, API and GitHub events, scoped connectors, and review of autonomous cloud runs for backlog grooming, docs drift, and deploy verification.

Open dossier

A practical walkthrough of running Claude Code non-interactively with claude -p: bare mode, output formats (text, json, stream-json), JSON schema output, piping stdin, auto-approving tools, and authentication for scripts and CI.

Open dossier

Set up Claude Code GitHub Actions for pull request review: install the Claude GitHub app, store ANTHROPIC_API_KEY in secrets, pin anthropics/claude-code-action to an audited commit SHA with least-privilege permissions, and follow documented security practices.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSubmission linkedSource submissionSource-backedSubmission linkedSource submission
SubmitterDifferskiannidevJPette1783kiannidev
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
BrandGitHub logoGitHub
Categoryguidesguidesguidesguides
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredkiannidevJPette1783kiannidev
Added2025-10-272026-06-162026-06-052026-06-16
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesAutomated runs can execute Bash and edit/write files. Scope `--allowedTools` and `--permission-mode` tightly; `dontAsk` denies anything outside your allow rules. Routines run with no approval prompts, so limit repositories, connectors, and network access to what each task actually needs.Routines run as full autonomous cloud sessions with no approval prompts—scope repos, network, and connectors narrowly. Actions through GitHub or connectors appear as your linked identity; treat routine output like your own commits and messages. Enable unrestricted branch pushes only on repositories where pushing to existing branches is explicitly approved.Headless runs act without a human present; scope tools tightly with --allowedTools or a locked-down permission mode (dontAsk) so the job cannot run more than intended. Bare mode (--bare) skips auto-discovery of hooks, skills, plugins, MCP servers, and CLAUDE.md, giving reproducible runs; pass only the context you need with explicit flags. Avoid broad Bash permissions in CI; prefer prefix-scoped rules like Bash(git diff *) and pipe data in so the agent does not need read permissions. Constrain which branches and paths the automation can touch, and review its output before it gates merges or deploys.The Claude GitHub app requests Contents, Issues, and Pull requests read and write permissions—scope installation to intended repositories. Never commit API keys; use GitHub encrypted secrets such as ANTHROPIC_API_KEY, and only expose them to workflows you trust. Pin third-party GitHub Actions to reviewed immutable commit SHAs rather than mutable tags. Declare least-privilege GITHUB_TOKEN permissions explicitly before enabling AI review workflows. Review Claude suggestions before merging; automation should not bypass CODEOWNERS. Workflows consume GitHub Actions minutes and Claude API tokens—set timeouts and max-turn limits.
Privacy notesHeadless and CI runs read your codebase and any piped stdin; GitHub Actions and routines need an `ANTHROPIC_API_KEY` or provider credentials stored as secrets, never hardcoded in workflow files. Routine actions appear under your linked GitHub and connector identities, so commits, PRs, and connector writes are attributed to you.Routine prompts and run transcripts may include proprietary code, issue titles, and connector payloads. API trigger tokens are secrets; store bearer tokens in a secret manager, not in public CI logs. Slack, Linear, or other connector actions may expose internal project metadata to linked workspaces.Headless runs send the prompt, piped stdin, and repository context to the model provider; review what a job exposes before running it on private code. Bare mode skips OAuth and keychain reads, so authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper; store these as CI secrets, never inline. CI logs can capture command output and the JSON result (including cost metadata); avoid printing secrets and mask sensitive variables.PR diffs and issue comments are attacker-controlled on public repositories; treat them as prompt-injection input and avoid giving untrusted PRs secret-backed tool access. PR diffs and issue comments are sent to the model provider during workflow runs. Logs may retain prompts—align retention with corporate data handling rules. Use repository secrets rather than echoing credentials in workflow YAML.
Prerequisites— none listed
  • Claude Pro, Max, Team, or Enterprise with Claude Code on the web and routines enabled.
  • GitHub repositories authorized for cloud sessions and routine branch pushes.
  • Connectors (MCP) only for services the routine truly needs; remove unused defaults.
  • A human reviewer for autonomous runs before merging routine-opened pull requests.
  • Claude Code installed in the environment where the script or CI job runs.
  • An authentication method that works headlessly: ANTHROPIC_API_KEY, a long-lived OAuth token, an apiKeyHelper, or a cloud provider's credentials.
  • jq or similar if you plan to parse JSON output in shell scripts.
  • Repository admin access to install the Claude GitHub app and add secrets.
  • Anthropic API access or approved provider setup documented for your org.
  • A CLAUDE.md or review rubric describing project standards.
  • Branch protection requiring human review before merging automation output.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.