Greenfield

This commit is contained in:
Eric Gullickson
2025-08-06 20:59:45 -05:00
parent 3d43cddd1f
commit 6c64a17e86
3 changed files with 1995 additions and 0 deletions

591
AI_STRUCTURE.md Normal file
View File

@@ -0,0 +1,591 @@
You are tasked with creating a new project that follows AI-optimized documentation and structure patterns designed for efficient AI-to-AI code maintenance. This project should be self-describing, context-efficient, and progressively discoverable.
Core Setup Instructions
1. Initialize Project Structure
Create this exact directory structure:
project-root/
├── AI_README.md # 200-token complete system overview
├── PROJECT_MAP.md # Navigation and quick reference
├── CONVENTIONS.md # Project patterns and standards
├── CLAUDE.md # This file - AI interaction guide
├── CHANGELOG_AI.md # AI-focused change tracking
├── src/
│ ├── core/ # Stable, critical functionality
│ │ └── README.md # Core module descriptions
│ ├── features/ # Business logic modules
│ │ └── README.md # Feature development guide
│ ├── shared/ # Reusable utilities
│ │ └── README.md # Utility usage patterns
│ └── index.{ts|py} # Main entry point
├── docs/
│ ├── ARCHITECTURE.md # System design decisions
│ ├── TROUBLESHOOTING.md # Common issues and solutions
│ ├── dependencies.md # External dependency documentation
│ └── diagrams/ # Visual architecture representations
├── tests/
│ ├── README.md # Testing strategy
│ ├── fixtures/ # Shared test data
│ └── examples/ # Usage examples
├── templates/ # Code generation templates
│ └── README.md # Template usage guide
├── .ai/ # AI-specific metadata
│ ├── context.json # Context navigation for AI
│ ├── dependencies.yaml # Module dependency graph
│ └── shortcuts.md # Quick command reference
└── scripts/
└── setup.{sh|py} # Project initialization scripts
2. Create Foundation Files
AI_README.md
markdown# Project Name
## AI Quick Start (50 tokens)
[One paragraph describing what this system does, its primary purpose, and key technologies]
## Navigation Guide
- Start here: PROJECT_MAP.md
- Conventions: CONVENTIONS.md
- Architecture: docs/ARCHITECTURE.md
- AI Metadata: .ai/context.json
## Critical Context
- [List 3-5 things an AI must always know when working on this codebase]
## Primary Entry Points
- Main application: src/index.{ts|py}
- Core modules: src/core/README.md
- Feature modules: src/features/*/index.{ts|py}
PROJECT_MAP.md
markdown# Project Navigation Map
## System Overview
[2-3 sentences about the system architecture]
## Quick Navigation
### By Task
- **Adding a feature**: Start with templates/ → src/features/
- **Fixing bugs**: TROUBLESHOOTING.md → tests/ → src/
- **Modifying core**: Read CONVENTIONS.md first → src/core/
- **Adding tests**: tests/README.md → tests/examples/
### By Frequency
- **Most changed**: [List top 3 most frequently modified paths]
- **Most critical**: src/core/*
- **Most complex**: [List complex modules needing extra context]
## Module Map
\`\`\`
src/
├── core/
│ ├── config/ # Environment and app configuration
│ ├── database/ # Data layer abstractions
│ ├── logging/ # Centralized logging
│ └── security/ # Auth and security primitives
├── features/
│ └── [feature]/ # Each feature is self-contained
│ ├── index # Public API
│ ├── service # Business logic
│ ├── types # Type definitions
│ └── tests # Feature tests
└── shared/
├── utils/ # Pure utility functions
└── types/ # Shared type definitions
\`\`\`
## AI Interaction Guide
- **Before modifying**: Read .ai/context.json for the area you're working in
- **When debugging**: Start with src/core/logging
- **When adding features**: Use templates/ for consistent patterns
- **After changes**: Update CHANGELOG_AI.md and .ai/dependencies.yaml
CONVENTIONS.md
markdown# Project Conventions
## Code Style
### Naming Conventions
- **Files**: kebab-case.ts or snake_case.py
- **Classes**: PascalCase with descriptive names
- **Functions**: camelCase (JS/TS) or snake_case (Python), verb_noun pattern
- **Constants**: UPPER_SNAKE_CASE
- **Interfaces/Types**: PascalCase with 'I' prefix for interfaces (optional)
### Self-Documenting Code Principles
1. **Prefer clear naming over comments**
\`\`\`typescript
// Bad
const d = new Date(); // Gets current date
// Good
const currentDate = new Date();
\`\`\`
2. **Use type hints as documentation**
\`\`\`python
def process_order(
order_data: OrderDict,
validate: bool = True
) -> Result[Order, OrderError]:
"""Process order. See OrderDict for structure."""
pass
\`\`\`
3. **Function names should describe complete behavior**
\`\`\`typescript
// Bad: validate(data)
// Good: validateOrThrow(data)
// Good: validateAndReturnErrors(data)
\`\`\`
## Documentation Standards
### Progressive Disclosure Pattern
\`\`\`javascript
/**
* @ai-summary Handles payment processing
* @ai-details docs/payments/PROCESSING.md
* @ai-examples tests/examples/payment-processing.test.js
* @critical-context PCI compliance required, no card storage
*/
\`\`\`
### Required Annotations
- **Services/Classes**: @ai-summary (one line)
- **Complex functions**: HANDLES, THROWS, SIDE_EFFECTS
- **Security-sensitive code**: SAFETY comment
- **External dependencies**: DEPENDS comment
### When to Comment
ONLY add inline comments for:
- Regulatory/compliance requirements
- Non-obvious business logic
- Performance optimizations (with metrics)
- Security considerations
- Workarounds with issue references
## Structure Patterns
### Feature Module Structure
\`\`\`
features/[feature-name]/
├── index.{ts|py} # Public API (exports only)
├── service.{ts|py} # Business logic
├── repository.{ts|py} # Data access
├── types.{ts|py} # Type definitions
├── validators.{ts|py} # Input validation
├── README.md # Feature documentation
└── __tests__/ # Feature tests
\`\`\`
### Service Class Pattern
\`\`\`typescript
export class FeatureService {
constructor(
private repository: FeatureRepository,
private logger: Logger
) {}
// Public methods first, prefixed with action verb
async createFeature(data: FeatureInput): Promise<Result<Feature>> {
const validated = this.validateOrFail(data);
return this.repository.create(validated);
}
// Private helpers last, prefixed with underscore
private validateOrFail(data: unknown): FeatureInput {
// Validation logic
}
}
\`\`\`
## Testing Standards
### Test Naming
- Test files: [module].test.{ts|py} or test_[module].py
- Test names: test_should_[expected_behavior]_when_[condition]
- Use @ai-coverage to link tests to code
### Test Organization
\`\`\`python
class TestFeatureService:
"""
@ai-coverage FeatureService
@ai-fixtures tests/fixtures/features/
"""
def test_should_create_feature_when_data_valid(self):
# Arrange → Act → Assert pattern
pass
def test_should_reject_when_missing_required_fields(self):
pass
\`\`\`
## Git Commit Standards
- Format: "type(scope): description"
- Types: feat, fix, docs, refactor, test, chore
- Include "AI-CONTEXT:" line for significant changes
## Error Handling
- Use Result<T, E> pattern or explicit error types
- Never catch and ignore errors silently
- Log errors with context at catch point
- Throw early, catch late
## Performance Guidelines
- Document Big-O complexity for algorithms
- Add benchmarks for critical paths
- Use caching for expensive computations
- Profile before optimizing
.ai/context.json
json{
"version": "1.0.0",
"project_type": "[web-api|cli-tool|library|full-stack-app]",
"language": "[typescript|python|javascript]",
"context_budget": {
"always_load": [
"AI_README.md",
"CONVENTIONS.md"
],
"essential_paths": [
"src/core/",
"src/index.{ts|py}"
],
"conditional": {
"if_modifying_auth": [
"src/features/auth/",
"docs/auth/",
"src/core/security/"
],
"if_debugging": [
"src/core/logging/",
"TROUBLESHOOTING.md",
"tests/"
],
"if_adding_feature": [
"templates/feature/",
"src/features/README.md",
"CONVENTIONS.md#structure-patterns"
],
"if_modifying_database": [
"src/core/database/",
"migrations/",
"docs/database/"
]
}
},
"common_tasks": {
"add_endpoint": {
"template": "templates/endpoint.template",
"checklist": [
"Define route in router",
"Add request/response types",
"Implement handler",
"Add validation",
"Write tests",
"Update API documentation"
],
"examples": "tests/examples/endpoints/"
},
"add_feature": {
"template": "templates/feature/",
"checklist": [
"Create feature folder",
"Define types",
"Implement service",
"Add repository if needed",
"Write tests",
"Update dependencies.yaml",
"Add to feature index"
]
},
"debug_issue": {
"start_with": [
"Check TROUBLESHOOTING.md",
"Review recent CHANGELOG_AI.md",
"Check logs in src/core/logging",
"Run relevant tests"
]
}
},
"danger_zones": {
"src/core/security/": {
"warning": "Security-critical code",
"required_review": true,
"checklist": [
"Run security tests",
"Check for credential exposure",
"Verify input validation"
]
},
"migrations/": {
"warning": "Database schema changes",
"required_review": true,
"checklist": [
"Test rollback procedure",
"Verify data preservation",
"Check migration order"
]
},
"src/core/config/": {
"warning": "System configuration",
"checklist": [
"Update .env.example",
"Check all environments",
"Verify defaults are safe"
]
}
},
"dependencies": {
"external": {
"critical": ["framework", "database", "auth-library"],
"optional": ["monitoring", "analytics"]
},
"internal": {
"most_imported": ["src/core/logger", "src/shared/types"],
"most_dependent": ["src/core/database", "src/core/config"]
}
},
"testing": {
"test_command": "npm test | pytest",
"coverage_threshold": 80,
"critical_paths": [
"src/core/security",
"src/core/database",
"src/features/auth"
]
},
"performance": {
"bottlenecks": [],
"optimization_notes": [],
"benchmarks": "tests/benchmarks/"
}
}
.ai/dependencies.yaml
yaml# Module Dependency Graph
# Format: module -> depends_on, consumed_by, impact_level
version: 1.0.0
last_updated: [DATE]
modules:
core/config:
depends_on: []
consumed_by: ["*"] # Everything depends on config
critical: true
modification_impact: "high - requires full system test"
test_command: "npm test core/config"
core/database:
depends_on: ["core/config", "core/logging"]
consumed_by: ["features/*", "migrations"]
critical: true
modification_impact: "high - affects all data operations"
test_command: "npm test core/database"
core/logging:
depends_on: ["core/config"]
consumed_by: ["*"]
critical: true
modification_impact: "medium - affects debugging capability"
test_command: "npm test core/logging"
core/security:
depends_on: ["core/config", "core/database", "core/logging"]
consumed_by: ["features/auth", "api/middleware"]
critical: true
modification_impact: "critical - security review required"
test_command: "npm test core/security"
features/[example]:
depends_on: ["core/*", "shared/utils"]
consumed_by: ["api/routes/[example]"]
critical: false
modification_impact: "low - isolated feature"
test_command: "npm test features/[example]"
# Dependency rules
rules:
- "Features cannot depend on other features"
- "Core modules cannot depend on features"
- "Shared utilities cannot depend on core or features"
- "All modules must depend on core/config"
# Import cycles to avoid
forbidden_cycles:
- ["core/database", "core/security", "core/database"]
# High-risk modification paths
high_risk_paths:
- description: "Authentication flow"
modules: ["core/security", "features/auth", "api/middleware/auth"]
test_suite: "npm test:auth:full"
- description: "Data persistence layer"
modules: ["core/database", "migrations", "features/*/repository"]
test_suite: "npm test:database:full"
3. Create Template Files
templates/feature/index.template
typescript/**
* @ai-summary [Feature description in one line]
* @ai-details docs/features/[feature-name].md
* @critical-context [Any critical information]
*/
export * from './types';
export * from './service';
export { [FeatureName]Repository } from './repository';
templates/feature/service.template
typescript/**
* @ai-summary Handles [feature] business logic
* @ai-examples tests/examples/[feature]/
*/
export class [FeatureName]Service {
constructor(
private repository: [FeatureName]Repository,
private logger: Logger
) {}
/**
* HANDLES: [What it processes]
* THROWS: [Error types]
* SIDE_EFFECTS: [External changes]
*/
async create[FeatureName](
data: [FeatureName]Input
): Promise<Result<[FeatureName], [FeatureName]Error>> {
// Validate -> Process -> Persist -> Return
const validated = this.validateOrFail(data);
const processed = this.processBusinessRules(validated);
return this.repository.create(processed);
}
private validateOrFail(data: unknown): [FeatureName]Input {
// Validation logic
throw new Error('Not implemented');
}
private processBusinessRules(data: [FeatureName]Input): [FeatureName]Data {
// Business logic transformations
throw new Error('Not implemented');
}
}
4. Project-Specific Setup Commands
Based on the project type, run these initialization commands:
bash# For TypeScript projects
npm init -y
npm install --save-dev typescript @types/node prettier eslint
npx tsc --init
# For Python projects
python -m venv venv
pip install black pytest mypy pylint
# Initialize git with proper ignores
git init
echo "node_modules/\nvenv/\n.env\n*.log\n.DS_Store" > .gitignore
# Create initial environment file
echo "# Development Environment Variables\nNODE_ENV=development\nLOG_LEVEL=debug" > .env.example
5. Initial CHANGELOG_AI.md Entry
markdown# AI-Focused Changelog
## [Date] - Project Initialization
**Created**: Initial project structure
**Architecture**: [Chosen architecture pattern]
**Key Technologies**: [List main technologies]
**AI Context**:
- Project follows AI-optimized documentation patterns
- Self-describing code structure implemented
- Progressive disclosure documentation in place
**Entry Points**:
- Start with AI_README.md
- Conventions in CONVENTIONS.md
- Navigation via PROJECT_MAP.md
Instructions for Claude Code
When creating a new project with these standards:
Start by asking the user:
Project type (API, CLI tool, web app, library)
Primary language (TypeScript, Python, JavaScript)
Key features needed initially
Any specific frameworks or libraries required
Then systematically:
Create the complete directory structure
Generate all foundation files with project-specific content
Set up the .ai/ metadata directory
Create initial templates based on project type
Initialize version control and package management
Write the first entry in CHANGELOG_AI.md
Customize based on project type:
API: Add OpenAPI specs, route templates, middleware patterns
CLI: Add command templates, argument parsing patterns
Library: Add export patterns, public API documentation
Full-stack: Add frontend/backend separation, API contracts
For each file you create:
Ensure it follows the self-documenting principles
Add appropriate @ai-* annotations
Include type hints/interfaces
Create corresponding test file structure
Update .ai/context.json with new paths
Before completing setup:
Verify all imports resolve correctly
Ensure templates have clear replacement markers
Check that navigation paths in documentation are accurate
Confirm .ai/dependencies.yaml reflects actual structure
Test that the project runs with minimal setup
Final output should include:
Complete file structure
All content for foundation files
Setup instructions in a setup.md
Initial test file examples
A "Getting Started for AI" section in AI_README.md
Remember: The goal is to create a codebase that another AI can understand and modify efficiently with minimal context loading. Every decision should optimize for clarity and discoverability.
Example First Response
When you run this setup, respond with:
I'll create an AI-optimized project structure for your [project type]. This setup will follow AI-to-AI communication patterns for maximum clarity and minimal context usage.
## Project Configuration
- Type: [selected type]
- Language: [selected language]
- Architecture: [chosen pattern]
## Creating Structure...
[Show the directory tree being created]
## Generating Foundation Files...
[List each file as it's created]
## Project Ready!
### Next Steps for AI Interaction:
1. Read AI_README.md for system overview
2. Check CONVENTIONS.md before making changes
3. Use PROJECT_MAP.md for navigation
4. Refer to .ai/context.json for task-specific guidance
### For Human Developers:
1. Run: [setup command]
2. Configure: Copy .env.example to .env
3. Install: [package manager] install
4. Test: [test command]
The project is now optimized for AI maintenance and collaboration!