Claude Code changes what "AI writing code" means. It is not an editor plugin — it is an autonomous coding AI Agent that runs directly in your terminal, reading and writing files, running commands, and managing Git within one continuous context. This guide covers how it actually works day to day, how to build on its SDK, how to wire it into CI/CD, and — because a terminal agent operates with real privileges — the security boundaries you keep firm when you hand it that access.

Key Takeaways

  • Terminal-native: Claude Code runs in the command line, autonomously reading/writing files, executing shell commands, and managing Git — no IDE required.
  • SDK-programmable: TypeScript/Python SDKs and a headless mode let you embed it into automation pipelines.
  • CI/CD integration: The official GitHub Action can review PRs and act on issues — with the permissions you grant it.
  • Persistent context: CLAUDE.md auto-loads project conventions each session, which shapes output but does not enforce anything.
  • Real privileges: An agent that can run your shell and push to your repo is a powerful identity — review its output and scope its access.

What Claude Code Is: A Terminal-Native Coding Agent

Claude Code is Anthropic's official agentic coding tool. It brings LLM reasoning directly into your development environment through the terminal.

Its trajectory is worth understanding as a direction, not a spec sheet: it began as a research preview, gained a persistent memory system and an SDK for programmatic use, reached general availability, and added CI/CD integration and multi-agent review over time. Exact version numbers and dated milestones change quickly, so check Anthropic's changelog for the current state rather than trusting any single "as of" table.

The design choice that matters is architectural: Claude Code does not embed in your IDE — it runs as an independent agent process in the terminal. That means it can directly operate on the file system, execute build commands, run test suites, and manage Git branches, all within a continuous context. It also means, from the first command, that it is acting with your file-system and shell privileges — a point we return to in the security section.

bash
# Install Claude Code
npm install -g @anthropic-ai/claude-code

# Start in your project root
cd your-project
claude

Once started, Claude Code scans your project structure, reads CLAUDE.md (if present), and enters an interactive session where you describe tasks in natural language.

Core Capabilities: Autonomy in the Terminal

Claude Code's core value is autonomy. It is not a completion tool waiting for line-by-line confirmation — it is an agent that completes multi-step tasks and then presents the result for review.

Multi-File Editing and Code Generation

Claude Code understands and modifies multiple files at once. Ask it to "add JWT authentication middleware to this Express app," and it will:

  1. Read the existing route and middleware structure
  2. Create the auth middleware file
  3. Modify route files to import the middleware
  4. Update package.json with new dependencies
  5. Generate corresponding unit tests
typescript
// JWT middleware generated by Claude Code
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';

interface AuthRequest extends Request {
  userId?: string;
}

export const authMiddleware = (req: AuthRequest, res: Response, next: NextFunction) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string };
    req.userId = decoded.userId;
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }
};

This is a useful starting point, and it also illustrates a boundary worth naming early: the middleware authenticates — it proves who is calling — but it does not authorize. It does not check whether that user may act on a specific record. A generated middleware like this is not object-level access control; your route handlers must still enforce that on every request. Review generated auth code with that distinction in mind rather than assuming a passing test means it is safe.

Git Operations

Claude Code's Git understanding goes beyond add and commit. It analyzes diffs, generates semantic commit messages, and can split changes into atomic commits:

bash
# In a Claude Code interactive session
> Split my recent changes into logical atomic commits

# Claude Code will:
# 1. Analyze all changes in the diff
# 2. Group them by functional semantics
# 3. Create commits sequentially, each with a clear message

Read the resulting commits before pushing — semantic grouping is a judgment call the agent gets mostly right, and occasionally wrong.

Test Generation and Execution

Claude Code generates tests and runs them immediately, reading your existing framework configuration (Jest, Vitest, pytest, etc.) and following your project's conventions:

bash
> Generate unit tests for src/utils/validator.ts covering edge cases

# Claude Code output:
# ✓ Created src/utils/__tests__/validator.test.ts
# ✓ Added test cases covering normal input, boundaries,
#   exceptions, and type checks
# ✓ Running npm test -- --testPathPattern=validator
# ✓ All tests passing

One caution that applies to any agent-written test: a passing suite proves only what the tests actually assert. An agent can generate tests that pass while checking the wrong behavior, so read the assertions, not just the green checkmark.

Claude Code Workflows: Usage Patterns

In daily development, Claude Code workflows split into two paradigms: interactive mode and headless mode.

Interactive Mode: Conversational Development

Interactive mode is the most common. Start claude in your terminal and describe tasks in natural language:

flowchart LR A["Developer Input"] --> B["Claude Analyzes Context"] B --> C["Plans Execution Steps"] C --> D["Read/Write Files, Run Commands"] D --> E["Self-Validates Results"] E -->|Needs Fix| C E -->|Done| F["Output Summary for Review"]

Typical workflow examples:

bash
$ claude

# Scenario 1: refactoring
> Refactor all callback-style async functions in src/api/ to async/await

# Scenario 2: bug fix
> Users report /api/orders returns 500 when page param is 0. Find and fix it.

# Scenario 3: code review
> Review the last commit's changes, focus on security and performance

Headless Mode: Script Integration

Headless mode uses the --print (or -p) flag for non-interactive, single-request execution — well suited to scripts and automation pipelines:

bash
# Basic usage
claude -p "Analyze dependency security for this project"

# Specify model and tool permissions
claude -p "Fix all ESLint errors in src/" \
  --model opus \
  --allowedTools "Bash,Read,Write" \
  --permission-mode acceptEdits

# Pipe input
echo "Explain the authentication flow" | claude -p

# Structured JSON output
claude -p "List all API endpoints" --output-format json

Key headless parameters:

Flag Description Example
--print, -p Non-interactive mode claude -p "query"
--model Select model --model opus
--allowedTools Allowed tools list --allowedTools "Bash,Read"
--permission-mode Permission mode --permission-mode acceptEdits
--output-format Output format --output-format json

--allowedTools and --permission-mode are not just convenience flags — they are the access boundary for an unattended run. In automation, grant the narrowest tool set the task needs (read-only where possible) rather than defaulting to everything.

Claude Code SDK: Building Custom Agent Applications

The Claude Code SDK (now renamed the Claude Agent SDK) enables programmatic access to Claude Code's capabilities for building custom agent applications. Confirm the current package names and interface in Anthropic's docs before you build on them.

Installation and Basic Usage

bash
# TypeScript SDK
npm install @anthropic-ai/claude-agent-sdk

# Python SDK
pip install claude-agent-sdk

Basic TypeScript SDK usage:

typescript
import { ClaudeAgent } from '@anthropic-ai/claude-agent-sdk';

const agent = new ClaudeAgent({
  model: 'opus',
  workingDirectory: './my-project',
  allowedTools: ['Read', 'Write', 'Bash'],
  permissionMode: 'acceptEdits',
});

// Single execution
const result = await agent.run('Refactor the database layer to use connection pooling');
console.log(result.output);

// Streaming output
const stream = agent.stream('Generate a comprehensive test suite');
for await (const event of stream) {
  if (event.type === 'text') {
    process.stdout.write(event.content);
  }
}

The allowedTools and permissionMode fields are your enforcement point in programmatic use. If your application runs the agent server-side, treat those settings as a security control, not a default.

Subagent Pattern

The SDK supports defining subagents via Markdown files, each with an independent role and tool permissions — useful for multi-agent collaboration:

markdown
<!-- .claude/agents/security-reviewer.md -->
# Security Reviewer Agent

You are a security review expert. Your responsibilities:
1. Check code for vulnerabilities (SQL injection, XSS, CSRF, etc.)
2. Verify authentication and authorization logic
3. Audit sensitive data handling

## Allowed Tools
- Read (read-only, no code modifications)
- Bash (limited to grep, find, and similar search commands)
typescript
// Invoke a subagent from the main agent
const result = await agent.run(
  'Use the security-reviewer agent to audit the authentication module'
);

Two things to keep clear about this pattern. First, the role prompt ("you are a security review expert") shapes behavior but does not confine capability — the tool permissions in the file do. Keep a reviewer subagent genuinely read-only in its allowed tools, not just in its instructions. Second, a subagent's "no issues found" is analysis, not a sign-off; human review of security-relevant changes still happens. For more on multi-agent architectures, see our AI Agent Development Guide.

GitHub Actions Integration: Agent Automation in CI/CD

Claude Code's GitHub Actions integration extends agent programming from local terminals into CI/CD pipelines. Using the official anthropics/claude-code-action, Claude can review PRs, act on issues, and generate documentation.

Basic Configuration

yaml
# .github/workflows/claude.yml
name: Claude Code Assistant

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, labeled]
  pull_request:
    types: [opened, synchronize]

jobs:
  claude:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          model: "opus"

The permissions block above is not boilerplate — it is the blast radius. This workflow can write to your repository, so grant only the scopes the task requires, and keep the API key in GitHub's encrypted secrets, never inline. Be especially careful with workflows triggered by comments on pull requests from forks, where an untrusted contributor's input can reach an agent that holds write permissions.

