/** * @akson/cortex-doc-standards - Rules Engine for CLAUDE.md Integration * * Provides a declarative way to include doc-standards rules in project CLAUDE.md files * with conditional loading and auto-detection support */ import type { ConditionalProjectRulesConfig, RuleDetectionResult } from './types/conditional-rules'; export interface RuleConfig { /** Rule identifier */ id: string; /** Whether this rule is enabled */ enabled: boolean; /** Custom variables for rule templates */ variables?: Record; /** Custom overrides for rule content */ overrides?: { title?: string; content?: string; append?: string; }; } export interface ProjectRulesConfig { /** Project name for context */ projectName: string; /** Project type for specialized rules */ projectType: 'nextjs' | 'flutter' | 'backend' | 'shopify' | 'monorepo' | 'other'; /** Rules to include in CLAUDE.md */ rules: RuleConfig[]; /** Global variables available to all rules */ globalVariables?: Record; /** Custom templates to include in CLAUDE.md */ templates?: Record; } export type { ConditionalRuleConfig, ConditionalProjectRulesConfig, ConditionalRuleDefinition, RuleDetectionResult, EnablementMode } from './types/conditional-rules'; /** * Built-in rule templates that can be referenced by projects */ export declare const BUILT_IN_RULES: { readonly 'project-workflow': { readonly id: "project-workflow"; readonly title: "๐Ÿ“‹ Project Workflow Integration"; readonly template: "## ๐Ÿ“‹ Project Workflow Integration\n\n**IMPORTANT**: GitHub issue tracking and shared package management patterns.\n\n### GitHub Implementation Workflow\n1. **Read issue description** and understand implementation tasks\n2. **Update issue description** to mark checkboxes complete `[x]` as you implement\n3. **Use `gh issue edit`** to update body directly - NEVER use comments for progress\n4. **Reference issues in commits**: \"fix: authentication (closes #35)\"\n\n### Required Commands\n```bash\ngh issue view 1 # Read current issue state\ngh issue edit 1 --body \"$(cat updated-issue.md)\" # Update description\n```\n\n### Issue Structure Format\n```markdown\n## Implementation Checklist\n- [x] ~~Task 1: Setup auth~~ โœ… DONE\n- [ ] Task 2: Add validation **IN PROGRESS**\n- [ ] Tests: Unit tests for auth\n\n**Status**: In Progress (1/3 complete)\n**Last Updated**: 2025-09-12\n```\n\n### Shared Package Modification (Cortex Packages)\n**ALWAYS modify the package directly** when functionality missing/insufficient.\n\n```bash\n# 1. Navigate to package\ncd /Users/antoineschaller/GitHub/cortex-packages/packages/[name]\n\n# 2. Implement changes following existing patterns\n\n# 3. Publish\nnpm run build\ngit add . && git commit -m \"feat: description\"\nnpm version patch && npm publish\ngit push origin main --tags\n\n# 4. Update project\ncd /path/to/project\n{package.manager} add {packages.namespace}/[package-name]@latest\n```\n\n### Modification Guidelines\n- **Extend existing APIs** rather than breaking them\n- **Test thoroughly** before publishing\n- **Use semantic versioning**: patch (fixes), minor (features), major (breaking)\n- **Document new features** - Update README, JSDoc\n\n### When to Modify\nโœ… **DO**: Props/features don't exist, bugs, performance improvements\nโŒ **DON'T**: Create local workarounds - fix root issue in package\n\n**Remember**: Issue descriptions are single source of truth. Cortex packages are shared foundations."; readonly description: "GitHub Projects workflow and shared package management standards"; readonly variables: { readonly 'packages.namespace': "Package namespace (e.g., @akson)"; readonly 'package.manager': "Package manager command (pnpm, npm)"; }; }; readonly 'security-standards': { readonly id: "security-standards"; readonly title: "๐Ÿ”’ Security Standards"; readonly template: "## ๐Ÿ”’ Security Standards\n\n**CRITICAL**: All security practices must be followed without exception.\n\n### Secrets Management\n- **NEVER commit secrets, passwords, or API keys to the repository**\n- **Use environment variables** for all sensitive configuration\n- **Use `{secrets.manager}`** for production secret storage\n- **Rotate secrets regularly** according to security policy\n\n### Authentication & Authorization\n- **Implement proper RBAC** using the centralized role system\n- **Use `{auth.method}`** for user authentication\n- **Validate all user inputs** against XSS, SQL injection, and other attacks\n- **Implement rate limiting** on all API endpoints\n\n### Data Protection\n- **Encrypt sensitive data** both at rest and in transit\n- **Use HTTPS** for all communications\n- **Implement proper CORS** policies\n- **Log security events** for monitoring and audit\n\n### Code Security\n- **Run security scans** before deployment: `{security.scanCommand}`\n- **Keep dependencies updated** to patch known vulnerabilities\n- **Use static analysis tools** to detect security issues\n- **Follow OWASP** security guidelines for web applications"; readonly description: "Core security standards and practices"; readonly variables: { readonly 'secrets.manager': "Secrets management system (e.g., 1Password, AWS Secrets)"; readonly 'auth.method': "Authentication method (e.g., Supabase Auth, Auth0)"; readonly 'security.scanCommand': "Security scan command (e.g., npm audit, snyk test)"; }; }; readonly 'testing-standards': { readonly id: "testing-standards"; readonly title: "๐Ÿงช Testing Standards"; readonly template: "## ๐Ÿงช Testing Standards\n\n**MANDATORY**: All code changes must include appropriate tests.\n\n### Test Coverage Requirements\n- **Unit tests**: Minimum {coverage.unit}% coverage for utilities and business logic\n- **Integration tests**: All API endpoints and data flows\n- **E2E tests**: Critical user journeys and workflows\n\n### Testing Commands\n```bash\n{test.unit} # Run unit tests\n{test.integration} # Run integration tests\n{test.e2e} # Run end-to-end tests\n{test.watch} # Run tests in watch mode\n{test.coverage} # Generate coverage report\n```\n\n### Test Structure\n- **Location**: Tests adjacent to source files or in `{test.directory}`\n- **Naming**: `*.test.{test.extension}` or `*.spec.{test.extension}`\n- **Organization**: Group related tests in describe blocks\n\n### Quality Gates\n- **All tests must pass** before merging to main branch\n- **No reduction in coverage** without explicit approval\n- **Performance tests** for critical paths and APIs"; readonly description: "Testing requirements and standards"; readonly variables: { readonly 'coverage.unit': "Minimum unit test coverage percentage"; readonly 'test.unit': "Unit test command"; readonly 'test.integration': "Integration test command"; readonly 'test.e2e': "E2E test command"; readonly 'test.watch': "Watch mode test command"; readonly 'test.coverage': "Coverage report command"; readonly 'test.directory': "Test files directory"; readonly 'test.extension': "Test file extension"; }; }; readonly 'claude-essentials': { readonly id: "claude-essentials"; readonly title: "๐Ÿค– Claude Essentials"; readonly template: "## ๐Ÿค– Claude Essentials\n\n**CRITICAL**: Core behavior rules for effective AI-assisted development.\n\n### Communication & Response Style\n- **Be concise, direct, to the point** - 1-3 sentences when possible, avoid preambles\n- **Address only the specific task** - No tangential information unless critical\n- **Prioritize technical accuracy** over emotional validation\n- **Reference specific locations** using `file_path:line_number` format\n\n### Tool Usage Patterns\n- **Use TodoWrite VERY frequently** for multi-step tasks (3+ steps)\n- **Mark exactly ONE task in_progress** at a time, complete immediately after finishing\n- **Always use Read tool first** before editing any existing file\n- **ALWAYS prefer editing existing files** over creating new ones\n\n### Code Quality Workflow\n- **First understand file conventions** before making changes\n- **Check `{package.file}`** dependencies before assuming libraries available\n- **Use existing utilities/components** rather than creating duplicates\n- **Use ONLY `{translation.function}`** for user-facing text - never hardcode strings\n- **Never introduce code that exposes secrets/keys**\n\n### Development Process\n1. **Research existing codebase** using search tools (Grep, Glob, Read)\n2. **Mark current todo as in_progress** before starting work\n3. **Follow existing code style** and naming conventions\n4. **Run quality checks**: `{lint.command}`, `{typecheck.command}`, `{test.command}`\n5. **Update documentation** if APIs changed\n\n**Remember**: Quality, accuracy, and following established patterns over speed."; readonly description: "Core Claude AI behavior and workflow fundamentals"; readonly variables: { readonly 'package.file': "Package configuration file (package.json, Cargo.toml, etc.)"; readonly 'translation.function': "Internationalization function name (e.g., t, __, translate)"; readonly 'lint.command': "Linting command (npm run lint, eslint, etc.)"; readonly 'typecheck.command': "Type checking command (tsc, mypy, etc.)"; readonly 'test.command': "Test command (npm test, pytest, etc.)"; }; }; readonly 'code-standards': { readonly id: "code-standards"; readonly title: "๐Ÿ”ง Code Standards"; readonly template: "## ๐Ÿ”ง Code Standards\n\n**CRITICAL**: Quality and naming standards that must never be compromised.\n\n### Quality Gates (Never Bypass)\n- **NEVER use `--no-verify`** on git commits or pre-commit hooks\n- **NEVER disable/bypass tests** when failing - fix them immediately\n- **NEVER skip linting/type-checking** when errors present\n- **NEVER set `ignoreBuildErrors: true`** in build configurations\n- **NEVER use `@ts-ignore`** as permanent solution\n- **NEVER commit broken code** with intention to \"fix later\"\n\n### File Naming: kebab-case\n**MANDATORY**: `address-input.tsx`, `phone-input.tsx`, `team-account-layout-sidebar.tsx`\n**NEVER**: `AddressInput.tsx` (PascalCase), `phoneInput.tsx` (camelCase), `phone_input.tsx` (snake_case)\n\n### Component Exports: PascalCase\n```typescript\n// File: address-input.tsx\nexport function AddressInput() { ... }\n```\n\n### Directory Structure: Feature-Based\nโœ… **Correct**: `features/auth/components/`, `features/dancers/components/`\nโŒ **Wrong**: `src/components/`, `src/types/`, `src/utils/`\n\n### Component Structure Template\n```typescript\n'use client'; // If client component\n// 1. React imports, 2. Third-party imports, 3. Internal UI, 4. Feature imports\n// 5. Type definitions, 6. Component implementation\n```\n\n### Naming Rules Summary\n1. **Files**: kebab-case, 2. **Components**: PascalCase, 3. **Variables/Functions**: camelCase\n4. **Constants**: SCREAMING_SNAKE_CASE, 5. **Types/Interfaces**: PascalCase\n\n### Documentation Organization (AI Best Practice)\n\n**CRITICAL**: Core documentation MUST use numbered prefixes for clear reading order.\n\n#### Numbered Documentation Structure\n```\ndocs/\nโ”œโ”€โ”€ 01-OVERVIEW.md # Project fundamentals (read first)\nโ”œโ”€โ”€ 02-ARCHITECTURE.md # System design\nโ”œโ”€โ”€ 03-SECURITY.md # Security patterns\nโ”œโ”€โ”€ 04-DATABASE.md # Data layer\nโ”œโ”€โ”€ 05-API_DESIGN.md # API conventions\nโ”œโ”€โ”€ 06-TESTING.md # Quality assurance\nโ”œโ”€โ”€ 07-DEPLOYMENT.md # Production deployment\nโ”œโ”€โ”€ 08-MONITORING.md # Observability\nโ””โ”€โ”€ 09+ # Additional specialized domains\n```\n\n**Why This Matters for AI**:\n- โœ… Creates predictable learning path for AI sessions\n- โœ… Reduces cognitive load in large codebases\n- โœ… Makes cross-references explicit (\"as discussed in 01-OVERVIEW\")\n- โœ… Enables efficient context building in new sessions\n- โœ… Establishes clear information hierarchy\n\n**Format Rules**:\n- **01-08**: Reserved for core documentation\n- **09+**: Available for specialized domains\n- **Format**: `NN-TOPIC.md` (two digits, ALL_CAPS topic)\n- **Archive docs**: No numbering required (docs/archive/)\n\n### Version Suffix Prohibition\n\n**CRITICAL**: NEVER create new files/functions/types with version suffixes. Always modify the original.\n\n#### Forbidden Suffixes (NEVER USE)\n**Strictly prohibited** in all names (files, functions, components, types, variables):\n- **Versions**: `v2`, `V2`, `new`, `old`, `legacy`, `2`, `II`\n- **Quality**: `enhanced`, `improved`, `better`, `optimized`, `simplified`, `modern`\n- **State**: `updated`, `modified`, `refactored`, `revised`, `extended`\n- **Temporary**: `temp`, `tmp`, `draft`, `test`, `backup`, `copy`\n- **Singles**: `single`, `singles`, `simple`\n\n#### Instead, Do This\nโŒ **WRONG**: `validateUserEnhanced()`, `UserProfileV2`, `ButtonNew.tsx`, `modernDashboard.tsx`, `singleUserView.tsx`\nโœ… **CORRECT**: Replace original or use descriptive names: `validateUser()`, `PublicUserProfile`, `IconButton.tsx`, `dashboard.tsx`, `userView.tsx`\n\n**Remember**: Fix problems properly the first time. Quality is built in, not added later."; readonly description: "Core code quality and naming standards including strict version suffix prohibition"; readonly variables: {}; }; readonly 'version-suffix-prohibition': { readonly id: "version-suffix-prohibition"; readonly title: "๐Ÿšซ Version Suffix Prohibition"; readonly template: "## ๐Ÿšซ Version Suffix Prohibition\n\n**CRITICAL**: NEVER create new files/functions/types with version suffixes. Always modify the original.\n\n### Forbidden Suffixes (NEVER USE)\n**Strictly prohibited** in all names (files, functions, components, types, variables):\n- **Versions**: `v2`, `V2`, `new`, `old`, `legacy`, `2`, `II`\n- **Quality**: `enhanced`, `improved`, `better`, `optimized`, `simplified`, `modern`\n- **State**: `updated`, `modified`, `refactored`, `revised`, `extended`\n- **Temporary**: `temp`, `tmp`, `draft`, `test`, `backup`, `copy`\n- **Singles**: `single`, `singles`, `simple`\n\n### Instead, Do This\nโŒ **WRONG**: `validateUserEnhanced()`, `UserProfileV2`, `ButtonNew.tsx`, `modernDashboard.tsx`, `singleUserView.tsx`\nโœ… **CORRECT**: Replace original or use descriptive names: `validateUser()`, `PublicUserProfile`, `IconButton.tsx`, `dashboard.tsx`, `userView.tsx`\n\n**Remember**: Fix problems properly the first time. Quality is built in, not added later."; readonly description: "Comprehensive version suffix prohibition to prevent code duplication and maintain clean codebases"; readonly variables: {}; }; readonly 'makerkit-complete': { readonly id: "makerkit-complete"; readonly title: "๐Ÿ› ๏ธ MakerKit Complete"; readonly template: "## ๐Ÿ› ๏ธ MakerKit Complete\n\n**CRITICAL**: Comprehensive MakerKit development guide. Use when project built on MakerKit framework.\n\n### ๐Ÿšจ Discovery First - ASK BEFORE BUILDING\nBefore creating any component/hook/utility:\n1. **Search MakerKit first** using MCP server tools\n2. **Ask user**: \"MakerKit might have this. Should I check first?\"\n3. **Only proceed** after confirmation MakerKit doesn't have it\n\n### ๐Ÿ” MCP Discovery Commands\n```bash\nget_components # List all available components\ncomponents_search \"keyword\" # Search by functionality (button, form, auth, upload)\nget_component_props \"component\" # Analyze component props and variants\nget_schema_files # List database schemas\n```\n\n### ๐Ÿ“ฆ Key Packages & Imports\n**Core**: @kit/ui (80+ components), @kit/supabase (DB/auth), @kit/shared (utilities)\n**Features**: @kit/auth, @kit/accounts, @kit/team-accounts, @kit/admin\n\n```typescript\n// Essential imports\nimport { useSupabase } from '@kit/supabase/hooks/use-supabase'\nimport { useUser } from '@kit/supabase/hooks/use-user'\nimport { getSupabaseServerClient } from '@kit/supabase/server-client'\nimport { Button } from '@kit/ui/button'\nimport { toast } from '@kit/ui/sonner'\nimport { useUserWorkspace } from '@kit/accounts/hooks/use-user-workspace'\nimport { useTeamAccountWorkspace } from '@kit/team-accounts/hooks/use-team-account-workspace'\n```\n\n### ๐Ÿš€ Turborepo Development Commands\n```bash\n# Core Development\n`{dev.command}` # Start all applications\n`{dev.filter}` # Start main SaaS app (port 3000)\n`{build.command}` # Build with caching\n`{lint.command}` && `{typecheck.command}` # Quality checks\n\n# Database Operations\n`{db.start}` # Start local Supabase\n`{db.reset}` # Reset DB + apply migrations\n`{db.typegen}` # Generate TypeScript types\n\n# Package Development\n`{package.build}` # Build specific package\n`{package.add}` # Add dependency to specific app\n```\n\n### ๐Ÿ—๏ธ Multi-Tenant Architecture\n**Account Types**: Personal (auth.users.id = accounts.id), Team (shared workspaces)\n\n```typescript\n// Workspace Context\nimport { useUserWorkspace } from '@kit/accounts/hooks/use-user-workspace'\nimport { useTeamAccountWorkspace } from '@kit/team-accounts/hooks/use-team-account-workspace'\nconst { data: workspace } = useUserWorkspace() // or useTeamAccountWorkspace()\n\n// Authentication Patterns\n// Server Components\nconst client = getSupabaseServerClient()\nconst user = await getCurrentUser(client)\nif (!user) redirect('/login')\n\n// Client Components\nconst user = useUser()\nif (!user) return \n```\n\n### ๐Ÿšง Data Isolation (CRITICAL)\n```typescript\n// โœ… CORRECT - Always filter by account\nconst { data } = await supabase.from('notes').select('*').eq('account_id', workspace.account.id)\n\n// โŒ WRONG - Missing account filter\nconst { data } = await supabase.from('notes').select('*')\n```\n\n### ๐Ÿ“ Form & Data Patterns\n**Stack**: Zod schemas โ†’ React Hook Form โ†’ Server Actions โ†’ Account isolation\n\n```typescript\n// Schema Definition\nexport const CreateNoteSchema = z.object({\n title: z.string().min(1, 'Required'),\n content: z.string().min(1, 'Required'),\n})\n\n// Server Action (Account-Aware)\nexport async function createNoteAction(data: unknown) {\n const client = getSupabaseServerClient()\n const user = await getCurrentUser(client)\n if (!user) throw new Error('Unauthorized')\n\n const workspace = await loadAccountWorkspace()\n const parsed = CreateNoteSchema.parse(data)\n\n return client.from('notes').insert({\n ...parsed,\n account_id: workspace.account.id, // Account isolation\n created_by: user.id,\n }).select().single()\n}\n\n// Client Form\nconst form = useForm({\n resolver: zodResolver(CreateNoteSchema),\n defaultValues: { title: '', content: '' },\n})\n```\n\n### ๐Ÿ—„๏ธ Database Types Integration\n```typescript\n// โœ… CORRECT - MakerKit pattern for custom schemas\nimport type { Database } from '@/types/database.types'\nconst supabase = useSupabase() // Pass custom types to MakerKit\nconst supabaseServer = getSupabaseServerClient()\n\n// โŒ WRONG - Don't create separate clients\n// const supabase = createBrowserClient(url, key)\n```\n\n### โŒ NEVER Build Custom\n- Custom Supabase client setup\n- UI components when @kit/ui equivalents exist\n- Workspace/account context providers\n- File upload when FileUploader exists\n- Admin guards when AdminGuard exists\n\n### ๐Ÿ”„ Extend, Don't Replace\n```typescript\nimport { Button } from '@kit/ui/button'\nimport { cn } from '@kit/ui/utils'\n\nexport function CustomButton({ specialFeature, ...props }) {\n return