diff --git a/AMBIENT_TECHNIQUES_INVENTORY.md b/AMBIENT_TECHNIQUES_INVENTORY.md deleted file mode 100644 index e3c34b5..0000000 --- a/AMBIENT_TECHNIQUES_INVENTORY.md +++ /dev/null @@ -1,812 +0,0 @@ -# Ambient Code Techniques Inventory - -**Repository**: `github.com/ambient-code/reference` -**Purpose**: Reference implementation demonstrating Ambient Code concepts for maximum agent productivity and issue-to-PR automation - -This document catalogs all techniques, patterns, and automation discovered across Ambient Code repositories, with a focus on productivity enhancements and agent performance optimization. - ---- - -## Table of Contents - -1. [Issue-to-PR Automation (CBA)](#issue-to-pr-automation-cba) -2. [GitHub Actions Workflows](#github-actions-workflows) -3. [Agent Orchestration Patterns](#agent-orchestration-patterns) -4. [Workflow Templates](#workflow-templates) -5. [CLAUDE.md Patterns](#claudemd-patterns) -6. [Code Quality Automation](#code-quality-automation) -7. [Security Patterns](#security-patterns) -8. [Productivity Multipliers](#productivity-multipliers) - ---- - -## Issue-to-PR Automation (CBA) - -### Overview - -**CBA** is a background agent that automatically converts GitHub issues into pull requests. This is the **core productivity multiplier** - team members can trigger automated fixes without direct access to Claude Code. - -### How It Works - -```mermaid -graph LR - A[Create Issue] --> B[Add Label] - B --> C[GHA Triggers] - C --> D[CBA Executes] - D --> E[Create PR] - E --> F[Review & Merge] -```text - -### Trigger Mechanisms - -1. **Labels** (Primary): - - `cba:auto-fix` - Low-risk formatting/linting fixes - - `cba:refactor` - Medium-risk refactoring - - `cba:test-coverage` - Add missing tests - -2. **Comments** (Alternative): - - `/cba execute` - Execute proposal in issue - - `@cba` - Mention CBA to trigger - -### Workflow Implementation - -**File**: `.github/workflows/cba-issue-handler.yml` - -**Key Features**: - -- ✅ Prevents duplicate PRs (checks for existing PRs) -- ✅ Creates sanitized branch names: `cba/issue-{number}-{sanitized-title}` -- ✅ Handles race conditions (PR closed during execution) -- ✅ Security: Validates branch names, prevents injection -- ✅ Retry logic with exponential backoff for API calls -- ✅ Comprehensive error handling and notifications - -**Security Practices**: - -- All user input passed via environment variables (no command injection) -- Branch name validation with regex: `^[a-zA-Z0-9/_.-]+$` -- Issue number validation (numeric only) -- Minimal token permissions: `contents:write`, `issues:write`, `pull-requests:write` - -### Issue Format Requirements - -For CBA to work effectively, structure issues like this: - -```markdown -## Problem -[Describe what needs to be fixed] - -## Files -File: `path/to/file.go` -File: `path/to/another.py` - -## Instructions -[Step-by-step instructions for CBA] - -## Success Criteria -- [ ] All linters pass -- [ ] All tests pass -- [ ] Follows CLAUDE.md standards -```text - -**Key Fields**: - -- `File:` or `Path:` - CBA extracts file paths automatically -- `Instructions:` or `Task:` - Main instructions section -- Success criteria checklist - -### Risk-Based Automation Policies - -**Configuration**: `.claude/cba-config.yml` - -| Risk Level | Actions | Auto-Merge | Examples | -|------------|---------|------------|----------| -| **Low** | Auto-fix, create PR | No (requires review) | Formatting, linting | -| **Medium** | Create PR with proposal | No | Refactoring, test additions | -| **High** | Report only, no PR | N/A | Breaking changes, security issues | - -### CBA Categories - -**Auto-Fix (Low Risk)**: - -- Code formatting (gofmt, black, prettier) -- Linting violations -- Unused import removal -- Documentation formatting - -**Refactoring (Medium Risk)**: - -- Breaking large files into modules -- Extracting repeated patterns -- Replacing `context.TODO()` with proper context -- Improving error handling - -**Test Coverage (Medium Risk)**: - -- Adding missing unit tests -- Contract tests for API endpoints -- Edge case coverage -- Improving test coverage percentage - -### Safety Guardrails - -```yaml -safety: - max_auto_prs_per_day: 5 - max_files_per_auto_pr: 10 - require_review_for_auto_merge: true - never_push_to_main: true - always_create_branch: true -```text - -### Monitoring & Reporting - -- Daily: Check recent commits, run linting, verify CI status -- Weekly: Full codebase health check, test coverage analysis -- Monthly: Architecture review, technical debt assessment - ---- - - - -## GitHub Actions Workflows - -### Core Workflows - -#### 1. CBA Issue Handler (`cba-issue-handler.yml`) - -**Purpose**: Convert issues to PRs via CBA agent - -**Triggers**: - -- Issue labeled: `cba:auto-fix`, `cba:refactor`, `cba:test-coverage` -- Issue comment: `/cba execute` or `@cba` - -**Steps**: - -1. Extract issue details (files, instructions) -2. Create CBA agent prompt -3. Check for existing PR (prevent duplicates) -4. Create/checkout feature branch -5. Execute Claude Code CLI -6. Check for changes -7. Push branch and create/update PR -8. Report results - -**Key Implementation Details**: - -- Uses `envsubst` for safe variable substitution -- Validates all inputs (issue numbers, branch names) -- Handles race conditions (PR closed during execution) -- Retry logic for transient API failures -- Comprehensive error reporting - -#### 2. Claude Code Review (`claude-code-review.yml`) - -**Purpose**: Automated code reviews on pull requests - -**Triggers**: - -- `@claude` mention in PR comments -- Pull request review comments - -**Features**: - -- Minimizes old review comments automatically -- Supports fork PRs -- Comprehensive review covering: - - Code quality & best practices - - Security vulnerabilities - - Performance bottlenecks - - Testing adequacy - - Architecture & design - - Documentation - -**Review Format**: - -```markdown -# Claude Code Review - -## Summary -[Brief overview] - -## Issues by Severity -### 🚫 Blocker Issues -### 🔴 Critical Issues -### 🟡 Major Issues -### 🔵 Minor Issues - -## Positive Highlights -## Recommendations -```text - -#### 3. Components Build & Deploy (`components-build-deploy.yml`) - -**Purpose**: Build and deploy platform components - -**Features**: - -- Change detection (only builds modified components) -- Multi-platform builds (linux/amd64, linux/arm64) -- Conditional registry push (main branch only) -- Component-specific tests - -**Change Detection**: - -- Frontend: `components/frontend/**` -- Backend: `components/backend/**` -- Operator: `components/operator/**` -- Runner: `components/runners/**` - -#### 4. E2E Tests (`e2e.yml`) - -**Purpose**: End-to-end testing in Kind cluster - -**Features**: - -- Full stack deployment -- Cypress UI testing -- Authentication testing -- Ingress routing validation - -#### 5. Dependabot Auto-Merge (`dependabot-auto-merge.yml`) - -**Purpose**: Automatically merge safe dependency updates - -**Behavior**: - -- Auto-merges patch/minor updates after CI passes -- Requires manual review for major updates -- Only for Dependabot PRs - -#### 6. CBA Dependency Sync (`cba-dependency-sync.yml`) - -**Purpose**: Daily sync of dependency versions to CBA knowledge base - -**Behavior**: - -- Runs daily at scheduled time -- Updates CBA's understanding of current dependencies -- Helps CBA make better decisions about updates - -#### 7. CBA Auto Review (`cba-auto-review.yml`) - -**Purpose**: Automatic code reviews on PRs (complement to manual @claude reviews) - -**Behavior**: - -- Runs on all PRs automatically -- Provides initial review before human review -- Uses same review format as manual reviews - -### Workflow Best Practices - -**Security**: - -- ✅ Use environment variables for user input -- ✅ Validate all inputs (regex, type checking) -- ✅ Minimal permissions per workflow -- ✅ Never interpolate user input in `run:` commands - -**Reliability**: - -- ✅ Retry logic with exponential backoff -- ✅ Handle race conditions gracefully -- ✅ Comprehensive error reporting -- ✅ Timeout limits (prevent runaway jobs) - -**Monitoring**: - -- ✅ Link to workflow runs in comments -- ✅ Log all decisions for audit trail -- ✅ Report failures to issues - ---- - - - -## Agent Orchestration Patterns - -### CBA - Workflow Orchestrator - -**Role**: Single point of contact, intelligent agent coordinator - -**Capabilities**: - -- Automatically invokes appropriate specialists -- Proactive engagement (brings in experts without explicit requests) -- Adaptive complexity handling -- Complete ecosystem access - -**Specialists CBA May Engage**: - -- **Stella (Staff Engineer)** - Complex debugging, architecture -- **Neil (Test Engineer)** - Testing strategies, automation -- **Taylor (Team Member)** - Straightforward implementations -- **secure-software-braintrust** - Security assessment -- **sre-reliability-engineer** - Performance, reliability -- **Terry (Technical Writer)** - Documentation -- **Any other platform agents** as needed - -### Agent Personas - -Located in `.claude/agents/` or `workflows/agent-bullpen/`: - -**Architecture & Engineering**: - -- `archie-architect.md` - System architecture -- `stella-staff_engineer.md` - Complex technical problems -- `taylor-team_member.md` - Implementation support - -**Product & Management**: - -- `parker-product_manager.md` - Product requirements -- `olivia-product_owner.md` - Feature ownership -- `jack-delivery_owner.md` - Delivery management - -**Testing & Quality**: - -- `neil-test_engineer.md` - Test strategies -- `phoenix-pxe_specialist.md` - PXE/Infrastructure testing - -**UX & Design**: - -- `aria-ux_architect.md` - UX architecture -- `steve-ux_designer.md` - UI design -- `ryan-ux_researcher.md` - User research - -**Content & Documentation**: - -- `terry-technical_writer.md` - Technical writing -- `tessa-writing_manager.md` - Content strategy - -**Management**: - -- `dan-senior_director.md` - Strategic direction -- `emma-engineering_manager.md` - Engineering management -- `lee-team_lead.md` - Team leadership -- `sam-scrum_master.md` - Agile facilitation - -### Agent Invocation Patterns - -**Explicit Invocation**: - -```text -"Invoke Stella to analyze this architectural issue" -```text - -**Implicit (CBA Orchestration)**: - -```text -"Fix this bug" → CBA automatically engages Neil for testing, Stella for complex parts -```text - -**Multi-Agent Collaboration**: - -```text -Feature development → Parker (requirements) → Archie (architecture) → Taylor (implementation) → Neil (testing) -```text - ---- - - - -## Workflow Templates - -### Spec Kit Workflow - -**Purpose**: Specification-first feature development - -**Phases**: - -1. `/specify` - Create detailed feature specifications -2. `/plan` - Generate technical implementation plans -3. `/tasks` - Break down into actionable tasks -4. `/implement` - Execute the implementation -5. `/analyze` - Review and analyze outcomes - -**Structure**: - -```text -workflows/spec-kit/ -├── .specify/ # Workflow configuration -│ ├── scripts/ # Automation scripts -│ ├── templates/ # Document templates -│ └── memory/ # Workflow knowledge base -└── .claude/ # Claude AI configuration - ├── agents/ # Agent personas - └── commands/ # Slash commands -```text - -### Bug Fix Workflow - -**Purpose**: Systematic bug resolution - -**Phases**: - -1. `/reproduce` - Systematically reproduce bug -2. `/diagnose` - Root cause analysis -3. `/fix` - Implement fix -4. `/test` - Verify fix and create regression tests -5. `/document` - Create complete documentation - -**Artifacts Generated**: - -- `artifacts/bugfix/reports/reproduction.md` -- `artifacts/bugfix/analysis/root-cause.md` -- `artifacts/bugfix/fixes/implementation-notes.md` -- `artifacts/bugfix/tests/verification.md` -- `artifacts/bugfix/docs/` (issue-update, release-notes, changelog, etc.) - -**Agent Recommendations**: - -- Complex bugs → Stella (Staff Engineer) -- Testing → Neil (Test Engineer) -- Straightforward → Taylor (Team Member) - -### Template Workflow - -**Purpose**: Base structure for custom workflows - -**Components**: - -- Field reference documentation -- Template structure -- Example commands - ---- - - - -## CLAUDE.md Patterns - -### Memory System - Loadable Context - -**Concept**: Structured context files instead of monolithic CLAUDE.md - -**Structure**: - -```text -.claude/ -├── context/ # Task-specific context -│ ├── backend-development.md -│ ├── frontend-development.md -│ └── security-standards.md -├── patterns/ # Code patterns -│ ├── error-handling.md -│ ├── k8s-client-usage.md -│ └── react-query-usage.md -└── repomix-guide.md # Architecture view usage -```text - -**Usage Pattern**: - -```text -"Claude, load the architecture view and backend-development context, -then help me add a new endpoint" -```text - -### Architecture Decision Records (ADRs) - -**Location**: `docs/adr/` - -**Purpose**: Document WHY decisions were made - -**Format**: - -- `0001-kubernetes-native-architecture.md` -- `0002-user-token-authentication.md` -- `0003-multi-repo-support.md` -- etc. - -### Repomix Integration - -**Purpose**: Single architecture view for all tasks - -**File**: `repomix-analysis/03-architecture-only.xml` - -**Benefits**: - -- Grade 8.8/10 architecture view -- 187K tokens of context -- Single view approach (vs. 7 views) -- Consistent context across all tasks - -**Usage**: - -- Load architecture view for all architectural questions -- Reference in context files -- Guide in `.claude/repomix-guide.md` - ---- - - - -## Code Quality Automation - -### Pre-Commit Hooks - -**Configuration**: `.pre-commit-config.yaml` - -**Language-Specific**: - -- **Python**: black, isort, ruff -- **JavaScript**: prettier, eslint -- **Go**: gofmt, golangci-lint - -**Installation**: - -```bash -pre-commit install -```text - -### Automated Linting - -**Workflows**: - -- `go-lint.yml` - Go formatting, vetting, linting -- `frontend-lint.yml` - ESLint, TypeScript checking - -**Behavior**: - -- Runs on all PRs -- Blocks merge if failures -- Auto-fix suggestions via CBA - -### Test Coverage - -**Requirements**: - -- Minimum thresholds per component -- Coverage reports in CI -- CBA can add missing tests (`cba:test-coverage`) - -### Code Review Automation - -**Two-Tier System**: - -1. **CBA Auto Review** - Automatic on all PRs -2. **Claude Manual Review** - On-demand via `@claude` - -**Review Focus Areas**: - -- Code quality & best practices -- Security vulnerabilities -- Performance bottlenecks -- Testing adequacy -- Architecture & design -- Documentation - ---- - - - -## Security Patterns - -### Token Handling - -**Pattern**: Never log tokens, always redact - -```go -// ✅ Good -log.Printf("Processing request with token (len=%d)", len(token)) - -// ❌ Bad -log.Printf("Token: %s", token) -```text - -### Input Validation - -**Pattern**: Validate all user inputs - -```yaml -# ✅ Good - Validate before use -if ! [[ "$ISSUE_NUMBER" =~ ^[0-9]+$ ]]; then - echo "Error: Invalid issue number" - exit 1 -fi - -# ❌ Bad - Use directly -echo "$ISSUE_NUMBER" -```text - -### Branch Name Sanitization - -**Pattern**: Sanitize and validate branch names - -```bash -SANITIZED_TITLE=$(echo "$ISSUE_TITLE" \ - | tr '[:upper:]' '[:lower:]' \ - | sed 's/[^a-z0-9-]/-/g' \ - | sed 's/--*/-/g' \ - | sed 's/^-//' \ - | sed 's/-$//' \ - | cut -c1-50) - -# Validate -if ! [[ "$BRANCH_NAME" =~ ^[a-zA-Z0-9/_.-]+$ ]]; then - echo "Error: Invalid branch name" - exit 1 -fi -```text - -### RBAC Enforcement - -**Pattern**: Always check permissions before operations - -```go -// Check permissions -ssar := &authv1.SelfSubjectAccessReview{ - Spec: authv1.SelfSubjectAccessReviewSpec{ - ResourceAttributes: &authv1.ResourceAttributes{ - Group: "vteam.ambient-code", - Resource: "agenticsessions", - Verb: "list", - Namespace: project, - }, - }, -} -res, err := reqK8s.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, ssar, v1.CreateOptions{}) -if err != nil || !res.Status.Allowed { - c.JSON(http.StatusForbidden, gin.H{"error": "Unauthorized"}) - return -} -```text - ---- - - - -## Productivity Multipliers - -### 1. Issue-to-PR Automation - -**Impact**: 10x productivity for routine tasks - -**Use Cases**: - -- Formatting fixes → Instant PR -- Linting violations → Automated fix -- Test coverage gaps → Auto-generated tests -- Documentation updates → Quick PRs - -**Time Savings**: - -- Before: 15-30 min per task (create branch, fix, test, PR) -- After: 2-5 min (create issue, review PR) - -### 2. Automated Code Reviews - -**Impact**: Catch issues before human review - -**Benefits**: - -- Consistent review standards -- 24/7 availability -- Catches security issues early -- Reduces reviewer fatigue - -### 3. Agent Orchestration - -**Impact**: Right expertise at the right time - -**Benefits**: - -- No need to manually select agents -- Automatic escalation for complex issues -- Multi-agent collaboration -- Consistent quality - -### 4. Workflow Templates - -**Impact**: Standardized processes - -**Benefits**: - -- Consistent output quality -- Faster onboarding -- Reusable patterns -- Best practices built-in - -### 5. Context-Aware Development - -**Impact**: Faster context loading - -**Benefits**: - -- Load only relevant context -- Faster response times -- Better accuracy -- Reduced token usage - -### 6. Automated Dependency Management - -**Impact**: Always up-to-date dependencies - -**Benefits**: - -- Security patches applied automatically -- No manual dependency updates -- CBA stays current with versions -- Reduced technical debt - ---- - -## Implementation Checklist - -For `github.com/ambient-code/reference`: - -### Phase 1: Core Infrastructure - -- [ ] Initialize git repository -- [ ] Set up GitHub repository (`ambient-code/reference`) -- [ ] Create basic README.md -- [ ] Add CLAUDE.md with memory system structure - -### Phase 2: CBA Automation - -- [ ] Create `.github/workflows/cba-issue-handler.yml` -- [ ] Create `.claude/cba-config.yml` -- [ ] Create issue templates: - - [ ] `.github/ISSUE_TEMPLATE/cba-auto-fix.yml` - - [ ] `.github/ISSUE_TEMPLATE/cba-refactor.yml` - - [ ] `.github/ISSUE_TEMPLATE/cba-test-coverage.yml` -- [ ] Test CBA workflow with sample issue - -### Phase 3: Code Quality Automation - -- [ ] Create `.pre-commit-config.yaml` -- [ ] Create `.github/workflows/go-lint.yml` (if Go) -- [ ] Create `.github/workflows/frontend-lint.yml` (if JS/TS) -- [ ] Set up test coverage reporting - -### Phase 4: Code Review Automation - -- [ ] Create `.github/workflows/claude-code-review.yml` -- [ ] Create `.github/workflows/cba-auto-review.yml` -- [ ] Test review workflows - -### Phase 5: Documentation - -- [ ] Create `docs/adr/` directory -- [ ] Create `.claude/context/` directory with context files -- [ ] Create `.claude/patterns/` directory with pattern files -- [ ] Document all workflows in `.github/workflows/README.md` - -### Phase 6: Workflow Templates - -- [ ] Create `workflows/bugfix/` template -- [ ] Create `workflows/spec-kit/` template (optional) -- [ ] Document workflow usage - -### Phase 7: Agent Personas - -- [ ] Create `.claude/agents/` directory -- [ ] Add key agent personas (Stella, Neil, Taylor, etc.) -- [ ] Document agent usage patterns - ---- - -## Key Takeaways - -1. **Issue-to-PR is the killer feature** - CBA automation provides 10x productivity gains -2. **Security is built-in** - All workflows follow security best practices -3. **Agent orchestration scales** - CBA automatically brings in the right expertise -4. **Context matters** - Structured context files beat monolithic CLAUDE.md -5. **Automation everywhere** - From linting to reviews to dependency updates -6. **Workflows standardize** - Templates ensure consistency and quality -7. **Monitoring is essential** - Track everything, learn from failures - ---- - -## Next Steps - -1. **Review this inventory** - Understand all techniques -2. **Prioritize features** - Which ones provide most value? -3. **Plan implementation** - Use checklist above -4. **Start with CBA** - Issue-to-PR automation is highest ROI -5. **Iterate** - Add more automation as needed - ---- - -**Repository Goal**: Demonstrate how these techniques enable teams to achieve maximum productivity with AI agents, solving real problems like issue-to-PR automation and agent performance optimization. diff --git a/CLAUDE.md b/CLAUDE.md index 5721d66..7f6b60c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,7 +56,7 @@ This is a **GitHub template repository** demonstrating AI-assisted development b ### Working Application Demo For a **working FastAPI application** demonstrating these patterns in practice, see: -**[demo-fastapi](https://github.com/jeremyeder/demo-fastapi)** - Toy application showing CBA patterns in action +**[demo-fastapi](https://github.com/ambient-code/demo-fastapi)** - Minimal application showing CBA patterns in action --- diff --git a/IMPLEMENTATION_CONTEXT.md b/IMPLEMENTATION_CONTEXT.md deleted file mode 100644 index 1a7b9fa..0000000 --- a/IMPLEMENTATION_CONTEXT.md +++ /dev/null @@ -1,267 +0,0 @@ -# Implementation Context for Ambient Code Reference Repository - -**Version**: 1.0 -**Date**: 2025-12-17 -**Companion to**: `IMPLEMENTATION_PROMPT.md` - ---- - -## Purpose - -This file provides the contextual information needed to execute the implementation prompt effectively. Fill in the sections below before starting implementation. - ---- - -## Reference Materials - -### Available Source Files - -**Codebase Agent Sources:** - -- [ ] `ambient-code/platform/agents/amber.md` - Location: **NEED INPUT** (See question form) -- [ ] `ambient-code/agentready/.claude/agents/agentready-dev.md` - Location: **NEED INPUT** (See question form) -- [ ] `ambient-code/platform/agents/terry-technical_writer.md` - Location: **NEED INPUT** (See question form) - -**Inventories:** - -- [X] `AMBIENT_TECHNIQUES_INVENTORY.md` - Location: `/Users/jeder/repos/reference/AMBIENT_TECHNIQUES_INVENTORY.md` (exists in repo) -- [X] `FEATURES_INVENTORY.md` - Location: `/Users/jeder/repos/reference/FEATURES_INVENTORY.md` (exists in repo) - -**Example Repositories:** - -- [ ] Existing FastAPI service to reference: **NEED INPUT** (See question form - optional) -- [ ] Existing agent configuration to reference: **NEED INPUT** (See question form - optional) - ---- - -## Strategic Context - -### Primary Objective - -Create the **Ambient Code Reference Repository** - a GitHub template demonstrating -AI-assisted development best practices for Python FastAPI services using the "standalone patterns approach" -where teams can adopt features independently without requiring full implementation. -This is pure "Ambient Code" documentation with NO Red Hat branding. - -### Success Metrics - -- **NEED INPUT** - See question form - -### Timeline & Priorities - -- **NEED INPUT** - See question form - ---- - -## Technical Environment - -### Repository Details - -- **Location**: **NEED INPUT** - See question form -- **Ownership**: Ambient Code organization (assumed) -- **Visibility**: Public (template repository) - -### Technology Stack Preferences - -- **Python Version**: 3.11 minimum, 3.12 supported (per Jeremy's N and N-1 policy) -- **Container Runtime**: Podman (required) / Docker (acceptable fallback) -- **CI/CD Platforms**: - - Primary: GitHub Actions - - Secondary: GitLab CI (examples only) - - Other: None - -### Existing Patterns to Follow - -- **Error Handling**: Follow FastAPI best practices (HTTPException, proper status codes) -- **Logging Format**: JSON structured logging (Python logging with json formatter) -- **Security Scanning**: Bandit + Safety (confirmed in prompt) - ---- - -## Style & Quality References - -### Documentation Examples - -**Good Documentation (What to Emulate):** - -- **NEED INPUT** - See question form (examples of good docs in your ecosystem) - -**AI Slop (What to Avoid):** - -- Characteristics: Verbose, repetitive, generic, non-specific, overly enthusiastic -- Phrases like "let's dive in", "it's important to note", "simply", "just" -- Unnecessary pleasantries and filler -- Examples: **NEED INPUT** - See question form - -### Terry vs. Standard Writing - -**Terry Style Characteristics:** - -- Clear, accessible, jargon-free -- Explains technical concepts in plain language -- "What Just Happened?" sections after complex steps -- Troubleshooting tips included -- Assumes less prior knowledge -- Uses analogies and examples - -**Standard Style Characteristics:** - -- Technical depth assumed -- Concise, reference-oriented -- Code-focused with minimal explanation -- Assumes familiarity with patterns -- Jeremy's style: "Succinct, quickstart-focused" - -**Example Comparison:** - -- **NEED INPUT** - See question form (existing Terry vs Standard documentation pair if available) - ---- - -## Agent Execution Preferences - -### Autonomy Level - -- [X] **Semi-Autonomous** - Show plan for each major section, proceed after approval - - Rationale: Jeremy prefers proactive agents but wants visibility into major changes - - Per Jeremy's CLAUDE.md: "Think like a seasoned strategic consultant" - -### Phase Approval Points - -Required approval before: - -- [X] Creating repository structure (Week 1) -- [X] Implementing FastAPI application (Week 2) -- [X] Writing CBA agent definition (Week 3) -- [X] Generating Terry documentation versions (Week 4) -- [X] Creating CI/CD workflows (Week 5) -- [ ] Generating Mermaid diagrams (can proceed, but validate rigorously) -- [X] Final validation and testing (Week 6) - -### Error Handling Strategy - -- [X] **Fix automatically** - Attempt to resolve errors autonomously - - Rationale: Jeremy's CLAUDE.md emphasizes "complete tasks fully", "unlimited context" - - Exception: Stop for security issues or architectural decisions - ---- - -## Integration Points - -### Existing CLAUDE.md Configurations - -- **Global CLAUDE.md**: `/Users/jeder/.claude/CLAUDE.md` (Jeremy's personal config) -- **Project CLAUDE.md**: `/Users/jeder/CLAUDE.md` (Jeremy's project config) -- **New Project CLAUDE.md**: Will be created by this implementation (~400 lines) -- **Conflicts to Avoid**: None anticipated - this is a new standalone repository - -### Observability & Monitoring - -- **Current Platform**: None -- **Requirements**: **Research only** (per prompt - document in `docs/observability-research.md`) -- **Explicitly state**: "This is RESEARCH ONLY, not implemented in the reference repository" - -### Existing CI/CD Configurations - -- **GitHub Actions**: No org-level workflows to integrate (standalone template) -- **GitLab CI**: No shared templates - discrete implementation (not mirror) -- **Security Scanning**: Standard Bandit + Safety (no org-specific requirements) - ---- - -## Constraints & Anti-Requirements - -### Must NOT Include - -- [X] Red Hat branding (confirmed in prompt) -- [X] "Amber" terminology (use "Codebase Agent" / "CBA" only) -- [X] Sequenced adoption path (standalone patterns approach only) -- [X] VictoriaMetrics (per Jeremy's CLAUDE.md) -- [X] Time estimates (per Jeremy's CLAUDE.md: "never include time estimates unless explicitly asked") -- [X] AI slop phrases ("let's dive in", "simply", "just", etc.) -- [X] Line length enforcement (per Jeremy's CLAUDE.md: "never enforce line length limits") -- [X] Actual ADR content (scaffolding/template only) -- [X] Implemented observability (research document only) -- [X] Mermaid syntax errors (must validate before commit) -- [X] Security overrotation (light touch only) - -### Budget Constraints - -- **Agent Execution**: No specific concerns - use appropriate models -- **CI/CD Minutes**: Standard GitHub free tier limits (2000 min/month) -- **Third-party Services**: Use free tiers (Codecov free tier, Safety free tier) - ---- - -## Validation Expectations - -### Pre-Submission Checklist - -Before considering implementation complete, verify: - -**Technical:** - -- [ ] `./scripts/setup.sh` completes in < 10 minutes -- [ ] `uvicorn app.main:app --reload` starts successfully -- [ ] All CRUD endpoints work via curl/Postman -- [ ] `pytest` achieves 80%+ coverage -- [ ] Container builds and runs successfully - -**Code Quality:** - -- [ ] All linters pass (black, isort, ruff) -- [ ] All GitHub Actions workflows pass -- [ ] Security scans complete successfully -- [ ] Mermaid diagrams validate successfully - -**Documentation:** - -- [ ] All 8 documentation files exist (4 pairs) -- [ ] Comparison webpage displays correctly -- [ ] No AI slop detected (human review) -- [ ] Terry versions clearly more accessible than standard - -**Standalone Patterns:** - -- [ ] Features are independent (can adopt individually) -- [ ] No prescribed sequence of adoption -- [ ] Clear "what's included" section in README - ---- - -## Open Questions - -*These questions will be answered via the question form:* - -1. **CBA Naming**: "Codebase Agent" is verbose - is "CBA" acceptable in all contexts? -2. **Mermaid Validation**: Install `mermaid-cli` globally or in dev dependencies? -3. **E2E Tests**: Should E2E test outline include mock GitHub API, or document manual testing only? -4. **Asciinema**: Required for v1.0 or optional for later enhancement? -5. **GitLab CI Detail Level**: How detailed should the discrete implementation be vs. minimal example? -6. **Repository Location**: Where should the new repository be created? (GitHub URL or local path) -7. **Timeline/Deadlines**: Are there specific deadlines or priority phases? -8. **Success Metrics**: How will we measure success of this reference repository? - ---- - -## Implementation Notes - -*Agent should update this section during implementation with key decisions:* - -### Decisions Made - -- [DATE] [DECISION]: [Rationale] - -### Blockers Encountered - -- [DATE] [BLOCKER]: [Resolution or workaround] - -### Deviations from Prompt - -- [DATE] [DEVIATION]: [Why necessary] - ---- - -## End of Implementation Context - -Fill in the sections above, then provide both `IMPLEMENTATION_PROMPT.md` and this context file to the implementing agent. diff --git a/IMPLEMENTATION_PROMPT.md b/IMPLEMENTATION_PROMPT.md deleted file mode 100644 index 3c62dfd..0000000 --- a/IMPLEMENTATION_PROMPT.md +++ /dev/null @@ -1,636 +0,0 @@ -# Ambient Code Reference Repository - Complete Implementation Prompt - -**Version**: 2.0 -**Date**: 2025-12-17 -**Type**: Cold-Start Implementation Guide - ---- - -## Mission - -Create the **Ambient Code Reference Repository** - a GitHub template demonstrating AI-assisted development best practices using the "standalone patterns approach" where teams can adopt features independently. - -**Critical**: No Red Hat branding. This is pure "Ambient Code" documentation. - ---- - -## Core Requirements - -### Repository Identity - -- **Name**: Ambient Code Reference Repository -- **Type**: GitHub template repository ("Use this template" button) -- **Audience**: Both AI agents and human developers -- **Philosophy**: Standalone patterns approach - features work standalone, not sequenced -- **Platform**: GitHub only - -### Technology Stack - -- **Application**: FastAPI microservice (Python 3.11+) -- **Agent**: "Codebase Agent" (CBA) - **NOT "Amber"** -- **Testing**: pytest with 80%+ coverage goal -- **Linting**: black (no line length), isort, ruff -- **CI/CD**: GitHub Actions -- **Container**: Podman-compatible Containerfile - -### Documentation Strategy - -- **Style**: Quickstart-focused, succinct, NO AI slop -- **Format**: GitHub-flavored markdown -- **Mermaid diagrams**: Rigorously validated (user notes diagrams always have errors) -- **ADR scaffolding**: Template only, NO actual content - ---- - -## Repository Structure (Complete) - -```text -ambient-code-reference/ -├── .github/ -│ ├── workflows/ -│ │ ├── ci.yml # Main CI pipeline -│ │ ├── security.yml # Security scanning -│ │ ├── cba-e2e.yml # CBA E2E tests -│ │ └── docs-validation.yml # Mermaid + markdown checks -│ ├── ISSUE_TEMPLATE/ -│ │ ├── bug_report.yml -│ │ └── feature_request.yml -│ ├── PULL_REQUEST_TEMPLATE.md -│ └── dependabot.yml -├── .claude/ -│ ├── agents/ -│ │ └── codebase-agent.md # "CBA" agent (NOT "Amber") -│ ├── commands/ -│ │ ├── quickstart.md # /quickstart -│ │ └── question-form.md # /formgen -│ ├── context/ # Modular memory system -│ │ ├── architecture.md -│ │ ├── security-standards.md -│ │ └── testing-patterns.md -│ ├── skills/ -│ │ └── question-form-generator/ # Custom skill example -│ └── settings.local.json -├── app/ # FastAPI microservice -│ ├── api/ -│ │ ├── __init__.py -│ │ ├── health.py # /health endpoint -│ │ └── v1/ -│ │ ├── __init__.py -│ │ └── items.py # Example resource -│ ├── core/ -│ │ ├── __init__.py -│ │ ├── config.py # Settings (Pydantic) -│ │ ├── security.py # Auth/validation -│ │ └── logging.py # Structured logging -│ ├── models/ -│ │ ├── __init__.py -│ │ └── item.py # Pydantic models -│ ├── services/ -│ │ ├── __init__.py -│ │ └── item_service.py -│ ├── __init__.py -│ └── main.py # Application entry point -├── tests/ -│ ├── unit/ -│ │ ├── __init__.py -│ │ └── test_items.py -│ ├── integration/ -│ │ ├── __init__.py -│ │ └── test_api.py -│ └── e2e/ -│ ├── __init__.py -│ └── test_cba_workflow.py # CBA integration test -├── docs/ -│ ├── quickstart.md # Getting started guide -│ ├── architecture.md # System design -│ ├── tutorial.md # Step-by-step guide -│ ├── api-reference.md # Complete API docs -│ ├── adr/ # Architecture Decision Records -│ │ ├── README.md # ADR guide (blank) -│ │ └── template.md # Format example -│ ├── tutorials/ # Asciinema demos -│ │ ├── setup.cast -│ │ ├── first-feature.cast -│ │ └── README.md -│ ├── diagrams/ # Mermaid sources -│ │ ├── architecture.mmd -│ │ ├── cba-workflow.mmd -│ │ └── validate.sh # Syntax checker -│ └── observability-research.md # Agent trajectory findings -├── scripts/ -│ ├── setup.sh # One-command setup -│ ├── validate-mermaid.sh # Diagram validation -│ └── record-demo.sh # Asciinema helper -├── .gitignore -├── .python-version # Python 3.11+ -├── pyproject.toml # Project config (Poetry/UV) -├── requirements.txt # Dependencies -├── requirements-dev.txt # Dev dependencies -├── CLAUDE.md # Agent configuration -├── README.md # Main quickstart -├── CONTRIBUTING.md -├── LICENSE # MIT -└── Containerfile # Podman/Docker image -```text - ---- - -## Codebase Agent (CBA) Definition - -**CRITICAL**: Use "Codebase Agent" or "CBA" terminology - **NEVER "Amber"** - -The Codebase Agent combines features from: - -- `ambient-code/platform/agents/amber.md` -- `ambient-code/agentready/.claude/agents/agentready-dev.md` - -### Core Capabilities - -1. **Issue-to-PR Automation** - Convert well-defined issues into pull requests -2. **Code Reviews** - Provide actionable feedback on PRs -3. **Proactive Maintenance** - Dependency updates, linting fixes, documentation improvements - -### Operating Principles - -- **Safety First**: Show plan before major changes, explain reasoning, provide rollback instructions -- **High Signal, Low Noise**: Only comment when adding unique value -- **Project Standards**: Follow CLAUDE.md (black, isort, ruff, pytest, 80%+ coverage) - -### Autonomy Level - -- **Level 1 (Default)**: PR creation only - WAIT for human approval -- **Level 2 (Future)**: Auto-merge for low-risk changes (requires explicit configuration) - -### Memory System - -Modular context files in `.claude/context/`: - -- `architecture.md` - Layered architecture patterns -- `security-standards.md` - Input validation, secrets management, OWASP prevention -- `testing-patterns.md` - Arrange-Act-Assert, fixtures, mocking patterns - ---- - -## FastAPI Application Architecture - -### Layered Architecture - -```text -API Layer (FastAPI routes) - ↓ -Service Layer (Business logic) - ↓ -Model Layer (Pydantic validation) - ↓ -Core Layer (Config, security, utilities) -```text - -### Example Resource: Items - -**Models**: `app/models/item.py` - -- ItemBase, ItemCreate, ItemUpdate, Item -- Pydantic validators for sanitization and slug validation - -**Service**: `app/services/item_service.py` - -- In-memory storage (simple) -- CRUD operations with business logic -- Singleton pattern - -**API**: `app/api/v1/items.py` - -- POST /api/v1/items (create) -- GET /api/v1/items (list with pagination) -- GET /api/v1/items/{id} (get by ID) -- GET /api/v1/items/slug/{slug} (get by slug) -- PATCH /api/v1/items/{id} (update) -- DELETE /api/v1/items/{id} (delete) - -### Health Endpoints: `app/api/health.py` - -- GET /health (health check) -- GET /readiness (Kubernetes readiness) -- GET /liveness (Kubernetes liveness) - -### Security Patterns (Light Touch) - -- **Input Validation**: Pydantic models at API boundary -- **Sanitization**: `app/core/security.py` - sanitize_string(), validate_slug() -- **Secrets**: Environment variables only (.env files in .gitignore) -- **Container**: Non-root user, minimal base image - ---- - -## Documentation System - -### Documentation Pages (4 total) - -1. **quickstart.md** - - 5-minute setup guide - - Prerequisites, installation, first API call - - Links to other documentation - -2. **architecture.md** - - Layered architecture explanation - - Component responsibilities - - Common patterns and conventions - -3. **tutorial.md** - - Step-by-step guide to building first feature - - Code examples - - Best practices - -4. **api-reference.md** - - Complete API documentation - - All endpoints with request/response examples - - Error codes and handling - -### Writing Style - -- **Succinct**: No AI slop, get to the point -- **Practical**: Focus on how to use, not theory -- **Code-heavy**: Show examples, not just descriptions -- **Quickstart-focused**: Help users get running fast - ---- - -## Testing Strategy - -### Unit Tests: `tests/unit/test_item_service.py` - -- Test service layer in isolation -- Arrange-Act-Assert pattern -- Fixtures for test data -- Edge cases (duplicates, missing items, pagination) - -### Integration Tests: `tests/integration/test_api.py` - -- Test API endpoints with TestClient -- Full request/response cycle -- Error cases (404, 409, 422) -- Input validation tests - -### E2E Tests: `tests/e2e/test_cba_workflow.py` - -- **OUTLINE ONLY** (requires GitHub API credentials) -- Documents CBA workflow: - 1. Create GitHub issue - 2. Trigger CBA (via label) - 3. Wait for PR creation - 4. Verify PR contents - 5. Verify CI passes - 6. Clean up - -### Coverage Goal - -- **Minimum**: 80% overall -- **Critical paths**: 100% (auth, business logic) -- **Configuration**: Excluded - ---- - -## CI/CD Strategy - -### GitHub Actions Workflows - -**`.github/workflows/ci.yml`**: - -- Lint: black --check, isort --check, ruff check -- Test: pytest with coverage (Python 3.11 + 3.12 matrix) -- Build: podman build + health check test -- Upload coverage to Codecov - -**`.github/workflows/security.yml`**: - -- Bandit: Python static analysis -- Safety: Dependency vulnerability scanning -- Weekly schedule + on push/PR - -**`.github/workflows/docs-validation.yml`**: - -- Mermaid validation (all diagrams) -- Markdownlint -- Triggers on docs/** changes - -**`.github/workflows/cba-e2e.yml`**: - -- E2E tests for CBA workflow -- Manual workflow_dispatch only -- Requires GITHUB_TOKEN - -**`.github/dependabot.yml`**: - -- Weekly Python dependency updates -- Auto-label "dependencies" + "security" - ---- - -## Observability Research (Document Only - NOT Implemented) - -**File**: `docs/observability-research.md` - -**Content**: - -1. **Anthropic API Capabilities**: Message response structure, tool use tracking -2. **Collection Strategies**: API response logging, Anthropic Console, third-party platforms -3. **CBA-Specific Considerations**: Tool sequences, decisions, errors, performance -4. **Example Trajectory Format**: JSON structure for session flow -5. **Recommendations**: Why NOT to implement (complexity, privacy, cost) -6. **Production Guidance**: How users could implement if needed - -**EXPLICITLY STATE**: "This is RESEARCH ONLY, not implemented in the reference repository" - ---- - -## Mermaid Validation (Critical) - -**User Note**: "Mermaid diagrams always have errors" - -### Validation Script: `scripts/validate-mermaid.sh` - -- Finds all .mmd files and embedded mermaid in markdown -- Validates with `mmdc` (mermaid-cli) -- Generates error log -- Exits 1 if any diagrams invalid - -### CI Integration - -- Runs in `.github/workflows/docs-validation.yml` -- Blocks merge if diagrams invalid -- Uploads error log as artifact on failure - -### Pre-commit Hook (Optional) - -- Can be enabled for local validation -- Prevents committing broken diagrams - ---- - -## Implementation Priorities - -### Critical Files (Start Here) - -1. **`CLAUDE.md`** (HIGHEST) - - Foundation for all agent behavior - - ~400 lines based on detailed agent plan - - Development standards, architecture, security, testing - -2. **`.claude/agents/codebase-agent.md`** (CRITICAL) - - Core CBA definition - - Combines Amber + AgentReady features - - Issue-to-PR automation patterns - -3. **`scripts/validate-mermaid.sh`** (HIGH) - - Prevents broken diagrams - - CI integration required - -4. **`README.md`** (HIGH) - - Standalone patterns approach landing page - - Quickstart (< 5 minutes) - - Links to documentation - -5. **`app/main.py`** (CRITICAL) - - Working FastAPI application - - Demonstrates patterns CBA can operate on - -### Documentation Files - -6. **`docs/quickstart.md`** (CRITICAL) -7. **`docs/architecture.md`** (HIGH) -8. **`docs/tutorial.md`** (HIGH) -9. **`docs/api-reference.md`** (MEDIUM) - ---- - -## 4-Week Implementation Sequence - -### Week 1: Foundation & Application - -- [ ] Git initialization (main branch, .gitignore) -- [ ] CLAUDE.md (~400 lines) -- [ ] pyproject.toml (UV-compatible) -- [ ] requirements.txt + requirements-dev.txt -- [ ] scripts/setup.sh (one-command setup) -- [ ] README.md (standalone patterns approach) -- [ ] LICENSE (MIT) -- [ ] .python-version (3.11) -- [ ] app/core/ (config.py, security.py, logging.py) -- [ ] app/models/item.py (Pydantic models with validators) -- [ ] app/services/item_service.py (business logic) -- [ ] app/api/health.py (health endpoints) -- [ ] app/api/v1/items.py (CRUD endpoints) -- [ ] app/main.py (FastAPI entry point) -- [ ] Containerfile (Podman-compatible) - -### Week 2: Codebase Agent + Tests - -- [ ] .claude/agents/codebase-agent.md -- [ ] .claude/context/ (architecture.md, security-standards.md, testing-patterns.md) -- [ ] tests/unit/test_item_service.py -- [ ] tests/integration/test_api.py -- [ ] tests/e2e/test_cba_workflow.py (outline) -- [ ] pytest configuration - -### Week 3: Documentation - -- [ ] docs/quickstart.md -- [ ] docs/architecture.md -- [ ] docs/tutorial.md -- [ ] docs/api-reference.md -- [ ] docs/adr/ scaffolding (template only, NO content) -- [ ] Mermaid diagrams (architecture.mmd, cba-workflow.mmd) - -### Week 4: CI/CD & Polish - -- [ ] .github/workflows/ci.yml -- [ ] .github/workflows/security.yml -- [ ] .github/workflows/docs-validation.yml -- [ ] .github/dependabot.yml -- [ ] scripts/validate-mermaid.sh -- [ ] Validate all diagrams pass -- [ ] docs/observability-research.md (research ONLY) -- [ ] Asciinema tutorials (scripts/record-demo.sh, demos/) -- [ ] Final testing (`./scripts/setup.sh` → `uvicorn app.main:app --reload`) -- [ ] Polish documentation - ---- - -## Acceptance Criteria (Must Have) - -### Repository & Configuration - -- [ ] MIT License -- [ ] .gitignore (Python, Node, OS-specific, Claude Code) -- [ ] .python-version (3.11) -- [ ] pyproject.toml (UV-compatible) -- [ ] requirements.txt + requirements-dev.txt -- [ ] README.md with standalone patterns approach -- [ ] CLAUDE.md with comprehensive standards -- [ ] CONTRIBUTING.md - -### Codebase Agent (CBA) - -- [ ] `.claude/agents/codebase-agent.md` (NOT "Amber") -- [ ] Modular context files (architecture, security, testing) -- [ ] Memory system documented -- [ ] Issue-to-PR workflow defined -- [ ] Code review patterns documented - -### FastAPI Application - -- [ ] Working microservice (app/main.py) -- [ ] Layered architecture (API, Service, Model, Core) -- [ ] Health endpoints (/health, /readiness, /liveness) -- [ ] CRUD endpoints for Items resource -- [ ] Pydantic models with validation -- [ ] Security patterns (input validation, sanitization) -- [ ] Structured logging (JSON format) -- [ ] Containerfile (Podman-compatible) - -### Testing - -- [ ] Unit tests (tests/unit/) -- [ ] Integration tests (tests/integration/) -- [ ] E2E test structure (outline) -- [ ] 80%+ coverage goal documented -- [ ] pytest configuration - -### Documentation - -- [ ] docs/quickstart.md -- [ ] docs/architecture.md -- [ ] docs/tutorial.md -- [ ] docs/api-reference.md - -### CI/CD & Quality - -- [ ] .github/workflows/ci.yml (lint, test, build) -- [ ] .github/workflows/security.yml (bandit, safety) -- [ ] .github/workflows/docs-validation.yml (Mermaid + markdown) -- [ ] .github/dependabot.yml -- [ ] scripts/validate-mermaid.sh -- [ ] All Mermaid diagrams syntax-validated - -### Other Requirements - -- [ ] scripts/setup.sh (one-command setup) -- [ ] docs/adr/ scaffolding (template only, NO content) -- [ ] docs/observability-research.md (research ONLY) -- [ ] Asciinema tutorials (docs/tutorials/) -- [ ] Question-form-generator skill integrated - ---- - -## Anti-Requirements (Must NOT Have) - -- ❌ **Red Hat branding** or references (keep as "Ambient Code") -- ❌ **"Amber" terminology** (use "Codebase Agent" or "CBA" only) -- ❌ **Sequenced/linear adoption path** (standalone patterns approach only) -- ❌ **Deployment infrastructure** (development-focused) -- ❌ **AI slop** in documentation (succinct, no fluff) -- ❌ **Security overrotation** (light touch only) -- ❌ **Mermaid syntax errors** (must validate before commit) -- ❌ **Actual ADR content** (scaffolding/template only) -- ❌ **Implemented observability** (research document only) -- ❌ **Time estimates** in documentation -- ❌ **GitLab support** (GitHub only) -- ❌ **Multiple documentation versions** (single version only) - ---- - -## Validation Checklist - -### Technical Success - -- [ ] `./scripts/setup.sh` completes successfully -- [ ] `uvicorn app.main:app --reload` starts without errors -- [ ] `curl http://localhost:8000/health` returns healthy status -- [ ] All CRUD operations work via API -- [ ] `pytest` runs with 80%+ coverage -- [ ] Container builds and runs successfully - -### Code Quality - -- [ ] `black --check app/ tests/` passes -- [ ] `isort --check-only app/ tests/` passes -- [ ] `ruff check app/ tests/` passes -- [ ] All GitHub Actions workflows pass -- [ ] Security scans complete (bandit, safety) - -### Documentation - -- [ ] Mermaid validation passes (all diagrams) -- [ ] Markdownlint passes -- [ ] All docs are succinct (no AI slop) - -### Standalone Patterns - -- [ ] Features are independent (can adopt one without others) -- [ ] Clear "what's included" section in README -- [ ] No prescribed sequence of adoption - ---- - -## Reference Materials - -### Codebase Agent Sources - -- `ambient-code/platform/agents/amber.md` -- `ambient-code/agentready/.claude/agents/agentready-dev.md` - -### Existing Inventories - -- `AMBIENT_TECHNIQUES_INVENTORY.md` (already exists in repo) -- `FEATURES_INVENTORY.md` (already exists in repo) - ---- - -## Quick Reference Commands - -```bash -# Setup -./scripts/setup.sh - -# Run application -source .venv/bin/activate -uvicorn app.main:app --reload - -# Run tests -pytest - -# Run linters -black app/ tests/ -isort app/ tests/ -ruff check app/ tests/ - -# Security scans -bandit -r app/ -safety check - -# Validate Mermaid diagrams -./scripts/validate-mermaid.sh - -# Record tutorial -./scripts/record-demo.sh setup -```text - ---- - -## Success Criteria Summary - -A successful implementation will: - -1. **Run locally** in < 10 minutes from clone to running app -2. **Pass all linters** (black, isort, ruff) -3. **Pass all tests** (80%+ coverage) -4. **Validate all diagrams** (no Mermaid syntax errors) -5. **Demonstrate standalone patterns approach** (features work independently) -6. **Work as GitHub template** ("Use this template" button functional) -7. **Have succinct documentation** (no AI slop) - ---- - -## End of Implementation Prompt - -Use this document as a standalone reference to implement the Ambient Code Reference Repository from scratch. All requirements, structure, and validation criteria are included above. diff --git a/PRESENTATION-ambient-code-reference.md b/PRESENTATION-ambient-code-reference.md index 8fda29a..1c3c0a5 100644 --- a/PRESENTATION-ambient-code-reference.md +++ b/PRESENTATION-ambient-code-reference.md @@ -218,7 +218,7 @@ AI assistants struggle with: - Mixed concerns (business logic in HTTP handlers) - Implicit dependencies (global state everywhere) -### The Four-Layer Pattern - used in the [FastAPI]([https://github.com/jeremyeder/fastapi-demo](https://github.com/jeremyeder/demo-fastapi) example +### The Four-Layer Pattern - used in the [demo-fastapi](https://github.com/ambient-code/demo-fastapi) example **API Layer** (app/api/) @@ -632,7 +632,7 @@ The code examples use Python, but the patterns transfer. Layered architecture, i ```bash # Clone the reference -git clone https://github.com/jeremyeder/reference.git +git clone https://github.com/ambient-code/reference.git cd reference # Explore the patterns @@ -648,7 +648,7 @@ cd /path/to/your/project/.claude/agents/ ### See It In Action -Working FastAPI demo: +Working FastAPI demo: --- @@ -672,6 +672,6 @@ The Ambient Code Reference Repository provides: ## Resources -- Reference Repository: -- Working Demo: +- Reference Repository: +- Working Demo: - Claude Documentation: diff --git a/README.md b/README.md index b5481c1..d427932 100644 --- a/README.md +++ b/README.md @@ -1,200 +1,41 @@ -# Ambient Code Reference Repository +# Ambient Code Reference -A **documentation-only** GitHub template demonstrating AI-assisted development patterns with a **standalone patterns approach** - adopt concepts independently, no prescribed sequence. +AI-assisted development patterns. Each pattern is standalone - adopt what you need. -## Quick Start +## Patterns -```bash -# Clone this repository -git clone https://github.com/jeremyeder/reference.git -cd reference +| Problem | Pattern | +|---------|---------| +| AI gives inconsistent answers | [Codebase Agent](docs/patterns/codebase-agent.md) | +| AI misses obvious bugs | [Self-Review Reflection](docs/patterns/self-review-reflection.md) | +| PRs take forever to create | [Issue-to-PR Automation](docs/patterns/issue-to-pr.md) | +| Code reviews are bottleneck | [PR Auto-Review](docs/patterns/pr-auto-review.md) | +| Dependency updates pile up | [Dependabot Auto-Merge](docs/patterns/dependabot-auto-merge.md) | +| Stale issues accumulate | [Stale Issue Management](docs/patterns/stale-issues.md) | +| Security feels ad-hoc | [Security Patterns](docs/patterns/security-patterns.md) | +| Tests are disorganized | [Testing Patterns](docs/patterns/testing-patterns.md) | -# Install documentation tooling -uv pip install -r requirements-dev.txt +## Getting Started -# Explore the documentation -cat docs/quickstart.md +See [Quickstart](docs/quickstart.md) for pattern overview and adoption guidance. -# Validate your own Mermaid diagrams -./scripts/validate-mermaid.sh -``` - -## What's Included - -This repository provides documentation and patterns for: - -- ✅ **Codebase Agent (CBA) Patterns** - AI agent configuration for issue-to-PR automation, code reviews, and proactive maintenance -- ✅ **Architecture Patterns** - Layered architecture, component responsibilities, data flow -- ✅ **Security Patterns** - Input validation, sanitization, secrets management -- ✅ **Testing Patterns** - Unit, integration, E2E test structures -- ✅ **CI/CD Patterns** - GitHub Actions for documentation validation -- ✅ **Documentation Templates** - Quickstart, architecture, tutorials, API reference -- ✅ **Quality Automation** - Markdown linting, Mermaid diagram validation - -## Standalone Patterns - -Pick what you need. Each pattern works independently: - -| Pattern | Description | How to Adopt | -| ------- | ----------- | ------------ | -| **Codebase Agent** | AI agent configuration patterns | Copy `.claude/` structure | -| **Self-Review Reflection** | Agent reviews own work before delivery | Reference `docs/patterns/self-review-reflection.md` | -| **GHA Automation** | Issue-to-PR, PR review, auto-merge, stale issues | Reference `docs/patterns/gha-automation-patterns.md` | -| **Architecture** | Layered architecture patterns | Reference `docs/architecture.md` | -| **Security** | Security best practices | Reference `.claude/context/security-standards.md` | -| **Testing** | Test organization patterns | Reference `.claude/context/testing-patterns.md` | -| **CI/CD** | Documentation validation | Copy `.github/workflows/docs-validation.yml` | -| **ADR** | Decision record scaffolding | Copy `docs/adr/` structure | - -## Repository Structure +## Repository Contents ```text -ambient-code-reference/ -├── .claude/ # Codebase Agent patterns -│ ├── agents/ # CBA agent definition patterns -│ └── context/ # Modular memory system examples -├── docs/ # Documentation templates -│ ├── quickstart.md # 5-minute introduction -│ ├── architecture.md # Architecture patterns -│ ├── tutorial.md # Implementation guide -│ ├── api-reference.md # API design patterns -│ └── adr/ # ADR scaffolding -├── .github/workflows/ # CI/CD for documentation -└── scripts/ # Validation and setup scripts +reference/ +├── docs/ +│ ├── quickstart.md # Pattern overview and adoption path +│ └── patterns/ # Individual pattern docs +├── .claude/ # Example CBA configuration +├── PRESENTATION-ambient-code-reference.md # 9-feature overview +└── CLAUDE.md # Agent instructions for this repo ``` -## Working Application Demo - -Want to see these patterns in a working FastAPI application? - -**→ [demo-fastapi](https://github.com/jeremyeder/demo-fastapi)** - Toy application demonstrating CBA patterns in practice - -The demo repository includes: - -- Working FastAPI service with CRUD endpoints -- CBA agent configuration -- Full test suite (unit, integration, E2E) -- Container support (Podman/Docker) - -## Key Patterns - -### Agent Behavior Patterns - -How AI agents work during development: - -- **[Self-Review Reflection](docs/patterns/self-review-reflection.md)** - Agent reviews own work before presenting to humans -- **[Autonomous Quality Enforcement](docs/patterns/autonomous-quality-enforcement.md)** - Validate code before presenting -- **[Multi-Agent Code Review](docs/patterns/multi-agent-code-review.md)** - Parallel specialized reviews - -### GHA Automation Patterns - -Proactive CI/CD workflows in [`docs/patterns/gha-automation-patterns.md`](docs/patterns/gha-automation-patterns.md): - -- **Issue-to-PR Automation** - Convert issues to draft PRs automatically -- **PR Auto-Review** - AI code review on every PR -- **Dependabot Auto-Merge** - Safe auto-merge for patch updates -- **Stale Issue Management** - Cleanup inactive issues - -### Codebase Agent (CBA) - -AI agent configuration patterns in [`.claude/agents/codebase-agent.md`](.claude/agents/codebase-agent.md): - -- **Issue-to-PR Automation** - Converting well-defined issues into pull requests -- **Code Reviews** - Providing actionable feedback -- **Proactive Maintenance** - Dependency updates, linting, documentation -- **Memory System** - Modular context files for consistency - -### Architecture Patterns - -Reference implementations for: - -- **Layered Architecture** - API, Service, Model, Core layers -- **Component Responsibilities** - Clear separation of concerns -- **Security Boundaries** - Validation at API boundaries only -- **Structured Logging** - JSON format for observability - -### Testing Patterns +## Links -- **Unit Testing** - Service layer isolation patterns -- **Integration Testing** - Full request/response cycle patterns -- **E2E Testing** - CBA workflow automation patterns -- **Coverage Goals** - 80%+ enforcement strategies - -### CI/CD Patterns - -GitHub Actions patterns for: - -- **Documentation Validation** - Markdown linting, Mermaid checking -- **Link Validation** - Broken link detection -- **Automated Updates** - Dependabot configuration -- **Quality Gates** - Blocking merges on validation failures - -## Documentation - -- **[Quickstart](docs/quickstart.md)** - 5-minute introduction to AI-assisted development -- **[Patterns Index](docs/patterns/README.md)** - All workflow patterns in one place -- **[Architecture](docs/architecture.md)** - Common architecture patterns -- **[Tutorial](docs/tutorial.md)** - Step-by-step implementation guide -- **[API Reference](docs/api-reference.md)** - API design patterns - -## Using This Template - -### For Documentation Projects - -```bash -# 1. Use this template on GitHub -# 2. Clone your new repository -# 3. Install doc tooling -uv pip install -r requirements-dev.txt - -# 4. Update documentation -# Edit files in docs/ - -# 5. Validate -markdownlint docs/**/*.md --fix -./scripts/validate-mermaid.sh - -# 6. Commit and push -git add docs/ -git commit -m "docs: Update patterns" -git push -``` - -### For Development Projects - -Reference the patterns and adapt to your needs: - -1. Copy `.claude/` for Codebase Agent setup -2. Reference architecture patterns in `docs/architecture.md` -3. Copy CI/CD workflows from `.github/workflows/` -4. Adapt testing patterns from context files -5. Customize for your tech stack - -## Development - -```bash -# Lint markdown files -markdownlint docs/**/*.md README.md CLAUDE.md --fix - -# Validate Mermaid diagrams -./scripts/validate-mermaid.sh - -# Lint any code examples -black docs/examples/ -isort docs/examples/ -ruff check docs/examples/ -``` - -## Contributing - -See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. +- **Working Demo**: [demo-fastapi](https://github.com/ambient-code/demo-fastapi) +- **Presentation**: [PRESENTATION-ambient-code-reference.md](PRESENTATION-ambient-code-reference.md) ## License -MIT - See [LICENSE](LICENSE) for details. - ---- - -**Use this template**: Click "Use this template" button to create your own repository with these patterns. - -**Note**: This is a documentation-only reference repository. Patterns and examples are provided for reference and adaptation to your specific needs. +MIT - See [LICENSE](LICENSE) diff --git a/docs/api-reference.md b/docs/api-reference.md deleted file mode 100644 index bb2a317..0000000 --- a/docs/api-reference.md +++ /dev/null @@ -1,423 +0,0 @@ -# API Reference - -Complete API documentation for the Ambient Code Reference Repository. - -## Base URL - -```text -http://localhost:8000 -```text - -## Authentication - -Current version: No authentication required. - -Production: Add JWT or OAuth2 as needed. - -## Health Endpoints - -### GET /health - -Health check endpoint. - -**Response** (200): - -```json -{ - "status": "healthy" -} -```text - -### GET /readiness - -Kubernetes readiness probe. - -**Response** (200): - -```json -{ - "status": "ready" -} -```text - -### GET /liveness - -Kubernetes liveness probe. - -**Response** (200): - -```json -{ - "status": "alive" -} -```text - -## Items Resource - -### POST /api/v1/items - -Create a new item. - -**Request Body**: - -```json -{ - "name": "Sample Item", - "slug": "sample-item", - "description": "Optional description" -} -```text - -**Field Constraints**: - -- `name`: 1-200 characters, sanitized -- `slug`: 1-100 characters, lowercase letters/numbers/hyphens only -- `description`: Optional, max 1000 characters - -**Response** (201 Created): - -```json -{ - "id": 1, - "name": "Sample Item", - "slug": "sample-item", - "description": "Optional description", - "created_at": "2025-12-17T12:00:00", - "updated_at": "2025-12-17T12:00:00" -} -```text - -**Error Responses**: - -409 Conflict (duplicate slug): - -```json -{ - "detail": "Item with slug 'sample-item' already exists" -} -```text - -422 Validation Error: - -```json -{ - "detail": [ - { - "loc": ["body", "slug"], - "msg": "Slug must contain only lowercase letters, numbers, and hyphens", - "type": "value_error" - } - ] -} -```text - -### GET /api/v1/items - -List all items with pagination. - -**Query Parameters**: - -- `skip`: Number of items to skip (default: 0) -- `limit`: Maximum items to return (default: 100) - -**Example**: - -```text -GET /api/v1/items?skip=10&limit=20 -```text - -**Response** (200): - -```json -[ - { - "id": 1, - "name": "Item 1", - "slug": "item-1", - "description": null, - "created_at": "2025-12-17T12:00:00", - "updated_at": "2025-12-17T12:00:00" - }, - { - "id": 2, - "name": "Item 2", - "slug": "item-2", - "description": "Description", - "created_at": "2025-12-17T12:01:00", - "updated_at": "2025-12-17T12:01:00" - } -] -```text - -### GET /api/v1/items/{id} - -Get item by ID. - -**Path Parameters**: - -- `id`: Integer item ID - -**Response** (200): - -```json -{ - "id": 1, - "name": "Sample Item", - "slug": "sample-item", - "description": null, - "created_at": "2025-12-17T12:00:00", - "updated_at": "2025-12-17T12:00:00" -} -```text - -**Error Responses**: - -404 Not Found: - -```json -{ - "detail": "Item not found" -} -```text - -### GET /api/v1/items/slug/{slug} - -Get item by slug. - -**Path Parameters**: - -- `slug`: URL-safe slug - -**Example**: - -```text -GET /api/v1/items/slug/sample-item -```text - -**Response** (200): - -```json -{ - "id": 1, - "name": "Sample Item", - "slug": "sample-item", - "description": null, - "created_at": "2025-12-17T12:00:00", - "updated_at": "2025-12-17T12:00:00" -} -```text - -**Error Responses**: - -404 Not Found: - -```json -{ - "detail": "Item not found" -} -```text - -### PATCH /api/v1/items/{id} - -Update an existing item. - -**Path Parameters**: - -- `id`: Integer item ID - -**Request Body** (partial update): - -```json -{ - "name": "Updated Name", - "description": "Updated description" -} -```text - -**Note**: Only include fields you want to update. Slug cannot be updated. - -**Response** (200): - -```json -{ - "id": 1, - "name": "Updated Name", - "slug": "sample-item", - "description": "Updated description", - "created_at": "2025-12-17T12:00:00", - "updated_at": "2025-12-17T12:05:00" -} -```text - -**Error Responses**: - -404 Not Found: - -```json -{ - "detail": "Item not found" -} -```text - -422 Validation Error: - -```json -{ - "detail": [ - { - "loc": ["body", "name"], - "msg": "String should have at least 1 character", - "type": "string_too_short" - } - ] -} -```text - -### DELETE /api/v1/items/{id} - -Delete an item. - -**Path Parameters**: - -- `id`: Integer item ID - -**Response** (204 No Content): - -No response body. - -**Error Responses**: - -404 Not Found: - -```json -{ - "detail": "Item not found" -} -```text - -## Error Codes - -| Code | Description | Common Causes | -|------|-------------|---------------| -| 200 | OK | Successful GET/PATCH | -| 201 | Created | Successful POST | -| 204 | No Content | Successful DELETE | -| 404 | Not Found | Resource doesn't exist | -| 409 | Conflict | Duplicate slug | -| 422 | Validation Error | Invalid request data | -| 500 | Internal Server Error | Server error | - -## Rate Limiting - -Current version: No rate limiting. - -Production: Add rate limiting middleware as needed. - -## Versioning - -API version: `v1` - -All endpoints prefixed with `/api/v1`. - -Future versions will use `/api/v2`, etc. - -## OpenAPI Documentation - -Interactive API documentation: - -- **Swagger UI**: -- **ReDoc**: -- **OpenAPI JSON**: - -## Example Workflows - -### Create and Retrieve - -```bash -# Create item -curl -X POST http://localhost:8000/api/v1/items \ - -H "Content-Type: application/json" \ - -d '{"name": "Test", "slug": "test"}' - -# Get by ID -curl http://localhost:8000/api/v1/items/1 - -# Get by slug -curl http://localhost:8000/api/v1/items/slug/test -```text - -### List and Paginate - -```bash -# Get first 10 items -curl http://localhost:8000/api/v1/items?limit=10 - -# Get next 10 items -curl http://localhost:8000/api/v1/items?skip=10&limit=10 -```text - -### Update and Delete - -```bash -# Update item -curl -X PATCH http://localhost:8000/api/v1/items/1 \ - -H "Content-Type: application/json" \ - -d '{"name": "Updated Name"}' - -# Delete item -curl -X DELETE http://localhost:8000/api/v1/items/1 -```text - -## Client Libraries - -### Python (httpx) - -```python -import httpx - -client = httpx.Client(base_url="http://localhost:8000") - -# Create item -response = client.post( - "/api/v1/items", - json={"name": "Test", "slug": "test"} -) -item = response.json() - -# List items -items = client.get("/api/v1/items").json() -```text - -### JavaScript (fetch) - -```javascript -// Create item -const response = await fetch('http://localhost:8000/api/v1/items', { - method: 'POST', - headers: {'Content-Type': 'application/json'}, - body: JSON.stringify({name: 'Test', slug: 'test'}) -}); -const item = await response.json(); - -// List items -const items = await fetch('http://localhost:8000/api/v1/items') - .then(r => r.json()); -```text - -## Testing - -Use TestClient for testing: - -```python -from fastapi.testclient import TestClient -from app.main import app - -client = TestClient(app) - -def test_create_item(): - response = client.post( - "/api/v1/items", - json={"name": "Test", "slug": "test"} - ) - assert response.status_code == 201 -```text diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index cb5d1c2..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,375 +0,0 @@ -# Architecture - -## Overview - -The Ambient Code Reference Repository demonstrates a **layered architecture** with clear separation of concerns. This pattern scales from small microservices to large applications. - -## Layered Architecture - -```mermaid -flowchart TB - subgraph API["API Layer (FastAPI)"] - direction LR - Routes[Routes] - Handlers[Handlers] - Serialization[Serialization] - end - subgraph Service["Service Layer (Logic)"] - direction LR - Business[Business Rules] - Orchestration[Orchestration] - end - subgraph Model["Model Layer (Pydantic)"] - direction LR - Validation[Validation] - Types[Types] - end - subgraph Core["Core Layer (Utilities)"] - direction LR - Config[Config] - Security[Security] - Logging[Logging] - end - - API --> Service - Service --> Model - Model --> Core - API --> Core - Service --> Core -``` - -### API Layer - -**Location**: `app/api/` - -**Responsibilities**: - -- FastAPI route handlers -- Request/response models -- HTTP status codes -- Error responses -- OpenAPI documentation - -**Example** (`app/api/v1/items.py`): - -```python -@router.post("/", response_model=Item, status_code=201) -def create_item(data: ItemCreate) -> Item: - try: - return item_service.create_item(data) - except ValueError as e: - raise HTTPException(status_code=409, detail=str(e)) -``` - -### Service Layer - -**Location**: `app/services/` - -**Responsibilities**: - -- Business logic -- CRUD operations -- Data manipulation -- No HTTP concerns - -**Example** (`app/services/item_service.py`): - -```python -def create_item(self, data: ItemCreate) -> Item: - if data.slug in self._slug_index: - raise ValueError(f"Item with slug '{data.slug}' already exists") - - item = Item( - id=self._next_id, - name=data.name, - slug=data.slug, - description=data.description, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow(), - ) - - self._items[item.id] = item - self._slug_index[item.slug] = item.id - self._next_id += 1 - - return item -``` - -### Model Layer - -**Location**: `app/models/` - -**Responsibilities**: - -- Pydantic models -- Field validation -- Type annotations -- Sanitization - -**Example** (`app/models/item.py`): - -```python -class ItemCreate(ItemBase): - name: str = Field(..., min_length=1, max_length=200) - slug: str = Field(..., min_length=1, max_length=100) - - @field_validator("name") - @classmethod - def sanitize_name(cls, v: str) -> str: - return sanitize_string(v, max_length=200) -``` - -### Core Layer - -**Location**: `app/core/` - -**Responsibilities**: - -- Configuration (Pydantic Settings) -- Security utilities -- Logging setup -- Shared utilities - -**Example** (`app/core/config.py`): - -```python -class Settings(BaseSettings): - app_name: str = "Ambient Code Reference" - api_v1_prefix: str = "/api/v1" - - class Config: - env_file = ".env" - -settings = Settings() -``` - -## Data Flow - -### Creating an Item - -```mermaid -sequenceDiagram - participant Client - participant API as API Layer - participant Svc as Service Layer - participant Model as Model Layer - - Client->>+API: POST /api/v1/items - API->>API: Pydantic validates request - API->>+Svc: create_item(data) - Svc->>Svc: Check business rules - Svc->>+Model: Create Item model - Model->>Model: Sanitize fields - Model->>Model: Validate types - Model-->>-Svc: Item instance - Svc->>Svc: Store in memory - Svc-->>-API: Item object - API->>API: Serialize to JSON - API-->>-Client: 201 Created + Item -``` - -## Design Patterns - -### Singleton Services - -Services use singleton pattern for shared state: - -```python -# app/services/item_service.py -class ItemService: - def __init__(self): - self._items: dict[int, Item] = {} - -item_service = ItemService() - -# app/api/v1/items.py -from app.services.item_service import item_service -``` - -### Dependency Injection (Implicit) - -FastAPI handles dependency injection: - -```python -# Current: Implicit singleton -from app.services.item_service import item_service - -# Future: Explicit DI -def create_item( - data: ItemCreate, - service: ItemService = Depends(get_item_service) -): - return service.create_item(data) -``` - -### Validation Pipeline - -Pydantic validators create a validation pipeline: - -```python -class ItemCreate(ItemBase): - @field_validator("name") # Step 1 - @classmethod - def sanitize_name(cls, v: str) -> str: - return sanitize_string(v) - - @field_validator("slug") # Step 2 - @classmethod - def validate_slug_field(cls, v: str) -> str: - return validate_slug(v) -``` - -## Security Architecture - -### Input Validation - -**Validate once at API boundary**: - -- Pydantic models validate all request payloads -- Sanitization in model validators -- Trust internal code - -### Sanitization Functions - -**Location**: `app/core/security.py` - -**Functions**: - -- `sanitize_string()` - Remove control characters, trim whitespace -- `validate_slug()` - Ensure URL-safe slugs - -### Secrets Management - -**Environment variables only**: - -```python -# .env (not committed) -SECRET_KEY=xxx - -# app/core/config.py -class Settings(BaseSettings): - secret_key: str - - class Config: - env_file = ".env" -``` - -## Testing Architecture - -### Test Pyramid - -```mermaid -flowchart TB - subgraph E2E["E2E Tests"] - E[Few, Slow - Workflow Tests] - end - subgraph Integration["Integration Tests"] - I[Some, Medium - API Tests] - end - subgraph Unit["Unit Tests"] - U[Many, Fast - Service Tests] - end - - E2E --> Integration - Integration --> Unit -``` - -**Unit**: Test service layer in isolation -**Integration**: Test API with TestClient -**E2E**: Test complete CBA workflows (outline) - -## Observability - -### Structured Logging - -JSON format for log aggregation: - -```python -{ - "timestamp": "2025-12-17T12:00:00", - "level": "INFO", - "logger": "app.api.v1.items", - "message": "Item created", - "request_id": "abc123" -} -``` - -### Health Endpoints - -- `/health` - Basic health check -- `/readiness` - Kubernetes readiness probe -- `/liveness` - Kubernetes liveness probe - -## Scalability Considerations - -### Current Design (Single Instance) - -- In-memory storage -- No database -- Stateful (data lost on restart) - -### Production Patterns - -**Database**: - -- Add SQLAlchemy models -- Repository pattern in service layer -- Migrations with Alembic - -**Caching**: - -- Redis for frequently accessed items -- Cache invalidation on updates - -**Async**: - -- Use `async def` for I/O-bound operations -- AsyncIO for concurrent requests - -## Extension Points - -### Adding a Resource - -1. Create model in `app/models/resource.py` -2. Create service in `app/services/resource_service.py` -3. Create API in `app/api/v1/resource.py` -4. Register router in `app/main.py` -5. Add tests - -### Adding Middleware - -```python -# app/main.py -from fastapi import Request - -@app.middleware("http") -async def add_request_id(request: Request, call_next): - request.state.request_id = generate_id() - response = await call_next(request) - return response -``` - -### Adding Database - -```python -# app/core/database.py -from sqlalchemy.ext.asyncio import create_async_engine - -engine = create_async_engine(settings.database_url) -``` - -## Best Practices - -✅ **DO**: - -- Keep layers independent -- Validate at boundaries -- Use Pydantic for all data -- Write tests for each layer - -❌ **DON'T**: - -- Put business logic in API layer -- Put HTTP logic in service layer -- Bypass validation -- Mix concerns across layers diff --git a/docs/getting-started/first-cba.md b/docs/getting-started/first-cba.md deleted file mode 100644 index 4b69c8a..0000000 --- a/docs/getting-started/first-cba.md +++ /dev/null @@ -1,78 +0,0 @@ -# Your First Codebase Agent - -**Create a CBA in 30 minutes.** - ---- - -## Overview - -!!! note "Section Summary" - What you'll build: a `.claude/` directory with agent definition and context files customized for your project. By the end, AI will know your coding conventions. - ---- - -## Step 1: Copy the Template - -!!! note "Section Summary" - Copy `.claude/` from reference repo to your project. Directory structure explanation. What each file does. - ---- - -## Step 2: Customize the Agent Definition - -!!! note "Section Summary" - Edit `.claude/agents/codebase-agent.md`. Key sections to customize: capability boundaries (what can the agent do autonomously?), quality gates (your linting/testing commands), safety guardrails (when to stop and ask). - ---- - -## Step 3: Create Context Files - -### Architecture Context - -!!! note "Section Summary" - `.claude/context/architecture.md` - describe your layers, component responsibilities, data flow. Template provided. Examples for common stacks (FastAPI, Express, Django). - -### Security Context - -!!! note "Section Summary" - `.claude/context/security-standards.md` - your validation rules, sanitization patterns, secrets management approach. What to validate, what to trust. - -### Testing Context - -!!! note "Section Summary" - `.claude/context/testing-patterns.md` - your test pyramid, where tests live, mocking conventions, coverage targets. - ---- - -## Step 4: Test Your CBA - -!!! note "Section Summary" - Interactive session: ask AI to perform a task in your codebase. Verify it follows conventions. Iterate on context files based on what it gets wrong. - ---- - -## Step 5: Share with Your Team - -!!! note "Section Summary" - Commit `.claude/` to your repo. Team onboarding: everyone gets the same AI behavior. Updating context files: when and how. - ---- - -## Memory System Deep Dive - -!!! note "Section Summary" - How modular context works. Loading context on-demand. Token efficiency. When to split vs combine context files. - ---- - -## Troubleshooting - -!!! note "Section Summary" - Common issues: AI ignores context (file not loaded), AI makes up conventions (context too vague), AI over-engineers (context too broad). Solutions for each. - ---- - -## Next Steps - -- [Patterns Index](../patterns/index.md) - Explore all available patterns -- [Self-Review Reflection](../patterns/self-review-reflection.md) - Add quality gates to your CBA diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md deleted file mode 100644 index f66902e..0000000 --- a/docs/getting-started/installation.md +++ /dev/null @@ -1,54 +0,0 @@ -# Installation - -**Set up tooling for AI-assisted development.** - ---- - -## Prerequisites - -!!! note "Section Summary" - This section covers required and recommended tooling: Python 3.11+, uv package manager, Claude CLI or API access, markdownlint, and Mermaid CLI. Includes verification commands for each tool. - ---- - -## Quick Install - -!!! note "Section Summary" - One-liner install scripts for macOS/Linux. Clone reference repo, install dependencies with uv, verify setup with validation scripts. - ---- - -## Tool-by-Tool Setup - -### Python Environment - -!!! note "Section Summary" - Virtual environment setup with uv. Why uv over pip (speed, reliability). Verification steps. - -### Claude CLI / API - -!!! note "Section Summary" - Claude Code installation and authentication. API key management. Verification that Claude can access your codebase. - -### Linting Tools - -!!! note "Section Summary" - markdownlint-cli installation. Black, isort, ruff for Python. Configuration files included in reference repo. - -### Mermaid Validation - -!!! note "Section Summary" - @mermaid-js/mermaid-cli installation. Why Mermaid validation matters for documentation CI. - ---- - -## Verification - -!!! note "Section Summary" - Run all validation scripts to confirm installation. Expected output for each. Troubleshooting common issues. - ---- - -## Next Steps - -- [Your First CBA](first-cba.md) - Create your first Codebase Agent diff --git a/docs/index.md b/docs/index.md index b572742..2e38567 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,187 +1,40 @@ # Ambient Code Reference -**AI-assisted development patterns for engineering teams.** +AI-assisted development patterns for engineering teams. --- -## Executive Summary +## Patterns -This repository provides battle-tested patterns for adopting AI-assisted development at scale. It answers the question every principal engineer faces: *"How do we use AI coding assistants without creating chaos?"* +### Agent Behavior -**Key Value Propositions:** +| Pattern | What It Does | +|---------|--------------| +| [Codebase Agent](patterns/codebase-agent.md) | Define AI behavior and guardrails | +| [Self-Review Reflection](patterns/self-review-reflection.md) | Agent reviews own work before presenting | +| [Autonomous Quality](patterns/autonomous-quality-enforcement.md) | Run linters/tests automatically | +| [Multi-Agent Review](patterns/multi-agent-code-review.md) | Parallel specialized reviews | -1. **Consistency** - Every AI interaction follows the same process -2. **Safety** - Human review gates prevent runaway automation -3. **Productivity** - 10x speedup for routine tasks -4. **Transferability** - Patterns work across tools and languages +### GHA Automation -**Approach:** Standalone patterns. Adopt what you need, skip what you don't. No prescribed sequence. +| Pattern | Trigger | +|---------|---------| +| [Issue-to-PR](patterns/issue-to-pr.md) | Issue labeled `cba` | +| [PR Auto-Review](patterns/pr-auto-review.md) | Pull request opened | +| [Dependabot Auto-Merge](patterns/dependabot-auto-merge.md) | Dependabot PR | +| [Stale Issues](patterns/stale-issues.md) | Weekly schedule | ---- - -## What's Inside - -### Patterns (9 Total) - -| Pattern | Category | Effort | Impact | -|---------|----------|--------|--------| -| [Codebase Agent (CBA)](patterns/codebase-agent.md) | Agent Behavior | Medium | High | -| [Memory System](getting-started/first-cba.md) | Agent Behavior | Low | Medium | -| [Self-Review Reflection](patterns/self-review-reflection.md) | Agent Behavior | Low | High | -| [Issue-to-PR Automation](patterns/issue-to-pr.md) | GHA Automation | High | Very High | -| [PR Auto-Review](patterns/pr-auto-review.md) | GHA Automation | Medium | High | -| [Dependabot Auto-Merge](patterns/dependabot-auto-merge.md) | GHA Automation | Low | Medium | -| [Stale Issue Management](patterns/stale-issues.md) | GHA Automation | Low | Medium | -| [Layered Architecture](patterns/layered-architecture.md) | Foundation | Low | Medium | -| [Security Patterns](patterns/security-patterns.md) | Foundation | Low | Medium | - -### Quick Start Paths - -=== "I want consistent AI assistance" - - Start with [Codebase Agent](patterns/codebase-agent.md) - one file that defines how AI works in your codebase. - -=== "AI keeps forgetting my conventions" - - Start with [Memory System](getting-started/first-cba.md) - modular context files that persist across sessions. - -=== "Routine fixes take too long" - - Start with [Issue-to-PR Automation](patterns/issue-to-pr.md) - convert well-defined issues to PRs automatically. - -=== "I want to see it working first" - - Check out the [demo-fastapi](https://github.com/jeremyeder/demo-fastapi) repository for a working example. - ---- - -## Documentation Structure - -### Getting Started - -| Section | Purpose | Time | -|---------|---------|------| -| [Quickstart](quickstart.md) | 5-minute introduction to AI-assisted development | 5 min | -| [Installation](getting-started/installation.md) | Set up tooling and dependencies | 15 min | -| [Your First CBA](getting-started/first-cba.md) | Create your first Codebase Agent | 30 min | - -**What you'll learn:** How to copy the `.claude/` directory to your project and customize it for your tech stack. - ---- - -### Patterns - -#### Agent Behavior Patterns - -How AI agents behave during development. - -| Pattern | What It Does | Section Summary | -|---------|--------------|-----------------| -| [Codebase Agent](patterns/codebase-agent.md) | Defines AI behavior, capabilities, and guardrails | Agent definition structure, autonomy levels, workflow examples, capability boundaries | -| [Self-Review Reflection](patterns/self-review-reflection.md) | Agent reviews own work before presenting | Reflection loop, checklist criteria, implementation prompts, anti-patterns | -| [Autonomous Quality](patterns/autonomous-quality-enforcement.md) | Validates code quality before delivery | Lint loops, test verification, error budgets | -| [Multi-Agent Review](patterns/multi-agent-code-review.md) | Multiple specialized agents review in parallel | Agent roles, consensus mechanisms, conflict resolution | - -#### GHA Automation Patterns - -Proactive CI/CD workflows. - -| Pattern | Trigger | Section Summary | -|---------|---------|-----------------| -| [Issue-to-PR](patterns/issue-to-pr.md) | `issues.opened` | Requirements analysis, draft PR creation, risk categories, safety gates | -| [PR Auto-Review](patterns/pr-auto-review.md) | `pull_request` | AI review format, severity levels, when to block vs comment | -| [Dependabot Auto-Merge](patterns/dependabot-auto-merge.md) | `pull_request` | Patch vs minor/major, CI requirements, safety conditions | -| [Stale Issues](patterns/stale-issues.md) | `schedule` | Inactivity thresholds, warning periods, exempt labels | - -#### Foundation Patterns +### Foundation -Enabling patterns that make AI more effective. - -| Pattern | Purpose | Section Summary | -|---------|---------|-----------------| -| [Layered Architecture](patterns/layered-architecture.md) | Code structure AI can reason about | Four layers, dependency rules, component responsibilities | -| [Security Patterns](patterns/security-patterns.md) | Practical protection without over-engineering | Boundary validation, sanitization, secrets management | -| [Testing Patterns](patterns/testing-patterns.md) | Test pyramid approach | Unit/integration/E2E, coverage targets, AI test generation | - ---- - -### Reference - -| Section | Purpose | Contents | -|---------|---------|----------| -| [Architecture](architecture.md) | Deep dive into architecture patterns | Data flow diagrams, layer boundaries, extension points | -| [API Patterns](api-reference.md) | API design for AI-assisted development | Request/response patterns, error handling, OpenAPI | -| [ADR Template](adr/template.md) | Decision record scaffolding | YYYYMMDD-title.md format, context/decision/consequences | +| Pattern | What It Does | +|---------|--------------| +| [Security Patterns](patterns/security-patterns.md) | Validate at boundaries | +| [Testing Patterns](patterns/testing-patterns.md) | Unit, integration, E2E pyramid | --- -### Tutorial - -| Section | Purpose | Time | -|---------|---------|------| -| [Full Tutorial](tutorial.md) | Step-by-step implementation guide | 2-4 hours | - -**What you'll build:** A complete AI-assisted development setup from scratch, including CBA, memory system, and GHA automations. - ---- - -### Resources - -| Resource | Format | Purpose | -|----------|--------|---------| -| [Presentation](resources/presentation.md) | Markdown | NotebookLM podcast generation, 9 features explained | -| [Demo Application](resources/demo-app.md) | GitHub Repo | Working FastAPI example | - ---- - -## Navigation Guide - -```mermaid -flowchart TD - A[Start Here] --> B{What do you need?} - B -->|Understand the concepts| C[Quickstart] - B -->|See it working| D[Demo App] - B -->|Implement patterns| E[Tutorial] - B -->|Reference specific pattern| F[Patterns Index] - - C --> G[Your First CBA] - D --> G - E --> G - F --> H[Choose Pattern] - - G --> I[Production Setup] - H --> I -``` - ---- - -## Design Principles - -1. **Standalone patterns** - No dependencies between patterns. Adopt one without adopting others. -2. **Copy-paste ready** - All configurations are complete and ready to customize. -3. **Human-in-the-loop** - AI assists, humans decide. Safety gates everywhere. -4. **Vendor-agnostic** - Patterns work with any AI tool or none at all. -5. **Minimal ceremony** - Start small, add complexity only when needed. - ---- - -## Who This Is For - -| Role | Benefit | -|------|---------| -| **Principal Engineers** | Evaluate AI adoption strategy with battle-tested patterns | -| **Team Leads** | Implement consistent AI workflows across your team | -| **Senior Developers** | Get productivity gains without sacrificing quality | -| **Junior Developers** | Get senior-level AI assistance with guardrails | - ---- - -## Quick Links - -- **GitHub Repository**: [jeremyeder/reference](https://github.com/jeremyeder/reference) -- **Demo Application**: [jeremyeder/demo-fastapi](https://github.com/jeremyeder/demo-fastapi) -- **Original SRE Coloring Book**: [red.ht/sre-coloring-book](https://red.ht/sre-coloring-book) - ---- +## Links -*"Stable, Secure, Performant, and Boring" - the goal is to make AI assistance invisible through excellence.* +- **Quickstart**: [quickstart.md](quickstart.md) +- **Demo App**: [demo-fastapi](https://github.com/ambient-code/demo-fastapi) +- **Presentation**: [PRESENTATION-ambient-code-reference.md](https://github.com/ambient-code/reference/blob/main/PRESENTATION-ambient-code-reference.md) diff --git a/docs/patterns/index.md b/docs/patterns/index.md deleted file mode 100644 index 461627d..0000000 --- a/docs/patterns/index.md +++ /dev/null @@ -1,81 +0,0 @@ -# Patterns Index - -Each pattern is standalone—adopt what you need. - ---- - -## Agent Behavior - -| Pattern | Effort | Impact | -|---------|--------|--------| -| [Codebase Agent](codebase-agent.md) | Medium | High | -| [Self-Review Reflection](self-review-reflection.md) | Low | High | -| [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) | Medium | High | -| [Multi-Agent Code Review](multi-agent-code-review.md) | High | Very High | - ---- - -## GHA Automation - -| Pattern | Trigger | Effort | -|---------|---------|--------| -| [Issue-to-PR](issue-to-pr.md) | `issues.opened` | High | -| [PR Auto-Review](pr-auto-review.md) | `pull_request` | Medium | -| [Dependabot Auto-Merge](dependabot-auto-merge.md) | `pull_request` | Low | -| [Stale Issue Management](stale-issues.md) | `schedule` | Low | - ---- - -## Foundation - -| Pattern | Purpose | -|---------|---------| -| [Layered Architecture](layered-architecture.md) | Code structure AI can reason about | -| [Security Patterns](security-patterns.md) | Validate at boundaries | -| [Testing Patterns](testing-patterns.md) | Test pyramid approach | - ---- - -## Start Here - -| Pain Point | Pattern | -|------------|---------| -| AI gives inconsistent answers | [Codebase Agent](codebase-agent.md) | -| AI misses obvious bugs | [Self-Review Reflection](self-review-reflection.md) | -| PRs take forever to create | [Issue-to-PR](issue-to-pr.md) | -| Code reviews are bottleneck | [PR Auto-Review](pr-auto-review.md) | -| Dependency updates pile up | [Dependabot Auto-Merge](dependabot-auto-merge.md) | - ---- - -## Pattern Dependencies - -```mermaid -flowchart TD - CBA[Codebase Agent] --> SR[Self-Review] - CBA --> AQE[Autonomous Quality] - AQE --> ITP[Issue-to-PR] - SR --> ITP - ITP --> PAR[PR Auto-Review] - LA[Layered Architecture] -.-> CBA - SEC[Security Patterns] -.-> CBA - TEST[Testing Patterns] -.-> AQE -``` - ---- - -## Quick Reference - -| File | Location | -|------|----------| -| CBA definition | `.claude/agents/codebase-agent.md` | -| Context files | `.claude/context/*.md` | -| Issue-to-PR | `.github/workflows/issue-to-pr.yml` | -| PR Review | `.github/workflows/pr-review.yml` | -| Dependabot | `.github/workflows/dependabot-auto-merge.yml` | -| Stale | `.github/workflows/stale.yml` | - -| Secret | Used By | -|--------|---------| -| `ANTHROPIC_API_KEY` | Issue-to-PR, PR Review | -| `GITHUB_TOKEN` | All workflows (auto-provided) | diff --git a/docs/patterns/layered-architecture.md b/docs/patterns/layered-architecture.md deleted file mode 100644 index 284c190..0000000 --- a/docs/patterns/layered-architecture.md +++ /dev/null @@ -1,93 +0,0 @@ -# Layered Architecture - -**Code structure AI can reason about.** - ---- - -## The Four Layers - -```text -┌─────────────────────────────────┐ -│ API Layer (FastAPI) │ Routes, HTTP status codes -├─────────────────────────────────┤ -│ Service Layer (Logic) │ Business rules -├─────────────────────────────────┤ -│ Model Layer (Pydantic) │ Validation, serialization -├─────────────────────────────────┤ -│ Core Layer (Utilities) │ Config, security -└─────────────────────────────────┘ -``` - -**Dependency rule**: Higher layers import lower, never reverse. - ---- - -## Directory Structure - -```text -app/ -├── api/v1/items.py # Routes -├── services/item_service.py # Business logic -├── models/item.py # Pydantic models -└── core/ - ├── config.py # Settings - └── security.py # Utilities -``` - ---- - -## Layer Responsibilities - -| Layer | Does | Doesn't | -|-------|------|---------| -| **API** | Routes, HTTP errors, OpenAPI docs | Business logic | -| **Service** | Business rules, CRUD, orchestration | HTTP concerns | -| **Model** | Validation, sanitization | Business logic | -| **Core** | Config, security utils | Domain logic | - ---- - -## Example - -```python -# API Layer - handles HTTP -@router.post("/items", status_code=201) -def create_item(data: ItemCreate): - try: - return item_service.create_item(data) - except ValueError as e: - raise HTTPException(status_code=409, detail=str(e)) - -# Service Layer - business logic -class ItemService: - def create_item(self, data: ItemCreate) -> Item: - if self._slug_exists(data.slug): - raise ValueError("Duplicate slug") - return Item(id=self._next_id, **data.model_dump()) - -# Model Layer - validation -class ItemCreate(BaseModel): - name: str = Field(..., min_length=1, max_length=200) - slug: str = Field(..., pattern=r"^[a-z0-9-]+$") -``` - ---- - -## Dependency Diagram - -```mermaid -flowchart TD - API[API Layer] --> Service[Service Layer] - Service --> Model[Model Layer] - Model --> Core[Core Layer] - API --> Model - API --> Core - Service --> Core -``` - ---- - -## Related Patterns - -- [Security Patterns](security-patterns.md) - Where validation happens -- [Testing Patterns](testing-patterns.md) - How to test each layer diff --git a/docs/patterns/security-patterns.md b/docs/patterns/security-patterns.md index fe6157f..fe2adc7 100644 --- a/docs/patterns/security-patterns.md +++ b/docs/patterns/security-patterns.md @@ -96,5 +96,4 @@ class Settings(BaseSettings): ## Related Patterns -- [Layered Architecture](layered-architecture.md) - Where validation happens - [PR Auto-Review](pr-auto-review.md) - Automated security checks diff --git a/docs/patterns/testing-patterns.md b/docs/patterns/testing-patterns.md index 061e1be..17b9836 100644 --- a/docs/patterns/testing-patterns.md +++ b/docs/patterns/testing-patterns.md @@ -130,5 +130,4 @@ def test_slug_validation(slug, valid): ## Related Patterns -- [Layered Architecture](layered-architecture.md) - What each test level covers - [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) - Running tests in CI diff --git a/docs/quickstart.md b/docs/quickstart.md index b2dc5db..bbbdde7 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,188 +1,110 @@ -# Quickstart Guide +# Quickstart -Get started with Ambient Code reference patterns in 5 minutes. +Each pattern below is standalone. Pick one, follow its quickstart, done. -## What This Repository Is +--- -This is a **documentation-only reference** for AI-assisted development patterns. It provides: +## Agent Behavior Patterns -- **Pattern documentation** - CBA, architecture, security, testing -- **Example configurations** - `.claude/` agent setup examples -- **Best practices** - Documentation templates and standards +How to configure AI agents for consistent, safe, high-quality assistance. -**Looking for a working application?** See [demo-fastapi](https://github.com/jeremyeder/demo-fastapi) +| Pattern | What It Does | Time | +|---------|--------------|------| +| [Codebase Agent (CBA)](patterns/codebase-agent.md) | Define AI behavior, capabilities, and guardrails | 30 min | +| [Self-Review Reflection](patterns/self-review-reflection.md) | Agent reviews own work before presenting | 5 min | +| [Autonomous Quality Enforcement](patterns/autonomous-quality-enforcement.md) | Agent runs linters/tests automatically | 15 min | +| [Multi-Agent Code Review](patterns/multi-agent-code-review.md) | Multiple specialized agents review in parallel | 1 hour | -### Getting Started Flow +**Start here if:** AI gives inconsistent answers, misses obvious bugs, or ignores conventions. -```mermaid -flowchart LR - A[Clone Repo] --> B[Explore Docs] - B --> C{What do you need?} - C -->|CBA Setup| D[Copy .claude/] - C -->|Architecture| E[Read docs/architecture.md] - C -->|Testing| F[Read testing-patterns.md] - C -->|CI/CD| G[Copy .github/workflows/] - D --> H[Customize for your project] - E --> H - F --> H - G --> H - H --> I[Ship It] -``` - -## Prerequisites - -- Python 3.11 or 3.12 (for documentation tooling) -- `uv` (recommended) or `pip` -- Git - -## Setup - -### 1. Clone the Repository - -```bash -git clone https://github.com/jeremyeder/reference.git -cd reference -``` - -### 2. Install Documentation Tooling (Optional) - -```bash -# Run setup script -./scripts/setup.sh - -# Or manually install -uv pip install -r requirements-dev.txt -``` - -This installs markdown linting and Mermaid validation tools. - -## Explore the Patterns - -### Browse Documentation - -```bash -# Read pattern overviews -cat docs/architecture.md -cat docs/tutorial.md -cat docs/api-reference.md - -# Explore CBA agent patterns -cat .claude/agents/codebase-agent.md +--- -# Check context examples -cat .claude/context/architecture.md -cat .claude/context/security-standards.md -cat .claude/context/testing-patterns.md -``` +## GHA Automation Patterns -### Understand the Structure +GitHub Actions workflows that handle routine work automatically. -```bash -# See repository layout -tree -L 2 -I '.venv|.git' +| Pattern | Trigger | Time | +|---------|---------|------| +| [Issue-to-PR Automation](patterns/issue-to-pr.md) | Issue labeled `cba` | 30 min | +| [PR Auto-Review](patterns/pr-auto-review.md) | Pull request opened | 15 min | +| [Dependabot Auto-Merge](patterns/dependabot-auto-merge.md) | Dependabot PR (patch versions) | 10 min | +| [Stale Issue Management](patterns/stale-issues.md) | Weekly schedule | 10 min | -# List available patterns -ls -la .claude/agents/ -ls -la .claude/context/ -ls -la docs/ -``` +**Start here if:** PRs take forever, dependency updates pile up, or stale issues accumulate. -## Validate Documentation (If You Modify) +--- -### Lint Markdown +## Foundation Patterns -```bash -markdownlint docs/**/*.md README.md CLAUDE.md --fix -``` +| Pattern | What It Does | Time | +|---------|--------------|------| +| [Security Patterns](patterns/security-patterns.md) | Input validation at boundaries, sanitization | 30 min | +| [Testing Patterns](patterns/testing-patterns.md) | Unit, integration, E2E test pyramid | 1 hour | -### Validate Mermaid Diagrams - -```bash -./scripts/validate-mermaid.sh -``` +--- -## Use the Patterns +## The CBA Demo -### Pick What You Need +The best way to understand CBA value is the **ADR before/after demo**. -This repository uses **standalone patterns** - adopt concepts independently: +### Scenario: User requests a change that conflicts with an existing ADR -1. **Codebase Agent Setup** - - Copy `.claude/` structure to your project - - Adapt agent definitions in `.claude/agents/` - - Customize context files in `.claude/context/` +**Without CBA (Vanilla AI):** -2. **Architecture Patterns** - - Reference layered architecture in `docs/architecture.md` - - Adapt for your tech stack (FastAPI, Express, Go, etc.) +- Implements immediately +- Ignores project decisions +- Creates technical debt +- Future AI interactions still confused -3. **Testing Patterns** - - Follow structures in `.claude/context/testing-patterns.md` - - Organize tests as unit/integration/e2e +**With CBA:** -4. **CI/CD Patterns** - - Copy workflows from `.github/workflows/` - - Adapt for your documentation validation needs +1. Reads CLAUDE.md and ADRs +2. Identifies conflict with existing decision +3. Asks before proceeding +4. Proposes ADR change for approval +5. Updates all references (ADR index, CLAUDE.md) +6. Only then implements +7. Self-reviews before presenting -### Example: Add CBA to Your Project - -```bash -# In your project -cp -r /path/to/reference/.claude . -cd .claude/agents/ - -# Edit codebase-agent.md for your needs -vim codebase-agent.md - -# Customize context files -cd ../context/ -vim architecture.md # Your project's architecture -vim security-standards.md # Your security practices +```mermaid +flowchart TD + A[User Request] --> B[CBA Loads Context] + B --> C[Read CLAUDE.md + ADRs] + C --> D{Conflicts with ADRs?} + D -->|Yes| E[Ask user, propose ADR change] + D -->|No| F[Implement] + E -->|Approved| G[Update ADRs] + G --> F + F --> H[Self-Review] + H --> I{Passes checklist?} + I -->|No| J[Fix issues] + J --> H + I -->|Yes| K[Create PR with findings] ``` -## Next Steps +See [demo-fastapi](https://github.com/ambient-code/demo-fastapi) for this pattern in action. -- **[Architecture](architecture.md)** - Understand pattern organization -- **[Tutorial](tutorial.md)** - Apply patterns to your project -- **[API Reference](api-reference.md)** - API design patterns +--- -## Working Application Demo +## Reference Files -Want to see these patterns in action? +The `.claude/` directory contains example configurations: -→ **[demo-fastapi](https://github.com/jeremyeder/demo-fastapi)** - Working FastAPI application demonstrating CBA patterns - -The demo includes: - -- Full CRUD API with FastAPI -- CBA agent configured for the app -- Complete test suite -- Containerfile for deployment - -## Troubleshooting - -**Markdown linting fails?** - -```bash -# Install markdownlint -npm install -g markdownlint-cli - -# Fix issues automatically -markdownlint docs/**/*.md --fix +```text +.claude/ +├── agents/ +│ └── codebase-agent.md # Example CBA definition +└── context/ + ├── architecture.md # Example architecture context + ├── security-standards.md + └── testing-patterns.md ``` -**Mermaid validation fails?** +Read these to understand the format. Create your own based on your project. -```bash -# Install mermaid-cli -npm install -g @mermaid-js/mermaid-cli - -# Run validation -./scripts/validate-mermaid.sh -``` +--- -**Need help with patterns?** +## Links -- Read detailed docs in `docs/` -- Check examples in `.claude/` -- See working implementation in [demo-fastapi](https://github.com/jeremyeder/demo-fastapi) +- **Working Demo**: [demo-fastapi](https://github.com/ambient-code/demo-fastapi) +- **Presentation**: [PRESENTATION-ambient-code-reference.md](../PRESENTATION-ambient-code-reference.md) diff --git a/docs/resources/demo-app.md b/docs/resources/demo-app.md deleted file mode 100644 index b7a755a..0000000 --- a/docs/resources/demo-app.md +++ /dev/null @@ -1,51 +0,0 @@ -# Demo Application - -**See AI-assisted development patterns in action.** - ---- - -## Overview - -!!! note "Section Summary" - The demo-fastapi repository is a working FastAPI application demonstrating all patterns from this reference. Not a toy example - a complete implementation you can run locally or deploy. - ---- - -## Repository - -**GitHub**: [jeremyeder/demo-fastapi](https://github.com/jeremyeder/demo-fastapi) - ---- - -## What's Included - -!!! note "Section Summary" - Working FastAPI service with CRUD endpoints. Full CBA configuration. Test suite (unit, integration, E2E). Container support (Podman/Docker). CI/CD workflows. - ---- - -## Quick Start - -!!! note "Section Summary" - Clone, install, run. API endpoints to try. How to trigger CBA workflows. Expected output for each. - ---- - -## Patterns Demonstrated - -!!! note "Section Summary" - Which patterns are implemented and where to find them in the demo. File paths for each pattern. How they interact in practice. - ---- - -## Extending the Demo - -!!! note "Section Summary" - How to add new endpoints following patterns. How to modify CBA for your needs. How to add new automations. - ---- - -## Comparing to Reference - -!!! note "Section Summary" - Reference repo = documentation-only patterns. Demo repo = working implementation. When to use which. diff --git a/docs/resources/presentation.md b/docs/resources/presentation.md deleted file mode 100644 index d7a45cc..0000000 --- a/docs/resources/presentation.md +++ /dev/null @@ -1,47 +0,0 @@ -# Presentation Document - -**Structured content for NotebookLM podcast generation.** - ---- - -## Overview - -!!! note "Section Summary" - A 9-feature presentation designed for NotebookLM to generate podcasts. Target audience: principal engineers evaluating AI-assisted development. Format: problem/solution/payoff for each feature. - ---- - -## Features Covered - -| # | Feature | Category | -|---|---------|----------| -| 1 | Codebase Agent (CBA) | Agent Behavior | -| 2 | Memory System | Agent Behavior | -| 3 | Issue-to-PR Automation | GHA Automation | -| 4 | Layered Architecture | Foundation | -| 5 | Security Patterns | Foundation | -| 6 | Testing Patterns | Foundation | -| 7 | CI/CD for Documentation | Foundation | -| 8 | Self-Review Reflection | Agent Behavior | -| 9 | Proactive GHA Workflows | GHA Automation | - ---- - -## Download - -!!! note "Section Summary" - Link to PRESENTATION-ambient-code-reference.md. Markdown format for NotebookLM ingestion. PDF version for sharing. - ---- - -## Using with NotebookLM - -!!! note "Section Summary" - How to upload to NotebookLM. Recommended prompts for podcast generation. Sample output audio (if available). - ---- - -## Presentation Outline - -!!! note "Section Summary" - For each of the 9 features: What it is, problem it solves, how it works, benefits for principal engineers. Adoption guidance. Common objections and responses. diff --git a/docs/tutorial.md b/docs/tutorial.md deleted file mode 100644 index 8e5787f..0000000 --- a/docs/tutorial.md +++ /dev/null @@ -1,301 +0,0 @@ -# Tutorial: Building Your First Feature - -Learn how to add a new resource to the Ambient Code Reference Repository by building a "Tags" feature. - -## Goal - -Add a Tags resource that allows: - -- Creating tags with name and color -- Listing tags -- Tagging items - -## Step 1: Create the Model - -Create `app/models/tag.py`: - -```python -from pydantic import BaseModel, Field, field_validator - -from app.core.security import sanitize_string - - -class TagBase(BaseModel): - name: str = Field(..., min_length=1, max_length=50) - color: str = Field(..., pattern=r"^#[0-9A-Fa-f]{6}$") - - @field_validator("name") - @classmethod - def sanitize_name(cls, v: str) -> str: - return sanitize_string(v, max_length=50) - - -class TagCreate(TagBase): - pass - - -class Tag(TagBase): - id: int -``` - -**What we did**: - -- Created Pydantic models for validation -- Added sanitization to name field -- Used regex to validate hex color codes - -## Step 2: Create the Service - -Create `app/services/tag_service.py`: - -```python -from app.models.tag import Tag, TagCreate - - -class TagService: - def __init__(self) -> None: - self._tags: dict[int, Tag] = {} - self._next_id: int = 1 - - def create_tag(self, data: TagCreate) -> Tag: - tag = Tag(id=self._next_id, name=data.name, color=data.color) - self._tags[tag.id] = tag - self._next_id += 1 - return tag - - def list_tags(self) -> list[Tag]: - return list(self._tags.values()) - - -tag_service = TagService() -``` - -**What we did**: - -- Created service with business logic -- Used singleton pattern -- In-memory storage (like items) - -## Step 3: Create the API - -Create `app/api/v1/tags.py`: - -```python -from fastapi import APIRouter, status - -from app.models.tag import Tag, TagCreate -from app.services.tag_service import tag_service - -router = APIRouter(prefix="/tags", tags=["tags"]) - - -@router.post("/", response_model=Tag, status_code=status.HTTP_201_CREATED) -def create_tag(data: TagCreate) -> Tag: - return tag_service.create_tag(data) - - -@router.get("/", response_model=list[Tag]) -def list_tags() -> list[Tag]: - return tag_service.list_tags() -``` - -**What we did**: - -- Created FastAPI router -- Defined POST and GET endpoints -- Connected to service layer - -## Step 4: Register the Router - -Update `app/main.py`: - -```python -from app.api.v1 import items, tags # Add tags import - -# Add this line after items router -app.include_router(tags.router, prefix=settings.api_v1_prefix) -``` - -**What we did**: - -- Imported tags router -- Registered with FastAPI app -- Used API v1 prefix - -## Step 5: Write Tests - -Create `tests/unit/test_tag_service.py`: - -```python -from app.models.tag import TagCreate -from app.services.tag_service import TagService - - -def test_create_tag(): - service = TagService() - data = TagCreate(name="Important", color="#ff0000") - - result = service.create_tag(data) - - assert result.id == 1 - assert result.name == "Important" - assert result.color == "#ff0000" - - -def test_list_tags(): - service = TagService() - service.create_tag(TagCreate(name="Tag1", color="#ff0000")) - service.create_tag(TagCreate(name="Tag2", color="#00ff00")) - - result = service.list_tags() - - assert len(result) == 2 -``` - -Create `tests/integration/test_tags_api.py`: - -```python -def test_create_tag(client): - response = client.post( - "/api/v1/tags", - json={"name": "Important", "color": "#ff0000"} - ) - - assert response.status_code == 201 - data = response.json() - assert data["name"] == "Important" - assert data["color"] == "#ff0000" - - -def test_list_tags(client): - client.post("/api/v1/tags", json={"name": "Tag1", "color": "#ff0000"}) - client.post("/api/v1/tags", json={"name": "Tag2", "color": "#00ff00"}) - - response = client.get("/api/v1/tags") - - assert response.status_code == 200 - assert len(response.json()) == 2 -``` - -## Step 6: Run Linters - -```bash -# Format -black app/ tests/ - -# Sort imports -isort app/ tests/ - -# Lint -ruff check app/ tests/ -``` - -Fix any issues reported. - -## Step 7: Run Tests - -```bash -pytest -``` - -Ensure all tests pass and coverage is above 80%. - -## Step 8: Test the API - -Start the server: - -```bash -uvicorn app.main:app --reload -``` - -Create a tag: - -```bash -curl -X POST http://localhost:8000/api/v1/tags \ - -H "Content-Type: application/json" \ - -d '{"name": "Important", "color": "#ff0000"}' -``` - -List tags: - -```bash -curl http://localhost:8000/api/v1/tags -``` - -## What You Learned - -✅ **Layered Architecture**: - -- Models for validation -- Services for logic -- API for HTTP - -✅ **Pydantic Validation**: - -- Field constraints -- Regex patterns -- Custom validators - -✅ **Testing Strategy**: - -- Unit tests for services -- Integration tests for API -- 80%+ coverage - -✅ **Code Quality**: - -- black formatting -- isort import sorting -- ruff linting - -## Next Steps - -Try these enhancements: - -1. **Add tag deletion**: - - `DELETE /api/v1/tags/{id}` - - Service method - - Tests - -2. **Add tag-item relationship**: - - Update Item model with tags field - - Add/remove tags from items - - List items by tag - -3. **Add validation**: - - Prevent duplicate tag names - - Add color name aliases - -4. **Add documentation**: - - OpenAPI descriptions - - Example responses - - Error codes - -## Common Issues - -**Import errors?** - -```python -# Make sure __init__.py exists in all directories -app/api/v1/__init__.py -app/models/__init__.py -``` - -**Tests failing?** - -```bash -# Check service initialization -# Each test should create fresh service instance -service = TagService() -``` - -**Linter errors?** - -```bash -# Run formatters first -black app/ tests/ -isort app/ tests/ - -# Then check linting -ruff check app/ tests/ -``` diff --git a/mkdocs.yml b/mkdocs.yml index 4dd6316..ac3b587 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,15 +1,12 @@ -# MkDocs configuration for Ambient Code Reference Repository site_name: Ambient Code Reference site_description: AI-assisted development patterns and best practices site_author: Jeremy Eder -site_url: https://jeremyeder.github.io/reference/ +site_url: https://ambient-code.github.io/reference/ -# Repository -repo_name: jeremyeder/reference -repo_url: https://github.com/jeremyeder/reference +repo_name: ambient-code/reference +repo_url: https://github.com/ambient-code/reference edit_uri: edit/main/docs/ -# Theme theme: name: material palette: @@ -36,7 +33,6 @@ theme: - content.code.copy - content.action.edit -# Extensions markdown_extensions: - admonition - pymdownx.details @@ -55,50 +51,34 @@ markdown_extensions: - toc: permalink: true -# Plugins plugins: - search - mermaid2 -# Navigation nav: - Home: index.md - - Getting Started: - - Quickstart: quickstart.md - - Installation: getting-started/installation.md - - Your First CBA: getting-started/first-cba.md + - Quickstart: quickstart.md - Patterns: - - Overview: patterns/index.md - Agent Behavior: - Codebase Agent (CBA): patterns/codebase-agent.md - Self-Review Reflection: patterns/self-review-reflection.md - Autonomous Quality Enforcement: patterns/autonomous-quality-enforcement.md - Multi-Agent Code Review: patterns/multi-agent-code-review.md - GHA Automation: - - Overview: patterns/gha-automation-patterns.md + - GHA Patterns Overview: patterns/gha-automation-patterns.md - Issue-to-PR: patterns/issue-to-pr.md - PR Auto-Review: patterns/pr-auto-review.md - Dependabot Auto-Merge: patterns/dependabot-auto-merge.md - Stale Issue Management: patterns/stale-issues.md - - Architecture: - - Layered Architecture: patterns/layered-architecture.md + - Foundation: - Security Patterns: patterns/security-patterns.md - Testing Patterns: patterns/testing-patterns.md - - Reference: - - Architecture: architecture.md - - API Patterns: api-reference.md - - ADR Template: adr/template.md - - Tutorial: tutorial.md - - Resources: - - Presentation: resources/presentation.md - - Demo Application: resources/demo-app.md + - ADR Template: adr/template.md -# Extra extra: social: - icon: fontawesome/brands/github - link: https://github.com/jeremyeder + link: https://github.com/ambient-code generator: false -# Copyright copyright: Copyright © 2024-2026 Jeremy Eder diff --git a/requirements-dev.txt b/requirements-dev.txt index 1a717ef..887e0c7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -2,4 +2,3 @@ black>=23.12.0 isort>=5.13.0 ruff>=0.1.0 -markdownlint-cli>=0.37.0 diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 37ddd06..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -# Ambient Code Reference Repository -# Documentation-only repository - minimal dependencies for linting examples - diff --git a/scripts/setup.sh b/scripts/setup.sh index 2d77fda..5ebe953 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -41,5 +41,5 @@ echo " 3. Validate Mermaid diagrams: ./scripts/validate-mermaid.sh" echo " 4. Lint markdown: markdownlint docs/**/*.md --fix" echo "" echo "For a working application demo, see:" -echo " https://github.com/jeremyeder/demo-fastapi" +echo " https://github.com/ambient-code/demo-fastapi" echo ""