Iqraa.tech

Claude Code Workflows and Automation

Claude Code Workflows enables automation through CI/CD integration, session management, and batch processing. The guide covers practical implementation steps using print mode for non-interactive execution, GitHub Actions integration, and patterns for building reliable multi-step workflows.

The content explores advanced features including scheduled tasks, background automation, and dynamic workflows using multiple agents. Real-world examples demonstrate how to integrate Claude Code into pipelines, manage sessions effectively, and implement verification steps to ensure automated changes are tested before merging.

Claude Code Workflows — Automating Claude Code workflows scales your productivity. Learn CI/CD integration, session management, and batch processing with Claude Code.

Claude Code Workflows

Claude Code Workflows: What You’ll Learn

In this guide to Claude Code Workflows, you’ll work through practical, hands-on steps with real examples. Claude Code Workflows is explained from the ground up so you can apply it immediately in your own projects.

Claude Code transforms from an interactive assistant into an active team member when you integrate it with your automation infrastructure. This lesson covers CI/CD integration, scheduled tasks, the GitHub Actions integration, and patterns for building reliable multi-step workflows.

CI/CD Integration with Programmatic Runs

The claude -p flag is the foundation of CI/CD integration. It runs Claude non-interactively, sends a prompt, and returns the result to stdout. Combine it with --output-format json for structured parsing, --permission-mode bypassPermissions for fully automated runs (no approval prompts), and --max-turns to cap execution time.

A common pattern is running Claude as part of a PR review process. Configure it as a GitHub Actions step:

- name: Claude Code Review
  run: |
    DIFF=$(git diff origin/main...HEAD)
    REVIEW=$(echo "$DIFF" | claude -p "Review these changes. Output JSON with fields: summary, critical_issues, suggestions"       --output-format json       --permission-mode bypassPermissions)
    echo "$REVIEW" | jq '.critical_issues[]' >> $GITHUB_STEP_SUMMARY

The --from-pr flag bootstraps a session from an existing pull request. It fetches the diff, description, and review comments so Claude can jump straight into fixing or extending PR feedback. As of v2.1.119, --from-pr accepts URLs from GitHub, GitHub Enterprise, GitLab merge requests, and Bitbucket pull requests:

claude --from-pr https://github.com/org/repo/pull/123
claude --from-pr https://gitlab.com/org/repo/-/merge_requests/456
claude --from-pr https://bitbucket.org/org/repo/pull-requests/789

For disposable automation, Claude can generate tests for new code, update documentation when APIs change, run linters and auto-fix issues, or check for security vulnerabilities. Use --no-session-persistence to avoid saving a session, and consider --bare when you want the cleanest scripted output.

Use prUrlTemplate (new in v2.1.119) to point the footer PR badge at a custom code-review URL instead of the default github.com link — useful for enterprise deployments with internal GitHub instances or custom review tooling:

{
  "prUrlTemplate": "https://review.example.internal/pr/{number}"
}

The /install-github-app command sets up the official GitHub integration, which allows Claude to respond to @claude mentions in PR comments and issues.

Mobile Push Notifications

When Remote Control is active, Claude can send push notifications to your phone. Claude decides when to push — typically when a long-running task finishes or when it needs a decision to continue. You can also request one in your prompt: notify me when the tests finish. Setup requires the Claude mobile app (iOS or Android), signed in with the same account, and Push when Claude decides enabled in /config. Beyond the on/off toggle, there is no per-event configuration. Requires Claude Code v2.1.110+.

For autonomous PR monitoring, /autofix-pr spawns a Claude Code on the web session that watches your current branch’s PR. When CI fails or a reviewer leaves a comment, Claude investigates and pushes a fix. Pass a prompt to narrow scope: /autofix-pr only fix lint and type errors. It requires the Claude GitHub App installed on the repository, access to Claude Code on the web, and is not available to organizations with Zero Data Retention enabled.

/ultrareview (new in v2.1.86, highlighted in v2.1.112) runs a comprehensive cloud-based code review using parallel multi-agent analysis and critique. It requires Claude.ai account authentication — if signed in with an API key only, run /login first. It runs on Claude Code on the web infrastructure. Invoke with no arguments to review your current branch, or /ultrareview <PR#> to fetch and review a specific GitHub PR.

Pro/Max get 3 free one-time runs (a one-time allotment per account, do not refresh), then each review costs roughly $5–$20 as extra usage. Team/Enterprise have no free runs and are billed as extra usage. Extra usage must be enabled on the account — if disabled, Claude Code blocks the launch and links to billing settings. Use /tasks to track running and completed reviews, open detail views, or stop an in-progress review (stopping archives the cloud session; partial findings are not returned).

/ultrareview           # review current branch
/ultrareview 456       # review GitHub PR #456

Scheduled Tasks, Routines, and Background Automation

