# @akson/cortex-doc-standards

Documentation standards and tooling for Cortex repositories. Provides CLAUDE.md generation, documentation rules, and MCP server integration for Claude AI workflows.

## Features

- 📝 **CLAUDE.md Generation** - Generate optimized CLAUDE.md files from rules
- 🔧 **Rules Management** - Initialize and manage documentation rules
- 🔌 **MCP Server** - Model Context Protocol server for Claude AI integration
- 🎯 **Standards Enforcement** - Documentation quality and naming conventions
- 🚀 **CLI Tools** - Simple command-line interface for common tasks

## Installation

```bash
npm install @akson/cortex-doc-standards
```

## Quick Start

```bash
# Initialize rules in your project
npx cortex-doc-standards rules init

# Generate CLAUDE.md from rules
npx cortex-doc-standards generate

# Start MCP server for Claude AI
npx cortex-doc-standards-mcp
```

## 📋 Configuration Examples

Ready-to-use configuration examples for different project types:

```bash
# Copy a project-specific example
cp node_modules/@akson/cortex-doc-standards/examples/nextjs-config.json ./doc-standards.config.json
cp node_modules/@akson/cortex-doc-standards/examples/monorepo-config.json ./doc-standards.config.json
cp node_modules/@akson/cortex-doc-standards/examples/flutter-config.json ./doc-standards.config.json
cp node_modules/@akson/cortex-doc-standards/examples/backend-config.json ./doc-standards.config.json
cp node_modules/@akson/cortex-doc-standards/examples/makerkit-monorepo-config.json ./doc-standards.config.json
cp node_modules/@akson/cortex-doc-standards/examples/makerkit-flutter-config.json ./doc-standards.config.json

# Or start with the comprehensive base example
cp node_modules/@akson/cortex-doc-standards/examples/base-config.json ./doc-standards.config.json
```

**Available Examples:**
- **[base-config.json](./examples/base-config.json)** - Comprehensive configuration with all rules
- **[nextjs-config.json](./examples/nextjs-config.json)** - Next.js application with TypeScript & Prisma
- **[monorepo-config.json](./examples/monorepo-config.json)** - Turbo monorepo with shared packages
- **[flutter-config.json](./examples/flutter-config.json)** - Cross-platform Flutter mobile app
- **[backend-config.json](./examples/backend-config.json)** - Node.js API server with database
- **[makerkit-monorepo-config.json](./examples/makerkit-monorepo-config.json)** - MakerKit SaaS framework with Turborepo
- **[makerkit-flutter-config.json](./examples/makerkit-flutter-config.json)** - MakerKit web + Flutter mobile cross-platform

See [examples/README.md](./examples/README.md) for detailed configuration guide.

## CLI Commands

### CLAUDE.md Generation (Recommended Workflow)

```bash
# 1. Initialize rules configuration (auto-detects project type)
npx cortex-doc-standards rules init

# 2. Edit .cortex-doc-standards/rules.json to customize your rules

# 3. Generate CLAUDE.md from your rules
npx cortex-doc-standards generate
```

### Available Built-in Rules

The package includes 6 optimized built-in rules that cover all aspects of AI-assisted development:

| Rule ID | Purpose | Description |
|---------|---------|-------------|
| `claude-essentials` | Core AI Behavior | Consolidated Claude communication, tool usage, and workflow fundamentals |
| `code-standards` | Quality & Naming | File naming conventions, quality gates, and version suffix prohibition |
| `security-standards` | Security & Testing | Security practices, secrets management, and testing requirements |
| `testing-standards` | Test Organization | Comprehensive testing standards and commands (merged with security) |
| `project-workflow` | Project Integration | GitHub issue tracking and shared package management |
| `makerkit-complete` | MakerKit Framework | Complete MakerKit development patterns and best practices |

### Rule Configuration Variables

Each rule supports customization through variables. Here are the key variables for each rule:

#### `claude-essentials`
```json
{
  "package.file": "package.json",           // Package config file
  "translation.function": "t",              // i18n function name
  "lint.command": "pnpm lint",             // Linting command
  "typecheck.command": "pnpm typecheck",   // Type checking command
  "test.command": "pnpm test"              // Test command
}
```

#### `security-standards`
```json
{
  "secrets.manager": "1Password",          // Secrets management system
  "auth.method": "Supabase Auth",          // Authentication method
  "security.scanCommand": "pnpm audit"    // Security scan command
}
```

