Skip to content

Integrating AI Agents

This guide covers everything you need to know about integrating AI coding agents with Cortex TMS. You’ll learn how to configure Claude Code, GitHub Copilot, and Cursor to read your documentation, follow your patterns, and work autonomously within your established conventions.

Why AI Agents Need Cortex TMS

Modern AI coding agents are powerful but suffer from a critical problem: they don’t know your project’s conventions unless you tell them explicitly.

The Traditional Workflow (Without TMS)

Developer: "Add authentication to the API"
AI Agent: "Sure! I'll use HS256 JWT tokens stored in localStorage"
Developer: "No, we use RS256 with httpOnly cookies"
AI Agent: "Got it! Let me update..."
Developer: "Also, tokens expire in 1 hour, not 24 hours"
AI Agent: "Updating..."
Developer: "And follow the error handling pattern from the last PR"
AI Agent: "Which PR? Can you share the pattern?"
Developer: 😩

Problem: Developers spend more time correcting AI than writing code themselves.

The Cortex TMS Workflow

Developer: "Add authentication to the API"
AI Agent: [Reads NEXT-TASKS.md → sees "Implement auth"]
[Reads docs/core/PATTERNS.md#authentication]
[Generates code with RS256, httpOnly cookies, 15-min expiry]
Developer: "Perfect! Ship it."

Solution: AI agents read your documented conventions and generate correct code the first time.


Supported AI Agents

Cortex TMS integrates with three major AI coding agents:

Claude Code

Best for: Autonomous workflows, complex refactoring, architectural decisions

Reads: CLAUDE.md automatically

Strength: Deep context understanding, follows multi-step workflows

GitHub Copilot

Best for: Inline suggestions, rapid autocomplete, incremental coding

Reads: .github/copilot-instructions.md

Strength: Fast suggestions, integrates with VS Code/JetBrains

Cursor

Best for: Chat-based development, multi-file edits, codebase exploration

Reads: .cursorrules

Strength: Excellent chat interface, fast multi-file edits


Part 1: Claude Code Integration

Claude Code is Anthropic’s official CLI for autonomous AI coding. It reads CLAUDE.md automatically and follows your documented workflows.

Prerequisites

  1. Install Claude Code

    Terminal window
    # macOS
    brew install anthropics/claude/claude-code
    # Linux/Windows (download from website)
    # Visit: https://claude.ai/claude-code
  2. Authenticate

    Terminal window
    claude-code auth

    Follow the browser authentication flow.

  3. Verify installation

    Terminal window
    claude-code --version

Understanding CLAUDE.md

Cortex TMS generates CLAUDE.md with this structure:

# 🤖 Agent Workflow & Persona
## 🎯 Role
Expert Senior Developer. Follow the **"Propose, Justify, Recommend"** framework.
## 💻 CLI Commands
- **Test**: `npm test` or `pnpm test`
- **Lint**: `npm run lint`
- **Build**: `npm run build`
## 🛠 Operational Loop
**Step 0: Git Protocol (MANDATORY)**
- Before ANY code changes: Create a branch using `git checkout -b type/ID-description`
- NEVER work directly on `main` branch
**Implementation Steps:**
1. Read `NEXT-TASKS.md` to understand the current objective.
2. Cross-reference `docs/core/PATTERNS.md` for existing code conventions.
3. If unsure of a term, check `docs/core/GLOSSARY.md`.
4. Execute TDD (Test-Driven Development).
## 🧹 Post-Task Protocol
After completing a task:
1. **Archive Completed Tasks**: Move done items from `NEXT-TASKS.md` to `docs/archive/`
2. **Run Validation**: Execute `cortex-tms validate --strict`
3. **Commit Changes**: Follow conventional commit format

Key sections:

  • Role: Defines the agent’s persona (senior dev, junior dev, code reviewer, etc.)
  • CLI Commands: Project-specific commands Claude should run
  • Operational Loop: Step-by-step workflow for every task
  • Post-Task Protocol: Cleanup and maintenance steps

Customizing CLAUDE.md for Your Project

Open CLAUDE.md and customize these sections:

## 🎯 Role
Expert TypeScript Developer specializing in React and Node.js APIs.
**Persona Traits**:
- Prioritize type safety (prefer strict TypeScript)
- Write testable code (dependency injection, pure functions)
- Follow functional programming principles where appropriate
- Question unclear requirements before implementing
**Communication Style**:
- Ask clarifying questions when acceptance criteria are vague
- Suggest improvements to patterns when you spot issues
- Explain trade-offs when multiple approaches exist

Testing Claude Code Integration

  1. Open your project with Claude Code

    Terminal window
    cd your-project
    claude-code .
  2. Test: Reading NEXT-TASKS.md

    Ask Claude:

    “What’s the current sprint goal?”

    Expected behavior:

    • Claude reads NEXT-TASKS.md
    • Summarizes the active sprint and tasks
    • Mentions blockers if any exist
  3. Test: Following Patterns

    Ask Claude:

    “Implement the authentication middleware from the current sprint”

    Expected behavior:

    • Claude reads NEXT-TASKS.md to find the task
    • Claude reads docs/core/PATTERNS.md#authentication for the pattern
    • Claude generates code matching your documented pattern exactly
  4. Test: Git Workflow

    Ask Claude:

    “Start working on the database setup task”

    Expected behavior:

    • Claude creates a feature branch: git checkout -b feature/database-setup
    • Claude confirms branch creation before starting work
  5. Test: Post-Task Protocol

    After implementing a feature, ask:

    “I’m done with this task. What’s next?”

    Expected behavior:

    • Claude runs cortex-tms validate
    • Claude commits changes with conventional format
    • Claude updates NEXT-TASKS.md to mark task complete
    • Claude suggests archiving if sprint is done

Advanced: Multi-Agent Collaboration

You can configure Claude to work alongside other AI agents:

## 🤝 Multi-Agent Workflow
**When working with GitHub Copilot**:
- Copilot handles inline autocomplete (micro-level)
- Claude handles feature implementation (macro-level)
- Copilot reads `.github/copilot-instructions.md` for critical rules
- Claude reads full context from `CLAUDE.md` and `docs/core/`
**Division of Labor**:
- **Copilot**: Variable names, function signatures, repetitive code
- **Claude**: Architecture decisions, test generation, refactoring
**Communication Protocol**:
- Copilot suggestions must follow patterns in `docs/core/PATTERNS.md`
- If Copilot suggests code that violates patterns, reject it
- Claude has final authority on architecture (defers to ADRs)

Part 2: GitHub Copilot Integration

GitHub Copilot reads .github/copilot-instructions.md to understand project conventions. Cortex TMS generates this file with a reference to CLAUDE.md.

Prerequisites

  1. Install GitHub Copilot

  2. Verify installation

    Open VS Code → Settings → Search “Copilot” → Ensure enabled

  3. Check Copilot reads instructions

    Open any .ts file and type a comment:

    // Generate a function that

    Copilot should suggest completions based on your project context.

Understanding .github/copilot-instructions.md

Cortex TMS generates .github/copilot-instructions.md with this default content:

# GitHub Copilot Instructions for [Project Name]
See `CLAUDE.md` for full project conventions and workflows.
## Critical Rules (Security & Correctness)
- **Never commit secrets**: No API keys, passwords, or tokens in source code
- **Authentication**: Use RS256 JWT tokens with httpOnly cookies (see `docs/core/PATTERNS.md#authentication`)
- **Error Handling**: Always use AppError class (see `docs/core/PATTERNS.md#error-handling`)
## Tech Stack
- **Language**: TypeScript (strict mode)
- **Framework**: Express.js
- **Database**: PostgreSQL with Drizzle ORM
- **Testing**: Jest (unit), Playwright (e2e)
## Quick Reference
- Coding patterns: `docs/core/PATTERNS.md`
- Architectural decisions: `docs/decisions/`
- Current sprint: `NEXT-TASKS.md`

Key sections:

  • Critical Rules: Security and correctness rules that must never be violated
  • Tech Stack: Technologies Copilot should use
  • Quick Reference: Pointers to detailed documentation

Customizing Copilot Instructions

Edit .github/copilot-instructions.md to add project-specific rules:

## Critical Rules (Security & Correctness)
**Authentication & Authorization**:
- Never use HS256 for JWT tokens → Use RS256 (asymmetric)
- Never store tokens in localStorage → Use httpOnly cookies
- Access tokens expire in 15 minutes
- Refresh tokens expire in 7 days
- Always validate token signature server-side
**Data Validation**:
- Validate all user input with Zod schemas
- Sanitize SQL inputs (Drizzle handles this automatically)
- Never trust client-provided data
**Secrets Management**:
- Never commit secrets to Git (check .gitignore)
- Use environment variables for all secrets
- Never log secrets (even in debug mode)
**Financial Data**:
- Use `Decimal` type for money (never `number`)
- Store cents as integers (avoid floating-point errors)
- Round currency to 2 decimal places

Testing Copilot Integration

  1. Open VS Code in your project

    Terminal window
    code your-project
  2. Test: Inline Suggestions

    Create a new file src/services/user.service.ts and start typing:

    import { db } from '@/db';
    import { users } from '@/models';
    export class UserService {
    async createUser

    Expected: Copilot suggests a function signature matching your patterns:

    async createUser(data: { name: string; email: string }) {
    const [user] = await db
    .insert(users)
    .values(data)
    .returning();
    return user;
    }
  3. Test: Security Rules

    Type a comment that violates security rules:

    // Store JWT token in localStorage

    Expected: Copilot should NOT suggest localStorage.setItem(...) because .github/copilot-instructions.md forbids it.

  4. Test: Chat Integration

    Open Copilot Chat (Cmd+Shift+I) and ask:

    “What’s our authentication pattern?”

    Expected: Copilot references .github/copilot-instructions.md and summarizes:

    • RS256 JWT tokens
    • httpOnly cookies
    • 15-minute access token expiry
  5. Test: Code Explanation

    Highlight a function and ask Copilot Chat:

    “Does this follow our error handling pattern?”

    Expected: Copilot checks if the code uses AppError class (as specified in .github/copilot-instructions.md).

Advanced: Copilot Chat Agents

GitHub Copilot Chat supports custom agents that can read your documentation:

## Copilot Chat Commands
**@workspace**: Ask about the entire codebase
- Example: "@workspace where is the authentication middleware?"
**@terminal**: Execute commands and explain output
- Example: "@terminal run npm test and explain failures"
**Custom Slash Commands**:
- `/explain`: Explain highlighted code
- `/fix`: Suggest fixes for linting errors
- `/tests`: Generate tests for highlighted function

Part 3: Cursor Integration

Cursor is an AI-powered code editor built on VS Code. It reads .cursorrules to understand project conventions.

Prerequisites

  1. Download Cursor

    Visit cursor.sh and download the installer for your OS.

  2. Migrate from VS Code (optional)

    Cursor can import your VS Code settings:

    Cursor → Settings → General → Import VS Code Settings
  3. Enable AI features

    Cursor requires an account (free tier available):

    Cursor → Sign In → Create Account

Understanding .cursorrules

Cursor reads .cursorrules from the project root. This file uses the same format as CLAUDE.md.

Two approaches:

Terminal window
# Copy CLAUDE.md to .cursorrules
cp CLAUDE.md .cursorrules
# Add .cursorrules to .gitignore (if team uses different editors)
echo ".cursorrules" >> .gitignore

Pros:

  • Full context available to Cursor
  • Includes all workflows and patterns

Cons:

  • Must manually sync changes between files
  • Risk of drift over time

Customizing .cursorrules

If you choose to maintain a separate .cursorrules file, customize it for Cursor’s strengths:

# Cursor Rules for [Project Name]
See `CLAUDE.md` for full project conventions.
## Tech Stack
- TypeScript (strict mode)
- Express.js API
- PostgreSQL with Drizzle ORM
- Jest + Playwright for testing
## Critical Rules
- Never commit secrets (API keys, passwords)
- Use RS256 JWT tokens (not HS256)
- Store tokens in httpOnly cookies (not localStorage)
- Follow patterns in `docs/core/PATTERNS.md`
## Cursor-Specific Workflows
**Multi-File Edits**:
- Use Cmd+K for inline edits (single file)
- Use Chat for multi-file refactoring (e.g., renaming across files)
**Codebase Exploration**:
- Use "@Codebase" in chat to search entire project
- Ask: "@Codebase where is the authentication logic?"
**Pattern Application**:
- Reference canonical examples: "Follow `src/services/tasks.service.ts` pattern"
- Cursor will analyze the example and apply the pattern
## Quick Commands
- **Test**: `npm test`
- **Lint**: `npm run lint`
- **Dev Server**: `npm run dev` (http://localhost:3000)

Testing Cursor Integration

  1. Open project in Cursor

    Terminal window
    cursor your-project
  2. Test: Inline Edits (Cmd+K)

    Open src/services/user.service.ts and place cursor on a function.

    Press Cmd+K (or Ctrl+K) and type:

    “Add error handling following our AppError pattern”

    Expected: Cursor reads .cursorrulesdocs/core/PATTERNS.md#error-handling and wraps the function in try/catch with AppError.

  3. Test: Chat Context (@Codebase)

    Open Cursor Chat (Cmd+L) and ask:

    “@Codebase What’s our authentication pattern?”

    Expected: Cursor searches the codebase, finds .cursorrulesdocs/core/PATTERNS.md#authentication, and summarizes the pattern.

  4. Test: Multi-File Refactoring

    In Cursor Chat, ask:

    “Rename getUserTasks to fetchUserTasks across all files”

    Expected: Cursor identifies all occurrences and proposes changes across multiple files.

  5. Test: Pattern Replication

    In Cursor Chat, ask:

    “Create a new ProjectService following the pattern in src/services/tasks.service.ts

    Expected: Cursor analyzes tasks.service.ts and generates project.service.ts with the same structure (class, methods, error handling, tests).

Advanced: Cursor Composer

Cursor Composer is a multi-file editing mode that applies changes across your codebase:

  1. Open Composer

    Press Cmd+Shift+I (or Ctrl+Shift+I)

  2. Describe multi-file change

    Type:

    “Refactor all services to use dependency injection. Inject the database connection via constructor instead of importing db directly.”

  3. Review proposed changes

    Cursor shows a diff of all affected files.

  4. Accept or reject

    Review each file and accept/reject changes individually.


Part 4: Comparing the Three Agents

Each AI agent has strengths and weaknesses. Here’s when to use each:

Feature Comparison Matrix

FeatureClaude CodeGitHub CopilotCursor
Inline Autocomplete❌ No✅ Excellent✅ Good
Multi-File Edits✅ Excellent❌ No✅ Excellent
Chat Interface✅ Terminal-based✅ VS Code sidebar✅ Built-in panel
Context Window200k tokens~4k tokens~32k tokens
Reads Documentation✅ CLAUDE.md⚠️ Limited (100 lines)✅ .cursorrules
Autonomous Workflows✅ Yes (follows CLAUDE.md)❌ No⚠️ Limited
Code Explanation✅ Excellent✅ Good✅ Good
Test Generation✅ Excellent✅ Good✅ Good
Refactoring✅ Excellent❌ Limited✅ Excellent
CostFree tier + paid$10-20/monthFree tier + paid

Use Case Recommendations

Daily Coding

Use Copilot

Fast inline autocomplete for variable names, function signatures, and repetitive code.

Feature Implementation

Use Claude Code or Cursor

Understands broader context, follows patterns, generates tests.

Large Refactoring

Use Cursor Composer

Multi-file edits with preview and granular accept/reject.

Architectural Decisions

Use Claude Code

Reads ADRs, suggests alternatives, creates documentation.


Part 5: Multi-Agent Workflows

You can use all three agents together for maximum productivity:

Example: Building a New Feature

  1. Planning (Claude Code)

    Ask Claude Code:

    “Read NEXT-TASKS.md and create a plan for implementing the ‘User Profile’ feature”

    Claude does:

    • Reads NEXT-TASKS.md to understand requirements
    • Checks docs/core/PATTERNS.md for existing patterns
    • Creates a step-by-step implementation plan
    • Suggests test cases
  2. Implementation (Copilot + Cursor)

    Copilot: Use for inline autocomplete while writing:

    • Controller methods
    • Service functions
    • Database queries

    Cursor: Use Cmd+K for:

    • Generating boilerplate (entire controller class)
    • Adding error handling to functions
    • Generating validation schemas
  3. Testing (Claude Code)

    Ask Claude Code:

    “Generate unit tests for UserProfileService”

    Claude does:

    • Reads docs/core/PATTERNS.md#testing
    • Generates tests matching your testing pattern
    • Mocks dependencies correctly
    • Runs npm test to verify
  4. Refactoring (Cursor Composer)

    After initial implementation, use Cursor Composer:

    “Refactor UserProfileService to use dependency injection”

    Cursor does:

    • Edits user-profile.service.ts
    • Updates user-profile.service.test.ts (mocks)
    • Updates src/index.ts (service instantiation)
  5. Documentation (Claude Code)

    Ask Claude Code:

    “Update docs/core/PATTERNS.md with the user profile pattern”

    Claude does:

    • Adds a new section to PATTERNS.md
    • Includes canonical example
    • Updates table of contents
  6. Validation (Claude Code)

    Ask Claude Code:

    “Run the post-task protocol”

    Claude does:

    • Runs cortex-tms validate --strict
    • Runs npm test
    • Commits changes with conventional format
    • Updates NEXT-TASKS.md to mark task complete

Part 6: Troubleshooting

Issue: AI agent isn’t reading documentation

Symptoms:

  • Claude Code generates code that violates patterns
  • Copilot suggests incorrect conventions
  • Cursor doesn’t reference .cursorrules

Solutions:

  1. Verify CLAUDE.md exists

    Terminal window
    ls -la CLAUDE.md

    If missing, run cortex-tms init to regenerate.

  2. Check file encoding

    CLAUDE.md must be UTF-8 encoded:

    Terminal window
    file CLAUDE.md
    # Output: CLAUDE.md: UTF-8 Unicode text
  3. Test with explicit reference

    Ask: “Read CLAUDE.md and summarize the operational loop”

    If Claude can’t read it, report a bug.


Issue: AI agent violates security rules

Symptoms:

  • Copilot suggests storing tokens in localStorage
  • Claude generates HS256 tokens instead of RS256
  • Cursor suggests committing secrets

Solutions:

  1. Add security rule to instructions

    Edit .github/copilot-instructions.md (or .cursorrules):

    ## Critical Rules (Security)
    **NEVER**:
    - Store tokens in localStorage (use httpOnly cookies)
    - Use HS256 for JWT (use RS256)
    - Commit secrets to Git (use environment variables)
  2. Move security rules to the top

    AI agents prioritize early content. Put critical rules first.

  3. Use explicit negative examples

    ## Authentication (Critical)
    **Good**: RS256 JWT tokens in httpOnly cookies
    ```typescript
    res.cookie('refreshToken', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    });

    Bad: HS256 tokens in localStorage

    // NEVER DO THIS
    localStorage.setItem('token', token);

Issue: AI agent doesn’t follow patterns

Symptoms:

  • Generated code doesn’t match docs/core/PATTERNS.md
  • Inconsistent naming conventions
  • Incorrect error handling

Solutions:

  1. Add canonical examples to PATTERNS.md

    AI agents learn better from examples than descriptions:

    ## Authentication Pattern
    **Canonical Example**: `src/middleware/auth.middleware.ts`
    ```typescript
    // Copy the ENTIRE implementation here
    export async function authenticateToken(req, res, next) {
    // ... full code
    }
  2. Reference patterns explicitly in NEXT-TASKS.md

    Instead of: “Implement authentication”

    Write: “Implement authentication following docs/core/PATTERNS.md#authentication (RS256, 15-min expiry, httpOnly cookies)”

  3. Use pattern validation

    After AI generates code, ask:

    “Does this code follow our authentication pattern from PATTERNS.md?”

    AI will self-correct if it finds discrepancies.


Best Practices

Keep Instructions Under 100 Lines

GitHub Copilot has a 100-line limit for .github/copilot-instructions.md. Use references to longer docs.

Update Docs as You Learn

When AI makes a mistake, update PATTERNS.md with the correct approach. This prevents future errors.

Use Canonical Examples

Point AI to real files: “Follow src/services/tasks.service.ts pattern”. Examples are better than descriptions.

Security Rules First

Put critical security rules at the top of instruction files. AI agents prioritize early content.

Test AI Integration Early

After setting up TMS, test each AI agent with sample tasks. Fix documentation gaps immediately.

Commit AI-Generated Code Carefully

Always review AI suggestions. Run tests and linting before committing.


Next Steps

Now that you’ve integrated AI agents with Cortex TMS: