intermediatepracticalsetuplocal-developmentworkflowclaude-code

Chapter 1 of 8

Setting Up a Local AI Loop Workflow

Configure Claude Code, Cursor, CLAUDE.md, hooks, and project structure — step-by-step environment setup.

This guide walks you through configuring a local AI agent loop workflow from scratch. You will set up Claude Code (github.com/anthropics/claude-code) as your primary loop engine, configure project context files that the agent reads automatically, wire up lifecycle hooks for automated validation, and optionally integrate Cursor Agent Mode (cursor.com) as a GUI-based alternative. By the end, you will have a repeatable, project-specific loop that reads instructions, writes code, validates its own output, and iterates until the task is complete.

Prerequisites

Before you begin, make sure your environment meets these requirements:

RequirementMinimum VersionInstallation CommandNotes
Node.jsv18+nodejs.orgRequired for Claude Code
Python3.10+python.orgOptional, for custom loop scripts
Git2.30+git-scm.comRequired for version control
Claude CodeLatestSee Option A belowAnthropic's official CLI agent (github.com/anthropics/claude-code)
CursorLatestcursor.comOptional, see Option B

Claude Code (github.com/anthropics/claude-code) is Anthropic's official CLI-based coding agent. It reads project configuration from CLAUDE.md files, supports lifecycle hooks for controlling agent behavior, and runs in both interactive and headless modes. This makes it the most flexible option for building automated loop workflows.

Installation

Install Claude Code globally via npm:

npm install -g @anthropic-ai/claude-code

Verify the installation:

claude --version

Authentication

When you run claude for the first time, it launches an OAuth flow in your browser. Sign in with your Anthropic account (Claude Pro or Max subscription). This is the simplest approach for interactive use.

Alternatively, set an environment variable to authenticate with an API key:

export ANTHROPIC_API_KEY="sk-ant-..."

Using an API key is required for headless mode and CI environments. For security, store the key in your shell profile (.bashrc, .zshrc) rather than exporting it inline.

Creating a CLAUDE.md File

The CLAUDE.md file is Claude Code's primary configuration mechanism. Place it at your project root, and Claude Code reads it automatically every time it starts. Think of it as the loop's system prompt -- it defines what the agent knows about your project, how it should work, and what conventions to follow.

Create a CLAUDE.md file at your project root:

# Project: my-loop-project

## Description
A REST API for task management built with Express.js and PostgreSQL.
The API supports user authentication, CRUD operations for tasks, and
real-time updates via WebSockets.

## Tech Stack
- Runtime: Node.js 20 with TypeScript
- Framework: Express.js with tRPC
- Database: PostgreSQL 16 with Prisma ORM
- Testing: Vitest for unit tests, Supertest for integration tests
- Linting: ESLint with Prettier

## Coding Conventions
- Use strict TypeScript (no `any` types). If a type is truly unknown, use `unknown`.
- All async functions must have explicit error handling -- never let exceptions propagate uncaught.
- Route handlers go in `src/routes/`. Business logic goes in `src/services/`.
- Database queries go in `src/repositories/`. Never query the database from route handlers.
- All new functions must have JSDoc comments describing parameters and return values.

## Testing Instructions
- Run unit tests: `npm run test:unit`
- Run integration tests: `npm run test:integration`
- Run all tests: `npm test`
- Tests must pass with zero failures before considering a task complete.

## Key File Paths
- `src/routes/` -- HTTP route definitions
- `src/services/` -- Business logic layer
- `src/repositories/` -- Database access layer
- `src/types/` -- Shared TypeScript type definitions
- `prisma/schema.prisma` -- Database schema
- `tests/` -- All test files mirror the `src/` structure

Configuring Hooks

Claude Code hooks let you inject custom behavior at specific points in the agent's lifecycle. Hooks are configured in .claude/settings.json at your project root. They run shell commands in response to events, giving you automated validation, logging, or workflow control without manual intervention.

The available lifecycle events are:

EventTrigger PointUse Case
PreToolUseBefore the agent executes a tool callValidate or block specific actions
PostToolUseAfter the agent executes a tool callRun linting, tests, or type checks
StopWhen the agent finishes its taskFinal validation, notifications
NotificationWhen the agent is waiting for user inputAlerts, logging

Create .claude/settings.json with a practical hook configuration:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx eslint --fix ${file_path} 2>&1 || true"
      }
    ],
    "Stop": [
      {
        "command": "npm test 2>&1 | tail -20"
      }
    ]
  }
}

Here is what this configuration does:

  • PostToolUse hook on Edit/Write: Every time Claude Code edits or creates a file, ESLint runs automatically on that file. The || true ensures the hook does not block the agent if there are lint errors -- the agent will see the output and can fix issues on its next iteration.
  • Stop hook: When Claude Code finishes its task, the full test suite runs. The agent sees the test results and can re-enter the loop if anything fails.

For more on how these hooks fit into loop architecture, see the auto-correction loop wiki page.

Running Your First Loop

Start an interactive Claude Code session:

claude

Or pass a task directly on the command line for a single-shot loop:

claude "Implement user authentication with JWT"

When you run this command, Claude Code performs a full loop internally:

  1. Reads CLAUDE.md -- Loads your project context, conventions, and constraints.
  2. Plans -- Analyzes the codebase and creates an implementation plan.
  3. Executes -- Writes and edits files according to the plan.
  4. Evaluates -- Hooks run ESLint after each file change; the Stop hook runs tests.
  5. Iterates -- If tests fail or lint errors remain, the agent re-enters the loop and fixes issues.

For non-interactive automation (scripts, CI pipelines, batch processing), use the --dangerously-skip-permissions flag. This allows Claude Code to run without pausing for permission confirmations:

claude "Refactor all repository functions to use Prisma transactions" \
  --dangerously-skip-permissions

Use this flag only in sandboxed or trusted environments where the agent cannot cause irreversible damage.

Headless / CI Mode

Claude Code supports a headless mode designed for programmatic use in scripts and CI pipelines:

claude -p "Run the full test suite and report any failures" \
  --output-format json

The -p flag (print mode) suppresses interactive features. The --output-format json flag returns structured JSON output that you can parse in scripts. This is useful for integrating Claude Code into larger automation workflows or custom loop scripts.

Option B: Cursor Agent Mode

If you prefer a GUI-based workflow, Cursor (cursor.com) provides similar loop capabilities through its editor interface. Cursor 2.0 supports up to 8 parallel agents in Agent Mode, with multi-file editing and Cascade-style multi-step execution similar to Windsurf (windsurf.ai).

Activating Agent Mode:

  • Press Cmd+L (macOS) or Ctrl+L (Windows/Linux) to open the agent panel.
  • Press Shift+Tab to toggle Plan Mode, which lets the agent outline its approach before making changes.

Project Configuration: Cursor reads project instructions from .cursorrules (placed at the project root). This file serves the same purpose as CLAUDE.md:

You are working on a TypeScript Express API.
- Use strict types, no `any`.
- Run tests with `npm test` after every change.
- Follow the existing patterns in src/routes/ and src/services/.

For specialized loop behaviors, Cursor supports custom modes defined in .mdc files. These let you create mode-specific instructions -- for example, a "testing mode" that focuses on writing and running tests, or a "refactoring mode" that prioritizes code quality over feature additions.

Project Structure for Loop Workflows

A well-organized project structure helps the agent navigate efficiently and understand your codebase. Here is a recommended layout optimized for loop workflows:

my-loop-project/
├── CLAUDE.md              # Agent instructions and context
├── .claude/
│   └── settings.json      # Hooks and permissions
├── src/                   # Application source
├── tests/                 # Test files (agent can run these)
├── .cursorrules           # Cursor project rules (optional)
├── .cursorrules           # Cursor project rules (optional)
└── docs/                  # Additional context docs
  • CLAUDE.md at the root is read automatically by Claude Code. Keep it focused and up to date.
  • .claude/settings.json contains your hook configuration. Version control this file so your team shares the same loop behavior.
  • tests/ is critical -- the agent needs runnable tests to evaluate whether its changes are correct. Structure test files to mirror src/.
  • docs/ can hold additional context that would bloat CLAUDE.md -- architecture diagrams, API specs, or domain knowledge that the agent can read on demand. This follows the dynamic context principle from the InfoQ context engineering framework: keep the core instructions small, and let the agent load additional context as needed.