#### `testing-standards`
```json
{
  "coverage.unit": "80",                   // Minimum unit test coverage
  "test.unit": "pnpm test",               // Unit test command
  "test.integration": "pnpm run test:integration",
  "test.e2e": "pnpm run test:e2e",
  "test.watch": "pnpm run test:watch",
  "test.coverage": "pnpm run test:coverage",
  "test.directory": "__tests__",          // Test directory
  "test.extension": "ts"                  // Test file extension
}
```

#### `project-workflow`
```json
{
  "packages.namespace": "@akson",         // Package namespace
  "package.manager": "pnpm"              // Package manager
}
```

#### `makerkit-complete` (MakerKit Projects)
```json
{
  "dev.command": "pnpm dev",              // Development start command
  "dev.filter": "pnpm --filter web dev", // Filtered dev command
  "build.command": "pnpm build",         // Build command
  "db.start": "pnpm supabase:web:start", // Database start
  "db.reset": "pnpm supabase:web:reset", // Database reset
  "db.typegen": "pnpm supabase:web:typegen", // Type generation
  "package.build": "pnpm --filter @kit/ui build",
  "package.add": "pnpm --filter web add lodash",
  "package.manager": "pnpm",
  "package.filter": "pnpm --filter"
}
```

## Configuration Best Practices

### Project Type Detection

The CLI automatically detects your project type based on:
- **Next.js**: Presence of `next` dependency
- **Monorepo**: `turbo` dependency or `workspaces` in package.json
- **Flutter**: `pubspec.yaml` file
- **Backend**: `express`, `fastify`, or `koa` dependencies

### Customizing Rules for Your Project

#### Essential Rules (Always Include)
```json
{
  "rules": [
    { "id": "claude-essentials", "enabled": true },
    { "id": "code-standards", "enabled": true },
    { "id": "security-standards", "enabled": true }
  ]
}
```

#### For MakerKit Projects
```json
{
  "rules": [
    // ... essential rules
    { "id": "makerkit-complete", "enabled": true }
  ]
}
```

#### For Projects with Shared Packages
```json
{
  "rules": [
    // ... essential rules
    {
      "id": "project-workflow",
      "enabled": true,
      "variables": {
        "packages.namespace": "@your-org",
        "package.manager": "pnpm"
      }
    }
  ]
}
```

### Migration from Older Versions

If you have an existing CLAUDE.md generated with older rules:

1. **Backup your current CLAUDE.md**: `cp CLAUDE.md CLAUDE.md.backup`
2. **Initialize new rules**: `npx cortex-doc-standards rules init`
3. **Customize the configuration**: Edit `.cortex-doc-standards/rules.json`
4. **Regenerate**: `npx cortex-doc-standards generate`
5. **Compare and merge**: Review any custom content from your backup

## Troubleshooting

### Common Issues

#### "No rules configuration found"
```bash
# Solution: Initialize rules first
npx cortex-doc-standards rules init
```

#### "Invalid configuration" errors
- **Check JSON syntax**: Ensure valid JSON in `.cortex-doc-standards/rules.json`
- **Verify rule IDs**: Use only built-in rule IDs listed above
- **Check variable format**: Ensure all variables are strings

#### "Unknown rule ID" warnings
- **Update package**: `npm install @akson/cortex-doc-standards@latest`
- **Check spelling**: Verify rule ID matches exactly (case-sensitive)

#### Variables not being replaced
- **Check braces**: Variables must use `{variable.name}` format
- **Verify placement**: Variables only work within rule templates
- **Check scope**: Ensure variable is defined for the specific rule

### Setup & Configuration

```bash
cortex-doc-standards init --type <nextjs|flutter|backend|shopify|monorepo>
cortex-doc-standards config                    # Show current config
cortex-doc-standards health --verbose          # System health check
```

### Validation & Quality

```bash
cortex-doc-standards validate                  # Validate all docs
cortex-doc-standards validate --file README.md # Single file
cortex-doc-standards validate --fix            # Auto-fix issues
cortex-doc-standards claude-check              # Claude AI standards check
cortex-doc-standards github-check              # GitHub Projects integration check
```

### Templates & Generation

```bash
cortex-doc-standards templates                 # List available templates
cortex-doc-standards generate claude --project-name MyProject --output CLAUDE.md
cortex-doc-standards generate <template> --project-type nextjs
```

### Reports & Analysis

```bash
cortex-doc-standards report --format table     # Human-readable report
cortex-doc-standards report --format json      # Machine-readable JSON
cortex-doc-standards naming --dry-run          # Preview naming fixes
cortex-doc-standards naming --fix              # Apply naming conventions
```

## Project Integration

### 1. Initialize Documentation Standards

```bash
cd your-project/
cortex-doc-standards init --type nextjs
# Creates cortex-docs.config.json with project-specific rules
```