Operational Modes

The integration supports two core modes.

Tag mode (on-demand): trigger by mentioning @claude in a PR or issue comment:

yaml
- uses: anthropics/claude-code-action@v1
  with:
    mode: "tag"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Usage:

code
@claude This PR has a potential N+1 query issue. Optimize database access in UserService.
@claude Generate OpenAPI docs for this new API endpoint.

Auto mode (automatic): analyze new PRs or issues automatically:

yaml
- uses: anthropics/claude-code-action@v1
  with:
    mode: "auto"
    direct_prompt: "Review this PR for security issues and performance problems"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

A new PR then triggers an automatic review with structured comments. This aligns with the ideas in LLM-Powered CI/CD Automated Code Review — with the same caveat: an automated review is a first pass that surfaces things to look at, not a gate you can substitute for human judgment on risky changes.

Security When You Grant an Agent Real Access

A terminal agent that can edit files, run shell commands, and push to your repository is operating with real privileges. A few boundaries do not move, no matter how capable the agent is:

  • Grant the least access that does the job. Use --allowedTools (and the SDK's allowedTools) to scope what an agent can do. Read-only review agents should not have write or arbitrary-shell access. In CI, scope workflow permissions to the minimum.
  • Authentication is identity, not authorization. Generated auth code — like the JWT middleware above — proves who is calling, not that the caller may act on a specific record. Object-level and tenant-level access control stays in your server, enforced on every request.
  • CLAUDE.md and MEMORY.md are convention aids, not controls. They shape what the agent tends to do; they do not enforce anything. A "never access the database directly" line in CLAUDE.md is a helpful nudge, not a guardrail — real guardrails live in your architecture and permissions.
  • Tests and green CI prove only what they cover. An agent can write passing tests that assert the wrong behavior, so treat a green run as evidence for the asserted behavior, not a security sign-off.
  • Treat untrusted input as untrusted. When an agent acts on issue text, PR comments, or content fetched via MCP, that content is data, not instructions with authority. Fork PRs and public issues are the obvious risk surface.

None of this reduces Claude Code's value — it defines the conditions under which that value is safe to collect.

Claude Code vs Cursor vs Copilot: Different Shapes

By 2026 the AI coding landscape settled into three recognizable shapes, each a different design bet rather than a ranking:

Dimension Claude Code Cursor GitHub Copilot
Interface Terminal CLI VS Code fork IDE IDE plugin
Design bet Terminal-native agent Visual agent IDE Ecosystem platform
Models Claude (Opus/Sonnet) Multi-model Multi-model
Tab completion Not the focus Dedicated model Core feature
Agent mode Full-time agent Composer / Background Agent Agent Mode
CLI integration Native Limited Limited
CI/CD integration Official GitHub Action Limited GitHub-native
Best fit Complex refactoring, CI/CD automation Interactive daily development Completion, GitHub workflows

Specific model names, capabilities, and pricing change often, so treat this as a map of shapes and verify current details at each vendor. There is no universal winner — the right choice depends on which shape matches your bottleneck. For a repeatable way to decide on your own tasks rather than on feature counts, see How to Run Your Own Evaluation of Cursor, Claude Code, and Copilot, and for the broader landscape, the AI Coding Tools 2026 Comparison.

For many teams the practical answer is combining tools: an IDE assistant for interactive editing, and Claude Code for terminal-first tasks and CI/CD automation. For the working discipline that makes any of them productive, see the Vibe Coding Practical Guide.

Long-Running Autonomy: What Actually Changed

The meaningful shift with recent Claude models is that a coding agent can work through a multi-step task across an extended session rather than a single prompt — holding context, maintaining a consistent style, and self-correcting issues it introduced earlier.

Be careful how you read this. The useful, durable claim is qualitative: long-running autonomy has moved from "a few coherent minutes" to "a sustained session," which is what makes delegation viable. Any specific figure attached to it — a number of hours in a vendor demo, a benchmark solve rate, a per-token price — is a dated data point, often measured on the vendor's own setup and changing with each release. Record such numbers with a source and a date if you need them, and verify before relying on them:

json
{
  "claim": "model solve rate / max autonomous duration / token price",
  "value": "as published",
  "plan_or_scope": "the benchmark or plan it applies to",
  "source_url": "vendor documentation or model card",
  "checked_at": "YYYY-MM-DD",
  "checked_by": "name or system"
}

More importantly, no benchmark predicts how a model behaves on your codebase. If autonomy on long tasks matters to your decision, run a small trial on your own work — the method in the evaluation guide above applies directly.

Best Practices: CLAUDE.md and the Memory System

CLAUDE.md is Claude Code's most important configuration mechanism — your project's "instruction manual," auto-loaded every session. It is a convention aid: it changes what the agent tends to produce, which is exactly why it is worth writing well, and exactly why it is not a substitute for real controls.

CLAUDE.md Configuration Example

markdown
# CLAUDE.md

## Project Overview
Next.js 14 + TypeScript SaaS platform using Prisma ORM with PostgreSQL.

## Common Commands
- Dev server: `npm run dev`
- Run tests: `npm test`
- Type check: `npx tsc --noEmit`
- Lint: `npm run lint`
- DB migration: `npx prisma migrate dev`

## Code Standards
- Functional components + Hooks only, no class components
- All API routes must include Zod input validation
- Error handling uses a custom AppError class
- All user-visible text uses i18n (next-intl)

## Architecture
- src/app/ - Next.js App Router pages
- src/lib/ - Business logic and utilities
- src/components/ - React components (shadcn/ui)
- prisma/schema.prisma - Database model definitions

## Forbidden
- Never modify existing files in prisma/migrations/
- Never access the database directly in client components
- Never use the `any` type

Memory Hierarchy

Claude Code's memory system uses a multi-level structure, from highest to lowest priority:

Level Location Scope Typical Use
Enterprise Admin dashboard config Entire org Compliance policy, forbidden operations
User ~/.claude/CLAUDE.md All projects Personal coding preferences, toolchain
Project ./CLAUDE.md Current project Architecture, tech stack, commands
Directory ./src/api/CLAUDE.md Subdirectory Module-specific conventions

Use /init to bootstrap a CLAUDE.md for your project:

bash
$ claude
> /init

# Claude analyzes your project structure and generates:
# - Detected tech stack and frameworks
# - Common build/test/lint commands
# - A project directory overview

Auto-Memory

Beyond a hand-written CLAUDE.md, Claude Code can capture corrections during a session into a MEMORY.md:

bash
# Corrections are recorded
> Don't use console.log for debugging, use the debug library
> Always use prepared statements for DB queries

# Claude updates MEMORY.md:
# - Prefer the debug library over console.log
# - Always use prepared statements for database queries

This makes an improvement persist across runs instead of being re-learned each time — a convention aid, again, not a security boundary. For the underlying discipline of Prompt Engineering and context management, and how Claude Code extends its capabilities through MCP, see our MCP Protocol Deep Dive.

Advanced Tips

Slash Command Reference

Command Function
/init Initialize CLAUDE.md
/memory Edit the auto-memory file
/compact Compress the current session context
/clear Clear session history
/cost View current session token usage
/model Switch models (opus/sonnet)
/permissions View and manage tool permissions

/compact is convenient, but remember that summarizing a long session is lossy — details can be dropped. For anything correctness-critical, put the constraint in CLAUDE.md rather than trusting it to survive compaction.

Effective Prompt Patterns

In Claude Code, effective prompts follow a "goal + constraints + verification criteria" structure:

bash
# ❌ Vague instruction
> Fix the login

# ✅ Clear three-part instruction
> Fix the login endpoint bug: users get intermittent 500s with Google OAuth.
> Constraints: don't modify the DB schema. Maintain backward compatibility.
> Verification: run npm test -- auth. All tests must pass.

MCP Protocol Integration

Claude Code supports the MCP (Model Context Protocol), connecting to external tool servers that extend it beyond local file operations to databases, API platforms, and monitoring systems. When you wire in an MCP server, remember the boundary from the security section: a result that matches the server's schema tells you the shape is valid, not that its content is safe to act on — and the connection runs with whatever access you granted it.

Summary

Claude Code marks a turning point in AI coding tools: from assisted completion to an autonomous agent. Its terminal-native design, SDK programmability, and CI/CD integration bring AI Agent capabilities into the full software lifecycle.

The upside is real:

  • Development velocity: autonomously handle refactoring, tests, and first-pass review.
  • Lower CI/CD friction: an official GitHub Action for issue- and PR-driven workflows.
  • Consistency: CLAUDE.md keeps the agent aligned with your conventions.
  • Scale: the SDK and subagent patterns support automation pipelines.

The upside is also conditional on discipline: scope the agent's access, review what it produces, and keep authorization and other real controls in your systems rather than in a config file or a model's output. Start with a simple claude command on a low-stakes task, and expand as your review process keeps pace.