Configuration Best Practices

These practices will make your loops more reliable and cost-efficient:

  1. Define clear success criteria. The loop needs to know when to stop. Include explicit exit conditions: "Run npm test. The task is complete when all tests pass with zero failures." Without clear exit conditions, agents risk falling into the infinite loop failure mode.

  2. Include error patterns to watch for. If there are known failure modes or common mistakes, list them: "Do not use raw SQL queries -- all database access must go through the repository layer." This prevents the agent from taking shortcuts that pass immediate checks but create maintenance debt.

  3. Reference key file paths. The agent navigates faster when it knows where things are. Listing directories like src/routes/, src/services/, and prisma/schema.prisma prevents the agent from searching the entire codebase, which wastes tokens and time.

  4. Use hooks for automated validation. PostToolUse hooks that run linting, type-checking, or tests after each agent action create a tight feedback loop. The agent sees validation results immediately and can self-correct within the same session. See the single-loop architecture page for the underlying pattern.

Testing Your Setup

Verify your loop workflow works end to end with this concrete test:

Step 1: Create a small test project.

mkdir test-loop && cd test-loop
git init
npm init -y
npm install --save-dev vitest typescript @types/node
npx tsc --init

Step 2: Write a CLAUDE.md.

# Test Loop Project

## Description
A minimal TypeScript project for testing the agent loop workflow.

## Conventions
- Use TypeScript strict mode.
- All functions must have unit tests.
- Place source files in `src/` and test files in `tests/`.

## Testing
- Run tests: `npx vitest run`
- All tests must pass before the task is complete.

## Key File Paths
- `src/` -- Source code
- `tests/` -- Test files

Step 3: Run the loop.

claude "Add a helloWorld function in src/greeting.ts that returns 'Hello, World!', and write a matching test in tests/greeting.test.ts"

Step 4: Verify the agent's behavior. Watch for these signals:

  • The agent reads CLAUDE.md first (you will see it reference the file).
  • It creates src/greeting.ts with the function.
  • It creates tests/greeting.test.ts with a test.
  • It runs npx vitest run to check if the test passes.
  • If anything fails, it iterates -- modifies the code, re-runs tests, and continues until the test passes.

If all four signals appear, your loop workflow is correctly configured.

Alternative Tools for Loop Workflows

Claude Code is the recommended primary engine, but the AI coding ecosystem offers several alternatives that follow the same loop pattern:

  • Aider (github.com/paul-gauthier/aider, 30K+ stars): A Git-first CLI AI coding tool. Aider commits each change to Git, giving you a natural undo trail. Run with aider --model claude-3.5-sonnet to use Claude as the backend while getting Aider's Git-integrated loop behavior.
  • Cline (github.com/cline/cline): A VS Code plugin with MCP protocol support. Cline's loop runs inside the editor and supports tool use via the Model Context Protocol, making it a good fit if you want loop capabilities without leaving your IDE.
  • Codex CLI (github.com/openai/codex): OpenAI's official CLI agent. If your team uses OpenAI models, Codex CLI provides a similar loop workflow to Claude Code with a different model backend.
  • Windsurf (windsurf.ai): Codeium's editor with Cascade agent support. Windsurf's Cascade agent performs multi-step execution with built-in terminal access, similar to Claude Code's hook-based validation approach.

Next Steps

Now that you have a working local loop workflow, explore these resources to go deeper:

  • Custom Loop Script with Python -- Build a fully custom loop script for advanced orchestration and multi-agent patterns using frameworks like CrewAI or LangGraph.
  • Agent Loop -- Understand the core loop architecture: sense, plan, act, evaluate, iterate.
  • State Persistence -- Learn how to maintain loop state across sessions so long-running tasks can resume after interruption.
  • Prompt to Loop Transition -- Evolve a simple prompt into a robust, repeatable loop workflow.