Skill: dannyxyz22/document-multiple-repository (version 0.1.0)

--- name: document-multiple-repository description: Gera documentação técnica consolidada para sistemas de software com múltiplos repositórios (frontend, backend, microservices, wikis). Use quando o usuário pedir documentação de multi-repo, visão de arquitetura consolidada, mapeamento de repositórios ou documentação a partir de vários repos locais. version: 0.1.0 --- # Skill: document-multiple-repository ## Propósito Gerar documentação técnica consolidada para sistemas de software compostos por múltiplos repositórios (frontend, backend, microservices, infra, docs, wikis) armazenados localmente em um sistema de arquivos compartilhado. ## Premissas - Todos os repositórios (incluindo Wikis) já estão clonados localmente. - Múltiplos repositórios podem compor um único sistema lógico. - Wikis são tipicamente repositórios git com o sufixo `.wiki`. - As linguagens podem incluir Java, Python, JavaScript. - Não existem convenções rígidas de nomenclatura. - A execução é manual via agente de IA (VS Code, Copilot, Gemini CLI, etc). ## Entradas (Inputs) - ROOT_PATH: pasta contendo múltiplos sistemas. - OUTPUT_PATH: destino para a documentação gerada. - TEMPLATES_PATH: templates para README, ARCHITECTURE, API, CODE_COMMENTS. ## Etapas de Processamento ### 1. Descoberta de Sistemas (Discover Systems) - Escanear ROOT_PATH recursivamente. - Detectar repositórios git (pastas .git). - Identificar repositórios de Wiki (nome da pasta termina com `.wiki`). - Agrupar (cluster) repositórios por proximidade no sistema de arquivos. - Tratar cada grupo (código + wikis) como um único sistema lógico. ### 2. Análise de Repositórios (Analyze Repositories) Para cada repositório: - Detectar o tipo (code, docs ou wiki). - Se for Code (Código): - Detectar linguagem e framework (Spring, Django, Node, etc). - Detectar o tipo de serviço (backend, frontend, microservice, infra). - Extrair: README, build files, manifests, API routes, entities, configs. - Se for Wiki: - Detectar páginas principais (Home.md, index.md). - Extrair: guias de infraestrutura, tutoriais de setup, processos de negócio (DoR/DoD) e links para legislação externa ou ativos. - Se for Docs: - Detectar geradores estáticos (MkDocs, Sphinx, etc). - Extrair: manuais funcionais e guias de usuário. ### 3. Geração de Documentação (Generate Documentation) Criar para cada sistema: - SYSTEM_OVERVIEW.md (Visão consolidada incluindo negócio e tecnologia). - ARCHITECTURE.md. - REPOSITORY_MAP.md. - DEPLOYMENT.md (Informações mescladas de manifests de código e guias de wiki). - PROCESSES_AND_GUIDELINES.md (Extraído de Wikis: DoR, DoD, regras de contribuição). Criar para cada repositório: - README.generated.md. - API.generated.md. - CODE_STRUCTURE.md (para repositórios de código). - WIKI_SUMMARY.md (para repositórios de wiki). ### 4. Estrutura de Saída (Output Structure) OUTPUT_PATH/ system-name/ SYSTEM_OVERVIEW.md ARCHITECTURE.md REPOSITORY_MAP.md DEPLOYMENT.md PROCESSES_AND_GUIDELINES.md repos/ repo-name/ README.generated.md API.generated.md CODE_STRUCTURE.md WIKI_SUMMARY.md ## Execução O agente recebe o comando: "Run skill document-multiple-repository on <ROOT_PATH>" ## Restrições (Constraints) - Não executar código. - Não modificar os repositórios originais. - Apenas documentação.

path: CHANGELOG.md
content: # Changelog

Todas as mudanças notáveis desta skill são documentadas aqui.

O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.0/).

## [1.0.0] - 2025-02-11

### Adicionado

- Publicação inicial no ClawHub.
- Fluxo completo: descoberta de sistemas, análise de repositórios, geração de documentação (SYSTEM_OVERVIEW, ARCHITECTURE, REPOSITORY_MAP, DEPLOYMENT, PROCESSES_AND_GUIDELINES).
- Suporte a repositórios de código, wiki (`.wiki`) e docs (MkDocs, Sphinx, etc.).
- Templates para README, ARCHITECTURE, API e CODE_COMMENTS na pasta `templates/`.


path: templates/API.template.md
content: # API Documentation

## Overview

This document provides comprehensive documentation for all API endpoints in [Project Name].

**Base URL:** `https://api.example.com/v1`

**API Version:** v1

**Last Updated:** [Date]

## Table of Contents

- [Authentication](#authentication)
- [Error Handling](#error-handling)
- [Rate Limiting](#rate-limiting)
- [Endpoints](#endpoints)
  - [Resource 1](#resource-1)
  - [Resource 2](#resource-2)

## Authentication

### Authentication Method

This API uses [JWT/API Keys/OAuth/etc.] for authentication.

**How to authenticate:**

1. [Step 1 to get credentials]
2. [Step 2 to use credentials]

**Example authentication header:**
```
[REDACTED_SECRET]
```

**Getting your API token:**
```bash
# Example command or process to obtain token
curl -X POST https://api.example.com/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "[REDACTED_SECRET]", "password": "password123"}'
```

**Response:**
```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": "2024-12-31T23:59:59Z"
}
```

## Error Handling

### Error Response Format

All errors follow this format:

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {
      "field": "Additional context about the error"
    }
  }
}
```

### Common Error Codes

| Status Code | Error Code | Description | Solution |
|------------|------------|-------------|----------|
| 400 | `INVALID_REQUEST` | Request validation failed | Check request format and required fields |
| 401 | `UNAUTHORIZED` | Authentication required or failed | Provide valid authentication token |
| 403 | `FORBIDDEN` | Insufficient permissions | Check user permissions and role |
| 404 | `NOT_FOUND` | Resource doesn't exist | Verify resource ID and URL |
| 429 | `RATE_LIMIT_EXCEEDED` | Too many requests | Wait before retrying (check Retry-After header) |
| 500 | `INTERNAL_ERROR` | Server error | Contact support if persistent |

### Error Examples

**401 Unauthorized:**
```json
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired authentication token"
  }
}
```

**400 Invalid Request:**
```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Validation failed",
    "details": {
      "email": "Invalid email format",
      "age": "Must be a positive number"
    }
  }
}
```

## Rate Limiting

**Rate limits:**
- **Authenticated requests:** 1000 requests per hour
- **Unauthenticated requests:** 100 requests per hour

**Rate limit headers:**
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

**When rate limited:**
- Status code: `429 Too Many Requests`
- Response includes `Retry-After` header (seconds until reset)

## Endpoints

---

## [Resource 1 - e.g., Users]

### List [Resources]

Retrieve a paginated list of [resources].

**Endpoint:**
```
GET /api/v1/[resources]
```

**Authentication:** Required

**Query Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | integer | No | 1 | Page number for pagination |
| `limit` | integer | No | 20 | Number of items per page (max 100) |
| `sort` | string | No | `created_at` | Sort field (e.g., `name`, `created_at`) |
| `order` | string | No | `desc` | Sort order (`asc` or `desc`) |
| `filter` | string | No | - | Filter by [field] |

**Example Request:**

```bash
curl -X GET "https://api.example.com/v1/users?page=1&limit=10&sort=created_at&order=desc" \
  -H "[REDACTED_SECRET]"
```

**Example Response:**

```json
{
  "data": [
    {
      "id": "usr_123abc",
      "name": "John Doe",
      "email": "[REDACTED_SECRET]",
      "role": "admin",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    },
    {
      "id": "usr_456def",
      "name": "Jane Smith",
      "email": "[REDACTED_SECRET]",
      "role": "user",
      "created_at": "2024-01-14T15:20:00Z",
      "updated_at": "2024-01-14T15:20:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 42,
    "pages": 5
  }
}
```

**Response Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique identifier |
| `name` | string | [Resource] name |
| `email` | string | Email address |
| `role` | string | User role (`admin`, `user`, `viewer`) |
| `created_at` | string (ISO 8601) | Creation timestamp |
| `updated_at` | string (ISO 8601) | Last update timestamp |

---

### Get [Resource]

Retrieve a single [resource] by ID.

**Endpoint:**
```
GET /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Example Request:**

```bash
curl -X GET "https://api.example.com/v1/users/usr_123abc" \
  -H "[REDACTED_SECRET]"
```

**Example Response:**

```json
{
  "id": "usr_123abc",
  "name": "John Doe",
  "email": "[REDACTED_SECRET]",
  "role": "admin",
  "profile": {
    "bio": "Software developer",
    "location": "San Francisco, CA"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

**Possible Errors:**

- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to view this [resource]

---

### Create [Resource]

Create a new [resource].

**Endpoint:**
```
POST /api/v1/[resources]
```

**Authentication:** Required

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | [Resource] name (3-100 characters) |
| `email` | string | Yes | Valid email address |
| `role` | string | No | User role (default: `user`) |
| `profile` | object | No | Additional profile information |

**Example Request:**

```bash
curl -X POST "https://api.example.com/v1/users" \
  -H "[REDACTED_SECRET]" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice Johnson",
    "email": "[REDACTED_SECRET]",
    "role": "user",
    "profile": {
      "bio": "Product designer",
      "location": "New York, NY"
    }
  }'
```

**Example Response:**

```json
{
  "id": "usr_789ghi",
  "name": "Alice Johnson",
  "email": "[REDACTED_SECRET]",
  "role": "user",
  "profile": {
    "bio": "Product designer",
    "location": "New York, NY"
  },
  "created_at": "2024-01-16T14:20:00Z",
  "updated_at": "2024-01-16T14:20:00Z"
}
```

**Possible Errors:**

- `400 INVALID_REQUEST` - Validation failed (see error details)
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to create [resource]
- `409 CONFLICT` - [Resource] with this email already exists

---

### Update [Resource]

Update an existing [resource].

**Endpoint:**
```
PATCH /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | No | [Resource] name (3-100 characters) |
| `email` | string | No | Valid email address |
| `role` | string | No | User role |
| `profile` | object | No | Additional profile information |

**Note:** Only include fields you want to update. Omitted fields remain unchanged.

**Example Request:**

```bash
curl -X PATCH "https://api.example.com/v1/users/usr_123abc" \
  -H "[REDACTED_SECRET]" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "admin",
    "profile": {
      "bio": "Senior Software Developer"
    }
  }'
```

**Example Response:**

```json
{
  "id": "usr_123abc",
  "name": "John Doe",
  "email": "[REDACTED_SECRET]",
  "role": "admin",
  "profile": {
    "bio": "Senior Software Developer",
    "location": "San Francisco, CA"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-16T15:00:00Z"
}
```

**Possible Errors:**

- `400 INVALID_REQUEST` - Validation failed
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to update this [resource]
- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist

---

### Delete [Resource]

Delete a [resource].

**Endpoint:**
```
DELETE /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Example Request:**

```bash
curl -X DELETE "https://api.example.com/v1/users/usr_123abc" \
  -H "[REDACTED_SECRET]"
```

**Example Response:**

```json
{
  "success": true,
  "message": "[Resource] deleted successfully"
}
```

**Possible Errors:**

- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to delete this [resource]
- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist

---

## [Resource 2 - e.g., Projects]

[Repeat the same pattern for another resource: List, Get, Create, Update, Delete]

---

## Webhooks

### Overview

[If your API supports webhooks, document them here]

**Webhook endpoint requirements:**
- Must accept POST requests
- Must respond with 200 status within 5 seconds
- Must use HTTPS

### Available Events

| Event | Description | Triggered When |
|-------|-------------|----------------|
| `[resource].created` | [Resource] was created | New [resource] is created |
| `[resource].updated` | [Resource] was updated | [Resource] is modified |
| `[resource].deleted` | [Resource] was deleted | [Resource] is deleted |

### Webhook Payload

```json
{
  "event": "[resource].created",
  "timestamp": "2024-01-16T15:30:00Z",
  "data": {
    "id": "usr_123abc",
    "name": "John Doe",
    "email": "[REDACTED_SECRET]"
  }
}
```

### Verifying Webhooks

[Explain how to verify webhook authenticity, e.g., signature verification]

---

## SDK Examples

### JavaScript/TypeScript

```javascript
// Install: npm install @example/api-client

import { APIClient } from '@example/api-client';

const client = new APIClient({
  [REDACTED_SECRET]'
});

// List resources
const users = await client.users.list({
  page: 1,
  limit: 10
});

// Get single resource
const user = await client.users.get('usr_123abc');

// Create resource
const newUser = await client.users.create({
  name: 'Alice Johnson',
  email: '[REDACTED_SECRET]'
});

// Update resource
const updatedUser = await client.users.update('usr_123abc', {
  role: 'admin'
});

// Delete resource
await client.users.delete('usr_123abc');
```

### Python

```python
# Install: pip install example-api-client

from example_api import APIClient

client = APIClient([REDACTED_SECRET]')

# List resources
users = client.users.list(page=1, limit=10)

# Get single resource
user = client.users.get('usr_123abc')

# Create resource
new_user = client.users.create(
    name='Alice Johnson',
    email='[REDACTED_SECRET]'
)

# Update resource
updated_user = client.users.update(
    'usr_123abc',
    role='admin'
)

# Delete resource
client.users.delete('usr_123abc')
```

---

## Best Practices

### Pagination

Always paginate list endpoints to avoid performance issues:
- Use `limit` parameter to control page size
- Don't request more than 100 items per page
- Use `page` parameter for subsequent pages

### Error Handling

Implement proper error handling:
```javascript
try {
  const user = await client.users.get('usr_123abc');
} catch (error) {
  if (error.code === 'NOT_FOUND') {
    console.log('User not found');
  } else if (error.code === 'UNAUTHORIZED') {
    console.log('Authentication failed');
  } else {
    console.log('Unexpected error:', error.message);
  }
}
```

### Rate Limiting

Monitor rate limit headers and implement backoff:
```javascript
const response = await fetch(url, options);
const remaining = response.headers.get('X-RateLimit-Remaining');

if (remaining < 10) {
  console.warn('Approaching rate limit');
}
```

---

## Support

**Questions or issues?**
- Documentation: [link]
- Support email: [email]
- Community forum: [link]
- Issue tracker: [link]

**API Status:**
- Status page: [link]
- Uptime: [link]


path: templates/ARCHITECTURE.template.md
content: # Architecture Overview

## What This Document Covers

This document explains the high-level architecture of [Project Name], including how different components interact, key design decisions, and where to make common changes.

**Target audience:** Developers who need to understand the system design before making significant changes.

## System Design

### High-Level Architecture

```
[Create a simple ASCII diagram or describe components]

┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   Frontend  │─────▶│   Backend   │─────▶│  Database   │
│  (React)    │◀─────│   (Node.js) │◀─────│ (Postgres)  │
└─────────────┘      └─────────────┘      └─────────────┘
       │                    │
       │                    ▼
       │             ┌─────────────┐
       └────────────▶│  API Layer  │
                     └─────────────┘
```

**Components:**

1. **Frontend** - [Explain what this component does and its responsibilities]
2. **Backend** - [Explain what this component does and its responsibilities]
3. **Database** - [Explain what data is stored and how it's organized]
4. **API Layer** - [Explain how components communicate]

### Technology Stack

| Layer | Technology | Why We Chose It |
|-------|-----------|-----------------|
| Frontend | [Technology] | [Reasoning for choice] |
| Backend | [Technology] | [Reasoning for choice] |
| Database | [Technology] | [Reasoning for choice] |
| Hosting | [Technology] | [Reasoning for choice] |

## Directory Structure

```
project-root/
├── src/
│   ├── components/          # Reusable UI components
│   │   ├── common/         # Shared components (buttons, inputs, etc.)
│   │   ├── features/       # Feature-specific components
│   │   └── layout/         # Layout components (header, footer, etc.)
│   │
│   ├── pages/              # Page-level components (one per route)
│   │   ├── Home/          # Home page and related components
│   │   ├── Dashboard/     # Dashboard page and related components
│   │   └── Settings/      # Settings page and related components
│   │
│   ├── services/           # Business logic and external integrations
│   │   ├── api.js         # API client configuration
│   │   ├── auth.js        # Authentication logic
│   │   └── [feature].js   # Feature-specific business logic
│   │
│   ├── store/              # State management (Redux/Context/etc.)
│   │   ├── slices/        # State slices by feature
│   │   └── store.js       # Store configuration
│   │
│   ├── utils/              # Helper functions and utilities
│   │   ├── validation.js  # Input validation helpers
│   │   ├── formatting.js  # Data formatting utilities
│   │   └── constants.js   # App-wide constants
│   │
│   ├── hooks/              # Custom React hooks
│   │   └── use[Feature].js # Feature-specific hooks
│   │
│   ├── types/              # TypeScript type definitions
│   │   ├── models.ts      # Data model types
│   │   └── api.ts         # API request/response types
│   │
│   └── index.js            # Application entry point
│
├── tests/                  # Test files (mirrors src/ structure)
├── public/                 # Static assets
├── config/                 # Configuration files
└── [build-output]/         # Build artifacts (gitignored)
```

### Directory Purpose and Rules

#### components/
**Purpose:** Reusable UI components that don't contain business logic.

**What goes here:**
- Presentational components (buttons, cards, modals)
- Layout components (headers, sidebars, containers)
- Feature-specific components used in multiple places

**What doesn't go here:**
- Business logic (put in `services/`)
- Page-level components (put in `pages/`)
- One-off components used in a single place (colocate with parent)

**When to add a file:** When you need a reusable component used in 2+ places.

#### services/
**Purpose:** Business logic, API calls, and external service integrations.

**What goes here:**
- API client functions
- Authentication and authorization logic
- Data transformation and validation
- Third-party service integrations

**What doesn't go here:**
- UI components (put in `components/`)
- State management (put in `store/`)
- Pure utility functions (put in `utils/`)

**When to add a file:** When you need to interact with external services or implement complex business logic.

#### utils/
**Purpose:** Pure utility functions with no side effects.

**What goes here:**
- Data formatting and parsing
- Validation helpers
- Constants and enumerations
- Date/time utilities

**What doesn't go here:**
- Functions that make API calls (put in `services/`)
- Functions that depend on React (make a custom hook in `hooks/`)
- Functions specific to one component (colocate with component)

**When to add a file:** When you have a pure function used in 3+ places.

## Data Flow

### [Feature Name] Flow

Explain how data flows through the system for a key feature:

```
User Action → Component → Service → API → Database
                ↓
            State Update
                ↓
            UI Re-render
```

**Step-by-step:**

1. **User triggers action** in `components/FeatureComponent.tsx`
   - User clicks button, submits form, etc.
   - Component calls `handleAction()` function

2. **Component dispatches action** to state management
   - Calls `dispatch(featureAction(data))`
   - State is updated optimistically

3. **Service layer processes request** in `services/feature.js`
   - Validates input data
   - Transforms data to API format
   - Makes HTTP request to backend

4. **Backend processes request** in `api/feature/route.js`
   - Validates authentication
   - Applies business logic
   - Updates database

5. **Response flows back** through the layers
   - Backend returns success/error
   - Service layer transforms response
   - State is updated with final result
   - Component re-renders with new data

### State Management

**Architecture:** [Describe state management approach - Redux, Context API, Zustand, etc.]

**State organization:**
```
Global State
├── auth          # User authentication state
├── user          # User profile data
├── [feature1]    # Feature-specific state
├── [feature2]    # Feature-specific state
└── ui            # UI state (modals, loading, etc.)
```

**Data flow rules:**
- Components read state via [hooks/selectors]
- Components update state via [dispatch/setState functions]
- Async operations handled in [middleware/thunks/services]

## Key Design Decisions

### Decision 1: [Architecture Choice]

**What we decided:** [Describe the decision made]

**Context:** [Explain the situation that required this decision]
- [Constraint or requirement 1]
- [Constraint or requirement 2]

**Why we decided this:**
- **Reason 1:** [Explain benefit]
- **Reason 2:** [Explain benefit]
- **Reason 3:** [Explain benefit]

**Trade-offs:**
- ✅ **Pros:** [What we gained]
- ❌ **Cons:** [What we sacrificed]
- 🤔 **When to reconsider:** [Conditions that might make this decision obsolete]

**Alternatives considered:**
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]

### Decision 2: [Technology Choice]

**What we decided:** [Describe the decision made]

**Context:** [Explain the situation that required this decision]

**Why we decided this:**
- [Reason 1]
- [Reason 2]

**Trade-offs:**
- ✅ **Pros:** [What we gained]
- ❌ **Cons:** [What we sacrificed]

**Alternatives considered:**
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]

## Module Dependencies

### Dependency Graph

```
pages/
  └─→ components/
        └─→ hooks/
              └─→ services/
                    └─→ utils/

store/
  └─→ services/
        └─→ utils/
```

**Dependency rules:**
1. **Lower layers can't depend on higher layers**
   - ❌ `services/` can't import from `components/`
   - ✅ `components/` can import from `services/`

2. **Same-level imports require careful consideration**
   - 🤔 Components importing other components: Usually OK
   - ⚠️ Services importing other services: Consider refactoring

3. **Avoid circular dependencies**
   - Use dependency injection or event systems when needed

### External Dependencies

| Package | Version | Used For | Notes |
|---------|---------|----------|-------|
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |

## Extension Points

### Adding a New Feature

To add a new feature to the codebase:

1. **Create feature structure:**
   ```
   src/
   ├── components/features/[FeatureName]/
   ├── services/[featureName].js
   └── store/slices/[featureName]Slice.js
   ```

2. **Implement components:**
   - Create UI components in `components/features/[FeatureName]/`
   - Follow existing component patterns
   - Use shared components from `components/common/`

3. **Add business logic:**
   - Create service file in `services/[featureName].js`
   - Implement API calls and data transformations
   - Follow existing error handling patterns

4. **Set up state management:**
   - Create slice in `store/slices/[featureName]Slice.js`
   - Define actions and reducers
   - Export selectors for components

5. **Add routes (if applicable):**
   - Register new routes in `routes.js`
   - Create page component in `pages/[FeatureName]/`

6. **Add tests:**
   - Mirror structure in `tests/`
   - Test components, services, and state

### Common Modification Points

**Adding a new API endpoint:**
- Backend: Create route in `api/[feature]/route.js`
- Frontend: Add service function in `services/[feature].js`
- Update types in `types/api.ts`

**Adding a new database table:**
- Create migration in `migrations/`
- Add model in `models/[tableName].js`
- Update seed data if applicable

**Adding a new component library:**
- Install package: `npm install [package]`
- Create wrapper in `components/common/[ComponentName]/`
- Configure theme/styling in `config/theme.js`

## Performance Considerations

### Critical Performance Paths

1. **[Path 1: e.g., Initial page load]**
   - Current performance: [metrics]
   - Bottlenecks: [known issues]
   - Optimization strategy: [approach]

2. **[Path 2: e.g., Search functionality]**
   - Current performance: [metrics]
   - Bottlenecks: [known issues]
   - Optimization strategy: [approach]

### Caching Strategy

**What we cache:**
- [Data type 1]: Cached in [location] for [duration]
- [Data type 2]: Cached in [location] for [duration]

**Cache invalidation:**
- [Trigger 1]: Clears [cache type]
- [Trigger 2]: Clears [cache type]

## Security Architecture

### Authentication Flow

[Describe how users authenticate]

1. User submits credentials
2. Backend validates and issues [JWT/session/etc.]
3. Token stored in [location]
4. Subsequent requests include token

### Authorization

**Permission levels:**
- [Role 1]: Can [actions]
- [Role 2]: Can [actions]
- [Role 3]: Can [actions]

**Implementation:**
- Frontend: Check permissions in [location]
- Backend: Enforce permissions in [location]

### Data Security

- Sensitive data encrypted at rest: [Yes/No - how]
- API communications: [HTTPS/TLS version]
- Input validation: [Where and how]
- XSS protection: [Strategy]
- CSRF protection: [Strategy]

## Deployment Architecture

### Environments

| Environment | URL | Purpose | Auto-deploys |
|------------|-----|---------|--------------|
| Development | [url] | Local development | No |
| Staging | [url] | Testing before production | Yes (main branch) |
| Production | [url] | Live application | Yes (release tags) |

### Build Process

```bash
# Development build
[build-command-dev]

# Production build
[build-command-prod]
```

**Build artifacts:**
- Output location: [path]
- Artifacts: [list of generated files]

### Deployment Steps

1. [Step 1]
2. [Step 2]
3. [Step 3]

## Monitoring and Observability

### Logging

**Log levels:**
- ERROR: [What gets logged]
- WARN: [What gets logged]
- INFO: [What gets logged]

**Log destinations:**
- Development: [Console/file]
- Production: [Service name/location]

### Metrics

**Key metrics tracked:**
- [Metric 1]: [What it measures]
- [Metric 2]: [What it measures]

**Monitoring tools:**
- [Tool name]: [What we monitor with it]

## Troubleshooting

### Common Architecture Issues

**Issue: [Common problem]**
- **Symptoms:** [How to recognize it]
- **Cause:** [Why it happens]
- **Solution:** [How to fix it]

## Additional Resources

- [Link to API documentation]
- [Link to database schema]
- [Link to deployment guide]
- [Link to contributing guidelines]

## Questions and Feedback

If you have questions about the architecture or suggestions for improvements:
- [Contact method]
- [Issue tracker link]


path: templates/CODE_COMMENTS.template.md
content: # Code Comments Guide

This document provides examples and patterns for writing effective inline documentation that helps new developers understand code quickly.

## Core Principles

1. **Explain "Why" not "What"** - The code shows what it does; comments should explain why it exists
2. **Provide Context** - Help readers understand the bigger picture
3. **Document Edge Cases** - Explain non-obvious behavior and special handling
4. **Include Examples** - Show how to use complex functions
5. **Keep Comments Current** - Update comments when code changes

## Function/Method Documentation

### JavaScript/TypeScript (JSDoc)

```javascript
/**
 * Calculates the prorated subscription cost for a partial billing period.
 *
 * Why this exists: Users can subscribe mid-month, so we need to charge
 * them only for the days remaining in the current billing cycle.
 *
 * @param {number} fullPrice - The normal monthly subscription price
 * @param {Date} startDate - When the user's subscription begins
 * @param {Date} periodEnd - End of the current billing period
 * @returns {number} The prorated amount to charge
 *
 * @example
 * // User subscribes on Jan 15, period ends Jan 31
 * calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
 * // Returns: 16.13 (17 days out of 31 days * $30)
 *
 * @throws {Error} If startDate is after periodEnd
 */
function calculateProratedCost(fullPrice, startDate, periodEnd) {
  if (startDate > periodEnd) {
    throw new Error('Start date must be before period end');
  }

  const daysInPeriod = (periodEnd - startDate) / (1000 * 60 * 60 * 24);
  const daysInMonth = new Date(periodEnd.getYear(), periodEnd.getMonth() + 1, 0).getDate();

  return (fullPrice / daysInMonth) * daysInPeriod;
}
```

### Python (Docstring)

```python
def calculate_prorated_cost(full_price: float, start_date: datetime, period_end: datetime) -> float:
    """
    Calculates the prorated subscription cost for a partial billing period.

    Why this exists: Users can subscribe mid-month, so we need to charge
    them only for the days remaining in the current billing cycle.

    Args:
        full_price: The normal monthly subscription price
        start_date: When the user's subscription begins
        period_end: End of the current billing period

    Returns:
        The prorated amount to charge

    Raises:
        ValueError: If start_date is after period_end

    Example:
        >>> # User subscribes on Jan 15, period ends Jan 31
        >>> calculate_prorated_cost(30, date(2024, 1, 15), date(2024, 1, 31))
        16.13  # 17 days out of 31 days * $30
    """
    if start_date > period_end:
        raise ValueError('Start date must be before period end')

    days_in_period = (period_end - start_date).days
    days_in_month = monthrange(period_end.year, period_end.month)[1]

    return (full_price / days_in_month) * days_in_period
```

### Java (JavaDoc)

```java
/**
 * Calculates the prorated subscription cost for a partial billing period.
 *
 * <p>Why this exists: Users can subscribe mid-month, so we need to charge
 * them only for the days remaining in the current billing cycle.</p>
 *
 * @param fullPrice The normal monthly subscription price
 * @param startDate When the user's subscription begins
 * @param periodEnd End of the current billing period
 * @return The prorated amount to charge
 * @throws IllegalArgumentException if startDate is after periodEnd
 *
 * <p>Example:
 * <pre>
 * // User subscribes on Jan 15, period ends Jan 31
 * double cost = calculateProratedCost(30.0,
 *     LocalDate.of(2024, 1, 15),
 *     LocalDate.of(2024, 1, 31));
 * // Returns: 16.13 (17 days out of 31 days * $30)
 * </pre>
 */
public double calculateProratedCost(double fullPrice, LocalDate startDate, LocalDate periodEnd) {
    if (startDate.isAfter(periodEnd)) {
        throw new IllegalArgumentException("Start date must be before period end");
    }

    long daysInPeriod = ChronoUnit.DAYS.between(startDate, periodEnd);
    int daysInMonth = periodEnd.lengthOfMonth();

    return (fullPrice / daysInMonth) * daysInPeriod;
}
```

## Complex Logic Documentation

### Documenting Business Rules

```javascript
// Why we check status in this specific order:
// 1. "cancelled" takes precedence because users might cancel during trial
// 2. "trial" is checked next so we can show trial-specific messaging
// 3. "active" is the default state for paying customers
// This ordering prevents edge cases like showing "active" status to
// cancelled trial users.

if (subscription.status === 'cancelled') {
  return <CancelledMessage />;
} else if (subscription.status === 'trial') {
  return <TrialMessage daysRemaining={subscription.trialDaysLeft} />;
} else if (subscription.status === 'active') {
  return <ActiveMessage />;
}
```

### Documenting Edge Cases

```python
# Why this check exists: The API returns None for deleted users,
# but empty string for users who never set a name. We need to
# distinguish between these cases for the audit log.
if user_name is None:
    # User was deleted - log this as a security event
    log_deletion_event(user_id, timestamp=datetime.now())
elif user_name == "":
    # User never completed onboarding - safe to skip
    continue
else:
    # Normal case - process the user
    process_user(user_id, user_name)
```

### Documenting Performance Considerations

```javascript
// Performance note: We use a Set here instead of an Array because
// we frequently check if user IDs exist (O(1) lookup vs O(n)).
// With 10,000+ users, this saves ~500ms per request.
const activeUserIds = new Set(users.map(u => u.id));

// Avoid: const activeUserIds = users.map(u => u.id); // O(n) lookups
if (activeUserIds.has(currentUserId)) {
  // User is active
}
```

### Documenting Workarounds and Gotchas

```python
# GOTCHA: The third-party API returns timestamps in Unix milliseconds,
# but Python's datetime expects seconds. We must divide by 1000.
# Bug reported upstream: https://github.com/vendor/lib/issues/123
timestamp = datetime.fromtimestamp(api_response['created_at'] / 1000)
```

```javascript
// WORKAROUND: Safari doesn't support lookbehind regex, so we use
// a more verbose approach here. Can simplify once we drop Safari 15 support.
// TODO: Replace with lookbehind regex when Safari 15+ usage drops below 1%
// Original regex: /(?<=@)\w+/g
const mentions = text.split('@').slice(1).map(part => part.split(/\s/)[0]);
```

## Class Documentation

### TypeScript Class

```typescript
/**
 * Manages user authentication state and provides methods for login/logout.
 *
 * Why this exists: We need centralized auth state management that works
 * across multiple components and persists across page refreshes.
 *
 * Usage:
 * ```typescript
 * const auth = new AuthManager();
 *
 * // Log in user
 * await auth.login('[REDACTED_SECRET]', 'password');
 *
 * // Check if user is authenticated
 * if (auth.isAuthenticated()) {
 *   // Show authenticated content
 * }
 *
 * // Get current user
 * const user = auth.getCurrentUser();
 * ```
 */
class AuthManager {
  private [REDACTED_SECRET] | null = null;
  private user: User | null = null;

  /**
   * Authenticates a user with email and password.
   *
   * Why async: Makes API call to backend for authentication.
   * Side effects: Stores token in localStorage and updates internal state.
   *
   * @throws {AuthenticationError} If credentials are invalid
   */
  async login(email: string, [REDACTED_SECRET]): Promise<User> {
    // Implementation
  }

  /**
   * Checks if a user is currently authenticated.
   *
   * Note: Performs local check only; doesn't verify token with backend.
   * Use refreshToken() if you need to verify token is still valid.
   */
  isAuthenticated(): boolean {
    return this.token !== null && !this.isTokenExpired();
  }

  /**
   * Checks if the current token has expired.
   *
   * Implementation note: Tokens expire 24 hours after issue.
   * We check 5 minutes before actual expiry to avoid edge cases.
   */
  private isTokenExpired(): boolean {
    // Implementation
  }
}
```

## Algorithm Documentation

### Complex Algorithm

```python
def find_shortest_path(graph, start, end):
    """
    Finds the shortest path between two nodes using Dijkstra's algorithm.

    Why we chose Dijkstra: We have a weighted graph with non-negative weights.
    If we had negative weights, we'd need Bellman-Ford instead.

    Time Complexity: O((V + E) log V) where V = vertices, E = edges
    Space Complexity: O(V) for storing distances and visited nodes

    Algorithm overview:
    1. Initialize distances to all nodes as infinity, except start (0)
    2. Use priority queue to always process closest unvisited node
    3. For each neighbor, check if we found a shorter path
    4. Continue until we reach the end node or exhaust all paths

    Args:
        graph: Adjacency list representation {node: [(neighbor, weight), ...]}
        start: Starting node
        end: Destination node

    Returns:
        List of nodes representing shortest path, or None if no path exists

    Example:
        >>> graph = {
        ...     'A': [('B', 4), ('C', 2)],
        ...     'B': [('D', 3)],
        ...     'C': [('B', 1), ('D', 5)],
        ...     'D': []
        ... }
        >>> find_shortest_path(graph, 'A', 'D')
        ['A', 'C', 'B', 'D']  # Cost: 6 (A->C: 2, C->B: 1, B->D: 3)
    """
    # Priority queue: [(distance, node, path)]
    # We store the full path to reconstruct it at the end
    queue = [(0, start, [start])]
    visited = set()

    while queue:
        # Pop node with smallest distance (priority queue property)
        distance, node, path = heapq.heappop(queue)

        # Skip if we've already processed this node
        # Important: Prevents infinite loops in cyclic graphs
        if node in visited:
            continue

        visited.add(node)

        # Success case: we reached the destination
        if node == end:
            return path

        # Explore neighbors
        for neighbor, weight in graph.get(node, []):
            if neighbor not in visited:
                # Calculate distance to neighbor through current path
                new_distance = distance + weight
                new_path = path + [neighbor]
                heapq.heappush(queue, (new_distance, neighbor, new_path))

    # No path exists between start and end
    return None
```

## API Integration Documentation

```javascript
/**
 * Fetches user data from the legacy API with proper error handling.
 *
 * API Quirks to be aware of:
 * 1. Returns 200 with error object instead of proper status codes
 * 2. Rate limit is 100 req/min but not documented in headers
 * 3. User IDs are strings, not numbers (despite API docs saying otherwise)
 * 4. Deleted users return {deleted: true} instead of 404
 *
 * Related Jira tickets:
 * - API-123: Rate limit enhancement request
 * - API-456: Proper status codes migration (planned for Q2)
 *
 * @param {string} userId - User ID as string (e.g., "usr_123abc")
 * @returns {Promise<User|null>} User object or null if deleted
 * @throws {APIError} If API is unavailable or rate limited
 */
async function fetchUserFromLegacyAPI(userId) {
  try {
    const response = await fetch(`https://legacy-api.example.com/users/${userId}`);

    // Check for pseudo-error responses (API returns 200 with error object)
    if (response.ok) {
      const data = await response.json();

      // Check for API's custom error format
      if (data.error) {
        throw new APIError(data.error.message, data.error.code);
      }

      // Check for deleted user (API quirk #4)
      if (data.deleted === true) {
        return null;
      }

      return data;
    }

    throw new APIError(`API returned ${response.status}`, response.status);
  } catch (error) {
    // Add context to help with debugging
    throw new APIError(`Failed to fetch user ${userId}: ${error.message}`);
  }
}
```

## Configuration Documentation

```typescript
// Database connection configuration
//
// Pool size tuning: After load testing, we found:
// - 10 connections: good for < 100 concurrent users
// - 20 connections: good for 100-500 concurrent users
// - 50 connections: good for 500-2000 concurrent users
// - Beyond 2000: consider read replicas
//
// Current setting (20) is sized for our typical load of ~300 concurrent users
// Last updated: 2024-01-15 after Q4 traffic analysis
const dbConfig = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME,

  // Connection pooling
  max: 20,  // Maximum number of connections in pool
  min: 5,   // Minimum number of connections (always maintained)

  // Timeout settings
  // - connectionTimeoutMillis: How long to wait for a connection from pool
  // - idleTimeoutMillis: How long a connection can sit idle before being closed
  // - query_timeout: PostgreSQL-specific timeout for long-running queries
  connectionTimeoutMillis: 5000,   // Fail fast if pool is exhausted
  idleTimeoutMillis: 30000,        // Close idle connections after 30s
  query_timeout: 60000,            // Kill queries running longer than 60s
};
```

## TODO Comments

Use TODO comments effectively:

```javascript
// TODO(username, 2024-01-15): Implement caching for this endpoint
// Why: API call takes 500ms, users report slowness
// Impact: High - affects all list views
// Complexity: Medium - need to handle cache invalidation
// Ticket: PERF-123
async function getUserList() {
  return await api.get('/users');
}

// TODO(username): Refactor to use new auth system
// Blocked by: AUTH-456 (auth system migration)
// Can remove after: All clients migrate to v2 API
function legacyAuthCheck(token) {
  // Old auth logic
}

// FIXME(username): This breaks when month has 31 days
// Bug report: BUG-789
// Workaround: Validate date before passing to this function
function calculateEndDate(startDay, daysToAdd) {
  return startDay + daysToAdd; // Simplified example
}

// HACK(username): Temporary workaround for Safari bug
// Remove when: Safari 16 usage drops below 5%
// Tracking: https://bugs.webkit.org/show_bug.cgi?id=12345
if (isSafari()) {
  // Workaround code
}
```

## When NOT to Write Comments

### Don't Explain Obvious Code

```javascript
// ❌ BAD: Comment explains what code obviously does
// Increment counter by 1
counter++;

// ✅ GOOD: No comment needed, code is self-explanatory
counter++;
```

### Don't Describe Implementation That's Clear

```javascript
// ❌ BAD: Describes obvious loop logic
// Loop through all users and find the one with matching ID
const user = users.find(u => u.id === userId);

// ✅ GOOD: No comment needed, code is clear
const user = users.find(u => u.id === userId);
```

### Don't Leave Commented-Out Code

```javascript
// ❌ BAD: Leaving old code as comments
function calculateTotal(items) {
  // return items.reduce((sum, item) => sum + item.price, 0);
  // return items.map(i => i.price).reduce((a, b) => a + b);
  return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}

// ✅ GOOD: Delete old code, use version control instead
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
```

## Summary

**Good comments:**
- Explain WHY, not WHAT
- Provide context and business logic
- Document edge cases and gotchas
- Include examples for complex functions
- Note performance considerations
- Explain workarounds with links to issues

**Avoid:**
- Describing obvious code
- Leaving commented-out code
- Outdated information
- Redundant descriptions
- Comments that duplicate code


path: templates/README.template.md
content: # [Project Name]

## What This Does

[Write 1-2 sentences explaining what this project does in plain English. Focus on the value it provides, not the technical implementation.]

Example: "This is a task management application that helps teams track project progress and collaborate on deliverables. It provides real-time updates and integrates with popular project management tools."

## Quick Start

Get up and running in under 5 minutes:

### Prerequisites

- [List required software/tools with versions]
- Example: Node.js 18+ or Python 3.9+
- Example: PostgreSQL 14+
- Example: API keys from [Service Name]

### Installation

```bash
# Clone the repository
git clone [repository-url]
cd [project-name]

# Install dependencies
[package-manager] install

# Set up environment variables
cp .env.example .env
# Edit .env with your configuration

# Run database migrations (if applicable)
[migration-command]

# Start the development server
[start-command]
```

### Verify It's Working

[Provide a quick way to verify the installation succeeded]
- Example: "Open http://localhost:3000 in your browser"
- Example: "Run `npm test` to verify all tests pass"
- Example: "You should see [specific output/page]"

## Project Structure

```
project-root/
├── src/                    # Source code
│   ├── components/        # [Explain what goes here]
│   ├── services/          # [Explain what goes here]
│   ├── utils/             # [Explain what goes here]
│   └── index.js           # [Explain what this file does]
├── tests/                 # Test files
├── public/                # Static assets
├── config/                # Configuration files
├── .env.example           # Environment variable template
├── package.json           # Dependencies and scripts
└── README.md              # This file
```

### Key Directories Explained

**src/components/** - [Detailed explanation of what goes in this directory and when to add files here]

**src/services/** - [Detailed explanation of what goes in this directory and when to add files here]

**src/utils/** - [Detailed explanation of what goes in this directory and when to add files here]

## Key Concepts

### [Concept 1 - Core Abstraction]

[Explain a key concept that users need to understand to work with this codebase]

**Why this matters:** [Explain why understanding this concept is important]

**Example:**
```javascript
// Show a concrete code example demonstrating this concept
```

### [Concept 2 - Important Pattern]

[Explain another important concept]

**Why this matters:** [Explain why understanding this concept is important]

**Example:**
```javascript
// Show a concrete code example demonstrating this concept
```

## Common Tasks

### [Task 1: Common Operation]

[Step-by-step guide for a task users will frequently perform]

1. First step with command: `command-here`
2. Second step with explanation
3. Third step with expected outcome

**Expected result:** [What should happen when this task succeeds]

### [Task 2: Another Common Operation]

[Step-by-step guide for another frequent task]

1. First step with command: `command-here`
2. Second step with explanation
3. Third step with expected outcome

**Expected result:** [What should happen when this task succeeds]

### [Task 3: Development Workflow]

[Explain the typical development workflow]

1. Create a new branch: `git checkout -b feature/your-feature`
2. Make your changes
3. Run tests: `[test-command]`
4. Commit your changes: `git commit -m "Description"`
5. Push and create pull request

## Configuration

### Environment Variables

| Variable | Description | Example | Required |
|----------|-------------|---------|----------|
| `VAR_NAME` | [What this variable controls] | `example-value` | Yes |
| `API_KEY` | [What this variable controls] | `sk_test_123abc` | Yes |
| `DEBUG` | [What this variable controls] | `true` | No |

### Configuration Files

**config/[file-name].js** - [Explain what this config file controls and when to modify it]

## Development

### Running Tests

```bash
# Run all tests
[test-command]

# Run specific test file
[specific-test-command]

# Run with coverage
[coverage-command]
```

### Code Style

[Explain code style conventions]
- [Convention 1]
- [Convention 2]
- Run linter: `[lint-command]`
- Format code: `[format-command]`

### Debugging

[Provide tips for debugging]

**Common debugging commands:**
```bash
# Command to enable debug mode
DEBUG=* [start-command]

# Command to see detailed logs
[log-command]
```

## Troubleshooting

### [Common Issue 1]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]
```bash
# Commands to fix the issue
```

### [Common Issue 2]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]
```bash
# Commands to fix the issue
```

### [Common Issue 3]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]

## Additional Documentation

- [ARCHITECTURE.md](./ARCHITECTURE.md) - Detailed system architecture
- [API.md](./API.md) - API endpoint documentation
- [CONTRIBUTING.md](./CONTRIBUTING.md) - Contribution guidelines
- [Link to external docs if applicable]

## Getting Help

- Check existing issues: [link to issues]
- Join our community: [link to Discord/Slack/forum]
- Contact: [email or contact method]

## License

[License information]


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)