diff --git a/.beads/.gitignore b/.beads/.gitignore new file mode 100644 index 0000000..d27a1db --- /dev/null +++ b/.beads/.gitignore @@ -0,0 +1,44 @@ +# SQLite databases +*.db +*.db?* +*.db-journal +*.db-wal +*.db-shm + +# Daemon runtime files +daemon.lock +daemon.log +daemon.pid +bd.sock +sync-state.json +last-touched + +# Local version tracking (prevents upgrade notification spam after git ops) +.local_version + +# Legacy database files +db.sqlite +bd.db + +# Worktree redirect file (contains relative path to main repo's .beads/) +# Must not be committed as paths would be wrong in other clones +redirect + +# Merge artifacts (temporary files from 3-way merge) +beads.base.jsonl +beads.base.meta.json +beads.left.jsonl +beads.left.meta.json +beads.right.jsonl +beads.right.meta.json + +# Sync state (local-only, per-machine) +# These files are machine-specific and should not be shared across clones +.sync.lock +sync_base.jsonl + +# NOTE: Do NOT add negation patterns (e.g., !issues.jsonl) here. +# They would override fork protection in .git/info/exclude, allowing +# contributors to accidentally commit upstream issue databases. +# The JSONL files (issues.jsonl, interactions.jsonl) and config files +# are tracked by git by default since no pattern above ignores them. diff --git a/.beads/README.md b/.beads/README.md new file mode 100644 index 0000000..50f281f --- /dev/null +++ b/.beads/README.md @@ -0,0 +1,81 @@ +# Beads - AI-Native Issue Tracking + +Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code. + +## What is Beads? + +Beads is issue tracking that lives in your repo, making it perfect for AI coding agents and developers who want their issues close to their code. No web UI required - everything works through the CLI and integrates seamlessly with git. + +**Learn more:** [github.com/steveyegge/beads](https://github.com/steveyegge/beads) + +## Quick Start + +### Essential Commands + +```bash +# Create new issues +bd create "Add user authentication" + +# View all issues +bd list + +# View issue details +bd show + +# Update issue status +bd update --status in_progress +bd update --status done + +# Sync with git remote +bd sync +``` + +### Working with Issues + +Issues in Beads are: +- **Git-native**: Stored in `.beads/issues.jsonl` and synced like code +- **AI-friendly**: CLI-first design works perfectly with AI coding agents +- **Branch-aware**: Issues can follow your branch workflow +- **Always in sync**: Auto-syncs with your commits + +## Why Beads? + +✨ **AI-Native Design** +- Built specifically for AI-assisted development workflows +- CLI-first interface works seamlessly with AI coding agents +- No context switching to web UIs + +🚀 **Developer Focused** +- Issues live in your repo, right next to your code +- Works offline, syncs when you push +- Fast, lightweight, and stays out of your way + +🔧 **Git Integration** +- Automatic sync with git commits +- Branch-aware issue tracking +- Intelligent JSONL merge resolution + +## Get Started with Beads + +Try Beads in your own projects: + +```bash +# Install Beads +curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash + +# Initialize in your repo +bd init + +# Create your first issue +bd create "Try out Beads" +``` + +## Learn More + +- **Documentation**: [github.com/steveyegge/beads/docs](https://github.com/steveyegge/beads/tree/main/docs) +- **Quick Start Guide**: Run `bd quickstart` +- **Examples**: [github.com/steveyegge/beads/examples](https://github.com/steveyegge/beads/tree/main/examples) + +--- + +*Beads: Issue tracking that moves at the speed of thought* ⚡ diff --git a/.beads/config.yaml b/.beads/config.yaml new file mode 100644 index 0000000..f242785 --- /dev/null +++ b/.beads/config.yaml @@ -0,0 +1,62 @@ +# Beads Configuration File +# This file configures default behavior for all bd commands in this repository +# All settings can also be set via environment variables (BD_* prefix) +# or overridden with command-line flags + +# Issue prefix for this repository (used by bd init) +# If not set, bd init will auto-detect from directory name +# Example: issue-prefix: "myproject" creates issues like "myproject-1", "myproject-2", etc. +# issue-prefix: "" + +# Use no-db mode: load from JSONL, no SQLite, write back after each command +# When true, bd will use .beads/issues.jsonl as the source of truth +# instead of SQLite database +# no-db: false + +# Disable daemon for RPC communication (forces direct database access) +# no-daemon: false + +# Disable auto-flush of database to JSONL after mutations +# no-auto-flush: false + +# Disable auto-import from JSONL when it's newer than database +# no-auto-import: false + +# Enable JSON output by default +# json: false + +# Default actor for audit trails (overridden by BD_ACTOR or --actor) +# actor: "" + +# Path to database (overridden by BEADS_DB or --db) +# db: "" + +# Auto-start daemon if not running (can also use BEADS_AUTO_START_DAEMON) +# auto-start-daemon: true + +# Debounce interval for auto-flush (can also use BEADS_FLUSH_DEBOUNCE) +# flush-debounce: "5s" + +# Git branch for beads commits (bd sync will commit to this branch) +# IMPORTANT: Set this for team projects so all clones use the same sync branch. +# This setting persists across clones (unlike database config which is gitignored). +# Can also use BEADS_SYNC_BRANCH env var for local override. +# If not set, bd sync will require you to run 'bd config set sync.branch '. +# sync-branch: "beads-sync" + +# Multi-repo configuration (experimental - bd-307) +# Allows hydrating from multiple repositories and routing writes to the correct JSONL +# repos: +# primary: "." # Primary repo (where this database lives) +# additional: # Additional repos to hydrate from (read-only) +# - ~/beads-planning # Personal planning repo +# - ~/work-planning # Work planning repo + +# Integration settings (access with 'bd config get/set') +# These are stored in the database, not in this file: +# - jira.url +# - jira.project +# - linear.url +# - linear.api-key +# - github.org +# - github.repo diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl new file mode 100644 index 0000000..e69de29 diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl new file mode 100644 index 0000000..4bf3e43 --- /dev/null +++ b/.beads/issues.jsonl @@ -0,0 +1,20 @@ +{"id":"ai-development-patterns-zqc","title":"Epic: Repo consistency + link health alignment","description":"Audit findings (2026-01-31):\n\n- README passes pattern-spec + hyperlink tests (including slow external link check).\n- 65 broken internal/relative links across 20 non-README markdown files (mostly stale anchors/paths from pre-migration naming).\n- Stable example directories are named correctly, but almost all example READMEs still use pre-migration pattern names (e.g., 'Rules as Code', 'AI Security Sandbox', etc.) and contain stale links.\n- Experimental docs/examples still reference old pattern names/anchors and some example READMEs reference missing files.\n- CLAUDE.md repo tree is out of date vs current directories.\n- index.html drifts from README (missing patterns + category mismatch).\n\nGoal: bring docs/examples/tests/scripts into alignment with pattern-spec.md conventions (names, links, structure) and ensure link integrity repo-wide.\n\nAcceptance:\n- All markdown internal/relative links validate repo-wide.\n- Examples/docs use current pattern names + anchors.\n- CI/tests cover links beyond README.","status":"closed","priority":2,"issue_type":"epic","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:27:56.125938-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T14:00:23.012581-05:00","closed_at":"2026-01-31T14:00:23.012581-05:00","close_reason":"Closed"} +{"id":"ai-development-patterns-zqc.1","title":"Fix placeholder links in pattern-spec.md","description":"pattern-spec.md currently contains markdown links that are meant to be examples/placeholders (e.g., [Pattern Name](#pattern-name-anchor), examples/pattern-name/). These render as broken links in link-audit tooling and undermine the spec’s own link-integrity guidance.\n\nScope:\n- pattern-spec.md: ensure example link syntax is presented as code/escaped text (not clickable broken links).\n\nNotes:\n- Link audit currently reports 4 broken internal/relative links in pattern-spec.md (missing internal anchor + missing file).","acceptance_criteria":"- pattern-spec.md contains no broken internal/relative links when running a repo-wide markdown link audit (excluding code blocks).\n- Example link formats remain clear (prefer code formatting/backticks or escaping).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:28:41.576272-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T12:57:21.381704-05:00","closed_at":"2026-01-31T12:57:21.381704-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.1","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:28:41.576846-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.10","title":"Update experiments/examples/README.md to current experimental catalog","description":"experiments/examples/README.md appears to be from a pre-migration state and references:\n- Experimental pattern names that no longer exist (e.g., AI Workflow Orchestration, Comprehensive AI Testing Strategy).\n- Example directories that do not exist (e.g., human-ai-handoff/, comprehensive-ai-testing-strategy/).\n- Broken links to stable examples (e.g., ../../examples/specification-driven-development/).\n\nScope:\n- Rewrite the table to match the current experiments/README.md pattern list and the actual directory names under experiments/examples/.\n- Fix links to stable examples to use existing paths and current anchors.","acceptance_criteria":"- experiments/examples/README.md accurately reflects experiments/examples/* directory names.\n- All links in experiments/examples/README.md resolve (repo-wide markdown link audit shows 0 broken links).\n- Terminology matches the current experimental pattern names (no legacy AI-prefixed names unless explicitly called out as history).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:43.505984-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:01.715712-05:00","closed_at":"2026-01-31T13:36:01.715712-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.10","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:43.5065-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.11","title":"Complete asynchronous-research example directory or remove dead links","description":"experiments/examples/asynchronous-research/README.md links to multiple files that are not present in the repo (setup/*.md, example-research-tasks/*/prompt.md, automation/summarize-workflow.yml). The directory currently contains only README.md.\n\nScope options:\nA) Add the referenced files/directories with minimal working content, consistent with the README.\nB) If the full implementation is not ready, update README.md to remove/replace links and clearly mark the example as a stub.\n\nGoal: avoid dead links and keep experimental examples trustworthy.","acceptance_criteria":"- Repo-wide markdown link audit shows 0 missing-file links for experiments/examples/asynchronous-research/README.md.\n- The directory either contains the referenced files or the README no longer references them.\n- Example directory passes ExampleDirectoryValidator expectations (README present, no obvious dead references).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:55.65752-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:01.87012-05:00","closed_at":"2026-01-31T13:36:01.87012-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.11","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:55.658056-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.12","title":"Update experimental example READMEs to current names + anchors","description":"Several tracked experimental example READMEs and example docs still reference legacy pattern names/anchors (ai-*, AI-Driven, etc.) and/or legacy pattern names in headings.\n\nKnown broken-link files from link audit:\n- experiments/examples/custom-commands/*.md (links to ../../README.md#ai-driven-refactoring, #specification-driven-development, etc.)\n- experiments/examples/handoff-protocols/README.md (links to ../../README.md#human-ai-handoff-protocol)\n- experiments/examples/workflow-orchestration/README.md (links to ../../README.md#ai-workflow-orchestration)\n- experiments/examples/review-automation/README.md (links to ../../README.md#ai-review-automation)\n\nScope:\n- Update these docs to reference current canonical pattern anchors in README and experiments/README.\n- Update H1s where they still use legacy names (e.g., “AI Review Automation Implementation” -\u003e “Review Automation Implementation”).","acceptance_criteria":"- All tracked experimental example docs use current pattern names.\n- Repo-wide markdown link audit shows 0 missing-target-anchor failures for experiments/examples/**.\n- No references to non-existent README anchors (ai-*, specification-driven-development, etc.).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:31:10.337672-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:02.026573-05:00","closed_at":"2026-01-31T13:36:02.026573-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.12","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:31:10.338208-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.13","title":"Normalize Foundation example READMEs to current pattern names","description":"Tracked example directories for Foundation patterns use correct directory names, but the README titles/content are still pre-migration (AI-prefixed names, old anchors) and include broken links.\n\nAffected dirs:\n- examples/codified-rules (README title: “Rules as Code Example”; broken links to old anchors)\n- examples/security-sandbox (README title: “AI Security Sandbox Implementation”; deeper path issues handled in separate sandbox task)\n- examples/developer-lifecycle (README title: “AI Developer Lifecycle Example”)\n- examples/tool-integration (README title: “AI Tool Integration - Complete Implementation”; broken links to ../../sandbox/ and old anchors)\n- examples/issue-generation (README title: “AI Issue Generation Examples”)\n\nScope:\n- Update each example README (and any adjacent docs in the directory) to use current canonical pattern names as per README/pattern-spec.\n- Update links to README anchors to current anchors (no ai-* legacy anchors).\n- Remove/replace references to non-existent ../../sandbox/ paths (use correct example paths).\n\nNote: Security Sandbox example path correctness is tracked separately (ai-development-patterns-zqc.8).","acceptance_criteria":"- Each listed examples/* README uses current canonical pattern name in its H1.\n- Repo-wide markdown link audit shows no broken internal/relative links in these example docs.\n- No remaining links to non-existent README anchors (ai-*, rules-as-code, specification-driven-development, etc.).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:31:22.980337-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:02.338277-05:00","closed_at":"2026-01-31T13:36:02.338277-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.13","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:31:22.980898-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.14","title":"Normalize Development example READMEs to current pattern names","description":"Most Development pattern examples still use pre-migration names in their README H1s and cross-links.\n\nAffected dirs (tracked):\n- examples/spec-driven-development (README title: “Specification Driven Development”; broken links to old anchors and missing ../../sandbox/)\n- examples/planned-implementation (README title: “AI Plan-First Development”; links to #ai-plan-first-development)\n- examples/atomic-decomposition (README title: “Atomic Task Decomposition Example”; links to #atomic-task-decomposition)\n- examples/parallel-agents (README title: “Parallelized AI Coding Agents”; links to #parallelized-ai-coding-agents)\n- examples/context-persistence (README title: “AI Context Persistence Implementation”)\n- examples/observable-development (README title: “Observable AI Development Implementation”)\n- examples/guided-refactoring (README title: “AI-Driven Refactoring Example”)\n- examples/automated-traceability (README title: “AI-Driven Traceability Implementation”)\n- examples/error-resolution (README title already matches, but verify links/naming within)\n\nScope:\n- Update README titles and any internal references/links to use current canonical names/anchors from root README.\n- Remove/replace any ../../sandbox/ references with paths that exist in this repo.\n- Ensure docs within these directories (e.g., markdown-iteration-techniques.md, function-level-decomposition.md) link to current anchors.","acceptance_criteria":"- Each listed examples/* README uses current canonical pattern name in its H1.\n- Repo-wide markdown link audit shows no broken internal/relative links in these example docs.\n- No remaining links to non-existent README anchors (ai-*, specification-driven-development, atomic-task-decomposition, parallelized-*, etc.).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:31:35.995254-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:02.183376-05:00","closed_at":"2026-01-31T13:36:02.183376-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.14","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:31:35.995827-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.15","title":"Normalize Operations example READMEs to current pattern names","description":"Operations pattern examples also contain legacy naming in their README H1s.\n\nAffected dirs (tracked):\n- examples/policy-generation (README title: “Policy-as-Code Generation Implementation”)\n- examples/security-orchestration (README title: “Security Scanning Orchestration Implementation”)\n- examples/baseline-management (README title: “Performance Baseline Management Implementation”)\n\nScope:\n- Update README titles and internal references to use current canonical names (Policy Generation, Security Orchestration, Baseline Management).\n- Ensure any cross-links to README anchors use current anchors.","acceptance_criteria":"- Each listed examples/* README uses current canonical pattern name in its H1.\n- Repo-wide markdown link audit shows no broken internal/relative links in these example docs.\n- No remaining legacy pattern names in headings unless explicitly documented as historical.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:31:44.480304-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:02.492339-05:00","closed_at":"2026-01-31T13:36:02.492339-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.15","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:31:44.480847-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.16","title":"Register pytest markers (slow) to remove warnings","description":"Running pytest currently emits PytestUnknownMarkWarning for pytest.mark.slow used in tests/test_links.py.\n\nScope:\n- Add pytest configuration (pytest.ini or pyproject.toml) to register the slow marker (and any other custom markers in use).\n- Ensure CI commands using -m slow / -m \"not slow\" continue to work without warnings.","acceptance_criteria":"- pytest runs without PytestUnknownMarkWarning for slow marker.\n- test_links.py still supports selecting slow vs not slow.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:31:54.023804-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:57:13.465384-05:00","closed_at":"2026-01-31T13:57:13.465384-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.16","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:31:54.024346-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.17","title":"Add repo-wide markdown link validation (docs/examples/experiments)","description":"Current CI/test coverage validates links mainly in README.md. A repo-wide audit found 65 broken internal/relative links across 20 non-README markdown files.\n\nScope:\n- Add a new pytest test (or extend existing link checker) to validate internal anchors + relative file links across markdown files in:\n - docs/\n - examples/\n - experiments/\n - pattern-spec.md and other top-level docs\n- Exclude code blocks and known placeholder/example snippets.\n- Integrate into GitHub Actions (pattern-validation.yml) so broken links are caught in PRs.\n\nSequencing note:\n- This should likely be enabled after existing broken links are fixed, otherwise it will fail immediately.","acceptance_criteria":"- A new test exists that validates internal/relative links across non-README markdown.\n- GitHub Actions runs the test and fails on broken links.\n- The test has reasonable exclusions (code blocks, explicit placeholder examples) and low flakiness.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:32:17.275923-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:57:13.518281-05:00","closed_at":"2026-01-31T13:57:13.518281-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.17","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:32:17.276425-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.18","title":"Normalize Python invocation in GitHub Actions workflows","description":"In .github/workflows/pattern-validation.yml, most jobs use python3, but the quality-gates job uses plain python for pytest invocations. This can be brittle across runner images.\n\nScope:\n- Use python3 consistently in workflow steps.\n- Optionally ensure the same virtualenv/dependencies are used for quality-gates steps.\n\nGoal: avoid environment-dependent failures.","acceptance_criteria":"- pattern-validation.yml uses consistent python3 invocation.\n- Workflow continues to run the same tests as before.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:32:27.230983-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:57:13.569013-05:00","closed_at":"2026-01-31T13:57:13.569013-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.18","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:32:27.231469-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.19","title":"Harden example-validation against local stray directories","description":"Local test run showed Example Code Validation failing due to directories that exist on disk but are not tracked in git (e.g., examples/ai-issue-generation/, examples/ai-context-persistence/, experiments/examples/ai-event-automation/), each missing README.md.\n\nThese directories are likely leftovers from earlier migrations or local experimentation; they are empty or contain only ignored files, so git status stays clean, but ExampleDirectoryValidator still scans them.\n\nOptions:\n- Update ExampleDirectoryValidator to only validate git-tracked example directories (or only directories containing a README.md).\n- Or document a cleanup step / add a guard that warns when such stray dirs exist.\n\nGoal: make local validation predictable and aligned with CI behavior.","acceptance_criteria":"- Running tests/run_all_tests.py on a working tree with stray empty example dirs does not fail Example Code Validation (or fails with a clear actionable message).\n- CI behavior remains unchanged.","status":"closed","priority":2,"issue_type":"chore","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:32:41.094839-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:57:13.619873-05:00","closed_at":"2026-01-31T13:57:13.619873-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.19","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:32:41.095486-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.2","title":"Fix docs/claude-code-guide.md TOC anchors","description":"docs/claude-code-guide.md has a manually-maintained Table of Contents whose anchors do not match the document headings (likely due to emoji in headings causing the TOC to include a leading hyphen / variation selector). Link audit reports 10 missing internal anchors at the top of the file.\n\nScope:\n- docs/claude-code-guide.md: update TOC links to match actual heading anchors (or adjust headings so anchors match TOC).\n- Also convert the single external YouTube link that uses http:// to https://.\n\nNotes:\n- Link audit: 10 broken internal anchors in docs/claude-code-guide.md.","acceptance_criteria":"- TOC links navigate correctly within docs/claude-code-guide.md on GitHub.\n- Repo-wide markdown link audit reports 0 broken internal anchors for docs/claude-code-guide.md.\n- No remaining http:// external links for that YouTube entry.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:29:24.015478-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:11:09.386386-05:00","closed_at":"2026-01-31T13:11:09.386386-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.2","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:29:24.016031-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.3","title":"Update CLAUDE.md to match current repo structure","description":"CLAUDE.md repository overview lists directories that do not exist in the current repo (sandbox/, specs/, policies/, monitoring/, ops/, pipelines/, deployment/) and includes line-number references that appear stale.\n\nScope:\n- CLAUDE.md: refresh the Repository Structure tree to match the actual repo layout.\n- Ensure pattern naming references align with current README/pattern-spec naming (no AI-prefixed pattern names unless intentionally describing legacy).\n\nAcceptance should be measurable by reading the file; no code changes beyond documentation.","acceptance_criteria":"- CLAUDE.md file tree matches the actual top-level directories in the repo.\n- Any referenced paths in CLAUDE.md exist.\n- Pattern name references match current README anchors.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:29:33.958199-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T12:57:21.692559-05:00","closed_at":"2026-01-31T12:57:21.692559-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.3","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:29:33.958741-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.4","title":"Align index.html with README pattern taxonomy","description":"index.html appears to be a GitHub Pages landing page but currently drifts from README:\n- It omits several patterns entirely (e.g., Planned Implementation, Choice Generation, Constrained Generation, Guided Architecture, Error Resolution).\n- It classifies Context Persistence as a Foundation pattern even though README categorizes it under Development.\n- Pattern count badge is hard-coded (22) and may drift if patterns change.\n\nScope:\n- index.html: update pattern lists/taxonomy to match README (or explicitly mark as a curated subset).\n- Consider making pattern count and lists generated or clearly documented to avoid drift.","acceptance_criteria":"- index.html pattern lists are consistent with README (either complete or clearly stated as intentionally partial).\n- Pattern categories in index.html match README taxonomy.\n- Pattern count badge cannot silently drift (auto-generated or documented update step).","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:29:41.658036-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T12:57:21.875327-05:00","closed_at":"2026-01-31T12:57:21.875327-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.4","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:29:41.658557-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.5","title":"Reconcile PATTERN_MIGRATION_GUIDE.md and migration scripts","description":"PATTERN_MIGRATION_GUIDE.md and scripts/*renames*.sh appear to describe/encode a migration to two-word naming, but multiple parts conflict with current README/pattern-spec:\n- Guide references pattern names/anchors that no longer exist (e.g., Spec-First) while README uses Spec-Driven Development.\n- Several examples/experiments still contain legacy names even though the guide claims repository references were updated.\n\nScope:\n- Decide whether PATTERN_MIGRATION_GUIDE.md is historical (archive it) or should reflect the current canonical names.\n- Update or retire scripts/apply-pattern-renames.sh and scripts/apply-experimental-renames.sh accordingly.\n- Update scripts/README.md examples that reference the old pattern count (21) to current count.\n\nGoal: remove confusion for readers and prevent future drift.","acceptance_criteria":"- Migration guide either (a) matches the current canonical naming/anchors, or (b) is clearly marked as historical and moved/segmented accordingly.\n- Any referenced “new names” in the guide exist in README.\n- Migration scripts are either updated to current names or clearly archived with warnings.\n- scripts/README.md examples reflect current pattern count.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:29:53.269232-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T12:57:22.037004-05:00","closed_at":"2026-01-31T12:57:22.037004-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.5","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:29:53.26976-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.6","title":"Update docs/introducing-ai-development-patterns.md to current pattern names","description":"docs/introducing-ai-development-patterns.md uses pre-migration pattern names (AI Readiness Assessment, Rules as Code, AI Security Sandbox, Specification Driven Development, Progressive AI Enhancement, etc.) and includes bare URLs.\n\nScope:\n- docs/introducing-ai-development-patterns.md: update pattern names to match current canonical names in README/pattern-spec.\n- Link pattern mentions to README anchors.\n- Convert bare repo URLs to standard markdown links.\n\nGoal: keep introductory content consistent with the current pattern catalog.","acceptance_criteria":"- docs/introducing-ai-development-patterns.md uses current canonical pattern names.\n- Pattern mentions are hyperlinked to README anchors.\n- No bare GitHub repo URLs remain (use markdown links).\\n- Repo-wide markdown link audit shows no broken links in this file.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:04.316634-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:11:09.227873-05:00","closed_at":"2026-01-31T13:11:09.227873-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.6","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:04.317199-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.7","title":"Align docs/ai-development-best-practices.md with canonical pattern names","description":"docs/ai-development-best-practices.md is framed as a best-practices list, but it references several patterns using legacy names (e.g., Rules as Code, Specification Driven Development, etc.) and includes legacy/experimental names that no longer match the current catalog.\n\nScope:\n- Update references to stable patterns to use current names (Codified Rules, Spec-Driven Development, etc.).\n- Where a best practice is directly derived from a pattern, hyperlink to README (or experiments/README for experimental patterns).\n- Keep the best-practices voice, but ensure nomenclature matches the repository.\n\nNote: do not try to force every bullet into a pattern; only update where it clearly maps.","acceptance_criteria":"- Stable pattern references use current canonical names.\n- Mapped pattern references are hyperlinked to the appropriate README/experiments anchors.\n- Repo-wide markdown link audit shows no broken links in this file.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:13.786074-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:11:09.545405-05:00","closed_at":"2026-01-31T13:11:09.545405-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.7","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:13.786729-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.8","title":"Align Security Sandbox blog + example paths","description":"docs/ai-security-sandbox-blog.md and examples/security-sandbox/ appear out of sync:\n- Blog uses the legacy pattern name “AI Security Sandbox” and references a root-level sandbox/ directory and ./sandbox/ai-sandbox.sh, but the repo uses examples/security-sandbox/.\n- examples/security-sandbox/README.md references files that are not present (e.g., security-monitor.py, init-sandbox.sh) and uses legacy naming.\n- examples/security-sandbox/docker-compose.ai-sandbox.yml references sandbox/Dockerfile.ai-sandbox and ./sandbox/* paths that do not exist.\n\nScope:\n- Decide the canonical location for the sandbox implementation (likely examples/security-sandbox/).\n- Update blog instructions + links accordingly.\n- Fix examples/security-sandbox/README.md file list to match actual files.\n- Fix docker-compose paths so the example is runnable (or clearly documented placeholders).\n\nThis is a high-impact consistency fix because Security Sandbox is a foundational pattern.","acceptance_criteria":"- docs/ai-security-sandbox-blog.md references the correct implementation paths in this repo.\n- examples/security-sandbox/README.md accurately lists files that exist.\n- Security sandbox compose files reference paths that exist in-repo.\n- Repo-wide markdown link audit shows no broken links for the blog and the example README.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:24.123607-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:11:09.702437-05:00","closed_at":"2026-01-31T13:11:09.702437-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.8","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:24.124151-05:00","created_by":"Paul Duvall"}]} +{"id":"ai-development-patterns-zqc.9","title":"Fix broken links + legacy anchors in experiments/README.md","description":"experiments/README.md still contains legacy links to main README anchors and missing example paths:\n- Broken internal link: #monitoring--intelligence\n- Legacy anchors: ../README.md#ai-choice-generation, ../README.md#parallelized-ai-coding-agents\n- Missing paths: examples/custom-ai-commands/* (should likely be examples/custom-commands/*)\n\nScope:\n- experiments/README.md: update internal anchor links and convert any legacy references to current anchors.\n- Update example-path references to match the actual experiments/examples directory structure.\n- Consider hyperlinking Dependencies in the experimental reference table for consistency with pattern-spec expectations.","acceptance_criteria":"- Repo-wide markdown link audit shows 0 broken internal/relative links in experiments/README.md.\n- No references to non-existent README anchors (ai-*, parallelized-*, etc.).\n- Example paths in the file exist.","status":"closed","priority":2,"issue_type":"task","owner":"pduvall@gmail.com","created_at":"2026-01-31T12:30:34.85363-05:00","created_by":"Paul Duvall","updated_at":"2026-01-31T13:36:01.55689-05:00","closed_at":"2026-01-31T13:36:01.55689-05:00","close_reason":"Closed","dependencies":[{"issue_id":"ai-development-patterns-zqc.9","depends_on_id":"ai-development-patterns-zqc","type":"parent-child","created_at":"2026-01-31T12:30:34.854165-05:00","created_by":"Paul Duvall"}]} diff --git a/.beads/metadata.json b/.beads/metadata.json new file mode 100644 index 0000000..c787975 --- /dev/null +++ b/.beads/metadata.json @@ -0,0 +1,4 @@ +{ + "database": "beads.db", + "jsonl_export": "issues.jsonl" +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..807d598 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ + +# Use bd merge for beads JSONL files +.beads/issues.jsonl merge=beads diff --git a/.github/workflows/pattern-validation.yml b/.github/workflows/pattern-validation.yml index 8e45c2b..cab8d40 100644 --- a/.github/workflows/pattern-validation.yml +++ b/.github/workflows/pattern-validation.yml @@ -62,13 +62,13 @@ jobs: - name: Check for pattern count changes run: | - if git diff --quiet README.md; then - echo "✓ Pattern count badge is up to date" + if git diff --quiet README.md index.html; then + echo "✓ Pattern count badges are up to date" else - echo "⚠️ Pattern count badge was updated" - git diff README.md + echo "⚠️ Pattern count badges were updated" + git diff README.md index.html # Fail the job if pattern count is wrong to remind developers to commit the change - echo "::error::Pattern count badge was out of date. Please run 'python3 scripts/update-pattern-count.py' and commit the changes." + echo "::error::Pattern count badges were out of date. Please run 'python3 scripts/update-pattern-count.py' and commit the changes." exit 1 fi @@ -273,11 +273,11 @@ jobs: run: | cd tests # Run only critical tests that should block merges - python -m pytest test_pattern_compliance.py::TestPatternSpecCompliance::test_all_expected_patterns_exist -v - python -m pytest test_pattern_compliance.py::TestPatternSpecCompliance::test_pattern_header_structure -v - python -m pytest test_readme_accuracy.py::TestReadmeAccuracy::test_pattern_reference_table_matches_implementations -v - python -m pytest test_links.py::TestHyperlinkIntegrity::test_internal_anchor_links_valid -v - python -m pytest test_dependencies.py::TestPatternDependencies::test_no_circular_dependencies -v + python3 -m pytest test_pattern_compliance.py::TestPatternSpecCompliance::test_all_expected_patterns_exist -v + python3 -m pytest test_pattern_compliance.py::TestPatternSpecCompliance::test_pattern_header_structure -v + python3 -m pytest test_readme_accuracy.py::TestReadmeAccuracy::test_pattern_reference_table_matches_implementations -v + python3 -m pytest test_links.py::TestHyperlinkIntegrity::test_internal_anchor_links_valid -v + python3 -m pytest test_dependencies.py::TestPatternDependencies::test_no_circular_dependencies -v - name: Check critical test results run: | @@ -322,4 +322,4 @@ jobs: title: title, body: body, labels: ['bug', 'automation', 'pattern-validation'] - }); \ No newline at end of file + }); diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..df7a4af --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,40 @@ +# Agent Instructions + +This project uses **bd** (beads) for issue tracking. Run `bd onboard` to get started. + +## Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --status in_progress # Claim work +bd close # Complete work +bd sync # Sync with git +``` + +## Landing the Plane (Session Completion) + +**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until `git push` succeeds. + +**MANDATORY WORKFLOW:** + +1. **File issues for remaining work** - Create issues for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **PUSH TO REMOTE** - This is MANDATORY: + ```bash + git pull --rebase + bd sync + git push + git status # MUST show "up to date with origin" + ``` +5. **Clean up** - Clear stashes, prune remote branches +6. **Verify** - All changes committed AND pushed +7. **Hand off** - Provide context for next session + +**CRITICAL RULES:** +- Work is NOT complete until `git push` succeeds +- NEVER stop before pushing - that leaves work stranded locally +- NEVER say "ready to push when you are" - YOU must push +- If push fails, resolve and retry until it succeeds + diff --git a/CLAUDE.md b/CLAUDE.md index 8194e6e..de30be3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,21 +9,16 @@ This is the AI Development Patterns repository - a comprehensive collection of p ## Repository Structure ``` -├── README.md # Main pattern documentation (3000+ lines) -├── pattern-spec.md # Pattern creation specification and formatting rules -├── examples/ # Working implementations of patterns -│ └── parallel-agents/ # Complete Docker-based parallel agent example -├── docs/ # Additional documentation and specs -│ ├── specs.md # Specification-driven development patterns -│ └── examples/ # Pattern implementation examples (au1a.md, pm7a.md, etc.) -├── sandbox/ # AI security isolation examples -├── specs/ # Example specifications (OpenAPI, Gherkin, etc.) -├── policies/ # Policy-as-code examples (Cedar, OPA) -├── tests/ # Testing pattern examples -├── monitoring/ # Observability and chaos engineering examples -├── ops/ # Operations pattern implementations -├── pipelines/ # CI/CD pattern examples -└── deployment/ # Deployment automation examples +├── README.md # Main pattern documentation +├── pattern-spec.md # Pattern creation specification and formatting rules +├── PATTERN_MIGRATION_GUIDE.md # Naming/anchor migration reference (historical + mapping) +├── index.html # GitHub Pages landing page +├── docs/ # Additional documentation +├── examples/ # Working implementations of stable patterns +├── experiments/ # Experimental patterns + examples +├── scripts/ # Repo automation scripts (validation, updates) +├── tests/ # Pytest-based validation suite +└── .github/ # GitHub Actions workflows ``` ## Key Architectural Principles @@ -36,7 +31,7 @@ This is the AI Development Patterns repository - a comprehensive collection of p ### Pattern Reference System - **Hyperlinked navigation**: Every pattern reference must link to its section using `#pattern-name-in-lowercase-with-hyphens` -- **Comprehensive reference table**: Lines 50-89 in README.md contain the master pattern index +- **Comprehensive reference table**: See "Complete Pattern Reference" in `README.md` - **Related patterns**: Each pattern explicitly lists dependencies and related patterns ### Documentation Standards @@ -49,15 +44,15 @@ This is the AI Development Patterns repository - a comprehensive collection of p ### Adding New Patterns 1. **Follow pattern-spec.md**: Strict adherence to the specification format is required -2. **Update reference table**: Add new pattern to the table at lines 50-89 with proper dependencies -3. **Add to correct section**: Foundation (lines 270+), Development (lines 1400+), or Operations (lines 2500+) +2. **Update reference table**: Add the pattern to the "Complete Pattern Reference" table with proper dependencies +3. **Add to correct section**: Add the full pattern under `README.md` headings: "Foundation Patterns", "Development Patterns", or "Operations Patterns" 4. **Include anti-pattern**: Every pattern must show what NOT to do 5. **Link related patterns**: Use proper markdown hyperlinks to related patterns ### Pattern Dependencies -- **Foundation patterns** (lines 270-960): Establish team readiness, security, and basic AI integration -- **Development patterns** (lines 960-1830): Daily workflows for AI-assisted coding -- **Operations patterns** (lines 1830+): CI/CD, security, compliance, and production management +- **Foundation patterns**: Establish team readiness, security, and basic AI integration +- **Development patterns**: Daily workflows for AI-assisted coding +- **Operations patterns**: CI/CD, security, compliance, and production management ### Content Guidelines - **Kanban workflow assumed**: No sprint-based or fixed iteration references @@ -94,4 +89,4 @@ This is the AI Development Patterns repository - a comprehensive collection of p - **Enterprise focus**: Operations patterns target compliance, security, and production concerns - **Scalability considerations**: Patterns support both small teams and enterprise deployments -When modifying this repository, maintain the established pattern structure, ensure all hyperlinks work correctly, and follow the dependency relationships defined in the reference table. \ No newline at end of file +When modifying this repository, maintain the established pattern structure, ensure all hyperlinks work correctly, and follow the dependency relationships defined in the reference table. diff --git a/PATTERN_MIGRATION_GUIDE.md b/PATTERN_MIGRATION_GUIDE.md index 687fb1e..c74889e 100644 --- a/PATTERN_MIGRATION_GUIDE.md +++ b/PATTERN_MIGRATION_GUIDE.md @@ -33,7 +33,7 @@ This change aligns with established pattern naming conventions: ## Complete Name Mapping -### Main Patterns (21 patterns) +### Main Patterns (22 patterns) | Old Name | New Name | Change Type | Notes | |----------|----------|-------------|-------| @@ -43,7 +43,7 @@ This change aligns with established pattern naming conventions: | AI Developer Lifecycle | Developer Lifecycle | Removed "AI" prefix | Lifecycle applies to AI development by default | | AI Tool Integration | Tool Integration | Removed "AI" prefix | Tools are AI tools in this context | | AI Issue Generation | Issue Generation | Removed "AI" prefix | Generation implies AI automation | -| Specification Driven Development | Spec-First | Simplified to 2 words | "Spec-First" is standard industry term | +| Specification Driven Development | Spec-Driven Development | Hyphenated compound + clarified | Aligns with the repository's current canonical naming | | AI Plan-First Development | Planned Implementation | Removed "AI", clarified | Describes planned approach to implementation | | Progressive AI Enhancement | Progressive Enhancement | Removed "AI" prefix | Progressive enhancement is well-known pattern | | AI Choice Generation | Choice Generation | Removed "AI" prefix | Generation implies AI automation | @@ -58,6 +58,7 @@ This change aligns with established pattern naming conventions: | Policy-as-Code Generation | Policy Generation | Simplified | "Generation" implies automation | | Security Scanning Orchestration | Security Orchestration | Simplified | Orchestration implies scanning/automation | | Performance Baseline Management | Baseline Management | Simplified | Context makes "Performance" implicit | +| Error Resolution | Error Resolution | No change | Already compliant (stable core pattern) | ### Main Antipatterns (31 antipatterns) @@ -71,7 +72,7 @@ This change aligns with established pattern naming conventions: | Prompt-Only AI Development | Disconnected Prompting | Simplified, negative implication | "Disconnected" clearly indicates isolation from tools | | Vague Issue Generation | Under-Specified Issues | Added negative prefix | "Under-Specified" indicates insufficiency | | Missing CI Integration | Broken Integration | Added negative prefix | "Broken" indicates failure | -| Implementation-First AI | Spec-Ignored | Symmetrical with "Spec-First" | Opposite of the pattern | +| Implementation-First AI | Spec-Ignored | Symmetrical with "Spec-Driven Development" | Opposite of the pattern | | Prompt Hoarding | Over-Prompting | Changed to "Over-" prefix | Indicates excess prompting | | Blind Code Generation | Blind Generation | Simplified | "Blind" already negative | | Analysis Paralysis | Over-Analysis | Changed to "Over-" prefix | More technical than "Paralysis" | @@ -92,7 +93,7 @@ This change aligns with established pattern naming conventions: | Alert Fatigue | Over-Alerting | Changed to "Over-" prefix | Indicates root cause (too many alerts) | | One-Off Alerts | Static Thresholds | Changed to technical term | "Static" indicates inflexibility | -### Experimental Patterns (21 patterns) +### Experimental Patterns (20 patterns) | Old Name | New Name | Change Type | Notes | |----------|----------|-------------|-------| @@ -116,7 +117,6 @@ This change aligns with established pattern naming conventions: | Visual Context Scaffolding | Image Spec | Simplified | More concise, "Image" specifies visual type | | AI Event Automation | Event Automation | Removed "AI" prefix | Automation implies AI | | Custom AI Commands | Custom Commands | Removed "AI" prefix | Commands are AI commands in context | -| Error Resolution | Error Resolution | No change | Already compliant | ### Experimental Antipatterns (25 antipatterns) @@ -161,9 +161,9 @@ This change aligns with established pattern naming conventions: - **Compliance after**: 98/98 (100%) ### By Category -- **Main Patterns**: 21 renamed, 0 unchanged +- **Main Patterns**: 21 renamed, 1 unchanged - **Main Antipatterns**: 28 renamed, 3 unchanged -- **Experimental Patterns**: 19 renamed, 2 unchanged +- **Experimental Patterns**: 19 renamed, 1 unchanged - **Experimental Antipatterns**: 22 renamed, 3 unchanged --- @@ -172,10 +172,10 @@ This change aligns with established pattern naming conventions: ### Internal Repository Changes -All references within this repository have been updated: +Core references within this repository were updated during the migration: 1. **README.md** - - Pattern reference table (lines 50-89) + - Complete Pattern Reference table - All pattern section headers - All hyperlinks and cross-references - All antipattern subsections @@ -190,6 +190,8 @@ All references within this repository have been updated: - Renamed to match new pattern names - Updated internal documentation +**Note**: The repository continues to evolve. If you find legacy names/anchors in other docs or example READMEs, treat them as stale references to be updated to match the current canonical names and anchors in `README.md`. + 4. **Configuration Files** - CLAUDE.md updated with new pattern references - pattern-spec.md updated with comprehensive naming rules @@ -245,7 +247,7 @@ All GitHub markdown anchor links have changed. Update your hyperlinks: | `#ai-developer-lifecycle` | `#developer-lifecycle` | | `#ai-tool-integration` | `#tool-integration` | | `#ai-issue-generation` | `#issue-generation` | -| `#specification-driven-development` | `#spec-first` | +| `#specification-driven-development` | `#spec-driven-development` | | `#ai-plan-first-development` | `#planned-implementation` | | `#progressive-ai-enhancement` | `#progressive-enhancement` | | `#ai-choice-generation` | `#choice-generation` | @@ -330,7 +332,7 @@ The old names are deprecated. This change improves consistency, discoverability, ### Are there any exceptions to the two-word rule? -No. All 98 patterns and antipatterns now comply with exactly two words (hyphenated compounds like "Spec-First" count as one word in this context). +No. All 98 patterns and antipatterns now comply with exactly two words (hyphenated compounds like "Spec-Driven" count as one word in this context). ### Will the old names ever be brought back? diff --git a/docs/ai-development-best-practices.md b/docs/ai-development-best-practices.md index c0ceeb5..d7154d4 100644 --- a/docs/ai-development-best-practices.md +++ b/docs/ai-development-best-practices.md @@ -4,49 +4,49 @@ A canonical, enumerated list of best practices derived from comprehensive analys ## Foundation & Team Readiness -1. **Assess Before Implementing**: Systematically evaluate team and codebase readiness using structured assessment frameworks before introducing AI development patterns. +1. **Assess Before Implementing**: Systematically evaluate team and codebase readiness using [Readiness Assessment](../README.md#readiness-assessment) before introducing AI development patterns. -2. **Establish Rules as Code**: Store AI coding standards, prompts, and preferences in versioned `.ai/` configuration directories rather than relying on ad-hoc prompting. +2. **Establish Codified Rules**: Store AI coding standards, prompts, and preferences in versioned `.ai/` configuration directories using [Codified Rules](../README.md#codified-rules) rather than relying on ad-hoc prompting. -3. **Security by Design**: Run AI tools in isolated environments with no network access, no system privileges, and read-only source code access to prevent credential leaks. +3. **Security by Design**: Run AI tools in isolated environments with no network access, no system privileges, and read-only source code access to prevent credential leaks using [Security Sandbox](../README.md#security-sandbox). -4. **Start Small, Scale Systematically**: Begin with simple AI-assisted tasks and progressively enhance complexity rather than attempting comprehensive solutions immediately. +4. **Start Small, Scale Systematically**: Begin with simple AI-assisted tasks and progressively enhance complexity using [Progressive Enhancement](../README.md#progressive-enhancement) rather than attempting comprehensive solutions immediately. ## Workflow & Development Process -5. **Specification-Driven Development**: Write machine-readable specifications with explicit authority levels (system/platform/feature) and unique identifiers before AI implementation to ensure consistent, testable outcomes. +5. **Spec-Driven Development**: Write machine-readable specifications with explicit authority levels (system/platform/feature) and unique identifiers before AI implementation to ensure consistent, testable outcomes using [Spec-Driven Development](../README.md#spec-driven-development). -6. **Test-First AI Development**: Create automated tests from specifications before AI code generation, ensuring every specification has corresponding test coverage with measurable success criteria. +6. **Test-First AI Development**: Create automated tests from specifications before AI code generation, ensuring every specification has corresponding test coverage with measurable success criteria using [Testing Orchestration](../experiments/README.md#testing-orchestration). -7. **Progressive Enhancement Over Big-Bang**: Apply Lean and Kanban principles by building features through small, deployable iterations with daily feedback cycles rather than large-scale AI generation attempts. +7. **Progressive Enhancement Over Big-Bang**: Apply Lean and Kanban principles by building features through small, deployable iterations with daily feedback cycles rather than large-scale AI generation attempts using [Progressive Enhancement](../README.md#progressive-enhancement). -8. **Structured Development Lifecycle**: Follow a systematic 9-stage process from problem definition through deployment and monitoring for consistent AI-assisted development. +8. **Structured Development Lifecycle**: Follow a systematic 9-stage process from problem definition through deployment and monitoring for consistent AI-assisted development using [Developer Lifecycle](../README.md#developer-lifecycle). -9. **Size Tasks Appropriately**: Use 4-8 hour work items for standard development and 1-2 hour atomic tasks for parallel AI agent execution. +9. **Size Tasks Appropriately**: Use 4-8 hour work items for standard development with [Issue Generation](../README.md#issue-generation) and 1-2 hour atomic tasks for parallel AI agent execution with [Atomic Decomposition](../README.md#atomic-decomposition). -10. **Generate Structured Work Items**: Break down features into specific, testable tasks with clear acceptance criteria using AI to ensure continuous development flow. +10. **Generate Structured Work Items**: Break down features into specific, testable tasks with clear acceptance criteria using [Issue Generation](../README.md#issue-generation) to ensure continuous development flow. ## Quality & Testing -11. **Comprehensive AI Testing Strategy**: Generate complete test suites (unit, integration, performance, security) automatically from specifications using AI assistance. +11. **Testing Orchestration**: Generate complete test suites (unit, integration, performance, security) automatically from specifications using [Testing Orchestration](../experiments/README.md#testing-orchestration). -12. **Maintain Test-to-Specification Traceability**: Link every specification element to automated tests with anchored references and coverage tracking. +12. **Maintain Test-to-Specification Traceability**: Link every specification element to automated tests with anchored references and coverage tracking using [Automated Traceability](../README.md#automated-traceability). -13. **Structured Observability**: Implement comprehensive logging with operation context, correlation IDs, and specific error details in standardized formats (JSON/structured) for AI analysis and debugging. +13. **Structured Observability**: Implement comprehensive logging with operation context, correlation IDs, and specific error details in standardized formats (JSON/structured) for AI analysis and debugging using [Observable Development](../README.md#observable-development). -14. **Transparent Error Handling**: Design error messages and system responses with sufficient context for AI diagnosis, including error codes, affected components, and suggested remediation steps. +14. **Transparent Error Handling**: Design error messages and system responses with sufficient context for AI diagnosis, including error codes, affected components, and suggested remediation steps using [Error Resolution](../README.md#error-resolution). 15. **Validate AI Output**: Always verify AI-generated code through automated testing and human review, especially for security and deployment configurations. ## Parallel & Multi-Agent Development -16. **Safe Agent Parallelization**: Use container isolation or Git worktrees to prevent AI agents from interfering with concurrent work on shared codebases. +16. **Safe Agent Parallelization**: Use container isolation or Git worktrees to prevent AI agents from interfering with concurrent work on shared codebases using [Parallel Agents](../README.md#parallel-agents) (and enforce isolation with [Security Sandbox](../README.md#security-sandbox)). 17. **Implement Resource Locking**: Use file-based locking and atomic operations when multiple AI agents need to access shared resources or directories. -18. **Atomic Task Decomposition**: Break complex features into independently implementable tasks that can be completed in isolation without cross-dependencies. +18. **Atomic Decomposition**: Break complex features into independently implementable tasks that can be completed in isolation without cross-dependencies using [Atomic Decomposition](../README.md#atomic-decomposition). -19. **Shared Memory for Coordination**: Enable AI agents to share discoveries and coordinate work while maintaining strict isolation boundaries for safety. +19. **Shared Memory for Coordination**: Enable AI agents to share discoveries and coordinate work while maintaining strict isolation boundaries for safety using [Context Persistence](../README.md#context-persistence). 20. **Conflict Detection and Resolution**: Implement automated systems to detect and resolve integration conflicts between parallel AI agent outputs. @@ -54,9 +54,9 @@ A canonical, enumerated list of best practices derived from comprehensive analys 21. **Capture High-Impact Knowledge**: Document successful patterns (>80% success rate) and failure modes (>30 minutes wasted) in structured, searchable formats with specific success metrics and context. -22. **Context Window Optimization**: Match AI tool selection to task complexity using defined criteria: simple models for queries <500 tokens, complex models for architecture decisions >2000 tokens. +22. **Context Optimization**: Match AI tool selection to task complexity using [Context Optimization](../experiments/README.md#context-optimization) and defined criteria: simple models for queries <500 tokens, complex models for architecture decisions >2000 tokens. -23. **Visual Context Scaffolding**: Use diagrams, mockups, and flows as primary specifications for complex needs, supplemented with structured text for precise details. +23. **Image Spec**: Use diagrams, mockups, and flows as primary specifications for complex needs using [Image Spec](../experiments/README.md#image-spec), supplemented with structured text for precise details. 24. **Version Knowledge Assets**: Treat AI development knowledge as code with semantic versioning, peer review processes, and automated quality checks. @@ -66,9 +66,9 @@ A canonical, enumerated list of best practices derived from comprehensive analys 26. **Smart Defaults with Extensibility**: Design AI development tools that work perfectly with no configuration while supporting advanced customization options. -27. **Self-Documenting Commands**: Include comprehensive built-in help with usage patterns, examples, and parameter explanations in every AI development tool. +27. **Self-Documenting Commands**: Include comprehensive built-in help with usage patterns, examples, and parameter explanations in every AI development tool using [Custom Commands](../experiments/README.md#custom-commands). -28. **Hooks-Based Governance**: Implement flexible hook systems for automated monitoring, logging, and policy enforcement at critical development workflow points. +28. **Hooks-Based Governance**: Implement flexible hook systems for automated monitoring, logging, and policy enforcement at critical development workflow points using [Event Automation](../experiments/README.md#event-automation). 29. **Modular Command Architecture**: Organize AI tools into clear categories with well-defined scopes (project-specific vs. machine-wide) for flexible workflows. @@ -78,13 +78,13 @@ A canonical, enumerated list of best practices derived from comprehensive analys ## Operations & Automation -32. **Policy as Code Generation**: Transform compliance specifications into executable Cedar/OPA policy files using AI assistance for consistency and automation. +32. **Policy Generation**: Transform compliance specifications into executable Cedar/OPA policy files using AI assistance for consistency and automation with [Policy Generation](../README.md#policy-generation). -33. **Intelligent Security Orchestration**: Aggregate multiple security tools and use AI to summarize findings, reducing alert fatigue while maintaining rigor. +33. **Security Orchestration**: Aggregate multiple security tools and use AI to summarize findings, reducing alert fatigue while maintaining rigor with [Security Orchestration](../README.md#security-orchestration). -34. **AI-Powered Performance Baselines**: Use AI to analyze historical data and establish intelligent monitoring thresholds that minimize false positives. +34. **Baseline Management**: Use AI to analyze historical data and establish intelligent monitoring thresholds that minimize false positives using [Baseline Management](../README.md#baseline-management). -35. **Automated Incident Response**: Generate actionable playbooks from historical incident data and continuously improve operational procedures. +35. **Incident Automation**: Generate actionable playbooks from historical incident data and continuously improve operational procedures using [Incident Automation](../experiments/README.md#incident-automation). 36. **Infrastructure as Specifications**: Generate deployment configurations and infrastructure code from plain-English specifications using AI assistance. @@ -205,4 +205,4 @@ A canonical, enumerated list of best practices derived from comprehensive analys --- -*This canonical list of 60 practices represents distilled wisdom from extensive AI development experience, emphasizing security, ethics, quality, and systematic approaches over ad-hoc AI usage. These practices provide a comprehensive MECE framework for teams to adopt AI-assisted development safely and effectively while maintaining high standards for code quality, system reliability, and ethical AI governance.* \ No newline at end of file +*This canonical list of 60 practices represents distilled wisdom from extensive AI development experience, emphasizing security, ethics, quality, and systematic approaches over ad-hoc AI usage. These practices provide a comprehensive MECE framework for teams to adopt AI-assisted development safely and effectively while maintaining high standards for code quality, system reliability, and ethical AI governance.* diff --git a/docs/ai-security-sandbox-blog.md b/docs/ai-security-sandbox-blog.md index 5db0e0f..aef1a37 100644 --- a/docs/ai-security-sandbox-blog.md +++ b/docs/ai-security-sandbox-blog.md @@ -1,4 +1,4 @@ -# AI Security Sandbox: Isolating AI Development Tools from Your Credentials +# Security Sandbox: Isolating AI Development Tools from Your Credentials ## The Problem @@ -8,7 +8,7 @@ AI development tools like Claude Code, GitHub Copilot, and ChatGPT plugins can a ## The Solution: Complete Network Isolation -The **AI Security Sandbox** provides complete credential isolation using Docker containers with `network_mode: none`. Even if AI tools suggest real credentials or generate malicious code, they cannot exfiltrate data or make external API calls. +The **Security Sandbox** provides complete credential isolation using Docker containers with `network_mode: none`. Even if AI tools suggest real credentials or generate malicious code, they cannot exfiltrate data or make external API calls. ## Quick Start (5 Minutes) @@ -16,12 +16,12 @@ The **AI Security Sandbox** provides complete credential isolation using Docker ```bash git clone https://github.com/PaulDuvall/ai-development-patterns.git cd ai-development-patterns - ./sandbox/ai-sandbox.sh start + ./examples/security-sandbox/ai-sandbox.sh start ``` 2. **Enter the sandbox:** ```bash - ./sandbox/ai-sandbox.sh shell + ./examples/security-sandbox/ai-sandbox.sh shell ``` 3. **Verify isolation (these should ALL FAIL):** @@ -77,13 +77,13 @@ volumes: ```bash # Start sandbox -./sandbox/ai-sandbox.sh start +./examples/security-sandbox/ai-sandbox.sh start # Run Claude Code in isolation -./sandbox/ai-sandbox.sh exec "claude 'Review this code for security issues' --file src/auth.py" +./examples/security-sandbox/ai-sandbox.sh exec "claude 'Review this code for security issues' --file src/auth.py" # Interactive session -./sandbox/ai-sandbox.sh shell +./examples/security-sandbox/ai-sandbox.sh shell # Inside sandbox: claude "Generate unit tests" --output tests/test_auth.py ``` @@ -92,7 +92,7 @@ claude "Generate unit tests" --output tests/test_auth.py ```bash # Built-in security checks -./sandbox/ai-sandbox.sh validate +./examples/security-sandbox/ai-sandbox.sh validate # Expected output: # ✅ Network isolation: ENABLED (network_mode: none) @@ -102,7 +102,7 @@ claude "Generate unit tests" --output tests/test_auth.py # ✅ Memory limit: 4GB # Test isolation -./sandbox/ai-sandbox.sh demo +./examples/security-sandbox/ai-sandbox.sh demo ``` ## Common Limitations and Solutions @@ -113,7 +113,7 @@ claude "Generate unit tests" --output tests/test_auth.py # Download documentation curl https://docs.python.org/3/library/index.html > ./docs/python-docs.html -# Mount in sandbox (edit docker-compose.ai-sandbox.yml) +# Mount in sandbox (edit examples/security-sandbox/docker-compose.ai-sandbox.yml) volumes: - ./docs:/workspace/docs:ro ``` @@ -126,20 +126,20 @@ mkdir -p ./mocks/api/ echo '{"status": "success", "data": {"id": 123}}' > ./mocks/api/user.json # Start mock server inside sandbox -./sandbox/ai-sandbox.sh shell +./examples/security-sandbox/ai-sandbox.sh shell cd /workspace/mocks && python -m http.server 8000 & ``` ### 3. No Dynamic Package Installation **Solution**: Pre-install packages: ```bash -# Edit sandbox/requirements-sandbox.txt -echo "requests==2.31.0" >> sandbox/requirements-sandbox.txt +# Edit examples/security-sandbox/requirements-sandbox.txt +echo "requests==2.31.0" >> examples/security-sandbox/requirements-sandbox.txt # Rebuild sandbox -./sandbox/ai-sandbox.sh stop -./sandbox/ai-sandbox.sh build -./sandbox/ai-sandbox.sh start +./examples/security-sandbox/ai-sandbox.sh stop +./examples/security-sandbox/ai-sandbox.sh build +./examples/security-sandbox/ai-sandbox.sh start ``` ## Architecture Overview @@ -154,7 +154,7 @@ graph TB Creds["AWS Keys, SSH Keys
Database Passwords"] end - subgraph Sandbox["AI Security Sandbox"] + subgraph Sandbox["Security Sandbox"] Container["Isolated Container
(network_mode: none)"] Workspace["/workspace
Read-only source
Write-only output"] end @@ -250,10 +250,10 @@ volumes: ```bash # Each developer runs isolated sandbox -./sandbox/ai-sandbox.sh start +./examples/security-sandbox/ai-sandbox.sh start # Version control shared configuration -cp sandbox/docker-compose.ai-sandbox.yml team-sandbox.yml +cp examples/security-sandbox/docker-compose.ai-sandbox.yml team-sandbox.yml git add team-sandbox.yml git commit -m "Add team sandbox configuration" ``` @@ -261,32 +261,32 @@ git commit -m "Add team sandbox configuration" ## Troubleshooting ### Common Issues: -1. **Slow AI responses**: Increase resource limits in docker-compose.ai-sandbox.yml +1. **Slow AI responses**: Increase resource limits in examples/security-sandbox/docker-compose.ai-sandbox.yml 2. **Need API access**: Use mock servers or fixture files 3. **Missing packages**: Pre-install in requirements-sandbox.txt 4. **File permissions**: Check user ID mapping (1000:1000) ### Quick Diagnostics: ```bash -./sandbox/ai-sandbox.sh status # Check sandbox health -./sandbox/ai-sandbox.sh validate # Security validation -./sandbox/ai-sandbox.sh demo # Test isolation +./examples/security-sandbox/ai-sandbox.sh status # Check sandbox health +./examples/security-sandbox/ai-sandbox.sh validate # Security validation +./examples/security-sandbox/ai-sandbox.sh demo # Test isolation ``` ## The Challenge -**Don't use any AI development tool again until you've implemented the AI Security Sandbox.** +**Don't use any AI development tool again until you've implemented the Security Sandbox.** Why? Every AI session without the sandbox is a potential credential leak. The 5-minute setup time is nothing compared to the months of recovery from a security incident. ## Get Started Now 1. **Clone**: `git clone https://github.com/PaulDuvall/ai-development-patterns.git` -2. **Start**: `./sandbox/ai-sandbox.sh start` -3. **Validate**: `./sandbox/ai-sandbox.sh validate` +2. **Start**: `./examples/security-sandbox/ai-sandbox.sh start` +3. **Validate**: `./examples/security-sandbox/ai-sandbox.sh validate` **The result**: Complete credential isolation with zero impact on AI productivity. --- -*Complete implementation available in the [AI Development Patterns repository](https://github.com/PaulDuvall/ai-development-patterns/tree/main/sandbox).* \ No newline at end of file +*Complete implementation available in the [AI Development Patterns repository](https://github.com/PaulDuvall/ai-development-patterns/tree/main/examples/security-sandbox).* diff --git a/docs/claude-code-guide.md b/docs/claude-code-guide.md index 2cf882a..522ce94 100644 --- a/docs/claude-code-guide.md +++ b/docs/claude-code-guide.md @@ -2,26 +2,26 @@ Transform your development workflow from traditional coding to powerful agentic programming with Claude Code. This comprehensive guide combines essential best practices, advanced techniques, and real-world workflows to help you leverage Claude as an autonomous development partner. -## 🎯 Core Philosophy: From Assistant to Agent +## Core Philosophy: From Assistant to Agent Claude Code represents a paradigm shift in development tooling. Rather than simply answering coding questions, it acts as an autonomous agent that can understand context, reason through complex problems, and execute sophisticated workflows. The key is learning how to communicate effectively and structure your environment for maximum collaboration. -## 📋 Table of Contents +## Table of Contents -1. [Foundation: Environment Setup](#️-foundation-environment-setup) -2. [Context Management Strategies](#-context-management-strategies) -3. [Communication & Reasoning Patterns](#-communication--reasoning-patterns) -4. [Security Architecture & Permissions](#-security-architecture--permissions) -5. [Advanced Tool Integration](#-advanced-tool-integration) -6. [Workflow Automation Patterns](#-workflow-automation-patterns) -7. [Team Collaboration Best Practices](#-team-collaboration-best-practices) -8. [Performance Optimization](#-performance-optimization) -9. [Troubleshooting & Common Pitfalls](#-troubleshooting--common-pitfalls) -10. [Future-Proofing Your Setup](#-future-proofing-your-setup) +1. [Foundation: Environment Setup](#foundation-environment-setup) +2. [Context Management Strategies](#context-management-strategies) +3. [Communication & Reasoning Patterns](#communication--reasoning-patterns) +4. [Security Architecture & Permissions](#security-architecture--permissions) +5. [Advanced Tool Integration](#advanced-tool-integration) +6. [Workflow Automation Patterns](#workflow-automation-patterns) +7. [Team Collaboration Best Practices](#team-collaboration-best-practices) +8. [Performance Optimization](#performance-optimization) +9. [Troubleshooting & Common Pitfalls](#troubleshooting--common-pitfalls) +10. [Future-Proofing Your Setup](#future-proofing-your-setup) --- -## 🏗️ Foundation: Environment Setup +## Foundation: Environment Setup ### The CLAUDE.md Manifesto @@ -140,7 +140,7 @@ if os.path.exists('CLAUDE.md'): --- -## 🧩 Context Management Strategies +## Context Management Strategies ### The Context Window Economy @@ -180,7 +180,7 @@ claude "refactor module" --context "src/legacy/**" --analyze-deps --- -## 💬 Communication & Reasoning Patterns +## Communication & Reasoning Patterns ### Paul Hammond's Communication Approach @@ -316,7 +316,7 @@ Review: Run performance tests and security audit after changes --- -## 🔒 Security Architecture & Permissions +## Security Architecture & Permissions ### Defense in Depth @@ -421,7 +421,7 @@ if __name__ == "__main__": --- -## 🔧 Advanced Tool Integration +## Advanced Tool Integration ### Tool Categories & Implementation @@ -603,7 +603,7 @@ workflows: --- -## 🔄 Workflow Automation Patterns +## Workflow Automation Patterns ### Common Automation Scenarios @@ -720,7 +720,7 @@ class FeatureDevelopmentAgent: --- -## 👥 Team Collaboration Best Practices +## Team Collaboration Best Practices ### Shared Knowledge Base @@ -833,7 +833,7 @@ Provide optimized version that maintains our 'functional light' principles. --- -## ⚡ Performance Optimization +## Performance Optimization ### Context Window Optimization @@ -985,7 +985,7 @@ class ClaudeUsageMonitor: --- -## 🔍 Troubleshooting & Common Pitfalls +## Troubleshooting & Common Pitfalls ### Common Issues and Solutions @@ -1105,7 +1105,7 @@ async def request_permission(task: Dict[str, Any]) -> bool: --- -## 🚀 Future-Proofing Your Setup +## Future-Proofing Your Setup ### Scalability Considerations @@ -1146,7 +1146,7 @@ metrics: --- -## 📚 Quick Reference Card +## Quick Reference Card ### Essential Commands ```bash @@ -1176,7 +1176,7 @@ claude report --format md --include-metrics --- -## 🎯 Next Steps Checklist +## Next Steps Checklist - [ ] Create comprehensive `CLAUDE.md` for your main project - [ ] Set up context initialization scripts @@ -1191,10 +1191,10 @@ claude report --format md --include-metrics --- -## 📺 Resources & References +## Resources & References ### Video Tutorials -- **[My TOP 6 Claude Code PRO tips for AI Coding](http://www.youtube.com/watch?v=wFQ_i9XdkXU)**: Comprehensive walkthrough of advanced techniques +- **[My TOP 6 Claude Code PRO tips for AI Coding](https://www.youtube.com/watch?v=wFQ_i9XdkXU)**: Comprehensive walkthrough of advanced techniques ### Real-World Practices - **[Paul Hammond's CLAUDE.md](https://github.com/citypaul/.dotfiles/blob/main/claude/.claude/CLAUDE.md)**: Production-tested practices for type-safe, test-driven development with Claude Code @@ -1217,7 +1217,7 @@ claude report --format md --include-metrics --- -## 🙏 Acknowledgments +## Acknowledgments Special thanks to **Paul Hammond** ([@paulhammond](https://github.com/citypaul)) for sharing his production-tested CLAUDE.md configuration and development practices. His rigorous approach to test-driven development, type safety, and functional programming principles has significantly influenced the practical sections of this guide. @@ -1230,4 +1230,4 @@ Key contributions from Paul Hammond's approach: --- -*Remember: The goal isn't to replace human developers but to augment their capabilities. Claude Code is most powerful when used as a collaborative partner that handles routine tasks while you focus on creative problem-solving and strategic decisions.* \ No newline at end of file +*Remember: The goal isn't to replace human developers but to augment their capabilities. Claude Code is most powerful when used as a collaborative partner that handles routine tasks while you focus on creative problem-solving and strategic decisions.* diff --git a/docs/introducing-ai-development-patterns.md b/docs/introducing-ai-development-patterns.md index 34afc2e..b134121 100644 --- a/docs/introducing-ai-development-patterns.md +++ b/docs/introducing-ai-development-patterns.md @@ -21,7 +21,7 @@ Equally important are the **anti-patterns**—those seemingly reasonable approac ## Open Source from Day One -I've published these patterns in a public GitHub repository: https://github.com/PaulDuvall/ai-development-patterns +I've published these patterns in a public GitHub repository: [PaulDuvall/ai-development-patterns](https://github.com/PaulDuvall/ai-development-patterns) Why make it public while it's still evolving? Three reasons: @@ -37,21 +37,23 @@ The repository currently organizes patterns into three main categories: ### Foundation Patterns Essential patterns for team readiness and basic AI integration: -- **AI Readiness Assessment**: Evaluating if your codebase and team are prepared for AI adoption -- **Rules as Code**: Versioning AI coding standards like infrastructure -- **AI Security Sandbox**: Running AI tools without credential leak risks +- **[Readiness Assessment](../README.md#readiness-assessment)**: Evaluating if your codebase and team are prepared for AI adoption +- **[Codified Rules](../README.md#codified-rules)**: Versioning AI coding standards like infrastructure +- **[Security Sandbox](../README.md#security-sandbox)**: Running AI tools without credential leak risks ### Development Patterns Daily practice patterns for AI-assisted coding workflows: -- **Specification Driven Development**: Using executable specs to guide AI code generation -- **Progressive AI Enhancement**: Building features incrementally rather than all at once -- **Context Window Optimization**: Matching AI tool selection to task complexity +- **[Spec-Driven Development](../README.md#spec-driven-development)**: Using executable specs to guide AI code generation +- **[Progressive Enhancement](../README.md#progressive-enhancement)**: Building features incrementally rather than all at once +- **[Context Persistence](../README.md#context-persistence)**: Managing context and continuity across AI-assisted sessions ### Operations Patterns CI/CD, security, and production management with AI: -- **Pipeline Synthesis**: Converting plain English to CI/CD configurations -- **Security Scanning Orchestration**: AI-powered security finding summarization -- **Technical Debt Forecasting**: Proactive AI-driven code quality management +- **[Policy Generation](../README.md#policy-generation)**: Transforming compliance requirements into executable policy files +- **[Security Orchestration](../README.md#security-orchestration)**: Aggregating security tools and summarizing findings for actionable insights +- **[Baseline Management](../README.md#baseline-management)**: Establishing intelligent performance baselines and monitoring thresholds + +For advanced and in-progress ideas, see the experimental catalog in [experiments/](../experiments/), including patterns like **[Pipeline Synthesis](../experiments/README.md#pipeline-synthesis)**, **[Debt Forecasting](../experiments/README.md#debt-forecasting)**, and **[Context Optimization](../experiments/README.md#context-optimization)**. ## What Makes This Different? @@ -85,8 +87,8 @@ The goal isn't to create rigid rules but to capture flexible practices that team ## Get Started -Visit https://github.com/PaulDuvall/ai-development-patterns to explore the current practices. Star the repository to stay updated, and consider contributing your own experiences. +Visit [PaulDuvall/ai-development-patterns](https://github.com/PaulDuvall/ai-development-patterns) to explore the current practices. Star the repository to stay updated, and consider contributing your own experiences. --- -*What practices have you discovered in your AI development journey? I'd love to hear about your experiences and add them to this growing collection.* \ No newline at end of file +*What practices have you discovered in your AI development journey? I'd love to hear about your experiences and add them to this growing collection.* diff --git a/examples/atomic-decomposition/README.md b/examples/atomic-decomposition/README.md index dbc397e..16f8a19 100644 --- a/examples/atomic-decomposition/README.md +++ b/examples/atomic-decomposition/README.md @@ -1,11 +1,11 @@ -# Atomic Task Decomposition Example +# Atomic Decomposition Example -This directory contains a complete implementation of the Atomic Task Decomposition pattern with contract validation, dependency resolution, and parallel execution coordination for AI agents. +This directory contains a complete implementation of the Atomic Decomposition pattern with contract validation, dependency resolution, and parallel execution coordination for AI agents. ## Directory Structure ``` -atomic-task-decomposition/ +atomic-decomposition/ ├── README.md # This file ├── function-level-decomposition.md # Function-level decomposition techniques when AI struggles ├── task-decomposer.py # AI-powered task decomposition tool @@ -116,4 +116,4 @@ This system integrates with: - **CI/CD Pipelines**: Automated testing and integration - **Monitoring Tools**: Real-time progress and conflict detection -See individual component files for detailed implementation and API documentation. \ No newline at end of file +See individual component files for detailed implementation and API documentation. diff --git a/examples/atomic-decomposition/function-level-decomposition.md b/examples/atomic-decomposition/function-level-decomposition.md index ac43a9e..488f6c2 100644 --- a/examples/atomic-decomposition/function-level-decomposition.md +++ b/examples/atomic-decomposition/function-level-decomposition.md @@ -1,6 +1,6 @@ # Function-Level Decomposition Techniques -This guide provides detailed techniques for decomposing atomic tasks into individual functions when AI struggles with larger implementations, as referenced in the [Atomic Task Decomposition](../../README.md#atomic-task-decomposition) pattern. +This guide provides detailed techniques for decomposing atomic tasks into individual functions when AI struggles with larger implementations, as referenced in the [Atomic Decomposition](../../README.md#atomic-decomposition) pattern. ## Overview @@ -307,4 +307,4 @@ function validateContract( - **Performance validation**: Combined functions should meet performance requirements - **Error handling**: Integration should handle individual function failures gracefully -This systematic approach to function-level decomposition enables successful AI implementation of complex tasks that would otherwise fail due to excessive complexity or unclear requirements. \ No newline at end of file +This systematic approach to function-level decomposition enables successful AI implementation of complex tasks that would otherwise fail due to excessive complexity or unclear requirements. diff --git a/examples/automated-traceability/README.md b/examples/automated-traceability/README.md index 33c6f7f..08b5cc0 100644 --- a/examples/automated-traceability/README.md +++ b/examples/automated-traceability/README.md @@ -1,10 +1,10 @@ -# AI-Driven Traceability Implementation +# Automated Traceability Implementation -This directory contains a complete implementation of the AI-Driven Traceability pattern, maintaining automated links between requirements, specifications, tests, implementation, and documentation using AI. +This directory contains a complete implementation of the Automated Traceability pattern, maintaining automated links between requirements, specifications, tests, implementation, and documentation using AI. ## Overview -AI-Driven Traceability enables teams to: +Automated Traceability enables teams to: - Automatically link code changes to requirements and user stories - Validate existing traceability links for accuracy - Generate impact analysis for code changes @@ -374,4 +374,4 @@ When extending traceability features: - Protect API credentials for project management integrations - Validate requirement IDs to prevent injection attacks - Audit traceability data access and modifications -- Secure webhook endpoints for external integrations \ No newline at end of file +- Secure webhook endpoints for external integrations diff --git a/examples/baseline-management/README.md b/examples/baseline-management/README.md index a0908d5..45f2918 100644 --- a/examples/baseline-management/README.md +++ b/examples/baseline-management/README.md @@ -1,10 +1,10 @@ -# Performance Baseline Management Implementation +# Baseline Management Implementation -This directory contains a complete implementation of the Performance Baseline Management pattern, establishing intelligent performance baselines and configuring monitoring thresholds automatically. +This directory contains a complete implementation of the Baseline Management pattern, establishing intelligent performance baselines and configuring monitoring thresholds automatically. ## Overview -Performance Baseline Management enables teams to: +Baseline Management enables teams to: - Establish intelligent performance baselines using historical data - Configure monitoring thresholds automatically based on patterns - Minimize false positives while catching real performance issues @@ -35,4 +35,4 @@ python threshold_calculator.py --input metrics.csv --output thresholds.json python autoscale_generator.py --thresholds thresholds.json --output policies/ ``` -**Complete Implementation**: This directory contains the full performance baseline management system with metric collection, AI-powered analysis, and policy generation tools. \ No newline at end of file +**Complete Implementation**: This directory contains the full performance baseline management system with metric collection, AI-powered analysis, and policy generation tools. diff --git a/examples/codified-rules/README.md b/examples/codified-rules/README.md index 65e049c..a08d382 100644 --- a/examples/codified-rules/README.md +++ b/examples/codified-rules/README.md @@ -1,10 +1,10 @@ -# Rules as Code Example +# Codified Rules Example Comprehensive rules framework for enforcing development standards, quality gates, and delivery practices through machine-readable rule files. ## Overview -This example demonstrates the **Rules as Code** pattern through three rule files that establish mandatory guardrails for AI-assisted development: +This example demonstrates the **Codified Rules** pattern through three rule files that establish mandatory guardrails for AI-assisted development: 1. **DEVELOPMENT_RULES.md** - Test-first specification-driven development 2. **QUALITY_RULES.md** - Code quality standards and observability @@ -283,16 +283,16 @@ echo "✅ All rules validated" ## Integration with Main Patterns This example demonstrates: -- **[Rules as Code](../../README.md#rules-as-code)** - Machine-readable development standards -- **[Specification Driven Development](../../README.md#specification-driven-development)** - Test-first with traceability -- **[Observable AI Development](../../README.md#observable-ai-development)** - Structured logging requirements -- **[AI-Driven Traceability](../../README.md#ai-driven-traceability)** - Spec-test-code linking +- **[Codified Rules](../../README.md#codified-rules)** - Machine-readable development standards +- **[Spec-Driven Development](../../README.md#spec-driven-development)** - Test-first with traceability +- **[Observable Development](../../README.md#observable-development)** - Structured logging requirements +- **[Automated Traceability](../../README.md#automated-traceability)** - Spec-test-code linking ## Related Patterns -- [Progressive AI Enhancement](../../README.md#progressive-ai-enhancement) - Gradual feature rollout -- [AI Security Sandbox](../../README.md#ai-security-sandbox) - Security validation rules -- [AI Developer Lifecycle](../../README.md#ai-developer-lifecycle) - Complete workflow integration +- [Progressive Enhancement](../../README.md#progressive-enhancement) - Gradual feature rollout +- [Security Sandbox](../../README.md#security-sandbox) - Security validation rules +- [Developer Lifecycle](../../README.md#developer-lifecycle) - Complete workflow integration ## Contributing diff --git a/examples/context-persistence/README.md b/examples/context-persistence/README.md index 2cdd43e..b22043f 100644 --- a/examples/context-persistence/README.md +++ b/examples/context-persistence/README.md @@ -1,4 +1,4 @@ -# AI Context Persistence Implementation +# Context Persistence Implementation Manage AI context as a finite resource through structured memory schemas and session continuity. @@ -259,7 +259,7 @@ For enterprise features, see [ADVANCED.md](ADVANCED.md): ## Files in this Implementation ``` -examples/ai-context-persistence/ +examples/context-persistence/ ├── README.md # This file ├── ADVANCED.md # Advanced features ├── templates/ # Memory schema templates diff --git a/examples/developer-lifecycle/README.md b/examples/developer-lifecycle/README.md index 13f1539..3d7a605 100644 --- a/examples/developer-lifecycle/README.md +++ b/examples/developer-lifecycle/README.md @@ -1,11 +1,11 @@ -# AI Developer Lifecycle Example +# Developer Lifecycle Example -This directory contains a working bash script that implements the 9-stage AI Developer Lifecycle, enhanced implementation techniques including the Five-Try Rule and systematic retry strategies, and a comprehensive workflow example showing how to apply these techniques in practice. +This directory contains a working bash script that implements the 9-stage Developer Lifecycle, enhanced implementation techniques including the Five-Try Rule and systematic retry strategies, and a comprehensive workflow example showing how to apply these techniques in practice. ## Current Structure ``` -ai-development-lifecycle/ +developer-lifecycle/ ├── README.md # This file ├── lifecycle-workflow.sh # ✅ Complete 9-stage workflow automation script └── examples/ # Empty directory for future examples @@ -16,7 +16,7 @@ ai-development-lifecycle/ A full implementation would include: ``` -ai-development-lifecycle/ +developer-lifecycle/ ├── README.md # This file ├── lifecycle-workflow.sh # ✅ Complete 9-stage workflow automation script ├── comprehensive-workflow-example.md # ✅ Complete 7-step implementation example @@ -173,4 +173,4 @@ To extend this example: 3. Add CI/CD integration templates in `ci-integration/` 4. Enhance the bash script with additional features -The current script provides a solid foundation for the complete AI Developer Lifecycle pattern. \ No newline at end of file +The current script provides a solid foundation for the complete [Developer Lifecycle](../../README.md#developer-lifecycle) pattern. diff --git a/examples/developer-lifecycle/enhanced-implementation-techniques.md b/examples/developer-lifecycle/enhanced-implementation-techniques.md index 4450f14..f302d6f 100644 --- a/examples/developer-lifecycle/enhanced-implementation-techniques.md +++ b/examples/developer-lifecycle/enhanced-implementation-techniques.md @@ -1,10 +1,10 @@ -# Enhanced AI Developer Lifecycle Implementation Techniques +# Enhanced Developer Lifecycle Implementation Techniques -This guide provides detailed implementation techniques for the [AI Developer Lifecycle](../../README.md#ai-developer-lifecycle) pattern, including the Five-Try Rule, systematic retry strategies, and integration approaches. +This guide provides detailed implementation techniques for the [Developer Lifecycle](../../README.md#developer-lifecycle) pattern, including the Five-Try Rule, systematic retry strategies, and integration approaches. ## Overview -The 9-stage AI Developer Lifecycle can be enhanced with proven implementation techniques that improve success rates, reduce iteration cycles, and provide systematic approaches to handling implementation challenges. +The 9-stage Developer Lifecycle can be enhanced with proven implementation techniques that improve success rates, reduce iteration cycles, and provide systematic approaches to handling implementation challenges. ## Stage-Specific Enhancement Techniques @@ -413,4 +413,4 @@ claude review "complete authentication flow" --focus="security, performance, int - [ ] Monitoring and observability implemented - [ ] Rollback procedures tested and documented -This enhanced implementation approach significantly improves success rates for AI-assisted development while maintaining high quality standards and systematic approaches to handling implementation challenges. \ No newline at end of file +This enhanced implementation approach significantly improves success rates for AI-assisted development while maintaining high quality standards and systematic approaches to handling implementation challenges. diff --git a/examples/guided-refactoring/README.md b/examples/guided-refactoring/README.md index 268cedd..0f46fb2 100644 --- a/examples/guided-refactoring/README.md +++ b/examples/guided-refactoring/README.md @@ -1,11 +1,11 @@ -# AI-Driven Refactoring Example +# Guided Refactoring Example -This directory contains a complete implementation of the AI-Driven Refactoring pattern with automated code smell detection, refactoring pipeline, and quality metrics tracking. +This directory contains a complete implementation of the Guided Refactoring pattern with automated code smell detection, refactoring pipeline, and quality metrics tracking. ## Directory Structure ``` -ai-driven-refactoring/ +guided-refactoring/ ├── README.md # This file ├── refactoring-rules.md # Configurable refactoring rules and thresholds ├── refactor-pipeline.sh # Automated refactoring pipeline script @@ -52,4 +52,4 @@ This example integrates with: - Git workflow with atomic commits - CI/CD pipelines for automated quality gates -See individual files for detailed implementation and usage instructions. \ No newline at end of file +See individual files for detailed implementation and usage instructions. diff --git a/examples/issue-generation/README.md b/examples/issue-generation/README.md index 94f789f..c934deb 100644 --- a/examples/issue-generation/README.md +++ b/examples/issue-generation/README.md @@ -1,4 +1,4 @@ -# AI Issue Generation Examples +# Issue Generation Examples Learn how to generate small, deployable work items for AI-assisted development with <1 hour cycle times. diff --git a/examples/observable-development/README.md b/examples/observable-development/README.md index d261682..20ef490 100644 --- a/examples/observable-development/README.md +++ b/examples/observable-development/README.md @@ -1,10 +1,10 @@ -# Observable AI Development Implementation +# Observable Development Implementation -This directory contains a complete implementation of the Observable AI Development pattern, providing comprehensive logging, tracing, and debugging capabilities that enable AI to understand system behavior and diagnose issues effectively. +This directory contains a complete implementation of the Observable Development pattern, providing comprehensive logging, tracing, and debugging capabilities that enable AI to understand system behavior and diagnose issues effectively. ## Overview -Observable AI Development ensures that: +Observable Development ensures that: - All system operations are logged with structured, AI-readable data - Performance metrics are captured automatically - Error conditions include sufficient context for AI diagnosis @@ -311,4 +311,4 @@ When extending observability features: - Implement data sanitization for production logs - Secure log storage and transmission - Regular audit of logged data for compliance -- Configure appropriate log retention policies \ No newline at end of file +- Configure appropriate log retention policies diff --git a/examples/parallel-agents/README.md b/examples/parallel-agents/README.md index 8544acc..14fefc1 100644 --- a/examples/parallel-agents/README.md +++ b/examples/parallel-agents/README.md @@ -1,6 +1,6 @@ -# Parallelized AI Coding Agents - Example Implementation +# Parallel Agents - Example Implementation -This directory contains a complete, practical implementation of the Parallelized AI Coding Agents pattern. The example demonstrates how to run multiple AI agents concurrently to build a Task Management SaaS application. +This directory contains a complete, practical implementation of the Parallel Agents pattern. The example demonstrates how to run multiple AI agents concurrently to build a Task Management SaaS application. ## 🎯 Overview @@ -14,7 +14,7 @@ This example shows how to: ## 📁 Directory Structure ``` -parallelized-ai-agents/ +parallel-agents/ ├── config/ │ └── tasks.yaml # Task definitions for agents ├── docker/ @@ -48,7 +48,7 @@ parallelized-ai-agents/ ```bash # Clone the repository git clone -cd examples/parallelized-ai-agents +cd examples/parallel-agents # Create necessary directories mkdir -p workspace/{frontend,backend,database,tests} @@ -587,7 +587,7 @@ The agents work in parallel, share discoveries through shared memory, and their ## 📚 Additional Resources -- [Pattern Documentation](../../README.md#parallelized-ai-coding-agents) +- [Pattern Documentation](../../README.md#parallel-agents) - [Shared Memory Module](scripts/shared_memory.py) - [Docker Compose Reference](https://docs.docker.com/compose/) - [Git Worktree Documentation](https://git-scm.com/docs/git-worktree) @@ -603,4 +603,4 @@ To improve this example: --- -**Note**: This is a demonstration of the pattern. In production, you would integrate with actual AI APIs and implement proper error handling, retries, and monitoring. \ No newline at end of file +**Note**: This is a demonstration of the pattern. In production, you would integrate with actual AI APIs and implement proper error handling, retries, and monitoring. diff --git a/examples/planned-implementation/README.md b/examples/planned-implementation/README.md index f59e43d..df0e627 100644 --- a/examples/planned-implementation/README.md +++ b/examples/planned-implementation/README.md @@ -1,10 +1,12 @@ -# AI Plan-First Development - Complete Implementation +# Planned Implementation - Complete Implementation -This directory contains comprehensive examples and templates for implementing the **AI Plan-First Development** pattern across different AI coding tools and development scenarios. +This directory contains comprehensive examples and templates for implementing the **Planned Implementation** pattern across different AI coding tools and development scenarios. ## Pattern Overview -AI Plan-First Development leverages the planning capabilities built into modern AI coding tools to create structured implementation approaches before writing any code. This pattern reduces iterations, improves code quality, and enables better team collaboration. +Planned Implementation leverages the planning capabilities built into modern AI coding tools to create structured implementation approaches before writing any code. This pattern reduces iterations, improves code quality, and enables better team collaboration. + +For complete pattern documentation, see: [Planned Implementation](../../README.md#planned-implementation) **Core Principle**: Generate explicit implementation plans before writing code to improve quality, reduce iterations, and enable better collaboration. @@ -218,4 +220,4 @@ Document successful applications of this pattern: - Quality improvements measured - Lessons learned from planning failures -This implementation demonstrates how AI Plan-First Development transforms ad-hoc coding into structured, predictable development workflows that scale across teams and project complexity levels. \ No newline at end of file +This implementation demonstrates how AI Plan-First Development transforms ad-hoc coding into structured, predictable development workflows that scale across teams and project complexity levels. diff --git a/examples/planned-implementation/markdown-iteration-techniques.md b/examples/planned-implementation/markdown-iteration-techniques.md index f287ce0..325a9ed 100644 --- a/examples/planned-implementation/markdown-iteration-techniques.md +++ b/examples/planned-implementation/markdown-iteration-techniques.md @@ -1,6 +1,6 @@ # Markdown Iteration Techniques -This guide provides detailed techniques for iterating on implementation plans using structured markdown documentation, as referenced in the [AI Plan-First Development](../../README.md#ai-plan-first-development) pattern. +This guide provides detailed techniques for iterating on implementation plans using structured markdown documentation, as referenced in the [Planned Implementation](../../README.md#planned-implementation) pattern. ## Overview @@ -237,4 +237,4 @@ claude validate "Check this plan for implementation readiness: [refined plan]" - Security tests: Permission boundary validation ``` -This complete iteration demonstrates how structured markdown planning evolves from simple concepts to implementation-ready specifications through systematic refinement cycles. \ No newline at end of file +This complete iteration demonstrates how structured markdown planning evolves from simple concepts to implementation-ready specifications through systematic refinement cycles. diff --git a/examples/policy-generation/README.md b/examples/policy-generation/README.md index 69051fa..1f61447 100644 --- a/examples/policy-generation/README.md +++ b/examples/policy-generation/README.md @@ -1,6 +1,6 @@ -# Policy-as-Code Generation Implementation +# Policy Generation Implementation -This directory contains a complete implementation of the Policy-as-Code Generation pattern, transforming compliance requirements into executable Cedar/OPA policy files using AI assistance. +This directory contains a complete implementation of the Policy Generation pattern, transforming compliance requirements into executable Cedar/OPA policy files using AI assistance. ## Overview @@ -177,4 +177,4 @@ When adding new policy generation capabilities: - Review all AI-generated policies before deployment - Test policies with realistic data scenarios - Maintain audit logs for policy changes -- Regular compliance validation and testing \ No newline at end of file +- Regular compliance validation and testing diff --git a/examples/security-orchestration/README.md b/examples/security-orchestration/README.md index 2ee7ffb..fd748fa 100644 --- a/examples/security-orchestration/README.md +++ b/examples/security-orchestration/README.md @@ -1,10 +1,10 @@ -# Security Scanning Orchestration Implementation +# Security Orchestration Implementation -This directory contains a complete implementation of the Security Scanning Orchestration pattern, aggregating multiple security tools and using AI to summarize findings for actionable insights. +This directory contains a complete implementation of the Security Orchestration pattern, aggregating multiple security tools and using AI to summarize findings for actionable insights. ## Overview -Security Scanning Orchestration enables teams to: +Security Orchestration enables teams to: - Aggregate results from multiple security scanning tools - Use AI to summarize and prioritize findings - Reduce alert fatigue while maintaining security rigor @@ -34,4 +34,4 @@ python ai_summarizer.py --input-dir scan-results/ --output pr-comment.md gh pr comment --body-file pr-comment.md ``` -**Complete Implementation**: This directory contains the full security scanning orchestration system with tool integration, AI-powered analysis, and CI/CD pipeline examples. \ No newline at end of file +**Complete Implementation**: This directory contains the full security scanning orchestration system with tool integration, AI-powered analysis, and CI/CD pipeline examples. diff --git a/examples/security-sandbox/Dockerfile.ai-sandbox b/examples/security-sandbox/Dockerfile.ai-sandbox index 19b48c8..680ff33 100644 --- a/examples/security-sandbox/Dockerfile.ai-sandbox +++ b/examples/security-sandbox/Dockerfile.ai-sandbox @@ -1,13 +1,13 @@ -# AI Security Sandbox Dockerfile +# Security Sandbox Dockerfile # Secure, isolated environment for AI-assisted development -# Based on AI Security Sandbox pattern from README.md +# Based on the Security Sandbox pattern from README.md # Use official Python slim image for smaller attack surface FROM python:3.11-slim-bullseye # Metadata LABEL maintainer="AI Development Team" -LABEL description="AI Security Sandbox - Isolated development environment" +LABEL description="Security Sandbox - Isolated development environment" LABEL ai.sandbox="true" LABEL ai.security.level="high" LABEL version="1.0" @@ -33,7 +33,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && apt-get clean # Set up Python environment -COPY sandbox/requirements-sandbox.txt /tmp/requirements-sandbox.txt +COPY requirements-sandbox.txt /tmp/requirements-sandbox.txt RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r /tmp/requirements-sandbox.txt && \ rm /tmp/requirements-sandbox.txt @@ -88,11 +88,11 @@ ENV HTTP_PROXY="" ENV HTTPS_PROXY="" # Health check script -COPY --chown=aiuser:aiuser sandbox/healthcheck.py /workspace/healthcheck.py +COPY --chown=aiuser:aiuser healthcheck.py /workspace/healthcheck.py RUN chmod +x /workspace/healthcheck.py # Create AI workspace initialization script -COPY --chown=aiuser:aiuser sandbox/init-workspace.sh /workspace/init-workspace.sh +COPY --chown=aiuser:aiuser init-workspace.sh /workspace/init-workspace.sh RUN chmod +x /workspace/init-workspace.sh # Security: Final permission lockdown @@ -123,5 +123,5 @@ CMD ["/bin/bash", "-c", "/workspace/init-workspace.sh && exec /bin/bash"] # 8. Health checks ensure container responsiveness # Usage: -# docker-compose -f sandbox/docker-compose.ai-sandbox.yml up ai-development -# docker exec -it ai-dev-sandbox /bin/bash \ No newline at end of file +# docker-compose -f docker-compose.ai-sandbox.yml up ai-development +# docker exec -it ai-dev-sandbox /bin/bash diff --git a/examples/security-sandbox/README.md b/examples/security-sandbox/README.md index 7e6d8c9..c667835 100644 --- a/examples/security-sandbox/README.md +++ b/examples/security-sandbox/README.md @@ -1,173 +1,46 @@ -# AI Security Sandbox Implementation +# Security Sandbox Implementation -This directory contains a complete implementation of the AI Security Sandbox pattern, providing secure isolation for AI tools that prevents access to secrets, credentials, or sensitive data. +This directory contains a runnable example implementation of the **[Security Sandbox](../../README.md#security-sandbox)** pattern: running AI tools in an isolated container with **no network access** and **no access to host credentials**. ## Overview -The AI Security Sandbox creates containerized environments that: -- Completely isolate AI tools from network access -- Prevent access to secrets and credentials -- Provide read-only access to source code -- Enable safe parallel agent execution -- Include emergency shutdown procedures - -## Files in this Implementation - -- `docker-compose.basic.yml` - Basic single-agent isolation -- `docker-compose.parallel-agents.yml` - Multi-agent isolation with coordination -- `resource-locking.sh` - Resource conflict prevention for parallel agents -- `emergency-shutdown.sh` - Safety monitoring and emergency procedures -- `security-monitor.py` - Violation detection and reporting -- `init-sandbox.sh` - Sandbox initialization script +The Security Sandbox example provides: +- Complete network isolation (`network_mode: none`) +- Non-root execution (UID 1000) +- Read-only source mounts +- Separate writable output and log mounts + +## Files in This Implementation + +- `Dockerfile.ai-sandbox` - Minimal container image for secure AI-assisted development +- `docker-compose.basic.yml` - Smallest, single-container sandbox +- `docker-compose.ai-sandbox.yml` - Script-friendly sandbox configuration +- `docker-compose.parallel-agents.yml` - Example multi-agent sandbox with isolated outputs +- `ai-sandbox.sh` - Convenience script to build/start/validate the sandbox +- `init-workspace.sh` - Container init script (creates runtime dirs and prints safety status) +- `healthcheck.py` - Basic sandbox health check +- `requirements-sandbox.txt` - Base Python dependencies installed in the image +- `resource-locking.sh` - Example resource locking helper for parallel agents +- `emergency-shutdown.sh` - Emergency shutdown helper ## Quick Start -### Single Agent Sandbox +From the repository root: ```bash -# Launch basic isolated sandbox -docker-compose -f docker-compose.basic.yml up -d - -# Work in isolated environment -docker-compose exec ai-development bash +./examples/security-sandbox/ai-sandbox.sh start +./examples/security-sandbox/ai-sandbox.sh shell ``` -### Multi-Agent Parallel Sandbox +Or run the minimal Compose file directly: ```bash -# Launch parallel agents -docker-compose -f docker-compose.parallel-agents.yml up -d - -# Monitor agent coordination -./resource-locking.sh monitor - -# Emergency shutdown if needed -./emergency-shutdown.sh +cd examples/security-sandbox +docker compose -f docker-compose.basic.yml up -d +docker compose exec ai-development bash ``` -## Security Features - -### Complete Network Isolation -- `network_mode: none` prevents all network access -- No DNS resolution or HTTP callbacks possible -- Agents cannot leak data via network requests - -### Privilege Restrictions -- `cap_drop: [ALL]` removes all system capabilities -- `no-new-privileges` prevents privilege escalation -- Containers run with minimal permissions - -### File System Controls -- Source code mounted read-only -- Secrets and credentials not mounted -- Isolated output directories per agent - -### Resource Constraints -- Process limits prevent resource exhaustion -- File descriptor limits protect host system -- Execution timeouts prevent runaway processes - -## Multi-Agent Coordination - -When running multiple AI agents in parallel, the sandbox provides: - -### Resource Locking -- File-based locking prevents conflicts -- Atomic operations for shared resources -- Automatic lock release on agent completion - -### Workspace Isolation -- Each agent gets isolated output directory -- No shared mutable state between agents -- Clear separation of agent workspaces - -### Emergency Procedures -- Violation monitoring and alerting -- Automatic shutdown on safety breaches -- Workspace cleanup and reset capabilities - -## Configuration - -### Environment Variables -- `AGENT_ID` - Unique identifier for each agent -- `MAX_EXECUTION_TIME` - Timeout in seconds -- `AI_SANDBOX` - Enables sandbox mode restrictions - -### Volume Mounts -- `/workspace/src:ro` - Read-only source code -- `/workspace/tests:rw` - Read-write test directory -- `/output:rw` - Agent-specific output directory - -## Monitoring and Safety - -### Violation Detection -The sandbox monitors for: -- Attempts to access restricted files -- Network access attempts -- Privilege escalation attempts -- Resource limit violations - -### Emergency Response -- Automatic shutdown on violation threshold -- Process termination and cleanup -- Workspace reset procedures -- Incident logging and reporting - -## Integration with CI/CD - -The sandbox integrates with continuous integration: -- Pre-commit hooks validate sandbox compliance -- CI pipelines run in sandboxed environments -- Security scans verify isolation effectiveness -- Deployment gates check for violations - -## Troubleshooting - -### Common Issues -- **Permission Denied**: Check volume mount permissions -- **Network Errors**: Verify `network_mode: none` is correct -- **Resource Limits**: Adjust ulimits for your workload -- **Lock Conflicts**: Check resource-locking.sh logs - -### Debug Commands -```bash -# Check container isolation -docker inspect ai-development | grep -i network - -# Monitor resource usage -docker stats ai-development - -# View security violations -tail -f logs/security-violations.log -``` - -## Advanced Configuration - -### Custom Security Policies -Edit `security-policies.json` to customize: -- File access restrictions -- Resource limits -- Violation thresholds -- Emergency response actions - -### Agent Specialization -Configure agent-specific restrictions: -- Language-specific tool access -- Framework-dependent permissions -- Project-specific security policies - -## Contributing - -When modifying the sandbox configuration: -1. Test with representative AI workloads -2. Verify security isolation effectiveness -3. Update documentation for new features -4. Add tests for security boundaries - -## Security Considerations +## Notes -⚠️ **Important Security Notes** -- Never mount credential directories (`.aws`, `.ssh`, etc.) -- Regularly audit mounted volumes for sensitive data -- Monitor sandbox escape attempts in logs -- Keep container images updated for security patches \ No newline at end of file +- `src/` is a small placeholder directory you can replace with your own code mount. +- `generated/` and `logs/` are created at runtime and are intentionally not committed. diff --git a/examples/security-sandbox/ai-sandbox.sh b/examples/security-sandbox/ai-sandbox.sh index 3e3f570..c254822 100755 --- a/examples/security-sandbox/ai-sandbox.sh +++ b/examples/security-sandbox/ai-sandbox.sh @@ -1,7 +1,7 @@ #!/bin/bash -# AI Security Sandbox Management Script -# Simplifies setup and usage of the AI Security Sandbox pattern +# Security Sandbox Management Script +# Simplifies setup and usage of the Security Sandbox pattern # Based on: https://github.com/PaulDuvall/ai-development-patterns set -euo pipefail @@ -39,7 +39,7 @@ log_error() { # Help function show_help() { cat << EOF -AI Security Sandbox Management Script +Security Sandbox Management Script USAGE: $0 [COMMAND] [OPTIONS] @@ -88,7 +88,7 @@ SECURITY FEATURES: ✓ Credential isolation (no AWS/SSH/env mounts) For more information, see: -https://github.com/PaulDuvall/ai-development-patterns/tree/main/sandbox +https://github.com/PaulDuvall/ai-development-patterns/tree/main/examples/security-sandbox EOF } @@ -813,4 +813,4 @@ main() { } # Run main function -main "$@" \ No newline at end of file +main "$@" diff --git a/examples/security-sandbox/docker-compose.ai-sandbox.yml b/examples/security-sandbox/docker-compose.ai-sandbox.yml index 2bee25c..f0cd693 100644 --- a/examples/security-sandbox/docker-compose.ai-sandbox.yml +++ b/examples/security-sandbox/docker-compose.ai-sandbox.yml @@ -1,205 +1,71 @@ version: '3.8' -# AI Security Sandbox - Complete network isolation for AI development -# Based on the AI Security Sandbox pattern from README.md +# Security Sandbox - complete network isolation for AI development +# Based on the Security Sandbox pattern from README.md services: ai-development: build: - context: .. - dockerfile: sandbox/Dockerfile.ai-sandbox + context: . + dockerfile: Dockerfile.ai-sandbox container_name: ai-dev-sandbox - + # Complete network isolation - no egress or ingress network_mode: none - + # Security constraints security_opt: - no-new-privileges:true cap_drop: - ALL - read_only: false # Allow writing to specific mounted volumes - - # Volume mounts - read-only source, read/write for development artifacts + read_only: false + + # Volume mounts - read-only source, read/write for AI outputs and logs volumes: - # Source code - read only to prevent accidental modification - ./src:/workspace/src:ro - - ./tests:/workspace/tests:rw - - ./specs:/workspace/specs:ro - - ./.ai:/workspace/.ai:ro - - # Development outputs - writable - ./generated:/workspace/generated:rw - ./logs:/workspace/logs:rw - - # Temporary workspace for AI operations - - ai-temp:/tmp/ai-workspace:rw - + # DO NOT mount sensitive directories: # - ~/.aws (AWS credentials) - # - ~/.ssh (SSH keys) + # - ~/.ssh (SSH keys) # - .env files (environment secrets) # - /var/run/docker.sock (Docker daemon) - # - /etc/passwd, /etc/shadow (system files) - + # Environment variables - development only, no secrets environment: - - NODE_ENV=development - AI_SANDBOX=true - WORKSPACE_DIR=/workspace - PYTHONPATH=/workspace/src - LOG_LEVEL=INFO - + # Prevent container from restarting automatically restart: no - - # Resource limits to prevent resource exhaustion + + # Resource limits to prevent exhaustion deploy: resources: limits: cpus: '2.0' memory: 4G - reservations: - cpus: '0.5' - memory: 1G - - # Health check to ensure container is responsive + healthcheck: - test: ["CMD", "python", "-c", "import sys; print('AI Sandbox Ready')"] + test: ["CMD", "python3", "/workspace/healthcheck.py"] interval: 30s timeout: 10s retries: 3 start_period: 40s - - # Working directory + working_dir: /workspace - - # User context - run as non-root user + + # User context - run as non-root user (must match Dockerfile UID) user: "1000:1000" - + # Keep container running for interactive use command: ["/bin/bash", "-c", "/workspace/init-workspace.sh && tail -f /dev/null"] - - # Labels for identification and management + labels: - "ai.sandbox=true" - "ai.network.isolated=true" - "ai.security.level=high" - "version=1.0" - - # Optional: Internal-only services for AI development - # Use only if inter-container communication is absolutely necessary - mock-api: - image: mockserver/mockserver:latest - container_name: ai-mock-api - - # Connect to isolated network only - networks: - - ai-isolated - - # No external network access - environment: - - MOCKSERVER_PROPERTY_FILE=/config/mockserver.properties - - volumes: - - ./mock-config:/config:ro - - # Security constraints - security_opt: - - no-new-privileges:true - cap_drop: - - ALL - read_only: true - - # Only accessible from within ai-isolated network - expose: - - "1080" - - labels: - - "ai.sandbox=true" - - "ai.service.type=mock" - - # Database for testing - isolated from production - test-database: - image: postgres:15-alpine - container_name: ai-test-db - - networks: - - ai-isolated - - environment: - - POSTGRES_DB=ai_test - - POSTGRES_USER=ai_test_user - - POSTGRES_PASSWORD=test_password_not_production - - POSTGRES_HOST_AUTH_METHOD=md5 - - volumes: - - ai-test-data:/var/lib/postgresql/data - - ./test-data/init.sql:/docker-entrypoint-initdb.d/init.sql:ro - - # Security constraints - security_opt: - - no-new-privileges:true - cap_drop: - - ALL - cap_add: - - CHOWN - - DAC_OVERRIDE - - FOWNER - - SETGID - - SETUID - - # Only accessible from within ai-isolated network - expose: - - "5432" - - labels: - - "ai.sandbox=true" - - "ai.service.type=database" - - "ai.data.classification=test" - -# Networks - isolated bridge network for inter-container communication -networks: - ai-isolated: - driver: bridge - # Internal only - no external connectivity - internal: true - ipam: - driver: default - config: - - subnet: 172.20.0.0/16 - labels: - - "ai.network.type=isolated" - - "ai.security.level=high" - -# Volumes for persistent data within sandbox -volumes: - ai-temp: - driver: local - labels: - - "ai.volume.type=temporary" - - "ai.cleanup=true" - - ai-test-data: - driver: local - labels: - - "ai.volume.type=test-database" - - "ai.data.classification=test" - -# Additional security configurations -configs: - sandbox-security-config: - file: ./sandbox/security.conf - -secrets: - # Only test secrets - never production credentials - test-api-key: - file: ./sandbox/test-secrets/api-key.txt - -# Logging configuration -x-logging: &default-logging - driver: "json-file" - options: - max-size: "10m" - max-file: "3" - labels: "ai.sandbox,ai.service.type" \ No newline at end of file diff --git a/examples/security-sandbox/init-workspace.sh b/examples/security-sandbox/init-workspace.sh index 6fe019a..273f455 100755 --- a/examples/security-sandbox/init-workspace.sh +++ b/examples/security-sandbox/init-workspace.sh @@ -1,7 +1,7 @@ #!/bin/bash -# AI Security Sandbox Workspace Initialization +# Security Sandbox Workspace Initialization -echo "🔒 Initializing AI Security Sandbox..." +echo "🔒 Initializing Security Sandbox..." echo "Workspace: $(pwd)" echo "User: $(whoami) ($(id))" echo "Python: $(python --version)" @@ -21,6 +21,6 @@ echo "✅ Non-root user: $(if [[ $(id -u) -eq 0 ]]; then echo 'DISABLED ⚠️'; echo "✅ Read-only source: $(if [[ -w /workspace/src ]] 2>/dev/null; then echo 'DISABLED ⚠️'; else echo 'ENABLED'; fi)" echo "" -echo "🚀 AI Security Sandbox ready for secure development!" +echo "🚀 Security Sandbox ready for secure development!" echo " Use 'python /workspace/healthcheck.py' to run full health check" echo "" diff --git a/examples/security-sandbox/src/README.md b/examples/security-sandbox/src/README.md new file mode 100644 index 0000000..25893ce --- /dev/null +++ b/examples/security-sandbox/src/README.md @@ -0,0 +1,5 @@ +# Placeholder Source Directory + +This `src/` directory exists so the sandbox Compose files can mount a **real, in-repo** path read-only at `/workspace/src`. + +For real usage, replace this directory with (or bind-mount) the source tree you want an AI tool to read. diff --git a/examples/spec-driven-development/README.md b/examples/spec-driven-development/README.md index b5f6d73..679156d 100644 --- a/examples/spec-driven-development/README.md +++ b/examples/spec-driven-development/README.md @@ -1,6 +1,6 @@ -# Specification Driven Development - Complete Implementation +# Spec-Driven Development - Complete Implementation -This directory contains the complete implementation of the **Specification Driven Development** pattern, demonstrating machine-readable specifications with authority levels, automated coverage tracking, and rigorous Test-Driven Development (TDD) integration. +This directory contains the complete implementation of the **Spec-Driven Development** pattern, demonstrating machine-readable specifications with authority levels, automated coverage tracking, and rigorous Test-Driven Development (TDD) integration. ## Pattern Overview @@ -9,7 +9,7 @@ SpecDriven AI combines three key elements: - **Rigorous Test-Driven Development** with coverage tracking and automated validation - **AI-powered implementation** with persistent context through structured specifications -For complete pattern documentation, see: [Specification Driven Development](../../README.md#specification-driven-development) +For complete pattern documentation, see: [Spec-Driven Development](../../README.md#spec-driven-development) ## Files in This Directory @@ -215,15 +215,15 @@ Coverage: 89% (31/35 spec requirements covered)" ## Integration with Other Patterns This implementation demonstrates integration with: -- [AI Security Sandbox](../../sandbox/) - Secure testing environment -- [Comprehensive AI Testing Strategy](../../README.md#comprehensive-ai-testing-strategy) - Multi-layered testing approach -- [Observable AI Development](../../README.md#observable-ai-development) - Logging and debugging capabilities +- [Security Sandbox](../security-sandbox/) - Secure testing environment +- [Testing Orchestration](../../experiments/README.md#testing-orchestration) - Multi-layered testing approach +- [Observable Development](../../README.md#observable-development) - Logging and debugging capabilities ## Running the Complete Example 1. **Install dependencies:** ```bash - cd examples/specification-driven-development + cd examples/spec-driven-development pip install -r requirements.txt ``` @@ -258,4 +258,4 @@ This example demonstrates how SpecDriven AI transforms AI development from ad-ho - [Blog Post: SpecDriven AI](https://www.paulmduvall.com/specdriven-ai-combining-specs-and-tdd-for-ai-powered-development/) - [OpenAI Model Spec](https://cdn.openai.com/spec/model-spec-2024-05-08.html) -- [AI Development Patterns Collection](../../README.md) \ No newline at end of file +- [AI Development Patterns Collection](../../README.md) diff --git a/examples/tool-integration/README.md b/examples/tool-integration/README.md index 707eeaa..d0d7746 100644 --- a/examples/tool-integration/README.md +++ b/examples/tool-integration/README.md @@ -1,12 +1,12 @@ -# AI Tool Integration - Complete Implementation +# Tool Integration - Complete Implementation -This directory contains the full implementation of the **AI Tool Integration** pattern, demonstrating how to connect AI systems to external data sources, APIs, and tools for enhanced capabilities beyond prompt-only interactions. +This directory contains the full implementation of the **Tool Integration** pattern, demonstrating how to connect AI systems to external data sources, APIs, and tools for enhanced capabilities beyond prompt-only interactions. ## Pattern Overview -The AI Tool Integration pattern enables the architectural shift from isolated prompt-only AI to connected AI systems that can interact with real-world data and services. This includes database queries, file operations, API calls, and system information access. +The Tool Integration pattern enables the architectural shift from isolated prompt-only AI to connected AI systems that can interact with real-world data and services. This includes database queries, file operations, API calls, and system information access. -For complete pattern documentation, see: [AI Tool Integration](../../README.md#ai-tool-integration) +For complete pattern documentation, see: [Tool Integration](../../README.md#tool-integration) ## Files in This Directory @@ -80,9 +80,9 @@ The implementation includes multiple security layers: - **Timeout Controls**: Prevents hanging requests and resource exhaustion - **Error Handling**: Graceful failure without exposing system details -### AI Security Sandbox Integration +### Security Sandbox Integration -When deployed with the [AI Security Sandbox](../../sandbox/), tool access remains secure: +When deployed with the [Security Sandbox](../security-sandbox/), tool access remains secure: ```yaml services: @@ -137,13 +137,13 @@ The tool-augmented approach provides accurate, current information instead of ed ## Integration with Other Patterns This pattern enables and enhances: -- [Specification Driven Development](../../README.md#specification-driven-development) - AI can validate against actual system state -- [Observable AI Development](../../README.md#observable-ai-development) - AI can read logs and monitoring data -- [AI Workflow Orchestration](../../README.md#ai-workflow-orchestration) - Enables data-driven workflow decisions -- [Performance Baseline Management](../../README.md#performance-baseline-management) - AI can analyze actual performance metrics +- [Spec-Driven Development](../../README.md#spec-driven-development) - AI can validate against actual system state +- [Observable Development](../../README.md#observable-development) - AI can read logs and monitoring data +- [Workflow Orchestration](../../experiments/README.md#workflow-orchestration) - Enables data-driven workflow decisions +- [Baseline Management](../../README.md#baseline-management) - AI can analyze actual performance metrics ## Further Reading - [Model Context Protocol (MCP) Documentation](https://www.anthropic.com/news/model-context-protocol) - [AI Development Patterns Collection](../../README.md) -- [AI Security Sandbox Pattern](../../sandbox/) \ No newline at end of file +- [Security Sandbox Example](../security-sandbox/) diff --git a/experiments/NOTES.md b/experiments/NOTES.md index 5f1ed72..80f9221 100644 --- a/experiments/NOTES.md +++ b/experiments/NOTES.md @@ -137,7 +137,7 @@ This file tracks patterns under exploration that may eventually be formalized in - [ ] Document checkpoint integration with CI/CD pipelines **Related Patterns**: -- [Code Quality Prerequisites](../README.md#code-quality-prerequisites) - CI/CD quality enforcement +- [Readiness Assessment](../README.md#readiness-assessment) - Code quality prerequisites before automation - [Security Sandbox](../README.md#security-sandbox) - Running agents in isolated environments - [Agentic Loops](#agentic-loops) - Long autonomous coding sessions with self-correction - [Guided Refactoring](../README.md#guided-refactoring) - Code improvement checks diff --git a/experiments/README.md b/experiments/README.md index 4d2b5b7..8e95c53 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -389,7 +389,7 @@ Running parallel agents without proper isolation, conflict detection, or sync po **Maturity**: Advanced **Description**: Match AI tool selection to task complexity and optimize cost/performance trade-offs by understanding different AI models' context window capabilities and computational costs. -**Related Patterns**: [Progressive Enhancement](../README.md#progressive-enhancement), [Choice Generation](../README.md#ai-choice-generation) +**Related Patterns**: [Progressive Enhancement](../README.md#progressive-enhancement), [Choice Generation](../README.md#choice-generation) **Tool Selection Decision Matrix** @@ -576,7 +576,7 @@ Event commands run with full system access. Always review scripts before enablin **Complete Example** -See [examples/ai-event-automation/](examples/ai-event-automation/) for working implementation with security scanning and slash command integration. +See [examples/event-automation/](examples/event-automation/) for a working implementation with security scanning and hooks. **Anti-pattern: Unchecked Events** @@ -656,10 +656,10 @@ Generate step-by-step refactoring plan prioritized by impact. Additional command examples with detailed implementations: -- **[Implement-Spec](examples/custom-ai-commands/implement-spec-example.md)** - Spec-driven implementation with TDD and traceability -- **[Security Review](examples/custom-ai-commands/security-review-example.md)** - Multi-layer security analysis (secrets, vulnerabilities, config) -- **[Safe-Refactor](examples/custom-ai-commands/safe-refactor-example.md)** - Safe refactoring with automated testing and rollback -- **[Test Runner](examples/custom-ai-commands/test-example.md)** - Smart test selection with coverage and health monitoring +- **[Implement-Spec](examples/custom-commands/implement-spec-example.md)** - Spec-driven implementation with TDD and traceability +- **[Security Review](examples/custom-commands/security-review-example.md)** - Multi-layer security analysis (secrets, vulnerabilities, config) +- **[Safe-Refactor](examples/custom-commands/safe-refactor-example.md)** - Safe refactoring with automated testing and rollback +- **[Test Runner](examples/custom-commands/test-example.md)** - Smart test selection with coverage and health monitoring **Tool Support** @@ -677,7 +677,7 @@ mkdir -p .ai/commands **Complete Implementation** -See [examples/custom-ai-commands/](examples/custom-ai-commands/) for ready-to-use commands, configuration files, and setup guide. +See [examples/custom-commands/](examples/custom-commands/) for ready-to-use commands, configuration files, and setup guide. **Anti-pattern: Redundant Commands** @@ -1562,7 +1562,7 @@ repo-c/.ai/rules/ # Custom fork, diverged **Maturity**: Intermediate **Description**: Automate review process for parallel agent outputs using AI to detect conflicts and coordinate integration. -**Related Patterns**: [Workflow Orchestration](#workflow-orchestration), [Atomic Decomposition](../README.md#atomic-decomposition), [Parallel Agents](../README.md#parallelized-ai-coding-agents) +**Related Patterns**: [Workflow Orchestration](#workflow-orchestration), [Atomic Decomposition](../README.md#atomic-decomposition), [Parallel Agents](../README.md#parallel-agents) **Automated Review and Merge System** diff --git a/experiments/examples/README.md b/experiments/examples/README.md index 38eec65..19db0de 100644 --- a/experiments/examples/README.md +++ b/experiments/examples/README.md @@ -1,131 +1,32 @@ # Experimental Pattern Examples -This directory contains working implementations of experimental AI development patterns. These examples demonstrate cutting-edge approaches that are under active development and evaluation. - -## Pattern Implementation Status - -| Pattern | Implementation Status | Directory | Description | -|---------|----------------------|-----------|-------------| -| **Human-AI Handoff Protocol** | ✅ Complete | `human-ai-handoff/` | Decision framework and automation for task transitions | -| **Comprehensive AI Testing Strategy** | ✅ Complete | `comprehensive-ai-testing-strategy/` | Unified test-first development and quality assurance | -| **AI Workflow Orchestration** | ✅ Complete | `ai-workflow-orchestration/` | Multi-agent coordination and parallel execution | -| **AI Review Automation** | ✅ Complete | `ai-review-automation/` | Automated parallel agent output review | -| **Technical Debt Forecasting** | ✅ Complete | `technical-debt-forecasting/` | Proactive technical debt analysis and prioritization | -| **Pipeline Synthesis** | ✅ Complete | `pipeline-synthesis/` | Generate CI/CD pipelines from plain-English specifications | -| **AI-Guided Blue-Green Deployment** | ✅ Complete | `ai-guided-blue-green-deployment/` | Generate validated blue-green deployment scripts | -| **Drift Detection & Remediation** | ✅ Complete | `drift-detection-remediation/` | Automated infrastructure drift detection and fixes | -| **Incident Response Automation** | ✅ Complete | `incident-response-automation/` | Generate incident response playbooks from historical data | -| **Dependency Upgrade Advisor** | ✅ Complete | `dependency-upgrade-advisor/` | Intelligent dependency upgrade management | -| **Context Window Optimization** | 🚧 In Progress | `context-window-optimization/` | AI tool selection and cost optimization | -| **Test Suite Health Management** | 🚧 In Progress | `test-suite-health/` | Flaky test detection and remediation | -| **On-Call Handoff Automation** | 📋 Planned | `on-call-handoff/` | Automated handoff brief generation | - -## Usage Guidelines - -### Experimental Nature Warning -⚠️ **These patterns are experimental and may:** -- Contain incomplete implementations -- Change significantly based on feedback -- Have limited testing and validation -- Require advanced AI development experience - -### Implementation Approach -Each experimental pattern example includes: -- **Working code samples** demonstrating the core concepts -- **Configuration files** for setup and customization -- **Documentation** explaining usage and limitations -- **Integration examples** showing how to combine with stable patterns - -### Prerequisites -- Familiarity with core AI development patterns -- Experience with AI tool integration -- Understanding of advanced development workflows -- Access to multiple AI development tools +This directory contains working implementations of selected experimental patterns from the catalog in [experiments/README.md](../README.md). + +## Example Catalog + +| Experimental Pattern | Example Directory | Notes | +|----------------------|------------------|-------| +| [Asynchronous Research](../README.md#asynchronous-research) | [`asynchronous-research/`](asynchronous-research/) | Fire-and-forget research workflows | +| [Centralized Rules](../README.md#centralized-rules) | [`centralized-rules/`](centralized-rules/) | Gateway-style enforcement and distribution | +| [Custom Commands](../README.md#custom-commands) | [`custom-commands/`](custom-commands/) | Extend assistants with project-specific commands | +| [Debt Forecasting](../README.md#debt-forecasting) | [`debt-forecasting/`](debt-forecasting/) | Proactive technical debt analysis | +| [Deployment Synthesis](../README.md#deployment-synthesis) | [`deployment-synthesis/`](deployment-synthesis/) | Generate validated deployment configurations | +| [Drift Remediation](../README.md#drift-remediation) | [`drift-remediation/`](drift-remediation/) | Detect and correct infrastructure drift | +| [Event Automation](../README.md#event-automation) | [`event-automation/`](event-automation/) | Automate actions at assistant lifecycle events | +| [Handoff Protocols](../README.md#handoff-protocols) | [`handoff-protocols/`](handoff-protocols/) | Human ↔ AI handoff decisioning and procedures | +| [Incident Automation](../README.md#incident-automation) | [`incident-automation/`](incident-automation/) | Generate incident response playbooks | +| [Pipeline Synthesis](../README.md#pipeline-synthesis) | [`pipeline-synthesis/`](pipeline-synthesis/) | Convert build specs into pipeline configs | +| [Review Automation](../README.md#review-automation) | [`review-automation/`](review-automation/) | Automate review of parallel outputs | +| [Test Promotion](../README.md#test-promotion) | [`test-promotion/`](test-promotion/) | Separate generated tests from golden tests | +| [Testing Orchestration](../README.md#testing-orchestration) | [`testing-orchestration/`](testing-orchestration/) | Coordinated testing strategy and automation | +| [Upgrade Advisor](../README.md#upgrade-advisor) | [`upgrade-advisor/`](upgrade-advisor/) | Intelligent dependency upgrades | +| [Workflow Orchestration](../README.md#workflow-orchestration) | [`workflow-orchestration/`](workflow-orchestration/) | Coordinate sequential and parallel workflows | ## Getting Started -### 1. Review Core Patterns First -Before implementing experimental patterns, ensure you have: -- Established [AI Security Sandbox](../../examples/ai-security-sandbox/) -- Implemented [Specification Driven Development](../../examples/specification-driven-development/) -- Set up [Observable AI Development](../../examples/observable-ai-development/) - -### 2. Choose Appropriate Patterns -Select experimental patterns based on: -- **Team maturity**: Advanced patterns require experienced AI developers -- **Use case complexity**: Match pattern sophistication to problem complexity -- **Risk tolerance**: Experimental patterns may have unexpected behaviors - -### 3. Implement with Caution -- Start with small, isolated experiments -- Monitor results carefully and document learnings -- Have rollback plans for production systems -- Share findings with the community - -## Contributing to Experimental Patterns - -### Pattern Development Lifecycle -1. **Concept**: Initial pattern idea and problem statement -2. **Prototype**: Basic implementation and validation -3. **Experiment**: Extended testing and refinement -4. **Stabilization**: Production-ready implementation -5. **Graduation**: Move to core patterns in main examples/ - -### Feedback and Iteration -- Report issues and suggestions via GitHub issues -- Share implementation experiences and learnings -- Contribute improvements and extensions -- Help validate patterns in different environments - -## Integration with Stable Patterns - -### Dependency Management -Experimental patterns often build on stable patterns: -```mermaid -graph TD - A[AI Security Sandbox] --> B[Human-AI Handoff Protocol] - C[Specification Driven Development] --> D[AI Workflow Orchestration] - E[Observable AI Development] --> F[Context Window Optimization] - G[Comprehensive AI Testing Strategy] --> H[Test Suite Health Management] -``` - -### Migration Path -As experimental patterns mature: -1. **Validation**: Thorough testing across multiple use cases -2. **Documentation**: Complete usage guides and best practices -3. **Standardization**: Consistent APIs and integration patterns -4. **Community Adoption**: Widespread usage and feedback -5. **Graduation**: Move to main examples/ directory - -## Safety Considerations - -### Risk Assessment -Before implementing experimental patterns: -- **Impact Analysis**: Assess potential effects on existing systems -- **Rollback Planning**: Ensure ability to revert changes quickly -- **Monitoring**: Set up observability for experimental features -- **Isolation**: Use sandboxed environments for initial testing - -### Best Practices -- **Gradual Rollout**: Implement patterns incrementally -- **Team Training**: Ensure team understands experimental nature -- **Documentation**: Maintain detailed logs of experiments -- **Community Engagement**: Share learnings and get feedback - -## Support and Resources - -### Getting Help -- Review pattern documentation thoroughly -- Check GitHub issues for known problems -- Engage with the community on discussions -- Consider consulting for complex implementations - -### Additional Resources -- [Main AI Development Patterns](../../README.md) -- [Pattern Creation Specification](../../pattern-spec.md) -- [Community Guidelines](../../docs/) -- [Integration Examples](../../examples/) - ---- - -**Remember**: Experimental patterns are evolving rapidly. Always check for updates and community feedback before production deployment. \ No newline at end of file +1. Review stable prerequisites in the main catalog: + - [Security Sandbox](../../README.md#security-sandbox) + - [Tool Integration](../../README.md#tool-integration) + - [Spec-Driven Development](../../README.md#spec-driven-development) +2. Pick an experimental example directory from the table above. +3. Follow the `README.md` in that directory. diff --git a/experiments/examples/asynchronous-research/automation/AGENTS.md.template b/experiments/examples/asynchronous-research/automation/AGENTS.md.template new file mode 100644 index 0000000..8246da8 --- /dev/null +++ b/experiments/examples/asynchronous-research/automation/AGENTS.md.template @@ -0,0 +1,12 @@ +# Agent Guidance (Template) + +## Research Standards +- Create one folder per research task. +- Include `prompt.md` (what you were asked) and `README.md` (what you found). +- Prefer runnable experiments and reproducible commands. + +## Output Expectations +- Summarize the key conclusion first. +- Include raw data artifacts when you benchmark (JSON/CSV). +- Note limitations and follow-up questions. + diff --git a/experiments/examples/asynchronous-research/automation/result-parser.py b/experiments/examples/asynchronous-research/automation/result-parser.py new file mode 100644 index 0000000..df21944 --- /dev/null +++ b/experiments/examples/asynchronous-research/automation/result-parser.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import argparse +from pathlib import Path + + +def find_tasks(repo_root: Path) -> list[Path]: + tasks: list[Path] = [] + for candidate in repo_root.iterdir(): + if not candidate.is_dir(): + continue + if candidate.name.startswith("."): + continue + if (candidate / "prompt.md").exists() or (candidate / "README.md").exists(): + tasks.append(candidate) + return sorted(tasks) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Summarize research task folders.") + parser.add_argument("root", nargs="?", default=".", help="Repository root to scan") + args = parser.parse_args() + + repo_root = Path(args.root).resolve() + tasks = find_tasks(repo_root) + + print(f"Found {len(tasks)} candidate task folder(s) in {repo_root}") + for task in tasks: + prompt = "prompt.md" if (task / "prompt.md").exists() else "-" + readme = "README.md" if (task / "README.md").exists() else "-" + print(f"- {task.name}/ ({prompt}, {readme})") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/experiments/examples/asynchronous-research/automation/summarize-workflow.yml b/experiments/examples/asynchronous-research/automation/summarize-workflow.yml new file mode 100644 index 0000000..a24b424 --- /dev/null +++ b/experiments/examples/asynchronous-research/automation/summarize-workflow.yml @@ -0,0 +1,17 @@ +name: Summarize Asynchronous Research + +on: + workflow_dispatch: {} + +jobs: + summarize: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Summarize research tasks + run: | + python3 automation/result-parser.py . + diff --git a/experiments/examples/asynchronous-research/example-research-tasks/markdown-comparison/prompt.md b/experiments/examples/asynchronous-research/example-research-tasks/markdown-comparison/prompt.md new file mode 100644 index 0000000..4d01fbe --- /dev/null +++ b/experiments/examples/asynchronous-research/example-research-tasks/markdown-comparison/prompt.md @@ -0,0 +1,20 @@ +# Python Markdown Library Comparison (Prompt) + +```text +Work in new folder: markdown-comparison/ + +Compare these Python Markdown libraries on performance and correctness: +- markdown +- markdown-it-py +- mistune + +Benchmark: +- render the same corpus N times +- report throughput and p95 latency + +Deliverables: +- benchmark code +- raw results (JSON/CSV) +- README.md with a summary table and recommendation +``` + diff --git a/experiments/examples/asynchronous-research/example-research-tasks/redis-notifications/prompt.md b/experiments/examples/asynchronous-research/example-research-tasks/redis-notifications/prompt.md new file mode 100644 index 0000000..a841a55 --- /dev/null +++ b/experiments/examples/asynchronous-research/example-research-tasks/redis-notifications/prompt.md @@ -0,0 +1,23 @@ +# Redis Notifications (Benchmark Prompt) + +```text +Work in new folder: redis-notifications/ + +Research question: +Can Redis Streams handle 10k concurrent notification subscribers? + +Build: +- publisher + subscriber simulator +- benchmark harness + +Measure: +- memory usage over time +- p95 delivery latency +- behavior under restart + +Deliverables: +- runnable code +- raw results +- README.md with findings +``` + diff --git a/experiments/examples/asynchronous-research/example-research-tasks/webassembly-compilation/prompt.md b/experiments/examples/asynchronous-research/example-research-tasks/webassembly-compilation/prompt.md new file mode 100644 index 0000000..3ae6f55 --- /dev/null +++ b/experiments/examples/asynchronous-research/example-research-tasks/webassembly-compilation/prompt.md @@ -0,0 +1,14 @@ +# WebAssembly Compilation Feasibility (Prompt) + +```text +Work in new folder: webassembly-compilation/ + +Goal: +Prove whether a small C extension can be compiled for a Python WebAssembly runtime (e.g., Pyodide). + +Deliverables: +- proof-of-concept build steps +- a minimal validation script +- README.md describing what worked and what didn't +``` + diff --git a/experiments/examples/asynchronous-research/prompt-templates/feasibility-study.md b/experiments/examples/asynchronous-research/prompt-templates/feasibility-study.md new file mode 100644 index 0000000..4d92b4f --- /dev/null +++ b/experiments/examples/asynchronous-research/prompt-templates/feasibility-study.md @@ -0,0 +1,17 @@ +# Prompt Template: Feasibility Study + +```text +Work in new folder: / + +Question: +Can work with under constraints ? + +Do: +1) Build the smallest proof-of-concept. +2) Document limitations and alternatives. + +Deliverables: +- README.md with conclusion + reproduction steps +- code for the proof-of-concept +``` + diff --git a/experiments/examples/asynchronous-research/prompt-templates/integration-proof.md b/experiments/examples/asynchronous-research/prompt-templates/integration-proof.md new file mode 100644 index 0000000..1a77796 --- /dev/null +++ b/experiments/examples/asynchronous-research/prompt-templates/integration-proof.md @@ -0,0 +1,16 @@ +# Prompt Template: Integration Proof + +```text +Work in new folder: / + +Prove that can integrate with . + +Constraints: +- must include a runnable example +- must include automated verification (tests or a script) + +Deliverables: +- code + minimal tests +- README.md with steps to run +``` + diff --git a/experiments/examples/asynchronous-research/prompt-templates/library-comparison.md b/experiments/examples/asynchronous-research/prompt-templates/library-comparison.md new file mode 100644 index 0000000..7a4b74a --- /dev/null +++ b/experiments/examples/asynchronous-research/prompt-templates/library-comparison.md @@ -0,0 +1,20 @@ +# Prompt Template: Library Comparison + +```text +Work in new folder: / + +Compare these libraries: +- +- +- + +For each library: +1) installation + basic usage snippet +2) feature comparison relevant to +3) performance micro-benchmark + +Output: +- README.md with a comparison table and recommendation +- benchmark code + raw results +``` + diff --git a/experiments/examples/asynchronous-research/prompt-templates/performance-benchmark.md b/experiments/examples/asynchronous-research/prompt-templates/performance-benchmark.md new file mode 100644 index 0000000..a053929 --- /dev/null +++ b/experiments/examples/asynchronous-research/prompt-templates/performance-benchmark.md @@ -0,0 +1,18 @@ +# Prompt Template: Performance Benchmark + +```text +Work in new folder: / + +Build a minimal benchmark harness for . + +Measure and report: +- throughput +- p95 latency +- memory usage + +Deliverables: +- code to run the benchmark +- raw results (JSON/CSV) +- README.md with charts + interpretation +``` + diff --git a/experiments/examples/asynchronous-research/setup/claude-code-config.md b/experiments/examples/asynchronous-research/setup/claude-code-config.md new file mode 100644 index 0000000..2d3da72 --- /dev/null +++ b/experiments/examples/asynchronous-research/setup/claude-code-config.md @@ -0,0 +1,37 @@ +# Claude Code Configuration (Asynchronous Research) + +Use this checklist to set up Claude Code for "fire-and-forget" research investigations. + +## Recommended Setup + +1. Create a dedicated research repository (no production secrets). +2. Add an `AGENTS.md` that defines: + - folder naming conventions + - deliverables (`prompt.md`, findings `README.md`, scripts/data) + - preferred tooling (pytest, Node, etc.) +3. Prefer PR-based workflows: + - one PR per research task + - clear titles: `research: ` +4. Keep tasks narrowly scoped and testable: + - "prove X", "measure Y", "compare A vs B" + - require runnable code + reproducible results + +## Prompt Template (Copy/Paste) + +```text +Work in new folder: / + +Goal: +- + +Do: +1) Create a minimal reproduction / benchmark harness. +2) Run it and capture results. +3) Summarize findings in README.md. + +Deliverables: +- prompt.md (this prompt) +- README.md (findings + how to reproduce) +- code + data + charts (if applicable) +``` + diff --git a/experiments/examples/asynchronous-research/setup/create-research-repo.sh b/experiments/examples/asynchronous-research/setup/create-research-repo.sh new file mode 100644 index 0000000..0dea643 --- /dev/null +++ b/experiments/examples/asynchronous-research/setup/create-research-repo.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'EOF' +Create a dedicated "research" repository for asynchronous investigations. + +Usage: + ./setup/create-research-repo.sh + +Notes: +- Requires GitHub CLI (gh) and git. +- Creates a private repo by default. +- Safe to run multiple times; will refuse to overwrite an existing directory. +EOF +} + +if [[ "${1:-}" == "" || "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +repo_name="$1" + +if ! command -v gh >/dev/null 2>&1; then + echo "ERROR: gh (GitHub CLI) is required." >&2 + exit 1 +fi + +if ! command -v git >/dev/null 2>&1; then + echo "ERROR: git is required." >&2 + exit 1 +fi + +if [[ -e "$repo_name" ]]; then + echo "ERROR: '$repo_name' already exists. Refusing to overwrite." >&2 + exit 1 +fi + +echo "Creating GitHub repo: $repo_name (private)" +gh repo create "$repo_name" --private --confirm + +echo "Cloning..." +git clone "https://github.com/$(gh api user -q .login)/$repo_name.git" +cd "$repo_name" + +cat > README.md <<'EOF' +# Research Repository + +Autonomous code investigations using asynchronous coding agents. + +Each folder contains one research task with: +- `prompt.md` (the research prompt) +- `README.md` (findings) +- supporting code/data as needed +EOF + +git add README.md +git commit -m "Initialize research repository" +git push -u origin main + +echo "Done: $(pwd)" + diff --git a/experiments/examples/asynchronous-research/setup/gemini-jules-config.md b/experiments/examples/asynchronous-research/setup/gemini-jules-config.md new file mode 100644 index 0000000..f929176 --- /dev/null +++ b/experiments/examples/asynchronous-research/setup/gemini-jules-config.md @@ -0,0 +1,16 @@ +# Gemini Jules Configuration (Asynchronous Research) + +This guide mirrors the Claude Code setup, but applies to "async agent" workflows that work through PRs/branches. + +## Checklist + +1. Use a dedicated repository with no production secrets. +2. Create one folder per research task: + - `prompt.md` (the task prompt) + - `README.md` (findings) +3. Require reproducibility: + - include commands to run + - include raw results (JSON/CSV) when possible +4. Keep tasks bounded (10–30 minutes of agent time): + - measure/compare/prove a single question + diff --git a/experiments/examples/asynchronous-research/setup/platform-comparison.md b/experiments/examples/asynchronous-research/setup/platform-comparison.md new file mode 100644 index 0000000..3a53fcc --- /dev/null +++ b/experiments/examples/asynchronous-research/setup/platform-comparison.md @@ -0,0 +1,18 @@ +# Async Agent Platform Comparison (2025+) + +This document is a lightweight comparison framework you can fill in for your team. + +## Comparison Criteria + +| Capability | What to Look For | Notes | +|-----------|------------------|------| +| PR workflow | Creates PRs/branches with changes | Essential for async review | +| Compute | Runs tests/benchmarks autonomously | Prefer deterministic runs | +| Network access | Can browse docs/repos | Safe only in research repos | +| Cost controls | Usage limits / model selection | Avoid runaway tasks | +| Traceability | Logs prompts + outputs | Needed for auditing results | + +## Team Notes + +- Add your preferred platforms and constraints here. + diff --git a/experiments/examples/centralized-rules/README.md b/experiments/examples/centralized-rules/README.md index 63b9c13..dc2af7a 100644 --- a/experiments/examples/centralized-rules/README.md +++ b/experiments/examples/centralized-rules/README.md @@ -1,7 +1,9 @@ -# Centralized AI Rules +# Centralized Rules Sync organization-wide AI development rules from a central Git repository to your projects. Auto-generates CLAUDE.md, AGENTS.md, and .cursorrules with language/framework-specific rules. +For complete pattern documentation, see: [Centralized Rules](../../README.md#centralized-rules) + ## TL;DR - 30 Second Start ```bash diff --git a/experiments/examples/custom-commands/README.md b/experiments/examples/custom-commands/README.md index a4b49d8..14af899 100644 --- a/experiments/examples/custom-commands/README.md +++ b/experiments/examples/custom-commands/README.md @@ -1,6 +1,6 @@ -# Custom AI Commands Example +# Custom Commands Example -Complete implementation of the Custom AI Commands pattern with ready-to-use command examples. +Complete implementation of the Custom Commands pattern with ready-to-use command examples. ## Quick Start @@ -357,7 +357,7 @@ To improve these commands: ## Additional Resources -- [Custom AI Commands Pattern](../../README.md#custom-ai-commands) - Full pattern documentation +- [Custom Commands Pattern](../../README.md#custom-commands) - Full pattern documentation - [Claude Code Slash Commands](https://docs.claude.com/en/docs/claude-code/slash-commands) - Official documentation - [Martin Fowler's Refactoring Catalog](https://refactoring.com/catalog/) - Refactoring reference - [OWASP Top 10](https://owasp.org/www-project-top-ten/) - Security guidelines diff --git a/experiments/examples/custom-commands/implement-spec-example.md b/experiments/examples/custom-commands/implement-spec-example.md index 3fc1c29..667b4a7 100644 --- a/experiments/examples/custom-commands/implement-spec-example.md +++ b/experiments/examples/custom-commands/implement-spec-example.md @@ -79,5 +79,5 @@ EOF ## Related Patterns -- [Specification Driven Development](../../README.md#specification-driven-development) -- [AI-Driven Traceability](../../README.md#ai-driven-traceability) +- [Spec-Driven Development](../../../README.md#spec-driven-development) +- [Automated Traceability](../../../README.md#automated-traceability) diff --git a/experiments/examples/custom-commands/safe-refactor-example.md b/experiments/examples/custom-commands/safe-refactor-example.md index 435f775..d1d3b7a 100644 --- a/experiments/examples/custom-commands/safe-refactor-example.md +++ b/experiments/examples/custom-commands/safe-refactor-example.md @@ -92,5 +92,5 @@ Automatic approval if ALL conditions met: ## Related Patterns -- [AI-Driven Refactoring](../../README.md#ai-driven-refactoring) -- [Comprehensive AI Testing Strategy](../README.md#comprehensive-ai-testing-strategy) +- [Guided Refactoring](../../../README.md#guided-refactoring) +- [Testing Orchestration](../../README.md#testing-orchestration) diff --git a/experiments/examples/custom-commands/security-review-example.md b/experiments/examples/custom-commands/security-review-example.md index ea2b9ea..94dd3d7 100644 --- a/experiments/examples/custom-commands/security-review-example.md +++ b/experiments/examples/custom-commands/security-review-example.md @@ -95,5 +95,5 @@ if (!API_KEY) throw new Error("STRIPE_API_KEY required") ## Related Patterns -- [Security Scanning Orchestration](../../README.md#security-scanning-orchestration) -- [AI Security Sandbox](../../README.md#ai-security-sandbox) +- [Security Orchestration](../../../README.md#security-orchestration) +- [Security Sandbox](../../../README.md#security-sandbox) diff --git a/experiments/examples/custom-commands/test-example.md b/experiments/examples/custom-commands/test-example.md index 10c5c56..6d05ad5 100644 --- a/experiments/examples/custom-commands/test-example.md +++ b/experiments/examples/custom-commands/test-example.md @@ -104,5 +104,5 @@ git diff --name-only HEAD~1 HEAD ## Related Patterns -- [Comprehensive AI Testing Strategy](../README.md#comprehensive-ai-testing-strategy) -- [Test Suite Health Management](../README.md#test-suite-health-management) +- [Testing Orchestration](../../README.md#testing-orchestration) +- [Suite Health](../../README.md#suite-health) diff --git a/experiments/examples/debt-forecasting/README.md b/experiments/examples/debt-forecasting/README.md index be7d9ab..f2ef213 100644 --- a/experiments/examples/debt-forecasting/README.md +++ b/experiments/examples/debt-forecasting/README.md @@ -1,10 +1,10 @@ -# Technical Debt Forecasting Implementation +# Debt Forecasting Implementation -This directory contains a complete implementation of the Technical Debt Forecasting pattern, proactively identifying and prioritizing technical debt using AI-powered code analysis. +This directory contains a complete implementation of the Debt Forecasting pattern, proactively identifying and prioritizing technical debt using AI-powered code analysis. ## Overview -Technical Debt Forecasting enables teams to: +Debt Forecasting enables teams to: - Proactively identify technical debt before it becomes critical - Prioritize debt remediation by business impact and maintenance cost - Forecast future maintenance burden and resource requirements @@ -12,6 +12,8 @@ Technical Debt Forecasting enables teams to: ## Files in this Implementation +For complete pattern documentation, see: [Debt Forecasting](../../README.md#debt-forecasting) + - `debt_analysis.md` - Complete technical debt forecasting documentation - `analyzers/` - Code quality and complexity analysis tools - `forecasting_models/` - AI-powered debt growth prediction models @@ -63,4 +65,4 @@ Prioritize by maintenance cost and business impact." ./create-roadmap.sh --prioritize-by impact --timeline quarters ``` -**Complete Implementation**: This directory contains the full technical debt forecasting system with automated analysis, AI-powered prediction models, and prioritized remediation planning. \ No newline at end of file +**Complete Implementation**: This directory contains the full technical debt forecasting system with automated analysis, AI-powered prediction models, and prioritized remediation planning. diff --git a/experiments/examples/deployment-synthesis/README.md b/experiments/examples/deployment-synthesis/README.md index f188c77..7d345e3 100644 --- a/experiments/examples/deployment-synthesis/README.md +++ b/experiments/examples/deployment-synthesis/README.md @@ -1,10 +1,10 @@ -# AI-Guided Blue-Green Deployment Implementation +# Deployment Synthesis Implementation -This directory contains a complete implementation of the AI-Guided Blue-Green Deployment pattern, generating blue-green deployment scripts with validation to prevent AI misconceptions about deployment strategies. +This directory contains a complete implementation of the Deployment Synthesis pattern, generating blue-green deployment scripts with validation to prevent AI misconceptions about deployment strategies. ## Overview -AI-Guided Blue-Green Deployment enables teams to: +Deployment Synthesis enables teams to: - Generate accurate blue-green deployment configurations using AI - Ensure proper atomic traffic switching (not gradual like canary) - Maintain two identical production environments @@ -12,6 +12,8 @@ AI-Guided Blue-Green Deployment enables teams to: ## Files in this Implementation +For complete pattern documentation, see: [Deployment Synthesis](../../README.md#deployment-synthesis) + - `blue_green_deployment.md` - Complete blue-green deployment pattern documentation - `deployment_templates/` - Infrastructure templates for blue-green environments - `traffic_switching/` - Load balancer and DNS switching configurations @@ -53,4 +55,4 @@ ai "Create blue-green deployment for microservice with: ./rollback.sh green-to-blue ``` -**Complete Implementation**: This directory contains the full blue-green deployment system with AI-generated configurations, validation procedures, and atomic traffic switching mechanisms. \ No newline at end of file +**Complete Implementation**: This directory contains the full blue-green deployment system with AI-generated configurations, validation procedures, and atomic traffic switching mechanisms. diff --git a/experiments/examples/drift-remediation/README.md b/experiments/examples/drift-remediation/README.md index 374b8dd..a8e3b39 100644 --- a/experiments/examples/drift-remediation/README.md +++ b/experiments/examples/drift-remediation/README.md @@ -1,10 +1,10 @@ -# Drift Detection & Remediation Implementation +# Drift Remediation Implementation -This directory contains a complete implementation of the Drift Detection & Remediation pattern, detecting infrastructure configuration drift and generating corrective patches automatically. +This directory contains a complete implementation of the Drift Remediation pattern, detecting infrastructure configuration drift and generating corrective patches automatically. ## Overview -Drift Detection & Remediation enables teams to: +Drift Remediation enables teams to: - Automatically detect infrastructure configuration drift - Generate corrective Terraform/CloudFormation patches - Assess drift risk levels and prioritize remediation @@ -12,6 +12,8 @@ Drift Detection & Remediation enables teams to: ## Files in this Implementation +For complete pattern documentation, see: [Drift Remediation](../../README.md#drift-remediation) + - `infrastructure_drift.md` - Complete drift detection pattern documentation - `drift_scanners/` - Automated drift detection tools for various platforms - `remediation_scripts/` - AI-generated corrective patch generators @@ -52,4 +54,4 @@ ai "Compare current AWS infrastructure against Terraform state: ./remediate-drift.sh --approve-critical --plan-others ``` -**Complete Implementation**: This directory contains the full drift detection and remediation system with automated scanning, AI-powered analysis, and corrective patch generation. \ No newline at end of file +**Complete Implementation**: This directory contains the full drift detection and remediation system with automated scanning, AI-powered analysis, and corrective patch generation. diff --git a/experiments/examples/event-automation/README.md b/experiments/examples/event-automation/README.md index b2ee206..3fe8fc3 100644 --- a/experiments/examples/event-automation/README.md +++ b/experiments/examples/event-automation/README.md @@ -1,7 +1,9 @@ -# AI Event Automation Example +# Event Automation Example Simple security automation that blocks sensitive file edits and scans for hardcoded secrets. +For complete pattern documentation, see: [Event Automation](../../README.md#event-automation) + ## Quick Start ```bash diff --git a/experiments/examples/handoff-protocols/README.md b/experiments/examples/handoff-protocols/README.md index aaba712..ff775c9 100644 --- a/experiments/examples/handoff-protocols/README.md +++ b/experiments/examples/handoff-protocols/README.md @@ -1,16 +1,16 @@ -# Human-AI Handoff Protocol Implementation +# Handoff Protocols Implementation -This directory contains a complete implementation of the Human-AI Handoff Protocol pattern, providing clear boundaries and automated procedures for transitioning work between human developers and AI tools based on complexity, security requirements, and creative problem-solving needs. +This directory contains a complete implementation of the Handoff Protocols pattern, providing clear boundaries and automated procedures for transitioning work between human developers and AI tools based on complexity, security requirements, and creative problem-solving needs. ## Pattern Overview -The Human-AI Handoff Protocol enables teams to: +Handoff Protocols enables teams to: - **Assess task complexity** automatically and recommend appropriate handoff strategies - **Execute handoff workflows** with clear automation and human review points - **Track handoff effectiveness** to continuously improve decision criteria - **Maintain quality standards** across different execution modes -For complete pattern documentation, see: [Human-AI Handoff Protocol](../../README.md#human-ai-handoff-protocol) +For complete pattern documentation, see: [Handoff Protocols](../../README.md#handoff-protocols) ## Files in This Implementation @@ -206,12 +206,12 @@ notifier.send_handoff_update( ## Integration with Other Patterns -### AI Workflow Orchestration +### Workflow Orchestration - Use handoff decisions to route tasks in parallel agent workflows - Coordinate handoff points in multi-agent systems - Optimize workflow efficiency based on handoff outcomes -### Comprehensive AI Testing Strategy +### Testing Orchestration - Apply handoff protocols to test generation and validation - Use quality gates to trigger human review of AI-generated tests - Track testing effectiveness across different handoff modes @@ -289,7 +289,7 @@ python quality_controller.py --validate-config handoff_config.yaml ## Contributing -When extending the Human-AI Handoff Protocol: +When extending Handoff Protocols: 1. Add new complexity assessment criteria for emerging task types 2. Implement domain-specific handoff strategies 3. Enhance quality gates with project-specific validation @@ -303,4 +303,4 @@ When extending the Human-AI Handoff Protocol: - Validate that AI tools don't have access to sensitive credentials - Audit handoff outcomes for security compliance -This implementation provides a foundation for intelligent human-AI collaboration that adapts to task complexity and maintains consistent quality standards across different execution modes. \ No newline at end of file +This implementation provides a foundation for intelligent human-AI collaboration that adapts to task complexity and maintains consistent quality standards across different execution modes. diff --git a/experiments/examples/incident-automation/README.md b/experiments/examples/incident-automation/README.md index e4b4272..284788b 100644 --- a/experiments/examples/incident-automation/README.md +++ b/experiments/examples/incident-automation/README.md @@ -1,10 +1,10 @@ -# Incident Response Automation Implementation +# Incident Automation Implementation -This directory contains a complete implementation of the Incident Response Automation pattern, generating actionable incident response playbooks from historical incident data. +This directory contains a complete implementation of the Incident Automation pattern, generating actionable incident response playbooks from historical incident data. ## Overview -Incident Response Automation enables teams to: +Incident Automation enables teams to: - Generate step-by-step incident response runbooks - Create automated triage rules from historical patterns - Suggest preventive monitoring alerts @@ -12,6 +12,8 @@ Incident Response Automation enables teams to: ## Files in this Implementation +For complete pattern documentation, see: [Incident Automation](../../README.md#incident-automation) + - `incident_playbook.md` - Complete incident response automation documentation - `runbook_generators/` - AI-powered runbook generation from incident history - `triage_automation/` - Automated incident classification and routing @@ -57,4 +59,4 @@ ai "Analyze last 50 incidents in PagerDuty/AWS CloudWatch to: ./deploy-automation.sh --enable-triage --update-runbooks ``` -**Complete Implementation**: This directory contains the full incident response automation system with historical analysis, AI-generated runbooks, and continuous improvement capabilities. \ No newline at end of file +**Complete Implementation**: This directory contains the full incident response automation system with historical analysis, AI-generated runbooks, and continuous improvement capabilities. diff --git a/experiments/examples/review-automation/README.md b/experiments/examples/review-automation/README.md index 7f7a61c..c705a50 100644 --- a/experiments/examples/review-automation/README.md +++ b/experiments/examples/review-automation/README.md @@ -1,17 +1,17 @@ -# AI Review Automation Implementation +# Review Automation Implementation -This directory contains a complete implementation of the AI Review Automation pattern, providing automated review processes for parallel agent outputs with conflict detection, quality validation, and intelligent merge coordination. +This directory contains a complete implementation of the Review Automation pattern, providing automated review processes for parallel agent outputs with conflict detection, quality validation, and intelligent merge coordination. ## Pattern Overview -AI Review Automation transforms manual code review bottlenecks into intelligent, automated processes that can handle parallel agent outputs while maintaining quality standards. The pattern enables teams to: +Review Automation transforms manual code review bottlenecks into intelligent, automated processes that can handle parallel agent outputs while maintaining quality standards. The pattern enables teams to: - **Detect conflicts automatically** between parallel agent outputs using content analysis - **Validate quality standards** through automated syntax, security, and test coverage checks - **Coordinate intelligent merging** with conflict resolution and rollback capabilities - **Generate actionable reports** for human review when automation limits are reached -For complete pattern documentation, see: [AI Review Automation](../../README.md#ai-review-automation) +For complete pattern documentation, see: [Review Automation](../../README.md#review-automation) ## Files in This Implementation @@ -485,12 +485,12 @@ class ReviewAutomationAnalytics: - Detect conflicts between specialized agent domains - Coordinate merge timing with agent completion -### Human-AI Handoff Protocol +### Handoff Protocols - Route complex conflicts to appropriate human reviewers - Apply handoff criteria for review escalation decisions - Track handoff effectiveness for continuous improvement -### Comprehensive AI Testing Strategy +### Testing Orchestration - Integrate with test generation and validation workflows - Ensure merged outputs maintain test coverage standards - Coordinate with CI/CD pipeline quality gates @@ -535,4 +535,4 @@ python merge_coordinator.py --simulate --conflicts test_conflicts.json - Validate that automated merge doesn't introduce security vulnerabilities - Audit review automation logs for potential information leakage -This implementation provides intelligent automation for parallel agent output review while maintaining quality standards and enabling human oversight where automation reaches its limits. \ No newline at end of file +This implementation provides intelligent automation for parallel agent output review while maintaining quality standards and enabling human oversight where automation reaches its limits. diff --git a/experiments/examples/testing-orchestration/README.md b/experiments/examples/testing-orchestration/README.md index 457d86b..2f0bbc0 100644 --- a/experiments/examples/testing-orchestration/README.md +++ b/experiments/examples/testing-orchestration/README.md @@ -1,15 +1,17 @@ -# Comprehensive AI Testing Strategy Implementation +# Testing Orchestration Implementation -This directory contains a complete implementation of the Comprehensive AI Testing Strategy pattern, providing a unified approach combining test-first development, automated test generation, and quality assurance patterns to ensure AI-generated code meets quality and behavioral specifications. +This directory contains a complete implementation of the Testing Orchestration pattern, providing a unified approach combining test-first development, automated test generation, and quality assurance patterns to ensure AI-generated code meets quality and behavioral specifications. ## Overview -Comprehensive AI Testing Strategy enables teams to: +Testing Orchestration enables teams to: - Implement test-first development with AI-generated tests - Create unified testing frameworks across unit, integration, and acceptance levels - Automate test generation from specifications and requirements - Establish quality gates and coverage thresholds for AI-generated code +For complete pattern documentation, see: [Testing Orchestration](../../README.md#testing-orchestration) + ## Files in this Implementation - `acceptance_tests/` - End-to-end acceptance test scenarios and examples @@ -46,17 +48,17 @@ Comprehensive AI Testing Strategy enables teams to: ## Integration with AI Development Patterns -### Specification Driven Development +### Spec-Driven Development - Tests generated from machine-readable specifications - Acceptance criteria converted to executable tests - Traceability maintained between specs and tests -### AI-Driven Traceability +### Automated Traceability - Requirements linked to test cases - Coverage tracking across requirement lifecycle - Impact analysis for specification changes -### Observable AI Development +### Observable Development - Test execution monitoring and analysis - Performance testing with baseline comparison - Failure pattern recognition and prevention @@ -218,4 +220,4 @@ When extending the testing strategy: - Sanitize test data to avoid exposing sensitive information - Use separate test environments with isolated data - Validate that tests don't create security vulnerabilities -- Regular audit of test credentials and access permissions \ No newline at end of file +- Regular audit of test credentials and access permissions diff --git a/experiments/examples/upgrade-advisor/README.md b/experiments/examples/upgrade-advisor/README.md index 12f8581..759edf4 100644 --- a/experiments/examples/upgrade-advisor/README.md +++ b/experiments/examples/upgrade-advisor/README.md @@ -1,10 +1,10 @@ -# Dependency Upgrade Advisor Implementation +# Upgrade Advisor Implementation -This directory contains a complete implementation of the Dependency Upgrade Advisor pattern, intelligently managing dependency upgrades with compatibility analysis and risk assessment. +This directory contains a complete implementation of the Upgrade Advisor pattern, intelligently managing dependency upgrades with compatibility analysis and risk assessment. ## Overview -Dependency Upgrade Advisor enables teams to: +Upgrade Advisor enables teams to: - Analyze dependencies for security vulnerabilities and upgrade opportunities - Assess breaking change risk for dependency upgrades - Generate staged upgrade plans with rollback procedures @@ -12,6 +12,8 @@ Dependency Upgrade Advisor enables teams to: ## Files in this Implementation +For complete pattern documentation, see: [Upgrade Advisor](../../README.md#upgrade-advisor) + - `dependency_advisor.md` - Complete dependency management pattern documentation - `analyzers/` - Dependency analysis tools for different package managers - `risk_assessment/` - Breaking change and compatibility analysis tools @@ -52,4 +54,4 @@ ai "Analyze package.json/requirements.txt for upgrade opportunities: ./execute-upgrades.sh --stage 1 --with-rollback ``` -**Complete Implementation**: This directory contains the full dependency upgrade advisory system with multi-language support, risk assessment, and automated upgrade execution. \ No newline at end of file +**Complete Implementation**: This directory contains the full dependency upgrade advisory system with multi-language support, risk assessment, and automated upgrade execution. diff --git a/experiments/examples/workflow-orchestration/README.md b/experiments/examples/workflow-orchestration/README.md index 8366c37..9c21cab 100644 --- a/experiments/examples/workflow-orchestration/README.md +++ b/experiments/examples/workflow-orchestration/README.md @@ -1,17 +1,17 @@ -# AI Workflow Orchestration Implementation +# Workflow Orchestration Implementation -This directory contains a complete implementation of the AI Workflow Orchestration pattern, enabling coordination of sequential pipelines, parallel agent workflows, and hybrid human-AI processes for complex development tasks. +This directory contains a complete implementation of the Workflow Orchestration pattern, enabling coordination of sequential pipelines, parallel agent workflows, and hybrid human-AI processes for complex development tasks. ## Pattern Overview -AI Workflow Orchestration transforms synchronous single-agent workflows into asynchronous, event-driven multi-agent architectures while maintaining safety and consistency. The pattern enables teams to: +Workflow Orchestration transforms synchronous single-agent workflows into asynchronous, event-driven multi-agent architectures while maintaining safety and consistency. The pattern enables teams to: - **Coordinate parallel AI agents** safely with conflict detection and resolution - **Orchestrate sequential workflows** with automated handoff between stages - **Manage hybrid human-AI processes** with intelligent task routing - **Ensure workflow safety** through isolation, monitoring, and rollback capabilities -For complete pattern documentation, see: [AI Workflow Orchestration](../../README.md#ai-workflow-orchestration) +For complete pattern documentation, see: [Workflow Orchestration](../../README.md#workflow-orchestration) ## Files in This Implementation @@ -311,7 +311,7 @@ result = await orchestrator.execute_workflow(hybrid_workflow) ./monitor_workflows.sh --dashboard # Expected output: -# AI Workflow Orchestration Dashboard +# Workflow Orchestration Dashboard # =================================== # # Active Workflows: 2 @@ -404,17 +404,17 @@ class PredictiveConflictDetector: ## Integration with Other Patterns -### Human-AI Handoff Protocol +### Handoff Protocols - Use handoff decisions to route tasks in orchestrated workflows - Apply complexity assessment to determine workflow automation levels - Integrate quality gates with workflow approval points -### Comprehensive AI Testing Strategy +### Testing Orchestration - Orchestrate parallel test generation across multiple agents - Coordinate integration testing after parallel development - Automate test execution in sequential pipeline workflows -### AI Security Sandbox +### Security Sandbox - Isolate parallel agents in secure sandboxed environments - Apply security controls to workflow execution environments - Monitor and audit orchestrated workflow activities @@ -459,4 +459,4 @@ python conflict_resolver.py --analyze --timeframe "7days" - Workflow orchestration logs may contain sensitive information requiring encryption - Agent communication channels must be secured against eavesdropping and tampering -This implementation provides a robust foundation for coordinating complex AI workflows while maintaining safety, consistency, and observability across parallel and sequential execution patterns. \ No newline at end of file +This implementation provides a robust foundation for coordinating complex AI workflows while maintaining safety, consistency, and observability across parallel and sequential execution patterns. diff --git a/index.html b/index.html index 4618559..916c1fe 100644 --- a/index.html +++ b/index.html @@ -72,8 +72,9 @@

AI Development Patterns

classDef development fill:#f9e79f,stroke:#b7950b,stroke-width:2px,color:#7d6608 classDef operations fill:#f5b7b1,stroke:#c0392b,stroke-width:2px,color:#78281f - class RA,CR,SS,DL,TI,IG,CP foundation + class RA,CR,SS,DL,TI,IG foundation class PE,SD,AD,PA,OD,GR,AT development + class CP development class PG,SO,BM operations click RA "https://github.com/PaulDuvall/ai-development-patterns#readiness-assessment" @@ -116,19 +117,24 @@

🟢 Foundation Patterns

  • Tool Integration - IDE and tool connections
  • Issue Generation - Automated issue creation
  • -
  • Context Persistence - Session state management
  • 🟡 Development Patterns

    Daily practice patterns for AI-assisted coding workflows.

    🔴 Operations Patterns

    diff --git a/pattern-spec.md b/pattern-spec.md index eb23f72..f30026f 100644 --- a/pattern-spec.md +++ b/pattern-spec.md @@ -8,7 +8,10 @@ This document defines the standard structure, content requirements, and formatti The main documentation MUST include a comprehensive reference table at the beginning that: - Lists ALL patterns in the collection - Includes maturity level, category, description, and dependencies for each pattern -- Provides internal reference links to each pattern using format: `[Pattern Name](#pattern-name-anchor)` +- Provides internal reference links to each pattern using format: + ```markdown + [Pattern Name](#pattern-name-anchor) + ``` - Organizes patterns by category (Foundation → Development → Operations) - Uses sub-category headers for Operations patterns (Security & Compliance, Deployment Automation, Monitoring & Maintenance) @@ -306,7 +309,10 @@ graph LR ``` ### Hyperlinks -- ALL pattern references MUST be hyperlinked using format: `[Pattern Name](#pattern-name-anchor)` +- ALL pattern references MUST be hyperlinked using format: + ```markdown + [Pattern Name](#pattern-name-anchor) + ``` - This applies to: Reference table, Related Patterns sections, pattern mentions in descriptions, implementation examples, and any other pattern references - External links should include brief context - Ensure all internal links work correctly @@ -317,7 +323,10 @@ graph LR - Keep README examples concise and scannable (prioritize clarity and understanding) - Show the pattern's essence and core value proposition with practical detail - For complex patterns, create `examples/pattern-name/` directories with complete working code -- ALWAYS reference detailed implementations: "Complete Example: See [examples/pattern-name/](examples/pattern-name/) for..." or "Complete Implementation: See [examples/pattern-name/](examples/pattern-name/) for..." +- ALWAYS reference detailed implementations using non-clickable code formatting (so the spec itself never contains broken links), for example: + ```markdown + Complete Example: See `examples/pattern-name/` for a full implementation. + ``` - Prefer real-world scenarios over abstract examples - Use consistent naming conventions (e.g., "myapp" for applications) - Include the most important commands, code snippets, or configurations that demonstrate the pattern @@ -452,4 +461,4 @@ Before adding a new pattern, verify: - Remove deprecated patterns after reasonable transition period - Update all references when patterns are removed -This specification ensures consistency, quality, and usability across all patterns in the AI Development Patterns collection. \ No newline at end of file +This specification ensures consistency, quality, and usability across all patterns in the AI Development Patterns collection. diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..74ef773 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +markers = + slow: slow tests (e.g., external link validation) diff --git a/scripts/README.md b/scripts/README.md index e471f0c..d97019f 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -7,16 +7,16 @@ This directory contains automation scripts for maintaining the AI Development Pa ### Pattern Count Management #### `update-pattern-count.py` -**Purpose**: Automatically updates the pattern count badge in README.md based on the current number of patterns in `tests/conftest.py`. +**Purpose**: Automatically updates the pattern count badges in README.md and index.html based on the current number of patterns in `tests/conftest.py`. **Usage**: ```bash -python scripts/update-pattern-count.py +python3 scripts/update-pattern-count.py ``` **Features**: - Counts patterns from the `EXPECTED_PATTERNS` list in conftest.py -- Updates the shields.io badge in README.md with the exact count +- Updates the shields.io badge in README.md and index.html with the exact count - Outputs pattern count for GitHub Actions integration - Validates that the badge pattern exists before updating @@ -67,7 +67,7 @@ The pattern count automation is integrated into the GitHub Actions workflow: When adding or removing patterns: 1. **Automatic (recommended)**: Install the pre-commit hook for automatic updates -2. **Manual**: Run `python scripts/update-pattern-count.py` before committing +2. **Manual**: Run `python3 scripts/update-pattern-count.py` before committing 3. **CI-only**: Let GitHub Actions catch and report badge mismatches ### For CI/CD @@ -79,9 +79,9 @@ The GitHub Actions integration ensures: ### Example Output ```bash 🔍 Counting patterns from conftest.py... -✓ Found 21 patterns -📝 Updating README.md badge... -✅ Successfully updated pattern count badge to 21 +✓ Found 22 patterns +📝 Updating pattern count badges... +✅ Successfully updated pattern count badges to 22 ``` ## Troubleshooting @@ -103,4 +103,4 @@ If the pre-commit hook fails: - Check that `scripts/update-pattern-count.py` is executable - Verify the script can find `tests/conftest.py` and `README.md` -This automation ensures the pattern count badge always reflects the current state of the repository without manual maintenance overhead. \ No newline at end of file +This automation ensures the pattern count badge always reflects the current state of the repository without manual maintenance overhead. diff --git a/scripts/apply-experimental-renames.sh b/scripts/apply-experimental-renames.sh index 01e9466..68e1d21 100755 --- a/scripts/apply-experimental-renames.sh +++ b/scripts/apply-experimental-renames.sh @@ -1,135 +1,152 @@ #!/bin/bash # Script to apply all experimental pattern name renames in experiments/README.md +# +# Note: This is a historical migration helper. The repository is already migrated, +# but keeping this script accurate helps prevent confusion and supports any future +# backports or forks that still contain legacy names. set -e +REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + +sed_i() { + local expression="$1" + local file="$2" + + if sed --version >/dev/null 2>&1; then + sed -i "$expression" "$file" + else + sed -i '' "$expression" "$file" + fi +} + echo "Applying experimental pattern name renames..." -file="/home/user/ai-development-patterns/experiments/README.md" +file="$REPO_ROOT/experiments/README.md" echo "Processing $file..." # Experimental Pattern Renames (headers and references) -sed -i 's/## Human-AI Handoff Protocol/## Handoff Protocols/g' "$file" -sed -i 's/\[Human-AI Handoff Protocol\](#human-ai-handoff-protocol)/[Handoff Protocols](#handoff-protocols)/g' "$file" -sed -i 's/#human-ai-handoff-protocol/#handoff-protocols/g' "$file" +sed_i 's/## Human-AI Handoff Protocol/## Handoff Protocols/g' "$file" +sed_i 's/\[Human-AI Handoff Protocol\](#human-ai-handoff-protocol)/[Handoff Protocols](#handoff-protocols)/g' "$file" +sed_i 's/#human-ai-handoff-protocol/#handoff-protocols/g' "$file" -sed -i 's/## Comprehensive AI Testing Strategy/## Testing Orchestration/g' "$file" -sed -i 's/\[Comprehensive AI Testing Strategy\](#comprehensive-ai-testing-strategy)/[Testing Orchestration](#testing-orchestration)/g' "$file" -sed -i 's/#comprehensive-ai-testing-strategy/#testing-orchestration/g' "$file" +sed_i 's/## Comprehensive AI Testing Strategy/## Testing Orchestration/g' "$file" +sed_i 's/\[Comprehensive AI Testing Strategy\](#comprehensive-ai-testing-strategy)/[Testing Orchestration](#testing-orchestration)/g' "$file" +sed_i 's/#comprehensive-ai-testing-strategy/#testing-orchestration/g' "$file" -sed -i 's/## AI Workflow Orchestration/## Workflow Orchestration/g' "$file" -sed -i 's/\[AI Workflow Orchestration\](#ai-workflow-orchestration)/[Workflow Orchestration](#workflow-orchestration)/g' "$file" -sed -i 's/#ai-workflow-orchestration/#workflow-orchestration/g' "$file" +sed_i 's/## AI Workflow Orchestration/## Workflow Orchestration/g' "$file" +sed_i 's/\[AI Workflow Orchestration\](#ai-workflow-orchestration)/[Workflow Orchestration](#workflow-orchestration)/g' "$file" +sed_i 's/#ai-workflow-orchestration/#workflow-orchestration/g' "$file" -sed -i 's/## AI Review Automation/## Review Automation/g' "$file" -sed -i 's/\[AI Review Automation\](#ai-review-automation)/[Review Automation](#review-automation)/g' "$file" -sed -i 's/#ai-review-automation/#review-automation/g' "$file" +sed_i 's/## AI Review Automation/## Review Automation/g' "$file" +sed_i 's/\[AI Review Automation\](#ai-review-automation)/[Review Automation](#review-automation)/g' "$file" +sed_i 's/#ai-review-automation/#review-automation/g' "$file" -sed -i 's/## Technical Debt Forecasting/## Debt Forecasting/g' "$file" -sed -i 's/\[Technical Debt Forecasting\](#technical-debt-forecasting)/[Debt Forecasting](#debt-forecasting)/g' "$file" -sed -i 's/#technical-debt-forecasting/#debt-forecasting/g' "$file" +sed_i 's/## Technical Debt Forecasting/## Debt Forecasting/g' "$file" +sed_i 's/\[Technical Debt Forecasting\](#technical-debt-forecasting)/[Debt Forecasting](#debt-forecasting)/g' "$file" +sed_i 's/#technical-debt-forecasting/#debt-forecasting/g' "$file" # Pipeline Synthesis - no change -sed -i 's/## AI-Guided Blue-Green Deployment/## Deployment Synthesis/g' "$file" -sed -i 's/\[AI-Guided Blue-Green Deployment\](#ai-guided-blue-green-deployment)/[Deployment Synthesis](#deployment-synthesis)/g' "$file" -sed -i 's/#ai-guided-blue-green-deployment/#deployment-synthesis/g' "$file" +sed_i 's/## AI-Guided Blue-Green Deployment/## Deployment Synthesis/g' "$file" +sed_i 's/\[AI-Guided Blue-Green Deployment\](#ai-guided-blue-green-deployment)/[Deployment Synthesis](#deployment-synthesis)/g' "$file" +sed_i 's/#ai-guided-blue-green-deployment/#deployment-synthesis/g' "$file" -sed -i 's/## Drift Detection & Remediation/## Drift Remediation/g' "$file" -sed -i 's/\[Drift Detection & Remediation\](#drift-detection--remediation)/[Drift Remediation](#drift-remediation)/g' "$file" -sed -i 's/#drift-detection--remediation/#drift-remediation/g' "$file" +sed_i 's/## Drift Detection & Remediation/## Drift Remediation/g' "$file" +sed_i 's/\[Drift Detection & Remediation\](#drift-detection--remediation)/[Drift Remediation](#drift-remediation)/g' "$file" +sed_i 's/#drift-detection--remediation/#drift-remediation/g' "$file" -sed -i 's/## Release Note Synthesis/## Release Synthesis/g' "$file" -sed -i 's/\[Release Note Synthesis\](#release-note-synthesis)/[Release Synthesis](#release-synthesis)/g' "$file" -sed -i 's/#release-note-synthesis/#release-synthesis/g' "$file" +sed_i 's/## Release Note Synthesis/## Release Synthesis/g' "$file" +sed_i 's/\[Release Note Synthesis\](#release-note-synthesis)/[Release Synthesis](#release-synthesis)/g' "$file" +sed_i 's/#release-note-synthesis/#release-synthesis/g' "$file" -sed -i 's/## Incident Response Automation/## Incident Automation/g' "$file" -sed -i 's/\[Incident Response Automation\](#incident-response-automation)/[Incident Automation](#incident-automation)/g' "$file" -sed -i 's/#incident-response-automation/#incident-automation/g' "$file" +sed_i 's/## Incident Response Automation/## Incident Automation/g' "$file" +sed_i 's/\[Incident Response Automation\](#incident-response-automation)/[Incident Automation](#incident-automation)/g' "$file" +sed_i 's/#incident-response-automation/#incident-automation/g' "$file" -sed -i 's/## Test Suite Health Management/## Suite Health/g' "$file" -sed -i 's/\[Test Suite Health Management\](#test-suite-health-management)/[Suite Health](#suite-health)/g' "$file" -sed -i 's/#test-suite-health-management/#suite-health/g' "$file" +sed_i 's/## Test Suite Health Management/## Suite Health/g' "$file" +sed_i 's/\[Test Suite Health Management\](#test-suite-health-management)/[Suite Health](#suite-health)/g' "$file" +sed_i 's/#test-suite-health-management/#suite-health/g' "$file" -sed -i 's/## Dependency Upgrade Advisor/## Upgrade Advisor/g' "$file" -sed -i 's/\[Dependency Upgrade Advisor\](#dependency-upgrade-advisor)/[Upgrade Advisor](#upgrade-advisor)/g' "$file" -sed -i 's/#dependency-upgrade-advisor/#upgrade-advisor/g' "$file" +sed_i 's/## Dependency Upgrade Advisor/## Upgrade Advisor/g' "$file" +sed_i 's/\[Dependency Upgrade Advisor\](#dependency-upgrade-advisor)/[Upgrade Advisor](#upgrade-advisor)/g' "$file" +sed_i 's/#dependency-upgrade-advisor/#upgrade-advisor/g' "$file" -sed -i 's/## On-Call Handoff Automation/## Handoff Automation/g' "$file" -sed -i 's/\[On-Call Handoff Automation\](#on-call-handoff-automation)/[Handoff Automation](#handoff-automation)/g' "$file" -sed -i 's/#on-call-handoff-automation/#handoff-automation/g' "$file" +sed_i 's/## On-Call Handoff Automation/## Handoff Automation/g' "$file" +sed_i 's/\[On-Call Handoff Automation\](#on-call-handoff-automation)/[Handoff Automation](#handoff-automation)/g' "$file" +sed_i 's/#on-call-handoff-automation/#handoff-automation/g' "$file" -sed -i 's/## Chaos Engineering Scenarios/## Chaos Engineering/g' "$file" -sed -i 's/\[Chaos Engineering Scenarios\](#chaos-engineering-scenarios)/[Chaos Engineering](#chaos-engineering)/g' "$file" -sed -i 's/#chaos-engineering-scenarios/#chaos-engineering/g' "$file" +sed_i 's/## Chaos Engineering Scenarios/## Chaos Engineering/g' "$file" +sed_i 's/\[Chaos Engineering Scenarios\](#chaos-engineering-scenarios)/[Chaos Engineering](#chaos-engineering)/g' "$file" +sed_i 's/#chaos-engineering-scenarios/#chaos-engineering/g' "$file" -sed -i 's/## ChatOps Security Integration/## ChatOps Security/g' "$file" -sed -i 's/\[ChatOps Security Integration\](#chatops-security-integration)/[ChatOps Security](#chatops-security)/g' "$file" -sed -i 's/#chatops-security-integration/#chatops-security/g' "$file" +sed_i 's/## ChatOps Security Integration/## ChatOps Security/g' "$file" +sed_i 's/\[ChatOps Security Integration\](#chatops-security-integration)/[ChatOps Security](#chatops-security)/g' "$file" +sed_i 's/#chatops-security-integration/#chatops-security/g' "$file" -sed -i 's/## Compliance Evidence Automation/## Evidence Automation/g' "$file" -sed -i 's/\[Compliance Evidence Automation\](#compliance-evidence-automation)/[Evidence Automation](#evidence-automation)/g' "$file" -sed -i 's/#compliance-evidence-automation/#evidence-automation/g' "$file" +sed_i 's/## Compliance Evidence Automation/## Evidence Automation/g' "$file" +sed_i 's/\[Compliance Evidence Automation\](#compliance-evidence-automation)/[Evidence Automation](#evidence-automation)/g' "$file" +sed_i 's/#compliance-evidence-automation/#evidence-automation/g' "$file" -sed -i 's/## Context Window Optimization/## Context Optimization/g' "$file" -sed -i 's/\[Context Window Optimization\](#context-window-optimization)/[Context Optimization](#context-optimization)/g' "$file" -sed -i 's/#context-window-optimization/#context-optimization/g' "$file" +sed_i 's/## Context Window Optimization/## Context Optimization/g' "$file" +sed_i 's/\[Context Window Optimization\](#context-window-optimization)/[Context Optimization](#context-optimization)/g' "$file" +sed_i 's/#context-window-optimization/#context-optimization/g' "$file" -sed -i 's/## Visual Context Scaffolding/## Image Spec/g' "$file" -sed -i 's/\[Visual Context Scaffolding\](#visual-context-scaffolding)/[Image Spec](#image-spec)/g' "$file" -sed -i 's/#visual-context-scaffolding/#image-spec/g' "$file" +sed_i 's/## Visual Context Scaffolding/## Image Spec/g' "$file" +sed_i 's/\[Visual Context Scaffolding\](#visual-context-scaffolding)/[Image Spec](#image-spec)/g' "$file" +sed_i 's/#visual-context-scaffolding/#image-spec/g' "$file" -sed -i 's/## AI Event Automation/## Event Automation/g' "$file" -sed -i 's/\[AI Event Automation\](#ai-event-automation)/[Event Automation](#event-automation)/g' "$file" -sed -i 's/#ai-event-automation/#event-automation/g' "$file" +sed_i 's/## AI Event Automation/## Event Automation/g' "$file" +sed_i 's/\[AI Event Automation\](#ai-event-automation)/[Event Automation](#event-automation)/g' "$file" +sed_i 's/#ai-event-automation/#event-automation/g' "$file" -sed -i 's/## Custom AI Commands/## Custom Commands/g' "$file" -sed -i 's/\[Custom AI Commands\](#custom-ai-commands)/[Custom Commands](#custom-commands)/g' "$file" -sed -i 's/#custom-ai-commands/#custom-commands/g' "$file" +sed_i 's/## Custom AI Commands/## Custom Commands/g' "$file" +sed_i 's/\[Custom AI Commands\](#custom-ai-commands)/[Custom Commands](#custom-commands)/g' "$file" +sed_i 's/#custom-ai-commands/#custom-commands/g' "$file" # Error Resolution - no change needed # Experimental Antipattern Renames -sed -i 's/\*\*Anti-pattern: Unclear Boundaries\*\*/\*\*Anti-pattern: Broken Boundaries\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Test Generation Without Strategy\*\*/\*\*Anti-pattern: Scattered Testing\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Uncoordinated Multi-Tool Usage\*\*/\*\*Anti-pattern: Chaotic Orchestration\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Unsafe Parallel Execution\*\*/\*\*Anti-pattern: Unsafe Parallelism\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Manual-Only Review\*\*/\*\*Anti-pattern: Manual Reviews\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Reactive Debt Management\*\*/\*\*Anti-pattern: Reactive Debt\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Manual Pipeline Maintenance\*\*/\*\*Anti-pattern: Manual Pipelines\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Blue-Green-Canary Confusion\*\*/\*\*Anti-pattern: Confused Deployment\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Manual Drift Checking\*\*/\*\*Anti-pattern: Manual Drift\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Manual Release Notes\*\*/\*\*Anti-pattern: Manual Releases\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Unclear Boundaries\*\*/\*\*Anti-pattern: Broken Boundaries\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Test Generation Without Strategy\*\*/\*\*Anti-pattern: Scattered Testing\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Uncoordinated Multi-Tool Usage\*\*/\*\*Anti-pattern: Chaotic Orchestration\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Unsafe Parallel Execution\*\*/\*\*Anti-pattern: Unsafe Parallelism\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Manual-Only Review\*\*/\*\*Anti-pattern: Manual Reviews\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Reactive Debt Management\*\*/\*\*Anti-pattern: Reactive Debt\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Manual Pipeline Maintenance\*\*/\*\*Anti-pattern: Manual Pipelines\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Blue-Green-Canary Confusion\*\*/\*\*Anti-pattern: Confused Deployment\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Manual Drift Checking\*\*/\*\*Anti-pattern: Manual Drift\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Manual Release Notes\*\*/\*\*Anti-pattern: Manual Releases\*\*/g' "$file" # Static Runbooks - no change -sed -i 's/\*\*Anti-pattern: Ignoring Flaky Tests\*\*/\*\*Anti-pattern: Ignored Flakiness\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Batch Upgrades\*\*/\*\*Anti-pattern: Reckless Upgrades\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Verbal-Only Handoffs\*\*/\*\*Anti-pattern: Undocumented Handoffs\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Ignoring Flaky Tests\*\*/\*\*Anti-pattern: Ignored Flakiness\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Batch Upgrades\*\*/\*\*Anti-pattern: Reckless Upgrades\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Verbal-Only Handoffs\*\*/\*\*Anti-pattern: Undocumented Handoffs\*\*/g' "$file" # Random Chaos - no change -sed -i 's/\*\*Anti-pattern: Delayed Security Feedback\*\*/\*\*Anti-pattern: Delayed Security\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Manual Evidence Collection\*\*/\*\*Anti-pattern: Manual Evidence\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: One-Size-Fits-All\*\*/\*\*Anti-pattern: Wasteful Context\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Kitchen Sink Upload\*\*/\*\*Anti-pattern: Overwhelming Visuals\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Unchecked Event Commands\*\*/\*\*Anti-pattern: Unchecked Events\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Ignoring Built-in Commands\*\*/\*\*Anti-pattern: Redundant Commands\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Delayed Security Feedback\*\*/\*\*Anti-pattern: Delayed Security\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Manual Evidence Collection\*\*/\*\*Anti-pattern: Manual Evidence\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: One-Size-Fits-All\*\*/\*\*Anti-pattern: Wasteful Context\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Kitchen Sink Upload\*\*/\*\*Anti-pattern: Overwhelming Visuals\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Unchecked Event Commands\*\*/\*\*Anti-pattern: Unchecked Events\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Ignoring Built-in Commands\*\*/\*\*Anti-pattern: Redundant Commands\*\*/g' "$file" # Shallow Commands - no change # Hardcoded Context - no change -sed -i 's/\*\*Anti-pattern: Context-Free Error Messages\*\*/\*\*Anti-pattern: Contextless Errors\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Blind Fix Application\*\*/\*\*Anti-pattern: Blind Fixes\*\*/g' "$file" -sed -i 's/\*\*Anti-pattern: Missing Rollback Strategy\*\*/\*\*Anti-pattern: Unprotected Fixes\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Context-Free Error Messages\*\*/\*\*Anti-pattern: Contextless Errors\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Blind Fix Application\*\*/\*\*Anti-pattern: Blind Fixes\*\*/g' "$file" +sed_i 's/\*\*Anti-pattern: Missing Rollback Strategy\*\*/\*\*Anti-pattern: Unprotected Fixes\*\*/g' "$file" # Update references to main patterns (from README.md) in experimental patterns -sed -i 's/AI Developer Lifecycle](\.\.\/README\.md#ai-developer-lifecycle)/Developer Lifecycle](..\/README.md#developer-lifecycle)/g' "$file" -sed -i 's/Observable AI Development](\.\.\/README\.md#observable-ai-development)/Observable Development](..\/README.md#observable-development)/g' "$file" -sed -i 's/Specification Driven Development](\.\.\/README\.md#specification-driven-development)/Spec-First](..\/README.md#spec-first)/g' "$file" -sed -i 's/AI Tool Integration](\.\.\/README\.md#ai-tool-integration)/Tool Integration](..\/README.md#tool-integration)/g' "$file" -sed -i 's/Atomic Task Decomposition](\.\.\/README\.md#atomic-task-decomposition)/Atomic Decomposition](..\/README.md#atomic-decomposition)/g' "$file" -sed -i 's/AI-Driven Refactoring](\.\.\/README\.md#ai-driven-refactoring)/Guided Refactoring](..\/README.md#guided-refactoring)/g' "$file" -sed -i 's/AI-Driven Architecture Design](\.\.\/README\.md#ai-driven-architecture-design)/Guided Architecture](..\/README.md#guided-architecture)/g' "$file" -sed -i 's/Progressive AI Enhancement](\.\.\/README\.md#progressive-ai-enhancement)/Progressive Enhancement](..\/README.md#progressive-enhancement)/g' "$file" -sed -i 's/Rules as Code](\.\.\/README\.md#rules-as-code)/Codified Rules](..\/README.md#codified-rules)/g' "$file" -sed -i 's/AI Security Sandbox](\.\.\/README\.md#ai-security-sandbox)/Security Sandbox](..\/README.md#security-sandbox)/g' "$file" -sed -i 's/Performance Baseline Management](\.\.\/README\.md#performance-baseline-management)/Baseline Management](..\/README.md#baseline-management)/g' "$file" -sed -i 's/Security Scanning Orchestration](\.\.\/README\.md#security-scanning-orchestration)/Security Orchestration](..\/README.md#security-orchestration)/g' "$file" +sed_i 's/AI Developer Lifecycle](\.\.\/README\.md#ai-developer-lifecycle)/Developer Lifecycle](..\/README.md#developer-lifecycle)/g' "$file" +sed_i 's/Observable AI Development](\.\.\/README\.md#observable-ai-development)/Observable Development](..\/README.md#observable-development)/g' "$file" +sed_i 's/Specification Driven Development](\.\.\/README\.md#specification-driven-development)/Spec-Driven Development](..\/README.md#spec-driven-development)/g' "$file" +sed_i 's/AI Tool Integration](\.\.\/README\.md#ai-tool-integration)/Tool Integration](..\/README.md#tool-integration)/g' "$file" +sed_i 's/Atomic Task Decomposition](\.\.\/README\.md#atomic-task-decomposition)/Atomic Decomposition](..\/README.md#atomic-decomposition)/g' "$file" +sed_i 's/AI-Driven Refactoring](\.\.\/README\.md#ai-driven-refactoring)/Guided Refactoring](..\/README.md#guided-refactoring)/g' "$file" +sed_i 's/AI-Driven Architecture Design](\.\.\/README\.md#ai-driven-architecture-design)/Guided Architecture](..\/README.md#guided-architecture)/g' "$file" +sed_i 's/Progressive AI Enhancement](\.\.\/README\.md#progressive-ai-enhancement)/Progressive Enhancement](..\/README.md#progressive-enhancement)/g' "$file" +sed_i 's/Rules as Code](\.\.\/README\.md#rules-as-code)/Codified Rules](..\/README.md#codified-rules)/g' "$file" +sed_i 's/AI Security Sandbox](\.\.\/README\.md#ai-security-sandbox)/Security Sandbox](..\/README.md#security-sandbox)/g' "$file" +sed_i 's/Performance Baseline Management](\.\.\/README\.md#performance-baseline-management)/Baseline Management](..\/README.md#baseline-management)/g' "$file" +sed_i 's/Security Scanning Orchestration](\.\.\/README\.md#security-scanning-orchestration)/Security Orchestration](..\/README.md#security-orchestration)/g' "$file" echo " ✅ Completed $file" diff --git a/scripts/apply-pattern-renames.sh b/scripts/apply-pattern-renames.sh index a10d560..4b7875a 100755 --- a/scripts/apply-pattern-renames.sh +++ b/scripts/apply-pattern-renames.sh @@ -1,8 +1,25 @@ #!/bin/bash -# Script to apply all pattern name renames in README.md and experiments/README.md +# Script to apply pattern name renames in README.md and experiments/README.md +# +# Note: This is a historical migration helper. The repository is already migrated, +# but keeping this script accurate helps prevent confusion and supports any future +# backports or forks that still contain legacy names. set -e +REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + +sed_i() { + local expression="$1" + local file="$2" + + if sed --version >/dev/null 2>&1; then + sed -i "$expression" "$file" + else + sed -i '' "$expression" "$file" + fi +} + echo "Applying pattern name renames..." # Function to apply renames to a file @@ -11,121 +28,122 @@ apply_renames() { echo "Processing $file..." # Main Pattern Renames (headers and references) - sed -i 's/## AI Readiness Assessment/## Readiness Assessment/g' "$file" - sed -i 's/\[AI Readiness Assessment\](#ai-readiness-assessment)/[Readiness Assessment](#readiness-assessment)/g' "$file" - sed -i 's/#ai-readiness-assessment/#readiness-assessment/g' "$file" + sed_i 's/## AI Readiness Assessment/## Readiness Assessment/g' "$file" + sed_i 's/\[AI Readiness Assessment\](#ai-readiness-assessment)/[Readiness Assessment](#readiness-assessment)/g' "$file" + sed_i 's/#ai-readiness-assessment/#readiness-assessment/g' "$file" - sed -i 's/## Rules as Code/## Codified Rules/g' "$file" - sed -i 's/\[Rules as Code\](#rules-as-code)/[Codified Rules](#codified-rules)/g' "$file" - sed -i 's/#rules-as-code/#codified-rules/g' "$file" + sed_i 's/## Rules as Code/## Codified Rules/g' "$file" + sed_i 's/\[Rules as Code\](#rules-as-code)/[Codified Rules](#codified-rules)/g' "$file" + sed_i 's/#rules-as-code/#codified-rules/g' "$file" - sed -i 's/## AI Security Sandbox/## Security Sandbox/g' "$file" - sed -i 's/\[AI Security Sandbox\](#ai-security-sandbox)/[Security Sandbox](#security-sandbox)/g' "$file" - sed -i 's/#ai-security-sandbox/#security-sandbox/g' "$file" + sed_i 's/## AI Security Sandbox/## Security Sandbox/g' "$file" + sed_i 's/\[AI Security Sandbox\](#ai-security-sandbox)/[Security Sandbox](#security-sandbox)/g' "$file" + sed_i 's/#ai-security-sandbox/#security-sandbox/g' "$file" - sed -i 's/## AI Developer Lifecycle/## Developer Lifecycle/g' "$file" - sed -i 's/\[AI Developer Lifecycle\](#ai-developer-lifecycle)/[Developer Lifecycle](#developer-lifecycle)/g' "$file" - sed -i 's/#ai-developer-lifecycle/#developer-lifecycle/g' "$file" + sed_i 's/## AI Developer Lifecycle/## Developer Lifecycle/g' "$file" + sed_i 's/\[AI Developer Lifecycle\](#ai-developer-lifecycle)/[Developer Lifecycle](#developer-lifecycle)/g' "$file" + sed_i 's/#ai-developer-lifecycle/#developer-lifecycle/g' "$file" - sed -i 's/## AI Tool Integration/## Tool Integration/g' "$file" - sed -i 's/\[AI Tool Integration\](#ai-tool-integration)/[Tool Integration](#tool-integration)/g' "$file" - sed -i 's/#ai-tool-integration/#tool-integration/g' "$file" + sed_i 's/## AI Tool Integration/## Tool Integration/g' "$file" + sed_i 's/\[AI Tool Integration\](#ai-tool-integration)/[Tool Integration](#tool-integration)/g' "$file" + sed_i 's/#ai-tool-integration/#tool-integration/g' "$file" - sed -i 's/## AI Issue Generation/## Issue Generation/g' "$file" - sed -i 's/\[AI Issue Generation\](#ai-issue-generation)/[Issue Generation](#issue-generation)/g' "$file" - sed -i 's/#ai-issue-generation/#issue-generation/g' "$file" + sed_i 's/## AI Issue Generation/## Issue Generation/g' "$file" + sed_i 's/\[AI Issue Generation\](#ai-issue-generation)/[Issue Generation](#issue-generation)/g' "$file" + sed_i 's/#ai-issue-generation/#issue-generation/g' "$file" - sed -i 's/## Specification Driven Development/## Spec-First/g' "$file" - sed -i 's/\[Specification Driven Development\](#specification-driven-development)/[Spec-First](#spec-first)/g' "$file" - sed -i 's/#specification-driven-development/#spec-first/g' "$file" + sed_i 's/## Specification Driven Development/## Spec-Driven Development/g' "$file" + sed_i 's/\[Specification Driven Development\](#specification-driven-development)/[Spec-Driven Development](#spec-driven-development)/g' "$file" + sed_i 's/#specification-driven-development/#spec-driven-development/g' "$file" - sed -i 's/## AI Plan-First Development/## Planned Implementation/g' "$file" - sed -i 's/\[AI Plan-First Development\](#ai-plan-first-development)/[Planned Implementation](#planned-implementation)/g' "$file" - sed -i 's/#ai-plan-first-development/#planned-implementation/g' "$file" + sed_i 's/## AI Plan-First Development/## Planned Implementation/g' "$file" + sed_i 's/\[AI Plan-First Development\](#ai-plan-first-development)/[Planned Implementation](#planned-implementation)/g' "$file" + sed_i 's/#ai-plan-first-development/#planned-implementation/g' "$file" - sed -i 's/## Progressive AI Enhancement/## Progressive Enhancement/g' "$file" - sed -i 's/\[Progressive AI Enhancement\](#progressive-ai-enhancement)/[Progressive Enhancement](#progressive-enhancement)/g' "$file" + sed_i 's/## Progressive AI Enhancement/## Progressive Enhancement/g' "$file" + sed_i 's/\[Progressive AI Enhancement\](#progressive-ai-enhancement)/[Progressive Enhancement](#progressive-enhancement)/g' "$file" # No anchor change needed for Progressive Enhancement - sed -i 's/## AI Choice Generation/## Choice Generation/g' "$file" - sed -i 's/\[AI Choice Generation\](#ai-choice-generation)/[Choice Generation](#choice-generation)/g' "$file" - sed -i 's/#ai-choice-generation/#choice-generation/g' "$file" + sed_i 's/## AI Choice Generation/## Choice Generation/g' "$file" + sed_i 's/\[AI Choice Generation\](#ai-choice-generation)/[Choice Generation](#choice-generation)/g' "$file" + sed_i 's/#ai-choice-generation/#choice-generation/g' "$file" - sed -i 's/## Atomic Task Decomposition/## Atomic Decomposition/g' "$file" - sed -i 's/\[Atomic Task Decomposition\](#atomic-task-decomposition)/[Atomic Decomposition](#atomic-decomposition)/g' "$file" - sed -i 's/#atomic-task-decomposition/#atomic-decomposition/g' "$file" + sed_i 's/## Atomic Task Decomposition/## Atomic Decomposition/g' "$file" + sed_i 's/\[Atomic Task Decomposition\](#atomic-task-decomposition)/[Atomic Decomposition](#atomic-decomposition)/g' "$file" + sed_i 's/#atomic-task-decomposition/#atomic-decomposition/g' "$file" - sed -i 's/## Parallelized AI Coding Agents/## Parallel Agents/g' "$file" - sed -i 's/\[Parallelized AI Coding Agents\](#parallelized-ai-coding-agents)/[Parallel Agents](#parallel-agents)/g' "$file" - sed -i 's/#parallelized-ai-coding-agents/#parallel-agents/g' "$file" + sed_i 's/## Parallelized AI Coding Agents/## Parallel Agents/g' "$file" + sed_i 's/\[Parallelized AI Coding Agents\](#parallelized-ai-coding-agents)/[Parallel Agents](#parallel-agents)/g' "$file" + sed_i 's/#parallelized-ai-coding-agents/#parallel-agents/g' "$file" - sed -i 's/## AI Context Persistence/## Context Persistence/g' "$file" - sed -i 's/\[AI Context Persistence\](#ai-context-persistence)/[Context Persistence](#context-persistence)/g' "$file" - sed -i 's/#ai-context-persistence/#context-persistence/g' "$file" + sed_i 's/## AI Context Persistence/## Context Persistence/g' "$file" + sed_i 's/\[AI Context Persistence\](#ai-context-persistence)/[Context Persistence](#context-persistence)/g' "$file" + sed_i 's/#ai-context-persistence/#context-persistence/g' "$file" - sed -i 's/## Constraint-Based AI Development/## Constrained Generation/g' "$file" - sed -i 's/\[Constraint-Based AI Development\](#constraint-based-ai-development)/[Constrained Generation](#constrained-generation)/g' "$file" - sed -i 's/#constraint-based-ai-development/#constrained-generation/g' "$file" + sed_i 's/## Constraint-Based AI Development/## Constrained Generation/g' "$file" + sed_i 's/\[Constraint-Based AI Development\](#constraint-based-ai-development)/[Constrained Generation](#constrained-generation)/g' "$file" + sed_i 's/#constraint-based-ai-development/#constrained-generation/g' "$file" - sed -i 's/## Observable AI Development/## Observable Development/g' "$file" - sed -i 's/\[Observable AI Development\](#observable-ai-development)/[Observable Development](#observable-development)/g' "$file" - sed -i 's/#observable-ai-development/#observable-development/g' "$file" + sed_i 's/## Observable AI Development/## Observable Development/g' "$file" + sed_i 's/\[Observable AI Development\](#observable-ai-development)/[Observable Development](#observable-development)/g' "$file" + sed_i 's/#observable-ai-development/#observable-development/g' "$file" - sed -i 's/## AI-Driven Refactoring/## Guided Refactoring/g' "$file" - sed -i 's/\[AI-Driven Refactoring\](#ai-driven-refactoring)/[Guided Refactoring](#guided-refactoring)/g' "$file" - sed -i 's/#ai-driven-refactoring/#guided-refactoring/g' "$file" + sed_i 's/## AI-Driven Refactoring/## Guided Refactoring/g' "$file" + sed_i 's/\[AI-Driven Refactoring\](#ai-driven-refactoring)/[Guided Refactoring](#guided-refactoring)/g' "$file" + sed_i 's/#ai-driven-refactoring/#guided-refactoring/g' "$file" - sed -i 's/## AI-Driven Architecture Design/## Guided Architecture/g' "$file" - sed -i 's/\[AI-Driven Architecture Design\](#ai-driven-architecture-design)/[Guided Architecture](#guided-architecture)/g' "$file" - sed -i 's/#ai-driven-architecture-design/#guided-architecture/g' "$file" + sed_i 's/## AI-Driven Architecture Design/## Guided Architecture/g' "$file" + sed_i 's/\[AI-Driven Architecture Design\](#ai-driven-architecture-design)/[Guided Architecture](#guided-architecture)/g' "$file" + sed_i 's/#ai-driven-architecture-design/#guided-architecture/g' "$file" - sed -i 's/## AI-Driven Traceability/## Automated Traceability/g' "$file" - sed -i 's/\[AI-Driven Traceability\](#ai-driven-traceability)/[Automated Traceability](#automated-traceability)/g' "$file" - sed -i 's/#ai-driven-traceability/#automated-traceability/g' "$file" + sed_i 's/## AI-Driven Traceability/## Automated Traceability/g' "$file" + sed_i 's/\[AI-Driven Traceability\](#ai-driven-traceability)/[Automated Traceability](#automated-traceability)/g' "$file" + sed_i 's/#ai-driven-traceability/#automated-traceability/g' "$file" - sed -i 's/## Policy-as-Code Generation/## Policy Generation/g' "$file" - sed -i 's/\[Policy-as-Code Generation\](#policy-as-code-generation)/[Policy Generation](#policy-generation)/g' "$file" - sed -i 's/#policy-as-code-generation/#policy-generation/g' "$file" + sed_i 's/## Policy-as-Code Generation/## Policy Generation/g' "$file" + sed_i 's/\[Policy-as-Code Generation\](#policy-as-code-generation)/[Policy Generation](#policy-generation)/g' "$file" + sed_i 's/#policy-as-code-generation/#policy-generation/g' "$file" - sed -i 's/## Security Scanning Orchestration/## Security Orchestration/g' "$file" - sed -i 's/\[Security Scanning Orchestration\](#security-scanning-orchestration)/[Security Orchestration](#security-orchestration)/g' "$file" - sed -i 's/#security-scanning-orchestration/#security-orchestration/g' "$file" + sed_i 's/## Security Scanning Orchestration/## Security Orchestration/g' "$file" + sed_i 's/\[Security Scanning Orchestration\](#security-scanning-orchestration)/[Security Orchestration](#security-orchestration)/g' "$file" + sed_i 's/#security-scanning-orchestration/#security-orchestration/g' "$file" - sed -i 's/## Performance Baseline Management/## Baseline Management/g' "$file" - sed -i 's/\[Performance Baseline Management\](#performance-baseline-management)/[Baseline Management](#baseline-management)/g' "$file" - sed -i 's/#performance-baseline-management/#baseline-management/g' "$file" + sed_i 's/## Performance Baseline Management/## Baseline Management/g' "$file" + sed_i 's/\[Performance Baseline Management\](#performance-baseline-management)/[Baseline Management](#baseline-management)/g' "$file" + sed_i 's/#performance-baseline-management/#baseline-management/g' "$file" # Antipattern Renames - sed -i 's/\*\*Anti-pattern: Rushing Into AI\*\*/\*\*Anti-pattern: Premature Adoption\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Context Drift\*\*/\*\*Anti-pattern: Broken Context\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Shared Agent Workspaces\*\*/\*\*Anti-pattern: Conflicting Workspaces\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Ad-Hoc AI Development\*\*/\*\*Anti-pattern: Unplanned Development\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Prompt-Only AI Development\*\*/\*\*Anti-pattern: Disconnected Prompting\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Vague Issue Generation\*\*/\*\*Anti-pattern: Under-Specified Issues\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Missing CI Integration\*\*/\*\*Anti-pattern: Broken Integration\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Implementation-First AI\*\*/\*\*Anti-pattern: Spec-Ignored\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Prompt Hoarding\*\*/\*\*Anti-pattern: Over-Prompting\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Blind Code Generation\*\*/\*\*Anti-pattern: Blind Generation\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Analysis Paralysis\*\*/\*\*Anti-pattern: Over-Analysis\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Big Bang Generation\*\*/\*\*Anti-pattern: Monolithic Generation\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Uncoordinated Parallel Execution\*\*/\*\*Anti-pattern: Uncoordinated Agents\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Knowledge Hoarding\*\*/\*\*Anti-pattern: Over-Documentation\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Context Bloat\*\*/\*\*Anti-pattern: Bloated Context\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Pseudo-Atomic Tasks\*\*/\*\*Anti-pattern: False Atomicity\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Black Box Development\*\*/\*\*Anti-pattern: Blind Development\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Shotgun Surgery\*\*/\*\*Anti-pattern: Scattered Refactoring\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Speculative Refactoring\*\*/\*\*Anti-pattern: Premature Refactoring\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Architecture Astronaut AI\*\*/\*\*Anti-pattern: Over-Architecting\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Manual Traceability Management\*\*/\*\*Anti-pattern: Broken Traceability\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Manual Policy Translation\*\*/\*\*Anti-pattern: Untested Policies\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: Alert Fatigue\*\*/\*\*Anti-pattern: Over-Alerting\*\*/g' "$file" - sed -i 's/\*\*Anti-pattern: One-Off Alerts\*\*/\*\*Anti-pattern: Static Thresholds\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Rushing Into AI\*\*/\*\*Anti-pattern: Premature Adoption\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Context Drift\*\*/\*\*Anti-pattern: Broken Context\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Shared Agent Workspaces\*\*/\*\*Anti-pattern: Conflicting Workspaces\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Ad-Hoc AI Development\*\*/\*\*Anti-pattern: Unplanned Development\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Prompt-Only AI Development\*\*/\*\*Anti-pattern: Disconnected Prompting\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Vague Issue Generation\*\*/\*\*Anti-pattern: Under-Specified Issues\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Missing CI Integration\*\*/\*\*Anti-pattern: Broken Integration\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Implementation-First AI\*\*/\*\*Anti-pattern: Spec-Ignored\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Prompt Hoarding\*\*/\*\*Anti-pattern: Over-Prompting\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Blind Code Generation\*\*/\*\*Anti-pattern: Blind Generation\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Analysis Paralysis\*\*/\*\*Anti-pattern: Over-Analysis\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Big Bang Generation\*\*/\*\*Anti-pattern: Monolithic Generation\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Uncoordinated Parallel Execution\*\*/\*\*Anti-pattern: Uncoordinated Agents\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Knowledge Hoarding\*\*/\*\*Anti-pattern: Over-Documentation\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Context Bloat\*\*/\*\*Anti-pattern: Bloated Context\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Pseudo-Atomic Tasks\*\*/\*\*Anti-pattern: False Atomicity\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Black Box Development\*\*/\*\*Anti-pattern: Blind Development\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Shotgun Surgery\*\*/\*\*Anti-pattern: Scattered Refactoring\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Speculative Refactoring\*\*/\*\*Anti-pattern: Premature Refactoring\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Architecture Astronaut AI\*\*/\*\*Anti-pattern: Over-Architecting\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Manual Traceability Management\*\*/\*\*Anti-pattern: Broken Traceability\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Manual Policy Translation\*\*/\*\*Anti-pattern: Untested Policies\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: Alert Fatigue\*\*/\*\*Anti-pattern: Over-Alerting\*\*/g' "$file" + sed_i 's/\*\*Anti-pattern: One-Off Alerts\*\*/\*\*Anti-pattern: Static Thresholds\*\*/g' "$file" echo " ✅ Completed $file" } # Apply to main README -apply_renames "/home/user/ai-development-patterns/README.md" +apply_renames "$REPO_ROOT/README.md" +apply_renames "$REPO_ROOT/experiments/README.md" echo "" echo "✅ Pattern rename script completed successfully!" diff --git a/scripts/rename-example-directories.sh b/scripts/rename-example-directories.sh index 8b48813..6169b9b 100755 --- a/scripts/rename-example-directories.sh +++ b/scripts/rename-example-directories.sh @@ -3,12 +3,14 @@ set -e +REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + echo "Renaming example directories..." # Main examples echo "Renaming main example directories..." -cd /home/user/ai-development-patterns +cd "$REPO_ROOT" # Use git mv for proper tracking git mv examples/ai-context-persistence examples/context-persistence @@ -26,7 +28,7 @@ git mv examples/performance-baseline-management examples/baseline-management git mv examples/policy-as-code-generation examples/policy-generation git mv examples/rules-as-code examples/codified-rules git mv examples/security-scanning-orchestration examples/security-orchestration -git mv examples/specification-driven-development examples/spec-first +git mv examples/specification-driven-development examples/spec-driven-development echo " ✅ Renamed 16 main example directories" diff --git a/scripts/update-pattern-count.py b/scripts/update-pattern-count.py index 60a37a2..38417bd 100755 --- a/scripts/update-pattern-count.py +++ b/scripts/update-pattern-count.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """ -Script to automatically update the pattern count badge in README.md -This script counts patterns from conftest.py and updates the badge dynamically. +Script to automatically update the pattern count badges in README.md and index.html. +This script counts patterns from conftest.py and updates any matching shields.io badges. """ import os @@ -33,62 +33,30 @@ def count_patterns_from_conftest(): return pattern_count -def update_readme_badge(pattern_count): - """Update the pattern count badge in README.md""" - readme_path = Path(__file__).parent.parent / "README.md" - - if not readme_path.exists(): - print(f"Error: README.md not found at {readme_path}") +def update_pattern_badge(file_path: Path, pattern_count: int) -> bool: + """Update the pattern count badge in a given file.""" + if not file_path.exists(): + print(f"Error: File not found at {file_path}") return False - with open(readme_path, 'r', encoding='utf-8') as f: + with open(file_path, 'r', encoding='utf-8') as f: content = f.read() - print(f"✓ README.md found, length: {len(content)} characters") - - # Multiple patterns to try, from most specific to most general - badge_patterns = [ - # Exact pattern with complete-pattern-reference link - r'(\[!\[Patterns\]\(https://img\.shields\.io/badge/patterns-)(\d+)(-blue\.svg\)\]\(#complete-pattern-reference\))', - # Pattern with any anchor link - r'(\[!\[Patterns\]\(https://img\.shields\.io/badge/patterns-)(\d+)(-blue\.svg\)\]\([^)]+\))', - # Pattern without link - r'(\[!\[Patterns\]\(https://img\.shields\.io/badge/patterns-)(\d+)(-blue\.svg\))', - ] - - updated_content = content - pattern_found = False - - for i, pattern in enumerate(badge_patterns): - def replace_count(match): - nonlocal pattern_found - pattern_found = True - return f"{match.group(1)}{pattern_count}{match.group(3)}" - - test_content = re.sub(pattern, replace_count, content) - if test_content != content: - updated_content = test_content - print(f"✓ Used pattern {i+1} to update badge") - break - - if not pattern_found: - print("Warning: No badge pattern found to update") - print("Searching for any Patterns badge in content...") - - # Debug: show what patterns we can find - lines = content.split('\n') - for line_num, line in enumerate(lines, 1): - if 'Patterns' in line and 'shields.io' in line: - print(f"Found badge-like line {line_num}: {repr(line)}") + badge_pattern = re.compile(r'(https://img\.shields\.io/badge/patterns-)(\d+)(-blue\.svg)') + updated_content, substitutions = badge_pattern.subn(rf'\g<1>{pattern_count}\g<3>', content) + + if substitutions == 0: + print(f"Warning: No pattern badges found to update in {file_path.name}") return False - with open(readme_path, 'w', encoding='utf-8') as f: + with open(file_path, 'w', encoding='utf-8') as f: f.write(updated_content) + print(f"✓ Updated {substitutions} badge reference(s) in {file_path.name}") return True def main(): - """Main function to count patterns and update README""" + """Main function to count patterns and update badges""" print("🔍 Counting patterns from conftest.py...") pattern_count = count_patterns_from_conftest() @@ -98,9 +66,16 @@ def main(): print(f"✓ Found {pattern_count} patterns") - print("📝 Updating README.md badge...") - if update_readme_badge(pattern_count): - print(f"✅ Successfully updated pattern count badge to {pattern_count}") + repo_root = Path(__file__).parent.parent + readme_path = repo_root / "README.md" + index_path = repo_root / "index.html" + + print("📝 Updating pattern count badges...") + updated_readme = update_pattern_badge(readme_path, pattern_count) + updated_index = update_pattern_badge(index_path, pattern_count) + + if updated_readme and updated_index: + print(f"✅ Successfully updated pattern count badges to {pattern_count}") # Output for GitHub Actions if 'GITHUB_OUTPUT' in os.environ: @@ -109,8 +84,8 @@ def main(): return pattern_count else: - print("❌ Failed to update README.md badge") + print("❌ Failed to update one or more pattern count badges") sys.exit(1) if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/scripts/validate-pattern-names.py b/scripts/validate-pattern-names.py index 8ed17f4..7caf2a0 100755 --- a/scripts/validate-pattern-names.py +++ b/scripts/validate-pattern-names.py @@ -55,7 +55,7 @@ def __init__(self): def count_words(self, name: str) -> int: """Count words in a pattern name. Hyphenated words count as one word.""" - # Remove hyphens within words (e.g., "Spec-First" is 1 word, "AI-Driven" is 1 word) + # Remove hyphens within words (e.g., "Spec-Driven" is 1 word, "AI-Driven" is 1 word) # Split by spaces words = name.strip().split() return len(words) @@ -93,7 +93,7 @@ def is_title_case(self, name: str) -> bool: """Check if name follows Title Case convention.""" words = name.split() for word in words: - # Handle hyphenated words (e.g., "Spec-First") + # Handle hyphenated words (e.g., "Spec-Driven") parts = word.split('-') for part in parts: if part and not part[0].isupper(): diff --git a/tests/test_examples.py b/tests/test_examples.py index 80e4311..933cf82 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -10,6 +10,7 @@ CodeValidator ) from utils.pattern_parser import PatternParser +from utils.git_utils import git_ls_files, git_tracked_child_dirs class TestCodeExamples: @@ -154,146 +155,151 @@ def test_all_example_directories_valid(self, repo_root): def test_example_directories_have_readmes(self, repo_root): """Verify all example directories contain README.md files""" - examples_dir = repo_root / "examples" missing_readmes = [] - - if examples_dir.exists(): - for example_dir in examples_dir.iterdir(): - if example_dir.is_dir() and not example_dir.name.startswith('.'): - readme_path = example_dir / "README.md" - if not readme_path.exists(): - missing_readmes.append(str(example_dir.relative_to(repo_root))) + + for example_dir in git_tracked_child_dirs(repo_root, "examples"): + readme_path = example_dir / "README.md" + if not readme_path.exists(): + missing_readmes.append(str(example_dir.relative_to(repo_root))) assert not missing_readmes, f"Example directories missing README.md: {missing_readmes}" def test_python_files_in_examples_valid(self, repo_root): """Test all Python files in example directories""" - examples_dir = repo_root / "examples" code_validator = CodeValidator(repo_root) invalid_python_files = [] - - if examples_dir.exists(): - for python_file in examples_dir.rglob("*.py"): - try: - with open(python_file, 'r', encoding='utf-8') as f: - content = f.read() - - is_valid, error = code_validator.validate_python_syntax( - content, str(python_file.relative_to(repo_root)) - ) - - if not is_valid: - invalid_python_files.append({ - 'file': str(python_file.relative_to(repo_root)), - 'error': error - }) - - except Exception as e: + + tracked_files = git_ls_files(repo_root, "examples") + for rel_path in tracked_files: + if not rel_path.endswith(".py"): + continue + python_file = repo_root / rel_path + + try: + with open(python_file, 'r', encoding='utf-8') as f: + content = f.read() + + is_valid, error = code_validator.validate_python_syntax(content, rel_path) + + if not is_valid: invalid_python_files.append({ - 'file': str(python_file.relative_to(repo_root)), - 'error': f"Failed to read file: {e}" + 'file': rel_path, + 'error': error }) + + except Exception as e: + invalid_python_files.append({ + 'file': rel_path, + 'error': f"Failed to read file: {e}" + }) assert not invalid_python_files, f"Invalid Python files in examples: {invalid_python_files}" def test_shell_scripts_in_examples_valid(self, repo_root): """Test all shell scripts in example directories""" - examples_dir = repo_root / "examples" code_validator = CodeValidator(repo_root) invalid_shell_files = [] - - if examples_dir.exists(): - for shell_file in examples_dir.rglob("*.sh"): - try: - with open(shell_file, 'r', encoding='utf-8') as f: - content = f.read() - - is_valid, error = code_validator.validate_bash_syntax( - content, str(shell_file.relative_to(repo_root)) - ) - - if not is_valid: - invalid_shell_files.append({ - 'file': str(shell_file.relative_to(repo_root)), - 'error': error - }) - - except Exception as e: + + tracked_files = git_ls_files(repo_root, "examples") + for rel_path in tracked_files: + if not rel_path.endswith(".sh"): + continue + shell_file = repo_root / rel_path + + try: + with open(shell_file, 'r', encoding='utf-8') as f: + content = f.read() + + is_valid, error = code_validator.validate_bash_syntax(content, rel_path) + + if not is_valid: invalid_shell_files.append({ - 'file': str(shell_file.relative_to(repo_root)), - 'error': f"Failed to read file: {e}" + 'file': rel_path, + 'error': error }) + + except Exception as e: + invalid_shell_files.append({ + 'file': rel_path, + 'error': f"Failed to read file: {e}" + }) assert not invalid_shell_files, f"Invalid shell scripts in examples: {invalid_shell_files}" def test_dockerfile_syntax_in_examples(self, repo_root): """Test Dockerfile syntax in example directories""" - examples_dir = repo_root / "examples" code_validator = CodeValidator(repo_root) invalid_dockerfiles = [] - - if examples_dir.exists(): - # Find all Dockerfiles (various naming conventions) - dockerfile_patterns = ["Dockerfile*", "*.dockerfile", "*Dockerfile*"] - dockerfiles = [] - - for pattern in dockerfile_patterns: - dockerfiles.extend(examples_dir.rglob(pattern)) - - for dockerfile in dockerfiles: - if dockerfile.is_file(): - try: - with open(dockerfile, 'r', encoding='utf-8') as f: - content = f.read() - - is_valid, error = code_validator.validate_dockerfile_syntax( - content, str(dockerfile.relative_to(repo_root)) - ) - - if not is_valid: - invalid_dockerfiles.append({ - 'file': str(dockerfile.relative_to(repo_root)), - 'error': error - }) - - except Exception as e: - invalid_dockerfiles.append({ - 'file': str(dockerfile.relative_to(repo_root)), - 'error': f"Failed to read file: {e}" - }) + + tracked_files = git_ls_files(repo_root, "examples") + for rel_path in tracked_files: + filename = rel_path.split("/")[-1] + is_dockerfile = ( + filename.lower().startswith("dockerfile") + or filename.lower().endswith(".dockerfile") + or "dockerfile" in filename.lower() + ) + if not is_dockerfile: + continue + + dockerfile = repo_root / rel_path + if not dockerfile.is_file(): + continue + + try: + with open(dockerfile, 'r', encoding='utf-8') as f: + content = f.read() + + is_valid, error = code_validator.validate_dockerfile_syntax(content, rel_path) + + if not is_valid: + invalid_dockerfiles.append({ + 'file': rel_path, + 'error': error + }) + + except Exception as e: + invalid_dockerfiles.append({ + 'file': rel_path, + 'error': f"Failed to read file: {e}" + }) assert not invalid_dockerfiles, f"Invalid Dockerfiles in examples: {invalid_dockerfiles}" def test_requirements_files_format(self, repo_root): """Test requirements.txt files format in examples""" - examples_dir = repo_root / "examples" invalid_requirements = [] - - if examples_dir.exists(): - for req_file in examples_dir.rglob("*requirements*.txt"): - try: - with open(req_file, 'r', encoding='utf-8') as f: - content = f.read() - - lines = content.strip().split('\n') - for line_num, line in enumerate(lines, 1): - line = line.strip() - if line and not line.startswith('#'): - # Basic validation for package names - # Should contain alphanumeric, hyphens, underscores, and version specifiers - if not any(c.isalnum() for c in line): - invalid_requirements.append({ - 'file': str(req_file.relative_to(repo_root)), - 'line': line_num, - 'content': line, - 'error': 'Line does not appear to be a valid requirement' - }) - - except Exception as e: - invalid_requirements.append({ - 'file': str(req_file.relative_to(repo_root)), - 'error': f"Failed to read file: {e}" - }) + + tracked_files = git_ls_files(repo_root, "examples") + for rel_path in tracked_files: + filename = rel_path.split("/")[-1] + if "requirements" not in filename or not filename.endswith(".txt"): + continue + + req_file = repo_root / rel_path + try: + with open(req_file, 'r', encoding='utf-8') as f: + content = f.read() + + lines = content.strip().split('\n') + for line_num, line in enumerate(lines, 1): + line = line.strip() + if line and not line.startswith('#'): + # Basic validation for package names + # Should contain alphanumeric, hyphens, underscores, and version specifiers + if not any(c.isalnum() for c in line): + invalid_requirements.append({ + 'file': rel_path, + 'line': line_num, + 'content': line, + 'error': 'Line does not appear to be a valid requirement' + }) + + except Exception as e: + invalid_requirements.append({ + 'file': rel_path, + 'error': f"Failed to read file: {e}" + }) assert not invalid_requirements, f"Invalid requirements files: {invalid_requirements}" @@ -367,4 +373,4 @@ def test_example_directories_match_patterns(self, readme_content, repo_root): if orphaned_examples: print(f"Example directories without direct pattern matches: {orphaned_examples}") - # We don't assert failure here since some examples might be shared utilities \ No newline at end of file + # We don't assert failure here since some examples might be shared utilities diff --git a/tests/test_links.py b/tests/test_links.py index 16e8e71..0f7f906 100644 --- a/tests/test_links.py +++ b/tests/test_links.py @@ -5,6 +5,7 @@ import pytest import os from utils.link_checker import LinkChecker +from utils.markdown_link_validator import MarkdownLinkValidator from utils.pattern_parser import PatternParser, ReferenceTableParser from conftest import EXPECTED_PATTERNS @@ -282,4 +283,23 @@ def test_link_text_descriptive(self, readme_content): # This is a quality check - warn but don't fail if poor_link_text: - print(f"Quality issue: Non-descriptive link text found: {poor_link_text}") \ No newline at end of file + print(f"Quality issue: Non-descriptive link text found: {poor_link_text}") + + +class TestRepositoryMarkdownLinks: + """Validate internal anchors + relative links across docs/examples/experiments markdown.""" + + def test_repo_wide_markdown_links_valid(self, repo_root): + validator = MarkdownLinkValidator(repo_root) + files = validator.markdown_files_in_scope() + errors = validator.validate_files(files) + + if errors: + sample = "\n".join( + f"{e.source_file}:{e.source_line} {e.link} -> {e.message}" + for e in errors[:25] + ) + pytest.fail( + f"Broken markdown links found: {len(errors)} total.\n" + f"First {min(len(errors), 25)}:\n{sample}" + ) diff --git a/tests/utils/example_validator.py b/tests/utils/example_validator.py index 8c4c852..9c6502f 100644 --- a/tests/utils/example_validator.py +++ b/tests/utils/example_validator.py @@ -10,6 +10,7 @@ import json from typing import List, Dict, Tuple, Optional from pathlib import Path +from utils.git_utils import git_ls_files, git_tracked_child_dirs class CodeValidator: @@ -209,7 +210,7 @@ def validate_example_directory(self, dir_path: Path) -> Dict[str, any]: except Exception as e: errors.append(f"Error reading README.md: {e}") - # Validate all code files + # Validate code files (tracked only to keep local runs aligned with CI) code_file_extensions = { '.py': self.code_validator.validate_python_syntax, '.sh': self.code_validator.validate_bash_syntax, @@ -217,40 +218,46 @@ def validate_example_directory(self, dir_path: Path) -> Dict[str, any]: '.yml': self.code_validator.validate_yaml_syntax, '.json': self.code_validator.validate_json_syntax } - - for file_path in dir_path.rglob('*'): - if file_path.is_file(): - suffix = file_path.suffix.lower() - - if suffix in code_file_extensions: - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - validator_func = code_file_extensions[suffix] - is_valid, error_msg = validator_func(content, str(file_path.relative_to(self.repo_root))) - - if not is_valid: - errors.append(error_msg) - - except Exception as e: - errors.append(f"Error reading {file_path.relative_to(self.repo_root)}: {e}") - - # Special case for Dockerfiles - elif file_path.name.lower().startswith('dockerfile'): - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - is_valid, error_msg = self.code_validator.validate_dockerfile_syntax( - content, str(file_path.relative_to(self.repo_root)) - ) - - if not is_valid: - errors.append(error_msg) - - except Exception as e: - errors.append(f"Error reading {file_path.relative_to(self.repo_root)}: {e}") + + rel_dir = str(dir_path.relative_to(self.repo_root)).replace("\\", "/") + tracked_files = git_ls_files(self.repo_root, rel_dir) + tracked_paths = [self.repo_root / path for path in tracked_files] + + for file_path in tracked_paths: + if not file_path.is_file(): + continue + + suffix = file_path.suffix.lower() + + if suffix in code_file_extensions: + try: + with open(file_path, 'r', encoding='utf-8') as f: + content = f.read() + + validator_func = code_file_extensions[suffix] + is_valid, error_msg = validator_func(content, str(file_path.relative_to(self.repo_root))) + + if not is_valid: + errors.append(error_msg) + + except Exception as e: + errors.append(f"Error reading {file_path.relative_to(self.repo_root)}: {e}") + + # Special case for Dockerfiles + elif file_path.name.lower().startswith('dockerfile'): + try: + with open(file_path, 'r', encoding='utf-8') as f: + content = f.read() + + is_valid, error_msg = self.code_validator.validate_dockerfile_syntax( + content, str(file_path.relative_to(self.repo_root)) + ) + + if not is_valid: + errors.append(error_msg) + + except Exception as e: + errors.append(f"Error reading {file_path.relative_to(self.repo_root)}: {e}") # Check for requirements files and validate they exist requirements_files = list(dir_path.glob('*requirements*.txt')) @@ -279,8 +286,8 @@ def validate_example_directory(self, dir_path: Path) -> Dict[str, any]: 'valid': len(errors) == 0, 'errors': errors, 'warnings': warnings, - 'files_checked': len(list(dir_path.rglob('*'))), - 'code_files': len([f for f in dir_path.rglob('*') if f.suffix.lower() in code_file_extensions]) + 'files_checked': len(tracked_paths), + 'code_files': len([p for p in tracked_paths if p.suffix.lower() in code_file_extensions]) } def validate_all_examples(self) -> Dict[str, Dict[str, any]]: @@ -289,14 +296,16 @@ def validate_all_examples(self) -> Dict[str, Dict[str, any]]: # Validate main examples if self.examples_dir.exists(): - for example_dir in self.examples_dir.iterdir(): + tracked_example_dirs = git_tracked_child_dirs(self.repo_root, "examples") + for example_dir in tracked_example_dirs: if example_dir.is_dir() and not example_dir.name.startswith('.'): results[f"examples/{example_dir.name}"] = self.validate_example_directory(example_dir) # Validate experimental examples experiments_examples_dir = self.experiments_dir / "examples" if experiments_examples_dir.exists(): - for example_dir in experiments_examples_dir.iterdir(): + tracked_experiment_dirs = git_tracked_child_dirs(self.repo_root, "experiments/examples") + for example_dir in tracked_experiment_dirs: if example_dir.is_dir() and not example_dir.name.startswith('.'): results[f"experiments/examples/{example_dir.name}"] = self.validate_example_directory(example_dir) @@ -414,4 +423,4 @@ def validate_all_code_blocks(self) -> List[Dict[str, any]]: 'code_preview': code[:100] + "..." if len(code) > 100 else code }) - return validation_results \ No newline at end of file + return validation_results diff --git a/tests/utils/git_utils.py b/tests/utils/git_utils.py new file mode 100644 index 0000000..78d8ba2 --- /dev/null +++ b/tests/utils/git_utils.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +import subprocess +from pathlib import Path + + +def git_ls_files(repo_root: Path, path: str | None = None) -> list[str]: + """ + Return git-tracked file paths (relative to repo_root). + + If `path` is provided, it is passed to `git ls-files` to scope results. + """ + repo_root = Path(repo_root) + cmd = ["git", "-C", str(repo_root), "ls-files"] + if path: + cmd.append(path) + + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + return [] + + return [line.strip() for line in result.stdout.splitlines() if line.strip()] + + +def git_tracked_child_dirs(repo_root: Path, base_dir: str) -> list[Path]: + """ + Return git-tracked immediate child directories under `base_dir`. + + Example: + base_dir="examples" yields: + [repo_root/examples/codified-rules, repo_root/examples/security-sandbox, ...] + """ + base_dir = base_dir.strip("/").replace("\\", "/") + prefix = f"{base_dir}/" if base_dir else "" + + tracked_files = git_ls_files(repo_root, base_dir if base_dir else None) + child_names: set[str] = set() + + for path in tracked_files: + if prefix and not path.startswith(prefix): + continue + remainder = path[len(prefix) :] if prefix else path + if "/" not in remainder: + continue + child_names.add(remainder.split("/", 1)[0]) + + repo_root = Path(repo_root) + return [repo_root / base_dir / name for name in sorted(child_names)] + diff --git a/tests/utils/markdown_link_validator.py b/tests/utils/markdown_link_validator.py new file mode 100644 index 0000000..862f996 --- /dev/null +++ b/tests/utils/markdown_link_validator.py @@ -0,0 +1,372 @@ +from __future__ import annotations + +import html +import re +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import Iterable +from urllib.parse import unquote, urlsplit + +from utils.git_utils import git_ls_files + + +@dataclass(frozen=True) +class MarkdownLinkError: + source_file: str + source_line: int + link: str + message: str + + +class MarkdownLinkValidator: + """ + Validate internal anchors and relative file links across git-tracked markdown files. + + Focus: deterministic checks with low flakiness (no network calls). + """ + + _LINK_PATTERN = re.compile(r"!?\[[^\]]*\]\(([^)]+)\)") + + def __init__(self, repo_root: Path): + self.repo_root = Path(repo_root) + self.tracked_files = set(git_ls_files(self.repo_root)) + self.tracked_dirs = self._build_tracked_dirs(self.tracked_files) + self._anchors_cache: dict[str, set[str]] = {} + + def validate_files(self, markdown_files: Iterable[Path]) -> list[MarkdownLinkError]: + errors: list[MarkdownLinkError] = [] + for path in markdown_files: + errors.extend(self.validate_file(path)) + return errors + + def validate_file(self, markdown_file: Path) -> list[MarkdownLinkError]: + rel_source = self._rel_path(markdown_file) + if rel_source is None: + return [] + + try: + content = markdown_file.read_text(encoding="utf-8") + except OSError as e: + return [ + MarkdownLinkError( + source_file=rel_source, + source_line=1, + link="", + message=f"Unable to read file: {e}", + ) + ] + + errors: list[MarkdownLinkError] = [] + for url, line_num in self._extract_markdown_links(content): + url = self._normalize_link_destination(url) + if not url or self._should_ignore_link(url): + continue + + errors.extend(self._validate_link(rel_source, markdown_file, url, line_num)) + + return errors + + def markdown_files_in_scope(self) -> list[Path]: + """ + Return git-tracked markdown files in scope: + - docs/ + - examples/ + - experiments/ + - selected top-level docs (excluding README.md) + """ + top_level = { + "pattern-spec.md", + "PATTERN_MIGRATION_GUIDE.md", + "CLAUDE.md", + "AGENTS.md", + } + in_scope_prefixes = ("docs/", "examples/", "experiments/") + + paths: list[Path] = [] + for rel in sorted(self.tracked_files): + if not rel.endswith(".md"): + continue + if rel == "README.md": + continue + if rel in top_level or rel.startswith(in_scope_prefixes): + paths.append(self.repo_root / rel) + return paths + + def _validate_link( + self, rel_source: str, source_file: Path, url: str, line_num: int + ) -> list[MarkdownLinkError]: + parsed = urlsplit(url) + + # External or unsupported schemes are intentionally ignored here. + if parsed.scheme or parsed.netloc: + return [] + + fragment = unquote(parsed.fragment or "").strip() + raw_path = unquote(parsed.path or "").strip() + + # Internal anchor within the same file + if not raw_path and fragment: + return self._validate_anchor( + rel_source=rel_source, + source_line=line_num, + link=url, + target_file=source_file, + fragment=fragment, + ) + + # Ignore empty or placeholder-only links (e.g., "(#)") + if not raw_path: + return [] + + resolved_target = self._resolve_link_path(source_file, raw_path) + if resolved_target is None: + return [ + MarkdownLinkError( + source_file=rel_source, + source_line=line_num, + link=url, + message=f"Link resolves outside repository: {raw_path}", + ) + ] + + rel_target = self._rel_path(resolved_target) + if rel_target is None or not self._tracked_path_exists(rel_target): + return [ + MarkdownLinkError( + source_file=rel_source, + source_line=line_num, + link=url, + message=f"Target not found in git-tracked paths: {raw_path}", + ) + ] + + # Directory links: map anchors to README.md when present. + target_for_anchor = resolved_target + if self._is_tracked_dir(rel_target) and rel_target not in self.tracked_files: + readme_rel = f"{rel_target.rstrip('/')}/README.md" + if readme_rel in self.tracked_files: + target_for_anchor = self.repo_root / readme_rel + + if fragment and target_for_anchor.suffix.lower() == ".md": + return self._validate_anchor( + rel_source=rel_source, + source_line=line_num, + link=url, + target_file=target_for_anchor, + fragment=fragment, + ) + + return [] + + def _validate_anchor( + self, + rel_source: str, + source_line: int, + link: str, + target_file: Path, + fragment: str, + ) -> list[MarkdownLinkError]: + anchors = self._anchors_for_file(target_file) + anchor = f"#{fragment}" + if anchor not in anchors: + target_rel = self._rel_path(target_file) or str(target_file) + return [ + MarkdownLinkError( + source_file=rel_source, + source_line=source_line, + link=link, + message=f'Anchor "{anchor}" not found in {target_rel}', + ) + ] + return [] + + def _anchors_for_file(self, markdown_file: Path) -> set[str]: + rel = self._rel_path(markdown_file) + if rel is None: + return set() + cached = self._anchors_cache.get(rel) + if cached is not None: + return cached + + try: + content = markdown_file.read_text(encoding="utf-8") + except OSError: + anchors: set[str] = set() + self._anchors_cache[rel] = anchors + return anchors + + anchors = self._extract_anchors(content) + self._anchors_cache[rel] = anchors + return anchors + + def _extract_markdown_links(self, markdown_text: str) -> list[tuple[str, int]]: + links: list[tuple[str, int]] = [] + in_fence = False + + for line_num, line in enumerate(markdown_text.splitlines(), 1): + stripped = line.lstrip() + if stripped.startswith("```") or stripped.startswith("~~~"): + in_fence = not in_fence + continue + if in_fence: + continue + + scan_line = self._strip_inline_code(line) + for match in self._LINK_PATTERN.finditer(scan_line): + dest = match.group(1).strip() + # Markdown allows optional titles: (url "title") + if dest.startswith("<") and ">" in dest: + dest = dest[1 : dest.find(">")].strip() + else: + dest = dest.split()[0] + + links.append((dest, line_num)) + + return links + + def _extract_anchors(self, markdown_text: str) -> set[str]: + anchors: set[str] = set() + in_fence = False + slug_counts: dict[str, int] = {} + lines = markdown_text.splitlines() + + def add_heading_anchor(heading_text: str) -> None: + base = self._github_heading_slug(heading_text) + if not base: + return + count = slug_counts.get(base, 0) + slug_counts[base] = count + 1 + slug = base if count == 0 else f"{base}-{count}" + anchors.add(f"#{slug}") + + i = 0 + while i < len(lines): + line = lines[i] + stripped = line.lstrip() + if stripped.startswith("```") or stripped.startswith("~~~"): + in_fence = not in_fence + i += 1 + continue + if in_fence: + i += 1 + continue + + normalized = self._strip_blockquote_prefix(line).strip() + + atx = re.match(r"^(#{1,6})\s+(.+?)\s*$", normalized) + if atx: + heading = atx.group(2) + heading = re.sub(r"\s+#+\s*$", "", heading).strip() + add_heading_anchor(heading) + i += 1 + continue + + # Setext-style headers + if i + 1 < len(lines): + underline = self._strip_blockquote_prefix(lines[i + 1]).strip() + if underline and re.fullmatch(r"=+", underline): + add_heading_anchor(normalized) + i += 2 + continue + if underline and re.fullmatch(r"-+", underline): + add_heading_anchor(normalized) + i += 2 + continue + + i += 1 + + return anchors + + def _github_heading_slug(self, heading_text: str) -> str: + text = heading_text.strip() + text = self._strip_markdown_formatting(text) + text = html.unescape(text) + text = text.strip().lower() + text = re.sub(r"\s+", "-", text) + text = re.sub(r"[^\w-]", "", text) + return text.strip("-") + + def _strip_markdown_formatting(self, text: str) -> str: + # Replace markdown links with their text: [text](url) -> text + text = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", text) + text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) + # Remove inline code ticks but keep content + text = re.sub(r"`([^`]*)`", r"\1", text) + # Remove emphasis markers + text = text.replace("**", "").replace("__", "") + text = text.replace("*", "").replace("_", "") + # Strip HTML tags + text = re.sub(r"<[^>]+>", "", text) + return text + + def _strip_inline_code(self, line: str) -> str: + return re.sub(r"`[^`]*`", "", line) + + def _strip_blockquote_prefix(self, line: str) -> str: + out = line.lstrip() + while out.startswith(">"): + out = out[1:].lstrip() + return out + + def _normalize_link_destination(self, dest: str) -> str: + dest = dest.strip() + if dest.startswith("<") and dest.endswith(">"): + dest = dest[1:-1].strip() + return dest + + def _should_ignore_link(self, url: str) -> bool: + lowered = url.lower() + if url == "#": + return True + if lowered.startswith(("mailto:", "tel:", "javascript:")): + return True + if "{{" in url or "}}" in url: + return True + if "<" in url or ">" in url: + return True + if "example.com" in lowered: + return True + if "/path/to/" in lowered or lowered.startswith("path/to/"): + return True + return False + + def _resolve_link_path(self, source_file: Path, link_path: str) -> Path | None: + link_path = link_path.strip() + try: + posix = PurePosixPath(link_path) + except Exception: + return None + + if posix.is_absolute(): + candidate = (self.repo_root / str(posix).lstrip("/")).resolve(strict=False) + else: + candidate = (source_file.parent / str(posix)).resolve(strict=False) + + if not candidate.is_relative_to(self.repo_root): + return None + return candidate + + def _tracked_path_exists(self, rel_path: str) -> bool: + if rel_path in self.tracked_files: + return True + return self._is_tracked_dir(rel_path) + + def _is_tracked_dir(self, rel_path: str) -> bool: + rel_path = rel_path.strip("/").replace("\\", "/") + return rel_path in self.tracked_dirs + + def _rel_path(self, path: Path) -> str | None: + try: + return path.resolve(strict=False).relative_to(self.repo_root).as_posix() + except Exception: + return None + + def _build_tracked_dirs(self, tracked_files: Iterable[str]) -> set[str]: + dirs: set[str] = set() + for rel in tracked_files: + p = PurePosixPath(rel) + for parent in p.parents: + if str(parent) == ".": + break + dirs.add(str(parent)) + return dirs
  • Developer Lifecycle - AI-integrated workflows