Blog

Claude Code Routines: How to Deploy 24/7 Autonomous Agents (Practical Guide)

A practitioner's guide to Claude Code Routines. What they are, how to set them up, what to watch out for, and a copy-paste prompt to get your first routine running in 5 minutes.

Claude Code Routines: How to Deploy 24/7 Autonomous Agents

Want to skip the explanation? Jump to the Quick Start Prompt and have your first routine running in 5 minutes.


What Are Routines

Claude Code Routines (research preview, April 2026) let you run a Claude Code agent on Anthropic's cloud infrastructure on a schedule, from an API call, or in response to a GitHub event.

You write a prompt. You connect a repo. You set a trigger. The agent runs autonomously with full capabilities: shell commands, file read/write, git, and any MCP connectors you attach. Your laptop can be closed. The routine keeps running.

Three trigger types:

  • Scheduled - cron expression (every 6 hours, daily, weekly, etc.)
  • API - an HTTP endpoint you can call from any webhook, CI pipeline, or script
  • GitHub events - fires on PRs, pushes, issues, workflow completions

Available on Pro, Max, Team, and Enterprise plans. No separate compute charge. Runs draw from your existing Claude subscription. Manage everything at claude.ai/code/routines or via /schedule in the CLI.


What You Can Build With This

Routines are not limited to one use case. Anything you do repeatedly that involves reading code, making decisions, and taking action is a candidate.

Monitoring and self-healing. Check if your services are healthy. If something is broken, read the source code, diagnose the root cause, write a fix, push it, verify the deploy.

Code review. Trigger on every new PR. Read the diff. Leave inline comments for bugs, security issues, style violations. Post a summary. Human reviewers focus on architecture, not mechanical checks.

Dependency maintenance. Weekly routine that checks for outdated packages, security advisories, and license issues. Opens PRs with updates. Runs the test suite to verify nothing breaks.

Deploy verification. Fire from your CI pipeline after every deploy. Run smoke tests against production. Check error rates. Post a go/no-go to your team channel.

Documentation drift. Weekly routine that scans merged PRs, finds documentation that references changed APIs or removed functions, and opens update PRs.

Data pipeline checks. Query your database for expected row counts, freshness timestamps, schema changes. If something is off, trace the pipeline code and flag it.

Backlog grooming. Nightly routine that reads new issues, applies labels based on the area of code referenced, assigns owners, posts a summary to Slack.

The pattern is always the same: check something, reason about what you find, take action, report.


How to Set One Up

1. Create an Environment

Go to claude.ai/code. Click the environment selector (bottom right of the prompt input, says "claude-code-default"). Click Add environment.

Configure:

  • Name - something descriptive ("Production Monitor", "PR Reviewer", etc.)
  • Network access - set to "Full" if your routine needs to call external APIs or endpoints. "Trusted" (the default) only allows known package registries and cloud providers.
  • Environment variables - add any API keys, tokens, or webhook URLs your routine needs. One KEY=value per line, no quotes:
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxx/xxx/xxx
API_KEY=your_api_key_here
DATABASE_URL=postgres://user:pass@host:5432/db

2. Create the Routine

Go to claude.ai/code/routines. Click New routine.

  • Name it
  • Write your prompt (or paste the Quick Start Prompt below)
  • Select a model - Sonnet is fast and cheap for recurring tasks. Opus for anything that requires deeper reasoning.
  • Add your repos - the agent clones these fresh every run
  • Pick your environment - select the one you just created
  • Set a trigger - pick scheduled (cron), API, or GitHub event
  • Review connectors - all your MCP connectors are included by default. Remove any the routine doesn't need.

Hit Create.

3. Branch Permissions

By default, routines can only push to claude/-prefixed branches. This is a safety net.

If you want the agent to push directly to main (for auto-deploy workflows), click the repo in the routine settings and enable "Allow unrestricted branch pushes".

For routines that only read code and report (no auto-fix), leave the default restriction on.

4. GitHub Access

The routine needs to clone your repos. You need either:

  • The Claude GitHub App installed on your repos (go to github.com/apps/claude and install it), OR
  • Run /web-setup in your CLI to sync your GitHub credentials

If you skip this, the routine will fail to clone and you will see "failed to start run."

5. Test It

Click Run now on the routine's detail page. Watch the session in real time. Check that it executes your prompt correctly and that env vars are picked up.


Quick Start Prompt

Copy this. Replace the [PLACEHOLDERS]. Paste it into your routine. You have a working agent.

This prompt follows a 4-phase pattern (check, diagnose, act, report) that works for most recurring tasks. Customize the checks in Phase 1 for your specific use case.

You are an autonomous agent for [DESCRIBE YOUR TASK IN ONE SENTENCE].

## What You Have Access To

- Repository: [org/repo-name] (cloned automatically)
- Environment variables: $SLACK_WEBHOOK_URL, $API_KEY, [list yours]
- Tools: bash, git, file read/write, curl

## Phase 1: Check

Run these checks and record each result:

1. [YOUR FIRST CHECK - e.g., "curl -sf $HEALTH_ENDPOINT and verify HTTP 200"]
2. [YOUR SECOND CHECK - e.g., "run npm test and verify all tests pass"]
3. [YOUR THIRD CHECK - e.g., "query the API at $API_KEY and verify valid response"]
4. [YOUR FOURTH CHECK - e.g., "verify last git commit on main is less than 24h old"]

If all checks pass, skip to Phase 4 (report healthy).

## Phase 2: Diagnose

If any check failed:

1. Read the relevant source code files in the cloned repo
2. Check git log for recent changes that might have caused the issue
3. Read error messages, stack traces, or API responses carefully
4. Identify the root cause. Be specific: which file, which function, what went wrong.
5. Determine confidence level: HIGH (clear cause and effect) or LOW (multiple possibilities)

## Phase 3: Act

Choose based on your confidence and the scope of the fix:

**AUTO-FIX** when ALL of these are true:
- Confidence is HIGH
- The fix is small (under 20 lines changed)
- You can verify the fix with a test or a re-check
- The change does not affect data integrity or business logic

Steps:
1. Make the fix
2. Run the build/test command to verify: [YOUR BUILD COMMAND, e.g., npm run build]
3. Commit with message: "fix: [description] (auto-remediation)"
4. Push to main (if unrestricted) or create a claude/ branch
5. Wait 60 seconds, then re-run the failed check to verify

**ESCALATE** when ANY of these are true:
- Confidence is LOW
- The fix is large or touches multiple files
- It involves database changes, auth, or business logic
- You are not sure

Steps:
1. Open a GitHub issue on the repo
2. Title: "[AUTO] [brief description of the failure]"
3. Include: which check failed, root cause analysis, recommended fix, risk assessment

## Phase 4: Report

Post a summary to Slack:

If all clear:
curl -s -X POST "$SLACK_WEBHOOK_URL" -H "Content-Type: application/json" \
  -d '{"text": "*[YOUR_APP_NAME] - All Clear*\n\nAll checks passed.\n[List each check and its result]"}'

If issue found:
curl -s -X POST "$SLACK_WEBHOOK_URL" -H "Content-Type: application/json" \
  -d '{"text": "*[YOUR_APP_NAME] - Issue Detected*\n\n:red_circle: [what failed]\n:wrench: [what was done about it]\n:link: [GitHub issue or commit link if applicable]"}'

## Rules

- Never modify database schemas or run migrations
- Never delete files, drop tables, or destroy data
- Never commit secrets, tokens, or credentials
- Never force-push or rewrite git history
- Never make speculative improvements or refactor working code
- If in doubt, escalate. Always.
- Keep Slack messages short. Details go in GitHub issues.

Adapting the Prompt

The 4-phase structure stays the same. Swap out the specifics:

For code review: Phase 1 reads the PR diff (trigger on GitHub PR event). Phase 2 analyzes for bugs and style. Phase 3 posts review comments instead of committing code. Phase 4 summarizes.

For dependency updates: Phase 1 runs npm outdated or equivalent. Phase 2 checks changelogs for breaking changes. Phase 3 opens a PR with updates and test results. Phase 4 reports.

For deploy verification: Trigger via API from your CI pipeline. Phase 1 runs smoke tests against production. Phase 2 checks error logs. Phase 3 posts go/no-go. Phase 4 summarizes to the release channel.


Gotchas (From Actual Usage)

1. Your .env does not exist in the cloud. Every API key, token, and URL must be added in the environment settings on claude.ai. Your prompt should reference them as $ENV_VAR. If you skip this, every API call and webhook post will fail silently.

2. Network access defaults to "trusted." This only allows connections to known package registries and cloud providers. If your routine needs to call custom endpoints, third-party APIs, or internal services, switch the environment to "full." If your routine silently fails to reach something, check this first.

3. No persistent state between runs. No cookies, no local files, no browser sessions. Each run starts completely fresh. If your routine needs to compare current state to a previous run, store that state somewhere external (a file in the repo, a database row, an API).

4. CLAUDE.md loads every run. If your repo has a large CLAUDE.md with extensive documentation and instructions, the agent spends tokens parsing it before doing useful work. For routines, consider either a dedicated repo with a minimal CLAUDE.md or keeping all instructions in the prompt itself.

5. Each run uses your session quota. A routine costs the same as a normal Claude Code conversation. Four routines at 6-hour intervals is 16 sessions per day. Plan your schedule against your plan limits. Check usage at claude.ai/settings/usage.

6. MCP connectors have one key baked in. The connector URL includes an API key. If you need different credentials per routine (different Slack workspaces, different database connections, different API accounts), skip the connector and call the API directly with curl using $ENV_VAR for auth.

7. Start in report-only mode. Before enabling auto-fix in Phase 3, run report-only for a week. Comment out the auto-fix section. Watch what it detects and how it diagnoses. Confirm it catches real issues, not false positives. Then enable fixes.

8. The 6-hour sweet spot. For scheduled routines that monitor something, every hour is expensive and rarely catches something a 6-hour window would miss. Every 24 hours is too slow - you want to know before your users do. Start at 6 hours. Adjust based on what you see.


What This Actually Looks Like in Practice

I set up two routines to monitor client integrations. Each one runs every 6 hours, checks health endpoints and sync status, tests that Slack notifications are going out, and verifies API keys are valid.

When everything is fine (which is most of the time), I get a one-line "All Clear" message in a Slack channel and move on with my day. When something breaks, the agent clones the repo, reads the code, diagnoses the root cause, writes a fix, pushes to main (which auto-deploys), and posts what it did.

Went from 4 hours/week of reactive maintenance to reading Slack messages over coffee.


Need help setting up automation that actually runs itself? We build AI-powered monitoring, outreach infrastructure, and data pipelines for B2B companies. alchemail.io

Don't know your TAM? Find out in 5 minutes.

Score your ICP clarity, estimate your total addressable market, and get 20 real target accounts — free.

Estimate Your TAM & ICP →

Get your free pipeline audit

A call with Artur. We'll size your TAM, audit your outbound, and give you a realistic meeting forecast.

Book Your Audit