
Brownfield Onboarding
- 17 installs
- 1 repo stars
- Updated June 13, 2026
- cyberelf/agent_skills
Onboard onto an existing codebase by scanning it, documenting structure and architecture, flagging design flaws, and generating an AGENTS.md constitution.
About
Systematically scans and documents an unfamiliar codebase, capturing structure, architecture, and design issues, then generates AI agent constitution files. A developer uses it to get up to speed on an inherited project and encode project-specific context for AI-assisted work.
- Analyzes architecture and stack, identifying design flaws and improvements
- Generates AGENTS.md with coding principles and UI/UX guidelines
Brownfield Onboarding by the numbers
- 17 all-time installs (skills.sh)
- Ranked #1,038 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/cyberelf/agent_skills --skill brownfield-onboardingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 17 |
|---|---|
| repo stars | ★ 1 |
| Last updated | June 13, 2026 |
| Repository | cyberelf/agent_skills ↗ |
What it does
Onboard onto an existing codebase by scanning it, documenting structure and architecture, flagging design flaws, and generating an AGENTS.md constitution.
Files
Brownfield Project Onboarding
Overview
This skill provides a systematic approach to understand and document existing projects. It helps developers quickly get up to speed with unfamiliar codebases by generating comprehensive documentation about the project's structure, architecture, design decisions, identifying areas for improvement, and creating AI agent constitution files (AGENTS.md) that encode project-specific knowledge, coding principles, and UI/UX guidelines for effective AI-assisted development.
When to Use This Skill
Invoke this skill when:
- Starting work on an unfamiliar or inherited codebase
- Joining a new team or project
- Conducting a technical audit of an existing system
- User requests "help me understand this project"
- Need to document an undocumented or poorly documented project
- Preparing for a major refactoring or modernization effort
- Setting up AI agent constitution files for better AI-assisted development
- Establishing coding principles and standards for a team
- Creating comprehensive context for AI agents working on the project
How This Skill Works
Upon invocation, this skill:
1. Analyzes the project to determine its documentation state 2. Selects the appropriate workflow based on project maturity 3. Executes the workflow to generate comprehensive documentation 4. Creates or enhances AGENTS.md files for AI agent context 5. Provides actionable recommendations for improvements
---
Workflow Selection
This skill uses different workflows based on the project's current state:
Project State Detection
The AI agent automatically analyzes the project to determine its documentation maturity level.
Detection Process: 1. Search for AGENTS.md files using file_search 2. Search for constitution/guideline files (.cursorrules, CONTRIBUTING.md, etc.) 3. Read and analyze README for depth and quality 4. Apply classification rules with intelligent judgment
Classification States:
- MATURE: AGENTS.md exists
- ESTABLISHED: Constitution files + substantial README (>100 lines)
- PARTIAL: Basic README (>50 lines) only
- VANILLA: Minimal/no documentation (default)
Detection Logic:
- Has AGENTS.md →
MATURE - Has constitution files + README >100 lines with depth →
ESTABLISHED - Has README >50 lines of meaningful content →
PARTIAL - Otherwise →
VANILLA(default)
The agent uses its intelligence to assess quality, not just quantity. A 60-line README with architecture details is better than a 150-line changelog.
Workflow Files
Based on the agent's assessment, one of these workflows is executed:
| Project State | Workflow File | Time | Use When |
|---|---|---|---|
| Vanilla | vanilla-project.md | 15-25 min | No/minimal docs, no constitutions |
| Partial Docs | partial-documentation.md | 10-20 min | Has README, no constitutions |
| Established | established-project.md | 10-15 min | Good docs, has constitutions, no AGENTS.md |
| Mature | mature-project.md | 5-10 min | Already has AGENTS.md files |
📖 For detailed workflow selection logic, see decision-guide.md
---
Core Workflow Phases
All workflows execute these five phases (adapted to project state):
Phase 1: Project Discovery
- Scan codebase structure
- Identify technologies and frameworks
- Discover features and entry points
- Output:
.onboard/overview.md
Phase 2: Architecture Analysis
- Document technical stack
- Identify architectural patterns
- Map data flow
- Output:
.onboard/architecture.md
Phase 3: Design Assessment
- Evaluate code quality
- Identify technical debt
- Propose improvements
- Output:
.onboard/design_suggestions.md
Phase 4: Quality & Automation Review
- Assess testing coverage
- Evaluate CI/CD maturity
- Recommend improvements
- Output:
.onboard/guardrail_suggestions.md
Phase 5: Agent Constitution Generation
- Detect/read existing constitutions
- Generate or enhance AGENTS.md files
- Create project-specific guidelines
- Outputs:
AGENTS.mdfiles +.onboard/agent_constitution.md
---
Execution Instructions
Step 1: Detect Project State
Analyze the project to determine its documentation maturity:
1. Search for AGENTS.md: Use file_search with pattern **/AGENTS.md
- If found → State is MATURE
2. Search for constitution files: Use file_search to look for:
.cursorrulesCONTRIBUTING.md.github/CONSTITUTION.md- Linter configs (
.eslintrc,.prettierrc, etc.) - Style guides
3. Analyze README: Use read_file to check README.md
- Count lines of meaningful content (exclude headers, badges, empty lines)
- Assess depth: Does it explain architecture, setup, contribution guidelines?
4. Classify based on findings:
- Has AGENTS.md → MATURE
- Has constitution files + substantial README (>100 lines) → ESTABLISHED
- Has basic README (>50 lines) but no constitution → PARTIAL
- Minimal/no README (<50 lines) → VANILLA (default)
Step 2: Load Appropriate Workflow
Based on your assessment, read and execute the corresponding workflow:
- MATURE → references/mature-project.md
- ESTABLISHED → references/established-project.md
- PARTIAL → references/partial-documentation.md
- VANILLA → references/vanilla-project.md
Step 3: Execute Workflow
Follow the instructions in the selected workflow file:
- Each workflow provides detailed, phase-by-phase instructions
- Each workflow adapts phases to the project's current state
- Each workflow includes specific tool usage recommendations
Step 4: Validate Outputs
Ensure all expected files are generated:
- [ ]
.onboard/overview.md - [ ]
.onboard/architecture.md - [ ]
.onboard/design_suggestions.md - [ ]
.onboard/guardrail_suggestions.md - [ ]
.onboard/agent_constitution.md - [ ]
./AGENTS.md(created or enhanced) - [ ] Subdirectory AGENTS.md files (if applicable)
Step 5: Provide Summary
Give user a comprehensive completion summary based on workflow type.
---
AGENTS.md Templates
This skill includes template files for generating AGENTS.md:
Available Templates
1. [root-agents-template.md](./templates/root-agents-template.md)
- Project-wide context and coding principles
- Placed at project root
2. [frontend-agents-template.md](./templates/frontend-agents-template.md)
- Frontend-specific guidelines
- UI/UX design system and accessibility
- Placed in frontend directory
3. [backend-agents-template.md](./templates/backend-agents-template.md)
- Backend-specific guidelines
- API design and security principles
- Placed in backend directory
Template Adaptation
Templates are adapted based on:
- Actual project structure and patterns
- Discovered design tokens and conventions
- Existing constitution file content
- Tech stack and framework conventions
---
Key Principles
1. Non-Destructive Enhancement
- Never overwrite existing documentation
- Enhance and complement, don't replace
- Preserve existing constitution files
- Mark all additions clearly
2. Context-Aware Generation
- Generate content based on actual code analysis
- Use project-specific examples
- Adapt to detected patterns
- Match existing documentation style
3. Workflow Adaptation
- Different approaches for different project maturities
- Respect existing work and conventions
- Focus effort where value is highest
- Minimize disruption to established projects
4. AI Agent Optimization
- Create machine-readable guidelines
- Include validation checklists
- Provide quick reference formats
- Synthesize across multiple docs
---
Common Tools Used
Across all workflows, these tools are commonly used:
Discovery Tools
list_dir- Explore directory structurefile_search- Find specific files by pattern (e.g.,**/AGENTS.md,**/.cursorrules)read_file- Read documentation and config files (README, CONTRIBUTING, etc.)
Analysis Tools
semantic_search- Find features and conceptsgrep_search- Pattern-based code searchlist_code_usages- Understand code relationships
Validation Tools
get_errors- Identify existing issues- Code analysis for patterns and anti-patterns
---
Output Directory Structure
After execution, the workspace contains:
.onboard/
├── overview.md # Project structure and features
├── architecture.md # Technical stack and architecture
├── design_suggestions.md # Improvement recommendations
├── guardrail_suggestions.md # Testing and CI/CD recommendations
└── agent_constitution.md # Constitution generation summary
AGENTS.md # Root project constitution
[frontend]/AGENTS.md # Frontend guidelines (if applicable)
[backend]/AGENTS.md # Backend guidelines (if applicable)---
Notes & Best Practices
- Comprehensive Analysis: Take time to thoroughly explore before documenting
- Be Specific: Include file paths and concrete examples
- Prioritize: Rank suggestions by impact and effort
- Actionable: Provide implementable recommendations
- Context-Aware: Tailor to project size, domain, and maturity
- Positive Framing: Start with strengths before improvements
- Realistic Estimates: Provide effort estimates for planning
- Agent-Friendly: Enable AI agents to validate their work
- Respect Existing Constitutions: Enhance rather than replace
- Non-Destructive: Always preserve existing content when merging
- Context-Rich Constitutions: Make AGENTS.md comprehensive with project-specific details
Common Pitfalls to Avoid
- ❌ Generating superficial documentation without deep analysis
- ❌ Making technology recommendations without understanding constraints
- ❌ Suggesting major rewrites instead of incremental improvements
- ❌ Ignoring existing documentation or architectural decisions
- ❌ Providing generic advice that doesn't apply to the specific project
- ❌ Overwhelming with too many suggestions without prioritization
- ❌ Missing critical security or performance issues
- ❌ Overwriting existing constitution files without preserving original content
- ❌ Creating generic AGENTS.md templates without project-specific context
- ❌ Skipping UI/UX principles analysis for frontend projects
---
Extension Points
This skill can be extended to include:
- Security Audit: Dedicated security vulnerability assessment
- Performance Profiling: Performance bottleneck identification
- Accessibility Review: WCAG compliance checking for web apps
- API Documentation: Automated API documentation generation
- Database Analysis: Schema design review and optimization suggestions
- UI/UX Deep Dive: Integration with ui-ux-pro-max skill for comprehensive UI/UX principles
- Dependency Audit: Automated dependency security and license checking
- Constitution Compliance: Automated checking of code against AGENTS.md guidelines
Related Skills
- ui-ux-pro-max: Can be invoked for comprehensive UI/UX analysis to enhance frontend AGENTS.md files
- openspec-constitution-guard: Can validate code changes against generated AGENTS.md constitutions
- issue-fixer: Uses project context from AGENTS.md files to fix issues more effectively
- retrospect: References AGENTS.md for project-specific context during retrospective analysis
---
Reference Documentation
Workflow References
- decision-guide.md - How to choose the right workflow
- vanilla-project.md - Workflow for minimal documentation
- partial-documentation.md - Workflow for basic README projects
- established-project.md - Workflow for well-documented projects
- mature-project.md - Workflow for projects with existing AGENTS.md
Template References
- templates/root-agents-template.md - Root constitution template
- templates/frontend-agents-template.md - Frontend constitution template
- templates/backend-agents-template.md - Backend constitution template
---
Quick Start
To use this skill:
1. User invokes: "Help me understand this project" or "Run brownfield onboarding" 2. Detect project state: Analyze project to determine maturity level (MATURE/ESTABLISHED/PARTIAL/VANILLA) 3. Load workflow: Read the appropriate workflow file from references/ 4. Execute phases: Follow workflow instructions for all 5 phases 5. Generate outputs: Create all documentation and AGENTS.md files 6. Provide summary: Give user comprehensive results and next steps
The workflow files contain all detailed instructions - this main SKILL.md serves as the orchestration guide.
Workflow Decision Guide
This guide helps determine which brownfield-onboarding workflow to use based on the project's current documentation state.
Quick Decision Tree
START: Analyze Project
│
├─> No README or minimal docs?
│ └─> Use: vanilla-project.md
│
├─> Has README but no constitution files?
│ └─> Use: partial-documentation.md
│
├─> Has constitution files (.cursorrules, CONTRIBUTING.md, etc.) but no AGENTS.md?
│ └─> Use: established-project.md
│
└─> Already has AGENTS.md files?
└─> Use: mature-project.mdWorkflow Descriptions
1. Vanilla Project (vanilla-project.md)
When to Use:
- No README or very minimal README (< 50 lines)
- No documentation directory
- No constitution files
- Typically inherited legacy code or proof-of-concept projects
Characteristics:
- Undocumented codebase
- Unknown architecture
- No established coding standards
- No testing infrastructure
Workflow Focus:
- Discovery and documentation from scratch
- Extract patterns from code analysis
- Create comprehensive initial documentation
- Generate complete AGENTS.md suite
Estimated Time: 15-25 minutes for thorough analysis
---
2. Partial Documentation (partial-documentation.md)
When to Use:
- Has README with basic project info
- May have some inline code comments
- No constitution or guideline files
- Minimal or no architecture documentation
Characteristics:
- Basic project description exists
- Some dependency documentation
- Entry points documented
- No coding standards documented
Workflow Focus:
- Build upon existing documentation
- Fill documentation gaps
- Discover undocumented patterns
- Create AGENTS.md from analyzed patterns
Estimated Time: 10-20 minutes
---
3. Established Project (established-project.md)
When to Use:
- Comprehensive README
- Has constitution files: .cursorrules, CONTRIBUTING.md, CODE_OF_CONDUCT.md
- Architecture docs in /docs or /wiki
- No AGENTS.md files yet
Characteristics:
- Well-documented project
- Established coding standards
- Testing and CI/CD in place
- Clear contribution guidelines
Workflow Focus:
- Respect existing documentation structure
- Non-destructive enhancement of constitutions
- Synthesize AGENTS.md from existing guidelines
- Complement rather than duplicate
Estimated Time: 10-15 minutes
---
4. Mature Project (mature-project.md)
When to Use:
- Already has AGENTS.md or similar AI constitution files
- Comprehensive documentation suite
- Well-established processes
- May need updates or validation
Characteristics:
- AGENTS.md exists at root or subdirectories
- Comprehensive documentation
- Mature processes
- May have outdated information
Workflow Focus:
- Validate existing AGENTS.md accuracy
- Identify outdated information
- Suggest updates based on current codebase
- Fill gaps in existing constitutions
Estimated Time: 5-10 minutes for validation and updates
---
Detection Logic
As an AI agent, analyze the project to determine its documentation maturity level.
Detection Steps
Step 1: Search for AGENTS.md
Use file_search with pattern: **/AGENTS.md- If found → State is MATURE
- If not found → Continue to Step 2
Step 2: Search for Constitution Files
Look for established project guidelines:
Use file_search for:
- **/.cursorrules
- **/CONTRIBUTING.md
- **/.github/CONSTITUTION.md
- Linter configs: .eslintrc*, .prettierrc*, etc.
- Style guides: STYLE_GUIDE.md, CODE_STANDARDS.mdStep 3: Analyze README
Read and evaluate README.md (or README.* variants):
Use read_file to examine:
- Line count (substantial content >100 lines, basic >50 lines)
- Content depth: Does it explain architecture, setup instructions, contribution guidelines?
- Quality: Just basic info or comprehensive documentation?Step 4: Classify the Project
Apply rules in priority order: 1. Has AGENTS.md → MATURE 2. Has constitution files + substantial README (>100 lines with depth) → ESTABLISHED 3. Has basic README (>50 lines) but no constitution → PARTIAL 4. Minimal/no README (<50 lines) or very basic → VANILLA (default)
Judgment Guidelines
Use your intelligence to assess quality, not just quantity:
- A 60-line README with architecture diagrams and clear setup > 150-line README with only changelog
- Evidence of standards (consistent naming, clear patterns) matters more than config files
- Consider project complexity: a microservice needs less docs than a monorepo
- When in doubt between categories, choose the lower maturity level
Workflow Selection in Practice
Step 1: Analyze the Project
Execute your analysis:
1. Search for AGENTS.md files using file_search 2. Search for constitution/guideline files 3. Read and analyze README for depth and quality 4. Count meaningful lines (exclude fluff)
Step 2: Determine Project State
Based on your findings, classify the project:
- MATURE → AGENTS.md exists
- ESTABLISHED → Constitution files + substantial README
- PARTIAL → Basic README only
- VANILLA → Minimal/no documentation
Step 3: Select and Load Workflow
Map your classification to the appropriate workflow:
- MATURE → mature-project.md
- ESTABLISHED → established-project.md
- PARTIAL → partial-documentation.md
- VANILLA → vanilla-project.md
Use read_file to load the selected workflow and follow its instructions.
Step 4: Execute Workflow
Use read_file to load and follow the appropriate workflow:
- Read the selected workflow markdown file
- Follow all phase instructions systematically
- Generate all required outputs
- Validate completeness
Hybrid Scenarios
Scenario: Large README but No Constitution
Classification: Partial → Established boundary
Solution: Start with partial-documentation.md but use constitution creation steps from vanilla-project.md
Scenario: AGENTS.md Exists but Outdated
Classification: Mature, but needs refresh
Solution: Use mature-project.md with validation focus, then apply updates from established-project.md if major gaps found
Scenario: Multiple Constitution Files but Inconsistent
Classification: Established with quality issues
Solution: Use established-project.md with extra synthesis step to resolve conflicts
Workflow Customization
Each workflow can be customized based on:
1. Project Size
- Small (< 10 files): Accelerated workflow
- Medium (10-100 files): Standard workflow
- Large (> 100 files): Deep analysis workflow
2. Tech Stack Complexity
- Simple (single language/framework): Basic analysis
- Moderate (frontend + backend): Standard analysis
- Complex (microservices, polyglot): Extended analysis
3. Domain Complexity
- General purpose: Standard patterns
- Domain-specific (fintech, healthcare): Industry-specific considerations
Verification
After selecting and executing a workflow, verify:
- [ ] All phases completed successfully
- [ ] Documentation generated at expected locations
- [ ] AGENTS.md files are comprehensive and accurate
- [ ] No existing documentation was overwritten
- [ ] Generated content aligns with existing standards
Fallback Strategy
If automatic detection is ambiguous:
1. Ask User: Present detected state and ask for confirmation 2. Conservative Approach: Default to established-project.md (most respectful of existing work) 3. Modular Execution: Run phases individually and skip completed sections
Next Steps
Once workflow is selected, proceed to: 1. Read the selected workflow file 2. Execute phases in sequence 3. Generate/update documentation 4. Validate outputs 5. Provide summary to user
Workflow: Established Project (Good Docs, Existing Constitutions)
Use this workflow when: The project has comprehensive documentation, constitution files (.cursorrules, CONTRIBUTING.md, etc.), but no AGENTS.md files.
Estimated Time: 10-15 minutes
Output Files:
.onboard/overview.md.onboard/architecture.md.onboard/design_suggestions.md.onboard/guardrail_suggestions.md.onboard/agent_constitution.md./AGENTS.md(synthesized from existing constitutions)./[frontend-dir]/AGENTS.md(if applicable)./[backend-dir]/AGENTS.md(if applicable)
---
Pre-Phase: Constitution & Documentation Discovery
Identify All Constitution Files
Use file_search to find existing project guidelines:
**/.cursorrules**/CONTRIBUTING.md**/.github/CONSTITUTION.md**/CODE_OF_CONDUCT.md**/STYLE_GUIDE.md**/ARCHITECTURE.md- Linter configs:
.eslintrc*,.prettierrc*,.pylintrc, etc.
Read Existing Constitutions
For each found file:
- Read complete content
- Extract coding principles
- Note branching strategy
- Identify code review process
- Extract testing requirements
- Note security guidelines
Inventory Existing Documentation
- README.md quality and completeness
- docs/ directory structure
- API documentation (Swagger, OpenAPI, etc.)
- Architecture decision records (ADRs)
- Wiki or Confluence links
---
Phase 1: Project Discovery (Quick Validation)
1.1 Validate Existing Documentation
- Read existing docs
- Cross-reference with actual code
- Note areas where docs are accurate
- Flag outdated information
1.2 Minimal Gap Filling
Only focus on:
- Undocumented features (rare in this scenario)
- Recent changes not yet documented
- Internal details not in user-facing docs
Generate: .onboard/overview.md with:
- Reference existing comprehensive docs
- Validation notes (docs accuracy: high/medium)
- Minor gaps filled
- Note: "Project has comprehensive existing documentation"
---
Phase 2: Architecture Analysis (Complement Existing)
2.1 Review Existing Architecture Docs
- Read ARCHITECTURE.md if exists
- Review ADRs if present
- Check diagrams in docs/
2.2 Validate and Enhance
- Confirm architecture claims with code
- Add runtime/operational details often missing from docs
- Note recent architectural changes
Generate: .onboard/architecture.md with:
- Reference to existing architecture docs
- Runtime behavior analysis
- Operational considerations
- Validation notes
- Updates to existing docs (if needed)
---
Phase 3: Design Assessment (Limited Scope)
3.1 Quick Quality Check
Since project is established:
- Focus on incremental improvements
- Check for recent technical debt
- Validate patterns against documented standards
3.2 Consistency Check
- Are documented patterns actually followed?
- Any drift from established guidelines?
Generate: .onboard/design_suggestions.md with:
- Minimal findings (project likely healthy)
- Consistency validation
- Minor improvement opportunities
- Suggestions for documentation updates
---
Phase 4: Quality & Automation Review (Validation Focus)
4.1 Validate Existing Testing
Established projects likely have tests:
- Assess coverage (likely good)
- Check test documentation
- Suggest minor improvements
4.2 Validate CI/CD
Likely has mature CI/CD:
- Assess pipeline completeness
- Suggest optimizations
- Check for best practices
Generate: .onboard/guardrail_suggestions.md with:
- Current state validation (likely mature)
- Minor enhancement suggestions
- Best practice recommendations
- Optimization opportunities
---
Phase 5: Agent Constitution Synthesis (Non-Destructive)
CRITICAL: This is the main value for established projects - synthesizing existing guidelines into AI-agent-friendly format.
5.1 Comprehensive Constitution Inventory
Read and analyze ALL found constitution files:
Found constitutions:
- CONTRIBUTING.md: [git workflow, PR process]
- .cursorrules: [VSCode/Cursor specific rules]
- CODE_OF_CONDUCT.md: [community guidelines]
- docs/STYLE_GUIDE.md: [coding style]
- .github/pull_request_template.md: [PR requirements]5.2 Extract Rules and Principles
From CONTRIBUTING.md, extract:
- Branch naming conventions
- Commit message format
- PR requirements
- Code review process
From .cursorrules, extract:
- Editor-specific conventions
- Code formatting rules
- Linting requirements
From STYLE_GUIDE.md, extract:
- Language-specific conventions
- Naming conventions
- Code organization rules
From code analysis, extract:
- Actual patterns in use
- Testing patterns
- Error handling approaches
5.3 Synthesize Root AGENTS.md (Non-Destructive)
Strategy: Merge, don't replace
# AI Agent Constitution - [Project Name]
> This file synthesizes project guidelines for AI agents.
> It respects and references existing constitution files.
> Last updated: [date]
## Existing Constitution Files
This project has the following guideline documents:
- [CONTRIBUTING.md](./CONTRIBUTING.md) - Contribution workflow and PR process
- [.cursorrules](./.cursorrules) - Editor-specific rules
- [docs/STYLE_GUIDE.md](./docs/STYLE_GUIDE.md) - Coding style guide
**Important**: Always review these files before making changes.
## Project Context
[Standard context from template]
## Coding Principles
### From STYLE_GUIDE.md
- [Extract and summarize key points]
- See full details: [STYLE_GUIDE.md](./docs/STYLE_GUIDE.md)
### From .cursorrules
- [Extract and summarize]
### Observed in Codebase
- [Additional patterns found in code]
## Git & Development Workflow
### From CONTRIBUTING.md
[Extract branch strategy, commit conventions, PR guidelines]
**For full contribution guidelines, see**: [CONTRIBUTING.md](./CONTRIBUTING.md)
## Testing Requirements
### From CONTRIBUTING.md and Code Analysis
- [Test requirements]
- [Coverage expectations]
## For AI Agents: Validation Checklist
When making changes, ensure:
- [ ] Follows CONTRIBUTING.md guidelines
- [ ] Adheres to STYLE_GUIDE.md conventions
- [ ] Respects .cursorrules specifications
- [ ] [Additional AI-specific checks]
---
## AI Agent Enhancements
### Additional Context for AI Agents
[Information not in existing docs but useful for AI agents:]
- Common patterns observed in codebase
- Error handling conventions
- Performance considerations
- Security patterns
### Quick Reference
[Synthesized cheat sheet from all constitution files]5.4 Add Merge Comment
Add at the top of generated AGENTS.md:
<!--
This AGENTS.md synthesizes existing project guidelines for AI agent consumption.
It does not replace existing documentation but complements it.
Existing constitution files remain the source of truth.
Generated by brownfield-onboarding on [date]
-->5.5 Generate Frontend/Backend AGENTS.md (if applicable)
Same synthesis approach for subdirectories:
- Extract relevant guidelines from main constitutions
- Add directory-specific patterns
- Reference root AGENTS.md and main constitutions
5.6 No Modification of Existing Files
CRITICAL RULE: Do NOT modify existing constitution files:
- ❌ Don't edit CONTRIBUTING.md
- ❌ Don't edit .cursorrules
- ❌ Don't edit CODE_OF_CONDUCT.md
- ✅ Only create new AGENTS.md files
- ✅ Reference existing files extensively
Generate:
./AGENTS.md(new, synthesized)./[frontend]/AGENTS.md(new, if applicable)./[backend]/AGENTS.md(new, if applicable).onboard/agent_constitution.md(synthesis summary)
---
Completion Summary
✅ Brownfield onboarding complete for established project!
📊 Project Status:
- Documentation: Comprehensive ✓
- Constitutions: Established ✓
- Testing: Mature ✓
- CI/CD: Mature ✓
📄 Existing Constitution Files Found:
✓ CONTRIBUTING.md
✓ .cursorrules
✓ docs/STYLE_GUIDE.md
[... list all found ...]
📝 Generated Documentation:
✓ .onboard/overview.md (Validation and minor gaps filled)
✓ .onboard/architecture.md (Validation and enhancements)
✓ .onboard/design_suggestions.md (Minor improvements)
✓ .onboard/guardrail_suggestions.md (Optimization suggestions)
✓ .onboard/agent_constitution.md (Synthesis summary)
🤖 Generated AI Agent Constitutions (NEW):
✓ ./AGENTS.md (Synthesized from existing guidelines)
[✓ ./[frontend]/AGENTS.md (Synthesized with frontend focus)]
[✓ ./[backend]/AGENTS.md (Synthesized with backend focus)]
✨ What Makes This Special:
The AGENTS.md files synthesize your existing comprehensive guidelines into
an AI-agent-friendly format WITHOUT modifying your established documentation.
All existing constitution files remain the authoritative source.
📋 Recommended Next Steps:
1. Review AGENTS.md for accuracy against existing constitutions
2. Share AGENTS.md with team for feedback
3. Consider minor updates to existing docs based on findings in:
- .onboard/design_suggestions.md
- .onboard/guardrail_suggestions.md
4. Add AGENTS.md to version control
5. Update onboarding docs to reference AGENTS.md for AI developers---
Special Considerations for Established Projects
Respect Existing Authority
- Existing constitutions are authoritative
- AGENTS.md is derivative, not replacement
- Always reference source documents
Resolve Conflicts
If existing documents conflict:
### Conflicting Guidelines
Note: CONTRIBUTING.md specifies 2-space indentation, while .cursorrules
specifies 4-space. Code analysis shows 4-space is actually used.
**Recommendation**: Update CONTRIBUTING.md to match actual practice,
or enforce 2-space via automated formatting.
**For AI Agents**: Use 4-space (actual practice) until conflict resolved.Add Value, Don't Duplicate
AGENTS.md should add:
- Quick reference/cheat sheet format
- AI-specific validation checklists
- Synthesized view across multiple docs
- Observed patterns not formally documented
Identify Documentation Drift
Note when docs don't match code:
### Documentation vs. Reality
STYLE_GUIDE.md suggests feature-based organization, but codebase
uses layer-based organization. Consider updating guide or refactoring code.---
Validation Checklist
- [ ] All constitution files identified and read
- [ ] No existing constitution files modified
- [ ] AGENTS.md synthesizes (not replaces) existing docs
- [ ] All guidelines cross-referenced to source docs
- [ ] Conflicts identified and documented
- [ ] Documentation drift noted
- [ ] AI-specific enhancements added
- [ ] References back to authoritative sources included
- [ ] Team review recommended in summary
Workflow: Mature Project (AGENTS.md Already Exists)
Use this workflow when: The project already has AGENTS.md files and comprehensive documentation. Focus is on validation, updates, and gap filling.
Estimated Time: 5-10 minutes
Output Files:
.onboard/overview.md.onboard/architecture.md.onboard/design_suggestions.md.onboard/guardrail_suggestions.md.onboard/agent_constitution.md./AGENTS.md(ENHANCED, not replaced)- Other AGENTS.md files (ENHANCED if found)
---
Pre-Phase: Existing AGENTS.md Analysis
Locate All AGENTS.md Files
Search comprehensively:
file_search:**/AGENTS.md
Expected locations:
./AGENTS.md(root)./frontend/AGENTS.md./backend/AGENTS.md- Other subdirectories
Read and Analyze Each AGENTS.md
For each file, assess: 1. Completeness: Does it cover all new features? 2. Accuracy: Does it match current codebase? 3. Currency: Is it up-to-date with recent changes? 4. Gaps: What's missing?
Document Current State
Found AGENTS.md files:
- ./AGENTS.md (last updated: [date], completeness: [high/medium/low])
- ./frontend/AGENTS.md (last updated: [date], completeness: [high/medium/low])
- ./backend/AGENTS.md (last updated: [date], completeness: [high/medium/low])
Initial Assessment:
- Outdated sections: [list]
- Missing information: [list]
- Excellent sections: [list]---
Phase 1: Project Discovery (Validation Mode)
1.1 Validate AGENTS.md Project Context
Check if current AGENTS.md accurately describes:
- Project purpose (has it evolved?)
- Current status (version, phase)
- Team size (if mentioned)
- Project health metrics
1.2 Identify New Features
Since last AGENTS.md update, identify:
- New features added
- Removed features
- Architectural changes
- New dependencies
Generate: .onboard/overview.md with:
- Validation results
- Identified changes since last update
- New features to document
- Accuracy assessment
---
Phase 2: Architecture Analysis (Change Detection)
2.1 Compare AGENTS.md Architecture to Reality
Check for drift:
- Stack changes (dependency updates, new tools)
- Architecture evolution
- Pattern changes
- Technology upgrades
2.2 Identify Undocumented Changes
- New architectural decisions
- Refactored patterns
- Infrastructure changes
Generate: .onboard/architecture.md with:
- Current state validation
- Changes detected
- Drift analysis
- Update recommendations
---
Phase 3: Design Assessment (Evolution Check)
3.1 Pattern Evolution
- Are documented patterns still followed?
- Have new patterns emerged?
- Any pattern deprecation?
3.2 Constitution Compliance
- Does code follow AGENTS.md guidelines?
- Where has practice diverged?
Generate: .onboard/design_suggestions.md with:
- Compliance assessment
- Pattern evolution notes
- Where to update AGENTS.md
- Where to update code
---
Phase 4: Quality & Automation Review (Maturity Check)
4.1 Validate Against AGENTS.md Claims
If AGENTS.md mentions:
- Test coverage: Verify actual coverage
- CI/CD maturity: Validate pipeline status
- Quality gates: Confirm they exist
4.2 Identify Improvements
Even mature projects can improve:
- New testing approaches
- CI/CD optimizations
- Emerging best practices
Generate: .onboard/guardrail_suggestions.md with:
- Claim validation results
- Incremental improvements
- Best practice updates
---
Phase 5: Agent Constitution Enhancement (Non-Destructive Updates)
CRITICAL: Do NOT replace existing AGENTS.md. Only enhance.
5.1 Enhancement Strategy
Enhancement Approach:
1. Preserve ALL existing content
2. Mark outdated sections with updates
3. Add missing sections
4. Append new information
5. Use comments to mark enhancements5.2 Section-by-Section Enhancement
For each AGENTS.md file:
Update Project Context Section
<!-- BEGIN: brownfield-onboarding enhancement [date] -->
## Project Context (UPDATED)
### Purpose
[Original content preserved]
[Add updates if purpose evolved]
### Current Status
- **Phase**: Production (UPDATED from Beta)
- **Version**: 3.0.0 (UPDATED from 2.3.0)
- **Last Updated**: [new date]
<!-- END: brownfield-onboarding enhancement -->Add Missing Sections
If sections missing from template but valuable:
<!-- BEGIN: brownfield-onboarding addition [date] -->
## Performance Guidelines
[Content from established patterns in code]
<!-- END: brownfield-onboarding addition -->Update Outdated Information
## Dependencies & External Services
### API Integrations
- Payment API: Stripe ~~v2~~ → **v3** (UPDATED)
- Email Service: SendGrid v3 (unchanged)
- ~~Analytics: Google Analytics~~ (REMOVED)
- **Analytics: PostHog** (NEW - added [date])Preserve Working Content
## Coding Principles
✅ The following sections are current and accurate:
- Code Style
- ~~Code Organization~~ (see updates below)
- Error Handling
- Testing Requirements5.3 Enhancement Documentation
At the top of each AGENTS.md, add:
<!--
Last validated: [date] by brownfield-onboarding
Last enhanced: [date] by brownfield-onboarding
Changes made:
- Updated project version from 2.3.0 to 3.0.0
- Added Performance Guidelines section
- Updated dependency versions
- Removed deprecated Google Analytics reference
- Added new PostHog integration
-->5.4 Create Change Summary
In .onboard/agent_constitution.md:
# Agent Constitution Enhancement Summary
## Existing AGENTS.md Files
### ./AGENTS.md
- **Status**: Enhanced (not replaced)
- **Last Updated Originally**: [original date]
- **Enhanced On**: [today]
- **Changes Made**:
- ✓ Updated project version (2.3.0 → 3.0.0)
- ✓ Added Performance Guidelines section
- ✓ Updated dependencies list
- ✓ Refreshed project health metrics
- **Preserved**: 95% of original content
- **Added**: 3 new sections
- **Updated**: 5 sections
### ./frontend/AGENTS.md
[Similar breakdown]
### ./backend/AGENTS.md
[Similar breakdown]
## Accuracy Validation
### Accurate and Current Sections
- [List sections that needed no updates]
### Updated Sections
- [List what was updated and why]
### Newly Added Sections
- [List what was added and rationale]
## Recommended Manual Reviews
Some changes need team input:
1. **Project Status**: Confirm if phase is still "Production" or moving to "Maintenance"
2. **Team Size**: Update "5 developers" to current count
3. **New Feature Documentation**: Review newly discovered features for accuracy5.5 Suggest Direct Edits (Don't Auto-Apply)
For subjective or team-decision items:
## Suggested Manual Edits to AGENTS.md
The following changes are recommended but not auto-applied:
### ./AGENTS.md Line 45
Current: "Test coverage target: 80%"
Actual coverage: 65%
Suggestion: Either update target to 70% or plan to increase coverage
### ./backend/AGENTS.md Lines 112-118
Current: Documents MongoDB as database
Actual: Project migrated to PostgreSQL (found in code)
Suggestion: Update database section completely
[Create these as enhancement comments in the file but don't apply]---
Completion Summary
✅ Brownfield onboarding complete for mature project!
📊 Project Status:
- Documentation: Comprehensive ✓
- AGENTS.md: Exists ✓ → ENHANCED ✓
- Updated: [X] sections, Added: [Y] sections
- Validation: [Z]% accurate
📄 Existing AGENTS.md Files Analyzed:
✓ ./AGENTS.md (enhanced with [N] updates)
✓ ./frontend/AGENTS.md (enhanced with [N] updates)
✓ ./backend/AGENTS.md (enhanced with [N] updates)
📝 Generated Documentation:
✓ .onboard/overview.md (Validation and changes)
✓ .onboard/architecture.md (Current state vs. documented)
✓ .onboard/design_suggestions.md (Compliance and improvements)
✓ .onboard/guardrail_suggestions.md (Maturity validation)
✓ .onboard/agent_constitution.md (Enhancement summary with change log)
🔄 Constitution Enhancements:
✓ Updated outdated information
✓ Added missing sections
✓ Preserved all working content
✓ Marked all changes with dates
✓ Created change log
✨ Enhancement Highlights:
- [List key updates made]
- [List key additions]
- [List sections validated as current]
⚠️ Manual Review Needed:
[List items that need team decision]
📋 Recommended Next Steps:
1. Review enhanced AGENTS.md files for accuracy
2. Address manual review items (see .onboard/agent_constitution.md)
3. Update team on AGENTS.md changes
4. Set reminder to re-validate in 3-6 months
5. Consider adding AGENTS.md update process to contribution workflow---
Special Considerations for Mature Projects
Trust but Verify
- Existing AGENTS.md was created with care
- Assume good faith but validate
- Don't assume outdated without evidence
Minimize Disruption
- Mark changes clearly
- Preserve original structure
- Don't reorganize sections
- Keep same tone and style
Identify Drift Patterns
## Drift Analysis
Common drift patterns found:
1. **Version Lag**: Documented versions older than actual
2. **Feature Additions**: 3 new features undocumented
3. **Deprecated Practices**: 2 patterns no longer used but still documented
4. **Dependency Updates**: 5 dependencies upgraded
**Root Cause**: AGENTS.md not updated since [date] ([X] months ago)
**Recommendation**: Add AGENTS.md review to quarterly maintenance checklistSuggest Maintenance Process
In .onboard/agent_constitution.md, add:
## Recommended AGENTS.md Maintenance Process
To keep AGENTS.md current:
1. **Quarterly Reviews** (every 3 months)
- Validate project context
- Check version numbers
- Review dependencies
- Update metrics
2. **Post-Release Updates** (after major releases)
- Document new features
- Update architecture if changed
- Add new patterns
3. **Automated Reminders**
- Add to release checklist
- Include in quarterly retro
- Assign constitution owner
4. **Version Control**
- Track AGENTS.md changes in git
- Require review for AGENTS.md updates
- Document change rationale in commits---
Validation Checklist
- [ ] All existing AGENTS.md files located and read
- [ ] NO content removed or replaced (only enhanced)
- [ ] All changes marked with dates and comments
- [ ] Change log created
- [ ] Accuracy validation performed
- [ ] Drift patterns identified
- [ ] Manual review items documented
- [ ] Maintenance process suggested
- [ ] Enhancement summary clear and actionable
- [ ] Original tone and structure preserved
Workflow: Partial Documentation Project
Use this workflow when: The project has a README with basic info, but no constitution files or comprehensive documentation.
Estimated Time: 10-20 minutes
Output Files:
.onboard/overview.md.onboard/architecture.md.onboard/design_suggestions.md.onboard/guardrail_suggestions.md.onboard/agent_constitution.md./AGENTS.md(root)./[frontend-dir]/AGENTS.md(if applicable)./[backend-dir]/AGENTS.md(if applicable)
---
Pre-Phase: Existing Documentation Review
Review README
- Read existing README completely
- Extract documented information:
- Project purpose and description
- Installation instructions
- Usage examples
- Known features
- Dependencies
- Note gaps and undocumented areas
Check for Other Docs
- Look for docs/ or documentation/ directory
- Check for inline code comments
- Look for API documentation (Swagger, JSDoc, etc.)
---
Phase 1: Project Discovery (Build Upon Existing)
1.1 Leverage README Content
- Use documented project purpose (don't re-discover)
- Reference documented features
- Build on documented entry points
1.2 Fill Documentation Gaps
Focus analysis on what's NOT documented:
- Undocumented directories and their purposes
- Features not mentioned in README
- Internal architecture not explained
- Hidden entry points or tools
1.3 Enhance Feature Understanding
- Expand on briefly mentioned features
- Discover features not in README
- Map feature locations in codebase
Generate: .onboard/overview.md with:
- Reference to existing README
- Enhanced feature descriptions
- Newly discovered features
- Complete folder structure (not just README's view)
- Note: "Built upon README.md documentation"
---
Phase 2: Architecture Analysis (Complement Existing Docs)
2.1 Extract Stack Info from README
- Use documented technology stack
- Note documented infrastructure
- Build on dependency lists
2.2 Deep Dive on Undocumented Aspects
Focus on what README doesn't cover:
- Architectural patterns and principles
- Internal module organization
- Data flow and request handling
- Design pattern usage
- Configuration management details
2.3 Validate README Information
- Cross-check README claims with actual code
- Note discrepancies
- Update outdated information
Generate: .onboard/architecture.md with:
- Technology stack (from README + code verification)
- Architecture patterns (discovered)
- Design patterns in use
- Data flow (not typically in README)
- Note areas where code differs from README
---
Phase 3: Design Assessment (Focused Analysis)
3.1 Pattern Identification
Since some structure is documented:
- Verify documented patterns are followed
- Identify undocumented patterns
- Check for consistency
3.2 Gap Analysis
- What's documented but not implemented well?
- What's implemented well but not documented?
3.3 Technical Debt
Look for:
- Code smells
- Outdated practices
- Areas flagged in TODOs/FIXMEs
Generate: .onboard/design_suggestions.md with:
- Pattern consistency assessment
- Documentation vs. reality gaps
- Improvement suggestions
- Update recommendations for README
---
Phase 4: Quality & Automation Review
4.1 Testing Status
- Check if README mentions testing
- Find and analyze existing tests
- Identify test coverage gaps
- Assess test quality
4.2 CI/CD Status
- Check if README documents CI/CD
- Analyze existing pipelines
- Identify automation gaps
Generate: .onboard/guardrail_suggestions.md with:
- Current testing state (likely incomplete)
- Testing gaps to fill
- CI/CD improvements
- Link to any existing testing docs
---
Phase 5: Agent Constitution Creation (New, but Context-Aware)
5.1 Check for Informal Guidelines
Even without formal constitutions, look for:
- Code comment conventions
- PR templates
- Issue templates
- CONTRIBUTING.md (even if brief)
- Code review guidelines in issues/PRs
5.2 Extract Coding Patterns
- README might mention code style
- Look for linter configurations
- Analyze actual code consistency
5.3 Generate Root AGENTS.md
Use template: ../../templates/root-agents-template.md
Populate with:
- Project context from README
- Discovered coding patterns
- Linter configurations found
- README's documented workflows
- Mark: "Generated based on README and code analysis"
5.4 Generate Subdirectory AGENTS.md
If frontend/backend split exists:
- Use template: ../../templates/frontend-agents-template.md
- Use template: ../../templates/backend-agents-template.md
- Extract UI/API patterns from code
5.5 Reference README
In each AGENTS.md, add:
## Additional Resources
- See [README.md](../README.md) for installation and usage
- Architecture details: see .onboard/architecture.mdGenerate:
./AGENTS.md./[frontend]/AGENTS.md(if applicable)./[backend]/AGENTS.md(if applicable).onboard/agent_constitution.md
---
Completion Summary
✅ Brownfield onboarding complete for partially-documented project!
📊 Project Analysis:
- Project: [name from README]
- Type: [from README]
- Documentation: Partial → Enhanced
- README Status: Good (enhanced with detailed analysis)
📝 Generated Documentation:
✓ .onboard/overview.md (Enhanced from README with detailed structure)
✓ .onboard/architecture.md (Detailed architecture analysis)
✓ .onboard/design_suggestions.md (Improvement opportunities)
✓ .onboard/guardrail_suggestions.md (Testing and CI/CD gaps)
✓ .onboard/agent_constitution.md (Constitution summary)
🤖 Generated AI Agent Constitutions:
✓ ./AGENTS.md (Project constitution with README context)
[✓ ./[frontend]/AGENTS.md (Frontend guidelines)]
[✓ ./[backend]/AGENTS.md (Backend guidelines)]
📋 README Enhancement Suggestions:
[List specific sections that could be added to README based on findings]
📋 Recommended Next Steps:
1. Review generated constitutions
2. Consider enhancing README with:
- Architecture overview (link to .onboard/architecture.md)
- Contributing guidelines (reference AGENTS.md)
- Testing instructions (from guardrail_suggestions.md)
3. Implement testing improvements
4. Add constitution files to version control---
Special Considerations for Partial Documentation
Leverage Existing Documentation
- Don't duplicate what's in README
- Reference and build upon it
- Create complementary documentation
Identify Staleness
- Check if README describes current state
- Note areas where code has evolved beyond docs
- Flag outdated instructions
Suggest README Improvements
In .onboard/overview.md, include section:
## Suggested README Enhancements
Based on code analysis, consider adding:
- [ ] Architecture overview section
- [ ] Contributing guidelines
- [ ] Testing instructions
- [ ] API documentation referenceRespect Existing Conventions
If README shows conventions (even informal):
- Follow same terminology
- Match existing structure
- Maintain consistency
---
Validation Checklist
- [ ] README reviewed and referenced
- [ ] Undocumented areas identified and analyzed
- [ ] Documentation gaps filled (not duplicated)
- [ ] README claims validated against code
- [ ] AGENTS.md complements (doesn't duplicate) README
- [ ] README enhancement suggestions provided
- [ ] All phases completed
- [ ] Generated docs reference existing docs appropriately
Workflow: Vanilla Project (Minimal/No Documentation)
Use this workflow when: The project has no README or minimal documentation, no constitution files, and appears undocumented.
Estimated Time: 15-25 minutes
Output Files:
.onboard/overview.md.onboard/architecture.md.onboard/design_suggestions.md.onboard/guardrail_suggestions.md.onboard/agent_constitution.md./AGENTS.md(root)./[frontend-dir]/AGENTS.md(if applicable)./[backend-dir]/AGENTS.md(if applicable)
---
Phase 1: Project Discovery (Deep Analysis Required)
Since documentation is minimal, perform exhaustive code analysis:
1.1 Root Structure Analysis
- List all directories at root level
- Identify project type from structure and files
- Check for config files (package.json, requirements.txt, pom.xml, go.mod, Cargo.toml)
- Infer project name from directory name or config files
1.2 Technology Detection
- Scan for programming languages (file extensions)
- Identify frameworks from imports and configs
- List all dependencies from package managers
- Detect build tools and task runners
1.3 Entry Points Discovery
Use aggressive search for main files:
file_search:**/main.*,**/index.*,**/app.*,**/server.*,**/__init__.pygrep_search:if __name__ == "__main__",def main(,app.listen,http.createServer
1.4 Feature Extraction
Since no docs exist, must discover features from code:
semantic_search: "main functionality", "core feature", "business logic", "user flow"grep_search:route|@app|@router|@RestController|@Controller|endpoint- Analyze file/directory names for domain concepts
1.5 Project Purpose Inference
Deduce purpose from:
- Directory structure (e-commerce, blog, API, tool, library?)
- Domain models and entities
- API endpoints or CLI commands
- UI pages or components
Generate: .onboard/overview.md with:
- Inferred project purpose and type
- Complete folder structure analysis
- All discovered features with evidence
- Technology stack summary
- Entry points
- "⚠️ Note: Documentation was minimal - this analysis is based on code inspection"
---
Phase 2: Architecture Analysis (Bottom-Up Discovery)
Must discover architecture from code patterns:
2.1 Technology Stack (Comprehensive)
- List all dependencies with versions and purposes
- Identify database from imports or configs
- Detect caching, queuing, external services
- Note frontend/backend split if applicable
2.2 Architecture Pattern Recognition
Look for evidence of patterns:
- Check directory structure (controllers/, services/, repositories/, models/)
grep_searchfor pattern indicators:class.*Controller,class.*Service,class.*Repositorysemantic_search: "architecture pattern", "design pattern", "layered"
2.3 Data Flow Mapping
Trace request/data flow:
- Entry point → routing → business logic → data access
- Identify middleware/interceptors
- Map error handling approach
Generate: .onboard/architecture.md with:
- Complete technology stack
- Discovered architectural style
- Design patterns in use
- Data flow diagrams
- Configuration approach
- "⚠️ Note: Architecture inferred from code structure - may benefit from team validation"
---
Phase 3: Design Assessment (Discovery + Analysis)
3.1 Pattern Discovery
Identify actual patterns used:
- Common code structures
- Repeated idioms
- Standard approaches
3.2 Anti-Pattern Detection
Look for code smells:
semantic_search: "TODO", "FIXME", "HACK", "XXX", "deprecated"- Large files (>500 lines)
- Deep nesting
- Circular dependencies
3.3 Dependency Analysis
- Check for outdated dependencies
- Security vulnerabilities
- Unused dependencies
Generate: .onboard/design_suggestions.md with:
- Discovered patterns (positives first)
- Code smells and technical debt
- Refactoring opportunities
- Dependency updates needed
- Prioritized action items
---
Phase 4: Quality & Automation Review
4.1 Testing Analysis
Check for any tests:
file_search:**/test_*,**/*.test.*,**/*.spec.*,**/tests/**- If tests exist: analyze coverage and quality
- If no tests: Propose complete testing strategy
4.2 CI/CD Detection
file_search:.github/workflows/*,.gitlab-ci.yml,Jenkinsfile,.circleci/*- If CI exists: evaluate maturity
- If no CI: Propose complete CI/CD setup
Generate: .onboard/guardrail_suggestions.md with:
- Testing gaps (likely extensive)
- Complete testing setup recommendations
- CI/CD recommendations from scratch
- Quality gates to implement
---
Phase 5: Agent Constitution Creation (From Scratch)
Since no existing guidelines, create comprehensive AGENTS.md from discovered patterns:
5.1 No Existing Constitution Check
Confirm no constitution files exist using file_search:
**/AGENTS.md**/.cursorrules**/CONTRIBUTING.md**/.github/CONSTITUTION.md- Linter configs
5.2 Extract Coding Patterns
From code analysis, identify:
- Naming conventions actually used
- Code organization approach
- Error handling patterns observed
- Common practices
5.3 Infer Coding Standards
- Check for linter configs (.eslintrc, .pylintrc, etc.)
- Analyze code formatting consistency
- Identify testing patterns if tests exist
5.4 Generate Root AGENTS.md
Use template: ../../templates/root-agents-template.md
Populate with:
- Discovered project context
- Inferred coding standards
- Observed patterns ("Pattern seen in codebase")
- Recommended practices (filling gaps)
- Mark status as "Generated from code analysis"
5.5 Generate Frontend AGENTS.md (if applicable)
If frontend directory exists:
- Extract design tokens from theme files
- Analyze component patterns
- Document UI library usage
- Use template: ../../templates/frontend-agents-template.md
5.6 Generate Backend AGENTS.md (if applicable)
If backend directory exists:
- Document API patterns found
- Extract data handling approaches
- Note security measures observed
- Use template: ../../templates/backend-agents-template.md
5.7 Add Disclaimer
Add to each generated AGENTS.md:
> ⚠️ **Note**: This constitution was auto-generated from code analysis.
> Please review and update with team-specific conventions.
> Generated on: [date]Generate:
./AGENTS.md./[frontend]/AGENTS.md(if applicable)./[backend]/AGENTS.md(if applicable).onboard/agent_constitution.md(summary)
---
Completion Summary
Provide comprehensive summary:
✅ Brownfield onboarding complete for vanilla project!
📊 Project Analysis:
- Project Type: [inferred type]
- Languages: [list]
- Architecture: [discovered pattern]
- Documentation Status: Minimal (now documented)
📝 Generated Documentation:
✓ .onboard/overview.md (Project structure and features - CODE-INFERRED)
✓ .onboard/architecture.md (Technical stack and architecture - CODE-INFERRED)
✓ .onboard/design_suggestions.md (Design improvements)
✓ .onboard/guardrail_suggestions.md (Testing and CI/CD recommendations)
✓ .onboard/agent_constitution.md (Constitution generation summary)
🤖 Generated AI Agent Constitutions:
✓ ./AGENTS.md (Root project constitution - from code analysis)
[✓ ./[frontend]/AGENTS.md (Frontend guidelines - from code analysis)]
[✓ ./[backend]/AGENTS.md (Backend guidelines - from code analysis)]
⚠️ Important: This project had minimal documentation. The generated documents
are based on code analysis and may need validation by the development team.
📋 Recommended Next Steps:
1. Review generated documentation for accuracy
2. Add project purpose/domain context to overview.md
3. Validate architecture interpretation in architecture.md
4. Review and customize AGENTS.md with team-specific conventions
5. Begin implementing testing strategy from guardrail_suggestions.md---
Special Considerations for Vanilla Projects
Challenge: Ambiguous Project Purpose
- Analyze domain models for clues
- Check for external API integrations
- Look at UI/endpoint names
- If still unclear: Document as "Purpose unclear - requires team input"
Challenge: Unknown Architecture
- Don't force-fit into known patterns
- Describe as observed
- Note if architecture seems ad-hoc or inconsistent
Challenge: No Coding Standards
- Document actual practices seen
- Suggest standards based on language/framework best practices
- Mark as recommendations, not rules
Challenge: Legacy or Mixed Patterns
- Document multiple patterns if project is inconsistent
- Note technical debt and evolution path
- Don't criticize - be descriptive and constructive
---
Validation Checklist
- [ ] Project purpose identified or marked as needing clarification
- [ ] All major directories analyzed and documented
- [ ] Entry points discovered and documented
- [ ] Technology stack completely identified
- [ ] Architectural style described (even if ad-hoc)
- [ ] All phases completed
- [ ] AGENTS.md files are comprehensive
- [ ] Disclaimers added about code-inferred content
- [ ] Next steps provided to user
Backend Agent Constitution - [Project Name]
Guidelines for AI agents working on backend code.
Last updated: [Date]
Backend Context
Technology Stack
- Language: [Python/Node.js/Rust/Go/etc.]
- Framework: [Django/Express/Axum/FastAPI/etc.]
- Version: [version]
- Database: [PostgreSQL/MongoDB/MySQL/etc.]
- ORM: [SQLAlchemy/Prisma/TypeORM/etc.]
- Cache: [Redis/Memcached/None]
- Message Queue: [RabbitMQ/Kafka/SQS/None]
Project Structure
[Backend directory structure]Backend Coding Principles
API Design
1. Endpoint Naming
- [RESTful conventions or other pattern]
- [Versioning strategy]
- [Naming conventions]
2. Request/Response Format
{
"success": true,
"data": {},
"error": null,
"meta": {}
}3. HTTP Status Codes
- 200: [usage]
- 201: [usage]
- 400: [usage]
- 401: [usage]
- 403: [usage]
- 404: [usage]
- 500: [usage]
4. Authentication/Authorization
- [Auth mechanism: JWT/Session/OAuth]
- [How to protect endpoints]
- [Permission checking pattern]
Data Handling
1. Database Access
- [ORM usage patterns]
- [Transaction handling]
- [Query optimization guidelines]
2. Data Validation
- [Validation library and approach]
- [Where validation happens]
- [Error message format]
3. Data Serialization
- [Serializer/DTO pattern]
- [Handling nested data]
- [Sensitive data filtering]
Business Logic
1. Service Layer
- [Location and organization]
- [Service responsibilities]
- [Dependency injection pattern]
2. Domain Models
- [Model organization]
- [Model methods vs. service methods]
- [Model relationships]
3. Error Handling
# Example error handling pattern
try:
# business logic
except SpecificError as e:
# handle and logPatterns to Follow
- ✅ [Pattern 1]: [Description]
- ✅ [Pattern 2]: [Description]
- ✅ [Pattern 3]: [Description]
Anti-Patterns to Avoid
- ❌ [Anti-pattern 1]: [Why and alternative]
- ❌ [Anti-pattern 2]: [Why and alternative]
Security Guidelines
- Input Validation: [Always validate and sanitize input]
- SQL Injection Prevention: [Use parameterized queries]
- XSS Prevention: [Output encoding requirements]
- CSRF Protection: [Token/header requirements]
- Secrets Management: [Environment variables, vault usage]
- Rate Limiting: [Implementation approach]
Performance Guidelines
- N+1 Query Prevention: [Eager loading patterns]
- Caching Strategy: [What to cache and when]
- Async Operations: [When to use async/background jobs]
- Database Indexing: [Index strategy and guidelines]
Testing Guidelines
- Unit Tests: [Service and model testing]
- Integration Tests: [API endpoint testing]
- Database Tests: [Test database usage]
- Mocking Strategy: [External service mocking]
Logging & Monitoring
Logging Standards
# Example logging pattern
logger.info("User action", extra={
"user_id": user.id,
"action": "login",
"ip": request.ip
})What to Log
- Authentication events
- Error conditions
- Performance metrics
- Business-critical operations
What NOT to Log
- Passwords or secrets
- PII (unless anonymized)
- Full request/response bodies (unless debugging)
For AI Agents: Backend Validation
When making backend changes:
- [ ] API follows project conventions
- [ ] Input validation implemented
- [ ] Error handling comprehensive
- [ ] Tests cover happy + error paths
- [ ] No SQL injection vulnerabilities
- [ ] Secrets not hardcoded
- [ ] Logging added for important operations
- [ ] Database migrations created if needed
Frontend Agent Constitution - [Project Name]
Guidelines for AI agents working on frontend code.
Last updated: [Date]
Frontend Context
Technology Stack
- Framework: [React/Vue/Angular/Svelte/etc.]
- Version: [version]
- Build Tool: [Vite/Webpack/etc.]
- State Management: [Redux/Zustand/Pinia/etc.]
- Styling: [CSS-in-JS/Tailwind/Sass/CSS Modules]
- UI Library: [Material-UI/Ant Design/Chakra/Custom]
Project Structure
[Frontend directory structure]UI/UX Principles
Design System
Color Palette
/* Primary colors */
--primary: [color]
--secondary: [color]
--accent: [color]
/* Semantic colors */
--success: [color]
--warning: [color]
--error: [color]
--info: [color]Typography
- Heading: [font and scale]
- Body: [font and scale]
- Monospace: [font]
Spacing Scale
[spacing system: 4px, 8px, 16px, etc.]
Breakpoints
--mobile: [breakpoint]
--tablet: [breakpoint]
--desktop: [breakpoint]Component Patterns
1. Component Structure
- [Preferred component organization]
- [Props naming conventions]
- [File naming pattern]
2. State Management
- [When to use local vs. global state]
- [State update patterns]
- [Side effects handling]
3. Styling Approach
- [How to style components]
- [Theme usage]
- [Responsive design approach]
Accessibility Standards
- Keyboard Navigation: [requirements]
- Screen Readers: [ARIA label requirements]
- Color Contrast: [minimum contrast ratios]
- Focus Management: [focus ring styling and management]
- Semantic HTML: [required semantic elements]
Frontend Coding Principles
Component Guidelines
1. Component Composition
- Prefer composition over inheritance
- [Pattern specifics for this project]
2. Props Validation
- [PropTypes/TypeScript requirements]
- [Required vs. optional props conventions]
3. Hook Usage (if React)
- [Custom hooks location and naming]
- [Effect dependencies best practices]
4. Performance
- [Memoization strategy]
- [Code splitting approach]
- [Image optimization requirements]
Patterns to Follow
- ✅ [Pattern 1]: [Description]
- ✅ [Pattern 2]: [Description]
- ✅ [Pattern 3]: [Description]
Anti-Patterns to Avoid
- ❌ [Anti-pattern 1]: [Why and alternative]
- ❌ [Anti-pattern 2]: [Why and alternative]
API Integration
API Client
[How API calls are made in this project]
Error Handling
[How to handle API errors in UI]
Loading States
[Pattern for loading indicators]
Data Fetching
[Fetch on mount, lazy loading, pagination approaches]
Testing Guidelines
- Unit Tests: [expectations for component testing]
- Integration Tests: [what to test]
- E2E Tests: [critical user flows]
- Testing Library: [Jest, Testing Library, Cypress, etc.]
For AI Agents: Frontend Validation
When making frontend changes:
- [ ] Components are accessible (keyboard + screen reader)
- [ ] Responsive across breakpoints
- [ ] Follows design system tokens
- [ ] Loading and error states handled
- [ ] Tests added/updated
- [ ] No console errors or warnings
- [ ] Performance implications considered
AI Agent Constitution - [Project Name]
This file provides context, principles, and guidelines for AI agents working on this project.
Last updated: [Date]
Project Context
Purpose
[Brief description of what this project does and why it exists]
Current Status
- Phase: [Development/Beta/Production/Maintenance]
- Version: [current version]
- Team Size: [if known]
- Active Development: [Yes/No - describe activity level]
Project Health
- Test Coverage: [percentage or "Unknown"]
- CI/CD: [Mature/Basic/None]
- Documentation: [Comprehensive/Adequate/Sparse]
- Technical Debt: [Low/Medium/High]
Architecture Quick Reference
Stack Overview
- Language(s): [languages]
- Framework(s): [frameworks]
- Database: [database]
- Deployment: [platform]
Architecture Pattern
[Monolith/Microservices/Serverless/etc.]
Key Directories
[Directory structure with brief descriptions]Coding Principles
General Guidelines
1. Code Style
- [Language-specific style guide reference]
- [Linter/formatter configuration: ESLint, Black, etc.]
- [Indentation, naming conventions]
2. Code Organization
- [Feature-based vs. layer-based organization]
- [Module boundaries and dependencies]
- [Import/export conventions]
3. Error Handling
- [Project's error handling strategy]
- [Logging conventions]
- [Error types and classification]
4. Testing Requirements
- [Required test coverage for new code]
- [Test file organization]
- [Mocking and fixtures approach]
5. Documentation Standards
- [Code comment expectations]
- [Function/method documentation format]
- [README requirements for new modules]
Patterns to Follow
- ✅ [Pattern 1]: [Description and when to use]
- ✅ [Pattern 2]: [Description and when to use]
- ✅ [Pattern 3]: [Description and when to use]
Anti-Patterns to Avoid
- ❌ [Anti-pattern 1]: [Why to avoid and alternative]
- ❌ [Anti-pattern 2]: [Why to avoid and alternative]
- ❌ [Anti-pattern 3]: [Why to avoid and alternative]
Dependencies & External Services
Adding New Dependencies
- [Process for adding dependencies]
- [Approval requirements]
- [Security/license considerations]
External Services
- [List of integrated services]
- [API key management approach]
- [Service-specific guidelines]
Git & Development Workflow
Branch Strategy
[Description of branching model: GitFlow, trunk-based, etc.]
Commit Conventions
[Commit message format and requirements]
PR/MR Guidelines
- [Review process]
- [Required checks]
- [Merge strategy]
Common Tasks
Running the Project
[Commands to install, run, test]Running Tests
[Test commands]Building for Production
[Build commands]Known Issues & Gotchas
- [Issue 1]: [Description and workaround]
- [Issue 2]: [Description and workaround]
Additional Resources
- [Link to detailed architecture docs]
- [Link to API documentation]
- [Link to design system]
- [Link to team wiki or confluence]
---
For AI Agents: Validation Checklist
When making changes, ensure:
- [ ] Code follows style guide and passes linting
- [ ] Tests are added/updated and passing
- [ ] Documentation is updated if needed
- [ ] No new security vulnerabilities introduced
- [ ] Dependencies are properly declared
- [ ] Commit message follows conventions
- [ ] Changes align with architectural patterns