### 2. Configure Rules (cortex-docs.config.json)

```json
{
  "name": "my-project",
  "type": "nextjs",
  "docsPath": "docs/",
  "claudePath": "CLAUDE.md",
  "rules": {
    "maxLines": 100,
    "minCodeBlockPercentage": 30,
    "requiredSections": ["Usage"],
    "blockedPatterns": [
      "This document provides",
      "Historical context",
      "Phase 1, Phase 2"
    ],
    "claudeEmojis": {
      "required": true,
      "validEmojis": ["🟣", "🟠"]
    },
    "enforcementLevel": "error"
  }
}
```

### 3. Add to CI/CD Pipeline

```yaml
# .github/workflows/docs-quality.yml
name: Documentation Quality
on: [push, pull_request]
jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npx @akson/cortex-doc-standards validate
      - run: npx @akson/cortex-doc-standards naming --dry-run
```

### 4. Pre-commit Hook

```json
// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "cortex-doc-standards validate --fix"
    }
  }
}
```

## Programmatic Usage

```typescript
import { ConsolidatedCLI } from "@akson/cortex-doc-standards/cli";

// Use CLI programmatically
const cli = new ConsolidatedCLI();
await cli.run();
```

### Available Exports

```typescript
// Main package
import { ConsolidatedCLI } from "@akson/cortex-doc-standards";

// CLI module
import { ConsolidatedCLI } from "@akson/cortex-doc-standards/cli";

// MCP server
import { DocStandardsMCPServer } from "@akson/cortex-doc-standards/mcp";

// Core validator
import { DocumentationValidator } from "@akson/cortex-doc-standards/core";

// Standards
import { GITHUB_PROJECTS_STANDARDS } from "@akson/cortex-doc-standards/standards";
```

## Unified Rules Migration

The unified rules system eliminates fragmented rule definitions and provides a single source of truth for all documentation standards.

### Key Changes

- **One rule type** – import `UnifiedRule` instead of legacy variants.
- **One validator** – use `UnifiedDocumentationValidator` or the `createValidator()` factory.
- **Shared defaults** – consume `DEFAULT_UNIFIED_RULES` for baseline configuration.
- **Centralized blocked patterns** – extend `BASE_BLOCKED_PATTERNS` rather than maintaining ad-hoc arrays.

```typescript
import {
  UnifiedDocumentationValidator,
  UnifiedRule,
  createValidator,
  DEFAULT_UNIFIED_RULES,
  BASE_BLOCKED_PATTERNS,
} from '@akson/cortex-doc-standards';

const validator = createValidator('nextjs', {
  maxLines: 150,
  requiredSections: ['Custom Section'],
});
```

### Migration Checklist

1. **Update imports** across projects to the unified exports shown above.
2. **Replace old types** (`ValidationRule`, `DocumentationRules`, etc.) with `UnifiedRule`.
3. **Instantiate validators** via `UnifiedDocumentationValidator` or `createValidator()`.
4. **Consolidate configuration** using helpers such as `mergeRules` and `getProjectRules`.
5. **Adopt common blocked patterns** from `BASE_BLOCKED_PATTERNS` and extend only when necessary.

```typescript
import { getProjectRules, mergeRules } from '@akson/cortex-doc-standards';

const baseRules = getProjectRules('monorepo');
const rules: UnifiedRule = mergeRules({
  maxLines: 180,
  requiredSections: ['Usage'],
}, baseRules);

const validator = new UnifiedDocumentationValidator(rules);
```

## Rules System Reference

### Quick Start

```bash
# Initialize rules configuration
npx @akson/cortex-doc-standards rules init --name "MyProject" --type nextjs

# Generate CLAUDE.md (standalone generator works without a build step)
npx @akson/cortex-doc-standards generate-claude generate --dry-run

# Validate configuration
npx @akson/cortex-doc-standards rules validate
```

### Built-in Rule Catalog

