# Claude Code Subagent System Overview

This document provides a comprehensive guide to the subagent system used in the Flyer Crawler project. Subagents are specialized AI assistants that focus on specific domains, allowing for more targeted and effective development workflows.

## What Are Subagents?

Subagents are task-specific Claude instances that can be launched using the `Task` tool in Claude Code. Each subagent has specialized knowledge and instructions tailored to a particular domain, such as coding, testing, database work, or DevOps.

**Why Use Subagents?**

- **Focused Expertise**: Each subagent has domain-specific knowledge and instructions
- **Better Context Management**: Subagents can work on isolated tasks without polluting the main conversation
- **Parallel Work**: Multiple subagents can work on independent tasks simultaneously
- **Consistency**: Subagents follow project-specific patterns and conventions automatically

## Available Subagents

The following subagents are available for use in this project:

### Core Development

| Subagent  | Purpose                                                         | When to Use                                                      |
| --------- | --------------------------------------------------------------- | ---------------------------------------------------------------- |
| **plan**  | Design implementation plans, identify files, analyze trade-offs | Starting new features, major refactoring, architecture decisions |
| **coder** | Write and modify production Node.js/TypeScript code             | Implementing features, fixing bugs, writing new modules          |

### Testing and Quality

| Subagent          | Purpose                                                           | When to Use                                          |
| ----------------- | ----------------------------------------------------------------- | ---------------------------------------------------- |
| **tester**        | Adversarial testing: edge cases, race conditions, vulnerabilities | Finding bugs, security testing, stress testing       |
| **testwriter**    | Create comprehensive tests for features and fixes                 | Writing unit tests, integration tests, test coverage |
| **code-reviewer** | Review code quality, security, best practices                     | Code review, PR reviews, architecture review         |

### Database and Infrastructure

| Subagent            | Purpose                                                   | When to Use                                                    |
| ------------------- | --------------------------------------------------------- | -------------------------------------------------------------- |
| **db-dev**          | Schemas, queries, migrations, optimization, N+1 problems  | Database development, query optimization, schema changes       |
| **db-admin**        | PostgreSQL/Redis admin, security, backups, infrastructure | Database administration, performance tuning, backup strategies |
| **devops**          | Containers, services, CI/CD pipelines, deployments        | Deployment issues, container configuration, CI/CD pipelines    |
| **infra-architect** | Resource optimization: RAM, CPU, disk, storage            | Capacity planning, performance optimization, cost reduction    |

### Specialized Technical

| Subagent                    | Purpose                                                    | When to Use                                               |
| --------------------------- | ---------------------------------------------------------- | --------------------------------------------------------- |
| **bg-worker**               | Background jobs: PM2 workers, BullMQ queues, async tasks   | Queue management, worker debugging, job scheduling        |
| **ai-usage**                | LLM APIs (Gemini, Claude), prompt engineering, AI features | AI integration, prompt optimization, Gemini API issues    |
| **security-engineer**       | Security audits, vulnerability scanning, OWASP, pentesting | Security reviews, vulnerability assessments, compliance   |
| **log-debug**               | Production errors, observability, Bugsink/Sentry analysis  | Debugging production issues, log analysis, error tracking |
| **integrations-specialist** | Third-party services, webhooks, external APIs              | External API integration, webhook implementation          |

### Frontend and Design

| Subagent                | Purpose                                                      | When to Use                                                   |
| ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- |
| **frontend-specialist** | UI components, Neo-Brutalism, Core Web Vitals, accessibility | Frontend development, performance optimization, accessibility |
| **uiux-designer**       | UI/UX decisions, component design, Neo-Brutalism compliance  | Design decisions, user experience improvements                |

### Documentation and Planning

| Subagent             | Purpose                                                     | When to Use                                                |
| -------------------- | ----------------------------------------------------------- | ---------------------------------------------------------- |
| **documenter**       | User docs, API specs, feature documentation                 | Writing documentation, API specs, user guides              |
| **describer-for-ai** | Technical docs for AI: ADRs, system overviews, context docs | Writing ADRs, technical specifications, context documents  |
| **planner**          | Break down features, roadmaps, scope management             | Project planning, feature breakdown, roadmap development   |
| **product-owner**    | Feature requirements, user stories, validation, backlog     | Requirements gathering, user story writing, prioritization |

### Support

| Subagent                         | Purpose                                  | When to Use                                          |
| -------------------------------- | ---------------------------------------- | ---------------------------------------------------- |
| **tools-integration-specialist** | Bugsink, Gitea, OAuth, operational tools | Tool configuration, OAuth setup, operational tooling |

## How to Launch a Subagent

Subagents are launched using the `Task` tool in Claude Code. Simply ask Claude to use a specific subagent for a task:

```
"Use the coder subagent to implement the new store search feature"
```

Or:

```
"Launch the db-dev subagent to optimize the flyer items query"
```

Claude will automatically invoke the appropriate subagent with the relevant context.

## Quick Reference Decision Tree

Use this flowchart to quickly identify the right subagent:

```
What do you need to do?
|
+-- Write/modify code? ----------------> Is it database-related?
|                                        |
|                                        +-- Yes -> db-dev
|                                        +-- No --> Is it frontend?
|                                                   |
|                                                   +-- Yes -> frontend-specialist
|                                                   +-- No --> Is it AI/Gemini?
|                                                              |
|                                                              +-- Yes -> ai-usage
|                                                              +-- No --> coder
|
+-- Test something? -------------------> Write new tests? -> testwriter
|                                        Find bugs/vulnerabilities? -> tester
|                                        Review existing code? -> code-reviewer
|
+-- Debug an issue? -------------------> Production error? -> log-debug
|                                        Database slow? -> db-admin
|                                        External API failing? -> integrations-specialist
|                                        AI extraction failing? -> ai-usage
|
+-- Infrastructure/Deployment? --------> Container/CI/CD? -> devops
|                                        Resource optimization? -> infra-architect
|                                        Background jobs? -> bg-worker
|
+-- Documentation? --------------------> User-facing docs? -> documenter
|                                        ADRs/Technical specs? -> describer-for-ai
|                                        Feature planning? -> planner
|                                        User stories? -> product-owner
|
+-- Security? -------------------------> security-engineer
|
+-- Design/UX? ------------------------> uiux-designer
```

## Subagent Selection Guide

### Which Subagent Should I Use?

**For Writing Code:**

- New features or modules: `coder`
- Complex architectural changes: `plan` first, then `coder`
- Database-related code: `db-dev`
- Frontend components: `frontend-specialist`
- Background job code: `bg-worker`

**For Testing:**

- Writing new tests: `testwriter`
- Finding edge cases and bugs: `tester`
- Reviewing test coverage: `code-reviewer`

**For Infrastructure:**

- Container issues: `devops`
- CI/CD pipelines: `devops`
- Database administration: `db-admin`
- Performance optimization: `infra-architect`

**For Debugging:**

- Production errors: `log-debug`
- Database issues: `db-admin` or `db-dev`
- AI/Gemini issues: `ai-usage`

**For Documentation:**

- API documentation: `documenter`
- Architecture decisions: `describer-for-ai`
- Planning and requirements: `planner` or `product-owner`

## Best Practices

### 1. Start with Planning

For complex features, always start with the `plan` subagent to:

- Identify affected files
- Understand architectural implications
- Break down the work into manageable tasks

### 2. Use Specialized Subagents for Specialized Work

Avoid using `coder` for database migrations. Use `db-dev` instead - it understands:

- The project's migration patterns
- Schema synchronization requirements
- PostgreSQL-specific optimizations

### 3. Let Subagents Follow Project Conventions

All subagents are pre-configured with knowledge of project conventions:

- ADR patterns (see [docs/adr/index.md](../adr/index.md))
- Repository pattern standards (ADR-034)
- Service layer architecture (ADR-035)
- Testing standards (ADR-010)

### 4. Combine Subagents for Complex Tasks

Some tasks benefit from multiple subagents:

1. **New API endpoint**: `plan` -> `coder` -> `testwriter` -> `code-reviewer`
2. **Database optimization**: `db-dev` -> `tester` -> `infra-architect`
3. **Security fix**: `security-engineer` -> `coder` -> `testwriter`

### 5. Always Run Tests in the Dev Container

Regardless of which subagent you use, remember:

> **ALL tests MUST be run in the dev container (Linux environment)**

The subagents know this, but as a developer, ensure you verify test results in the correct environment:

```bash
podman exec -it flyer-crawler-dev npm run test:unit
```

## Subagent Communication

Subagents can pass information back to the main conversation and to each other through:

1. **Direct Output**: Results and recommendations returned to the conversation
2. **File Changes**: Code, documentation, and configuration changes
3. **Todo Lists**: Task tracking and progress updates

## Related Documentation

### Subagent Guides

| Guide                                                | Subagents Covered                                     |
| ---------------------------------------------------- | ----------------------------------------------------- |
| [CODER-GUIDE.md](./CODER-GUIDE.md)                   | coder                                                 |
| [TESTER-GUIDE.md](./TESTER-GUIDE.md)                 | tester, testwriter                                    |
| [DATABASE-GUIDE.md](./DATABASE-GUIDE.md)             | db-dev, db-admin                                      |
| [DEVOPS-GUIDE.md](./DEVOPS-GUIDE.md)                 | devops, infra-architect, bg-worker                    |
| [FRONTEND-GUIDE.md](./FRONTEND-GUIDE.md)             | frontend-specialist, uiux-designer                    |
| [SECURITY-DEBUG-GUIDE.md](./SECURITY-DEBUG-GUIDE.md) | security-engineer, log-debug, code-reviewer           |
| [AI-USAGE-GUIDE.md](./AI-USAGE-GUIDE.md)             | ai-usage                                              |
| [INTEGRATIONS-GUIDE.md](./INTEGRATIONS-GUIDE.md)     | integrations-specialist, tools-integration-specialist |
| [DOCUMENTATION-GUIDE.md](./DOCUMENTATION-GUIDE.md)   | documenter, describer-for-ai, planner, product-owner  |

### Project Documentation

- [../adr/index.md](../adr/index.md) - Architecture Decision Records
- [../development/TESTING.md](../development/TESTING.md) - Testing guide
- [../development/CODE-PATTERNS.md](../development/CODE-PATTERNS.md) - Code patterns reference
- [../architecture/OVERVIEW.md](../architecture/OVERVIEW.md) - System architecture

## Troubleshooting

### Subagent Not Available

If a subagent fails to launch, it may be due to:

- Incorrect subagent name (check the list above)
- Network or API issues
- Context length limitations

### Subagent Gives Incorrect Advice

All subagents follow the CLAUDE.md instructions. If advice seems wrong:

1. Verify the project context is correct
2. Check if the advice conflicts with an ADR
3. Provide additional context to the subagent

### Subagent Takes Too Long

For complex tasks, subagents may take time. Consider:

- Breaking the task into smaller pieces
- Using the `plan` subagent first to scope the work
- Running simpler queries first to verify understanding