Claude Code supports multiple scheduling layers. /loop creates session-scoped recurring checks while Claude Code is running. Routines are cloud-backed scheduled tasks that persist independently of your local terminal — each run clones your repo fresh, executes autonomously, and can push branches or open PRs.

# Check build status every 5 minutes (session-scoped)
/loop 5m check if the build succeeded and summarize any failures

# Create a cloud routine from the CLI
/schedule "run a full security audit at 2am"
/schedule daily PR review at 9am

Routines

A routine is a saved Claude Code configuration — a prompt, one or more repositories, and a set of connectors — packaged once and run automatically on Anthropic-managed infrastructure. Create and manage them from the web at claude.ai/code/routines, from the Desktop app, or via /schedule in the CLI. Use /schedule list to view all routines, /schedule update to modify one, and /schedule run to trigger one immediately.

Each routine can have multiple triggers combined:

Routines run as full Claude Code cloud sessions with no permission prompts. They can use your connected MCP connectors (included by default — remove any that aren’t needed) and are scoped by the repositories you select, the cloud environment’s network access, and the connectors you include. By default, Claude can only push to claude/-prefixed branches; enable Allow unrestricted branch pushes per repository if needed.

Routines are available on Pro, Max, Team, and Enterprise plans. Team and Enterprise admins can disable routines via the Routines toggle at claude.ai/admin-settings/claude-code. API and GitHub triggers are configured from the web UI only; /schedule in the CLI creates scheduled routines.

Background Automation

Background subagents with background: true in their frontmatter run without blocking the main conversation. This enables workflows where you kick off a long analysis, continue other work, and get notified when it completes. If you need automation around follow-up work, use the officially documented task and team hook events in their intended contexts: TaskCompleted for task state changes and TeammateIdle for agent teams teammates about to go idle.

{
  "hooks": {
    "TaskCompleted": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "curl -X POST $SLACK_WEBHOOK -d '{"text": "Task completed: $TASK_NAME"}'"
          }
        ]
      }
    ]
  }
}

For long-running research that spans multiple sessions, resumable agents and regular memory workflows are the safer mental model: let the agent write findings into memory or project docs, then resume the agent or session later when needed.

Dynamic Workflows

Beyond single-session patterns, Claude Code supports dynamic workflows — a research-preview feature introduced in v2.1.154 that lets you orchestrate dozens to hundreds of subagents from a JavaScript script Claude writes. Unlike /loop or /batch, which run within a single conversation, a workflow moves the plan into a script: the script holds the loop, the branching, and the intermediate results, so Claude’s context keeps only the final answer.

To run a workflow, include the word ultracode anywhere in your prompt (the trigger keyword was renamed from workflow to ultracode in v2.1.160; asking for one in your own words still works), or turn on /effort ultracode to let Claude plan one for every substantial task. Claude writes an orchestration script tailored to your goal, then a runtime executes it in the background while your session stays responsive. Dynamic workflows fit codebase-wide audits, large migrations, cross-checked research, and any task that needs more agents than one conversation can coordinate.

The bundled /deep-research <question> workflow automates multi-source research: it fans out web searches across several angles, fetches and cross-checks the sources it finds, votes on each claim, and returns a cited report with claims that didn’t survive cross-checking filtered out. It requires the WebSearch tool to be available:

/deep-research What changed in the Node.js permission model between v20 and v22?

Run /workflows to list running and completed workflows and open a progress view that shows each phase’s agent count, token total, and elapsed time. When a run does what you wanted, select it in the /workflows view and press s to save its script as a command — it then runs as /<name> in future sessions, alongside the bundled workflows. Reuse pays off for recurring work like a weekly code audit or a release checklist.

For maximum reasoning depth, /effort ultracode combines xhigh effort with automatic workflow orchestration — Claude decides when a task warrants a workflow and coordinates the agents without being asked. It lasts for the current session; drop back with /effort high for routine work.

Dynamic workflows require Claude Code v2.1.154+ and are available on all paid plans (Pro, Max, Team, Enterprise). On Pro, turn them on from the Dynamic workflows row in /config. To disable them, toggle Dynamic workflows off in /config, set "disableWorkflows": true in settings, or set CLAUDE_CODE_DISABLE_WORKFLOWS=1.

Multi-Step Workflow Patterns

The most reliable workflows combine skills, hooks, and subagents into a pipeline where each step has clear inputs, outputs, and error handling.

The “develop and verify” pattern pairs a Stop prompt hook that checks completion criteria against an implementation skill. When Claude stops, the hook evaluates whether all requirements were met. If not, it tells Claude what’s missing and Claude continues:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Check: 1) Were all files in the spec modified? 2) Do tests pass? 3) Is the implementation complete per the requirements? If anything is incomplete, explain what remains.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

The “parallel review” pattern uses Agent Teams (experimental, disabled by default — requires CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1) to have multiple specialists review simultaneously. One agent checks security, another checks performance, another checks test coverage. The team lead synthesizes their findings into a single report. Agent Teams have known limitations around session resumption, task coordination, and shutdown behavior.

For tasks that modify many files across a codebase, /batch <instruction> plans the work, splits it across background agents in isolated git worktrees, and is designed for large-scale refactors or repetitive changes. Depending on the workflow, it can also run verification steps and help open PRs for the results.

Git worktrees (isolation: worktree on subagents) are also useful for experimental work. The agent makes changes in an isolated branch, returns the worktree path when done, and you review or discard without affecting your working tree.


Real-World Workflow Examples

Here are production-ready CI/CD and automation patterns for Claude Code:

Example 1: CI/CD Pipeline Integration

Running Claude Code non-interactively in a CI pipeline with structured JSON output:

#!/bin/bash
# Run Claude in print mode with JSON output and turn limit
claude -p --output-format json --max-turns 3 "review code for security issues"

# Pipe a file into Claude for analysis
cat error.log | claude -p --output-format json "explain this error"

# Process multiple files in batch
for file in src/*.ts; do
  claude -p "summarize: $(cat $file)" --output-format json > "${file%.ts}.summary.json"
done

# Verify authentication before pipeline runs
claude auth status || exit 1

Example 2: Fork and Compare Sessions

Using session forking to try different approaches without losing the original:

# Resume an existing session and fork it to try a new approach
claude --resume my-feature --fork-session "approach-v2"

# The original session is preserved
# The forked branch gets its own independent conversation history

Example 3: GitHub Actions Workflow

Integrating Claude Code into a GitHub Actions CI/CD pipeline:

# .github/workflows/claude-review.yml
name: Claude Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Claude review
        run: |
          claude auth status
          claude -p --output-format json --max-turns 3             "Review this PR for security and quality issues."
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

Pro Tips


Hands-On Challenge

Build a complete CI/CD pipeline that runs Claude Code in print mode to review every pull request automatically.

Task

Create a GitHub Actions workflow that triggers on PRs, uses Claude Code headless mode (-p) to review the diff, posts findings as a PR comment, and gates merging on critical issues.

Steps

  1. In your repository, create .github/workflows/claude-review.yml.
  2. Configure it to trigger on pull_request events for the opened and synchronize activity types.
  3. Add a step that checks out the code and sets up Node.js.
  4. Run claude -p "Review this PR diff for security issues, bugs, and style. Output a markdown summary." --output-format text with ANTHROPIC_API_KEY from repository secrets.
  5. Capture the output and post it as a comment using the actions/github-script action or gh pr comment.
  6. (Optional) Add a second job that fails the check if the review output contains "CRITICAL".

Expected Outcome

A working workflow file that automatically reviews every PR, posts a structured review comment within seconds, and optionally blocks merges when critical issues are found.

Hint

Print mode (claude -p) runs non-interactively and exits after producing output—perfect for CI. Use --output-format json if you need to parse the response programmatically. Store your API key in GitHub Secrets (never hardcode it), and use --no-session-persistence to avoid filling up disk with session data on the runner.


Knowledge Check

Test your understanding of Claude Code workflows and automation:

Q1: What is the foundation of CI/CD integration with Claude Code?

A) The --ci flag
B) Print mode (claude -p) which runs non-interactively and outputs to stdout
C) The GitHub Actions marketplace app
D) The claude pipeline command

Correct answer: B — Print mode (-p) runs Claude non-interactively, accepts a prompt, and returns the result to stdout.

Q2: How do you guarantee schema-valid JSON output from Claude in a CI pipeline?

A) Just use --output-format json
B) Use --output-format json --json-schema with a JSON Schema definition
C) Use --strict-json flag
D) JSON output is always schema-valid

Correct answer: B — Adding --json-schema guarantees the output matches the schema for reliable parsing.

Q3: What is the recommended pattern for batch processing multiple files with Claude Code?

A) claude --batch *.md
B) Use a shell for-loop with print mode for each file independently
C) claude -p --files *.md "summarize all"
D) Batch processing is not supported

Correct answer: B — Use shell for-loops with print mode to process files one at a time independently.

Q4: Which exit code from claude auth status indicates a successful login?

A) 1
B) 0
C) 200
D) It doesn’t return an exit code

Correct answer: B — Exit code 0 means logged in, 1 means not. This makes it scriptable for CI/CD auth checks.

Q5: How do you fork an existing session to try a different approach without losing the original?

A) Use /fork command
B) Use --resume session-name --fork-session "branch name"
C) Use --clone session-name
D) Use /branch session-name

Correct answer: B--resume with --fork-session creates an independent branch preserving the original conversation.

Test Your Knowledge

/5

Lesson 11 Quiz: Workflows & Best Practices

Test your knowledge of Claude Code workflows, patterns, and best practices.

1 / 5

How do you effectively use git checkpoints with Claude Code?

Committing before Claude makes changes gives you a clean rollback point. Use git alongside Claude's checkpoint system.

2 / 5

What is context window management and why is it important?

Claude Code has a context window limit. Use /compact to summarize conversation, or start subagents for isolated tasks.

3 / 5

What is the recommended approach for complex multi-step tasks in Claude Code?

For complex tasks: use planning mode to outline strategy, then delegate subtasks to subagents with isolated context.

4 / 5

Which is the best practice for code review with Claude Code?

Use planning mode for read-only analysis first, review the proposed changes, then approve before Claude edits.

5 / 5

What is the recommended workflow for debugging with Claude Code?

Effective debugging: share the error output, let Claude investigate the root cause, review the proposed fix, and test before committing.

Your score is

0%

Additional Resources

Resource Type What You'll Learn
Headless Mode Documentation Docs Running Claude Code non-interactively for automation, CI/CD, and scripting
CLI Reference Reference -p, --output-format, --resume, and session management flags
Scheduled Tasks Documentation Docs Recurring tasks (hourly, daily, weekly) for automated workflows
Hooks System Reference Guide Event-driven shell commands that automate workflows before/after tool use
Claude Code Changelog Changelog Dynamic workflows, background tasks, and /schedule improvements

Claude Code Workflows gives you a solid, repeatable workflow. Bookmark this Claude Code Workflows guide and revisit the steps whenever you need them.

Setting Up an Automated PR Review: A Step-by-Step Walkthrough

The fastest way to see Claude Code Workflows pay off is to automate the review step every pull request already needs. This walkthrough wires Claude into GitHub Actions so every PR gets a structured review comment automatically.

  1. Add the workflow file. Create .github/workflows/claude-review.yml triggered on pull_request for the opened and synchronize event types, so re-pushes get reviewed too, not just the initial PR.
  2. Store the API key as a secret. Add ANTHROPIC_API_KEY under repository secrets — never hardcode it in the workflow file — and reference it as ${{ secrets.ANTHROPIC_API_KEY }}.
  3. Run Claude in print mode. The review step calls claude -p non-interactively so it exits automatically once done:
    DIFF=$(git diff origin/main...HEAD)
    echo "$DIFF" | claude -p "Review this diff for security issues, bugs, and style. Output JSON with fields: summary, critical_issues, suggestions" 
      --output-format json --permission-mode bypassPermissions --max-turns 3
  4. Post the result as a PR comment. Pipe the JSON output through jq to extract the fields you want, then post them with gh pr comment or the actions/github-script action so the review appears directly on the PR.
  5. Gate merges on critical issues, optionally. Add a second job that checks whether the output contains a critical-issue flag and fails the check if so — this turns the review from advisory into a real quality gate.
  6. Graduate to a routine for anything recurring. Once the review step is solid, consider moving broader checks — a nightly security audit, a weekly dependency review — into a cloud-backed routine via /schedule, so they run independently of any single PR or local terminal session.

This same shape — print mode, JSON output, a turn limit, and credentials in secrets — is the backbone of most Claude Code Workflows you’ll build for CI/CD, whether the task is reviewing diffs, generating docs, or running a linter automatically.

Keep the scope of each automated step narrow. A review job that only reviews, a docs job that only regenerates documentation, and a lint job that only fixes style issues are each easier to debug than one enormous workflow that tries to do everything in a single Claude Code invocation.

Claude Code Workflows: Common Mistakes to Avoid

Automation multiplies mistakes as easily as it multiplies productivity. Watch for these before wiring Claude Code Workflows into anything that runs unattended.

Claude Code Workflows: Best Practices

Claude Code Workflows: Frequently Asked Questions

What’s the difference between /loop and a routine?

/loop is session-scoped and stops when you close the terminal. A routine created with /schedule is cloud-backed and keeps running on its own schedule independently of your local session.

Can Claude Code Workflows push directly to protected branches?

By default, routines can only push to claude/-prefixed branches. Unrestricted branch pushes have to be enabled explicitly per repository.

How do I keep a CI run from hanging indefinitely?

Set –max-turns to cap the number of turns, and use –permission-mode bypassPermissions so the run never stalls waiting for an approval prompt that will never come.

What triggers can a routine respond to?

Scheduled cadence, an API endpoint you can call from other systems, or GitHub events like pull requests and releases, and a routine can combine more than one trigger.

Are dynamic workflows the same thing as CI/CD workflows?

No — dynamic workflows orchestrate many subagents from a script for large in-session tasks, while CI/CD workflows in this guide refer to running Claude Code inside your existing pipeline.

Exit mobile version