| Rule ID                            | Description                                        | Key Variables                                                |
| ---------------------------------- | -------------------------------------------------- | ------------------------------------------------------------ |
| `claude-prompting-fundamentals`   | AI interaction and communication standards        | `translation.function`                                       |
| `claude-development-workflow`      | Structured development process with Claude AI      | `lint.command`, `test.command`, `mobile.platform`            |
| `shared-packages`                  | Governance for modifying Cortex shared packages   | `packages.namespace`, `packages.registry`                    |
| `github-projects`                  | GitHub Projects workflow standards                 | `project.owner`, `project.repo`                              |
| `security-standards`               | Security best practices & secret management       | `secrets.manager`, `auth.method`, `security.scanCommand`     |
| `testing-standards`                | Testing requirements and quality gates            | `coverage.unit`, `test.unit`, `test.e2e`, `test.integration` |
| `makerkit-framework-integration`   | **NEW** MakerKit SaaS framework guidance          | `mobile.platform`, `mobile.commands`, `makerkit.location`    |
| `makerkit-package-discovery`       | **NEW** Component discovery using MCP server      | Auto-configured                                               |
| `makerkit-development-workflow`    | **NEW** MakerKit-specific development patterns    | `ui.library`, `auth.system`, `state.library`                 |
| `makerkit-architecture-patterns`   | **NEW** Multi-tenant architecture guidance        | Auto-configured                                               |
| `makerkit-form-data-patterns`      | **NEW** Form handling with MakerKit components    | Auto-configured                                               |

Project templates automatically compose rule sets:

- **Next.js / Backend** – includes all core rules plus GitHub workflows.
- **Monorepo** – core rules + shared package governance.
- **Flutter / Mobile** – security + testing rules.
- **Package / Library** – minimal standards with publication guidance.
- **MakerKit SaaS** – complete framework integration with all MakerKit rules enabled.
- **Cross-Platform** – MakerKit web + Flutter mobile with shared backend patterns.

### Configuration Schema

```json
{
  "projectName": "MyProject",
  "projectType": "nextjs",
  "rules": [
    {
      "id": "shared-packages",
      "enabled": true,
      "variables": {
        "packages.namespace": "@akson",
        "packages.registry": "https://registry.npmjs.org"
      },
      "overrides": {
        "title": "Custom Title",
        "append": "Additional custom content"
      }
    }
  ],
  "globalVariables": {
    "project.name": "MyProject",
    "project.type": "nextjs"
  }
}
```

### CLI Reference

```bash
# Discover rules
npx @akson/cortex-doc-standards rules list

# Initialize with explicit output path
npx @akson/cortex-doc-standards rules init \
  --name "MyApp" \
  --type backend \
  --output ./docs/rules.json

# Generate CLAUDE.md from a custom config
npx @akson/cortex-doc-standards rules generate \
  --config ./docs/rules.json \
  --output ./CLAUDE.md

# Validate or augment an existing configuration
npx @akson/cortex-doc-standards rules add-rule --id security-standards --enabled
npx @akson/cortex-doc-standards rules validate --config ./docs/rules.json
```

### Advanced Usage

- **Custom variables** – supply project-specific data for templates.

  ```json
  {
    "rules": [
      {
        "id": "testing-standards",
        "variables": {
          "test.unit": "vitest",
          "test.e2e": "playwright test",
          "coverage.unit": "90"
        }
      }
    ]
  }
  ```

- **Rule overrides** – tailor headings, append custom notes, or disable sections while staying within the unified schema.
- **Factory helpers** – `createValidator(projectType, overrides)` merges defaults with overrides and resolves variables before validation.

```typescript
const validator = createValidator('package', {
  blockedPatterns: [...BASE_BLOCKED_PATTERNS, 'My legacy phrase'],
});

const results = await validator.validate('./docs');
```


## Documentation Standards

This package helps enforce consistent documentation standards across Cortex projects:

### Core Principles

- **Clarity** - Clear, concise documentation
- **Consistency** - Standardized formats and naming
- **Maintainability** - Rules-based generation and validation
- **AI Integration** - Claude AI workflow optimization

## MCP Server Integration

The package includes an MCP (Model Context Protocol) server for Claude AI integration:

### Starting the MCP Server

```bash
# Run the MCP server
npx cortex-doc-standards-mcp
```

### MCP Tools Available

The MCP server provides tools for:

- Documentation validation
- Rules management
- Template generation
- Standards enforcement

### Integration with Claude

Add the MCP server to your Claude configuration to access documentation tools directly in Claude conversations.

## Configuration

The package uses a simple JSON-based configuration system:

### Rules File Structure

```json
{
  "version": "1.0.0",
  "rules": [
    // Your documentation rules here
  ],
  "templates": {
    // Template configurations
  }
}
```

### TypeScript Types

```typescript
interface RulesConfig {
  version: string;
  rules: DocumentationRule[];
  templates: Record<string, TemplateConfig>;
}
```

## Version History

- **3.0.0** - Current version with CLI and MCP server
- **2.x.x** - Legacy versions

## Contributing

Part of the Cortex packages ecosystem. Contributions welcome!

## License

MIT

## Support

For support, please open an issue in the [Cortex Packages repository](https://github.com/antoineschaller/cortex-packages).
