From c374cc28a1465c26eea191b31fde5071513478d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 19 May 2026 00:27:13 +0000 Subject: [PATCH] docs(claude-md): dogfood /sync-claude-md on root CLAUDE.md Splits the 518-line root CLAUDE.md into a 70-line root plus four chained sub-files (skill/, command/, agent/, docs/), all under the 150-line cap, and prunes stale references uncovered by the audit. - CLAUDE.md (518 -> 70): project overview, navigation with @-imports, behavioural guidelines summary, naming reference, license link - skill/CLAUDE.md (85): component flow, Python module architecture, modifying modules, adding templates, tech-stack detection, quality scoring, karpathy skill - command/CLAUDE.md (38): slash command development, top-level .md install layout, skill <-> command integration - agent/CLAUDE.md (70): guardian frontmatter, hook responsibilities, skill <-> agent integration, git triggers - docs/CLAUDE.md (109): install verification, smoke test, manual e2e tests, common operations, release process Stale content removed: - 'Dual Directory Structure' section (claude-md-enhancer/ legacy dir does not exist on disk) - '20-300 lines' / '300-line cap' references rewritten to 150 - '~/.claude/commands/enhance-claude-md/' bundle paths rewritten to top-level '.md' files (matching the new installer layout) - 'Three integrated components' updated to five - 'Current Version: 2.0.0' updated to 2.1.0 - '6 examples' in sample_input.json claim corrected (file has 1 scenario) Each sub-file opens with a markdown back-link and @../CLAUDE.md import; root contains @-imports for all four sub-files. Validator passes (status pass) for every file. --- CLAUDE.md | 540 ++++------------------------------------------ agent/CLAUDE.md | 70 ++++++ command/CLAUDE.md | 38 ++++ docs/CLAUDE.md | 109 ++++++++++ skill/CLAUDE.md | 85 ++++++++ 5 files changed, 348 insertions(+), 494 deletions(-) create mode 100644 agent/CLAUDE.md create mode 100644 command/CLAUDE.md create mode 100644 docs/CLAUDE.md create mode 100644 skill/CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md index 4ab7ddc..aef48cd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,518 +1,70 @@ # CLAUDE.md -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - ---- +Top-level guidance for Claude Code when working on this repository. ## Project Overview -**ClaudeForge** is a Claude Code plugin (manifest at `.claude-plugin/plugin.json`) and standalone toolkit for the CLAUDE.md lifecycle: initialise, enhance, sync, and modularise CLAUDE.md files with a hard 150-line cap, automatic chaining via `@path` imports, and Karpathy behavioural guardrails. Works in any Claude Code or Claude.cowork project. The repository consists of five integrated components: +**ClaudeForge** is a Claude Code plugin (manifest at `.claude-plugin/plugin.json`) and standalone toolkit for the CLAUDE.md lifecycle: initialise, enhance, sync, and modularise files with a hard **150-line cap**, automatic chaining via `@path` imports, and Karpathy behavioural guardrails. Works in any Claude Code or Claude.cowork project. -1. **Skill** (`claudeforge-skill`) - Core Python modules for analysis, generation, and validation. Enforces a 150-line hard cap per CLAUDE.md. -2. **Slash Command** (`/enhance-claude-md`) - Interactive multi-phase discovery workflow. Delegates deep codebase scans to the Explore subagent to avoid context bloat. -3. **Slash Command** (`/sync-claude-md`) - Walks every CLAUDE.md in the project, prunes stale references, enforces the 150-line cap, and repairs the root ↔ subdirectory chain (markdown links + `@path` imports). -4. **Guardian Agent** (`claude-md-guardian`) - Background maintenance agent -5. **Karpathy Guidelines Skill** (`karpathy-guidelines`) - Behavioral guardrails embedded into every generated CLAUDE.md and installed as a standalone skill, adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository +Five components ship in this repo: ---- +1. **Skill** (`claudeforge-skill`, in `skill/`) — Python modules for analysis, generation, validation. Enforces the 150-line cap. +2. **Slash command** (`/enhance-claude-md`, in `command/`) — interactive init/enhance workflow. Delegates deep codebase scans to the Explore subagent. +3. **Slash command** (`/sync-claude-md`, in `command/`) — walks every CLAUDE.md, prunes stale references, enforces the 150-line cap, repairs the root ↔ sub chain. +4. **Guardian agent** (`claude-md-guardian`, in `agent/`) — background sync triggered by `SessionStart` / `PreToolUse` / `PostToolUse` hooks. +5. **Karpathy guidelines skill** (`karpathy-guidelines`, in `skill/karpathy-guidelines/`) — behavioural guardrails embedded into every generated CLAUDE.md. Adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repo. -## What's New in v2.0.0 +Current version: **2.1.0** — see `CHANGELOG.md`. v1 → v2 upgrade: `docs/MIGRATION_V2.md`. -**Claude Code v2.1.4+ Support:** -- **Lifecycle Hooks**: Guardian agent uses SessionStart, PreToolUse, PostToolUse hooks -- **Modern Permissions**: Updated to `permissions:` array syntax -- **Hot-Reload**: Skills auto-reload when modified (no restart needed) -- **Fork-Safe Mode**: Guardian runs independently with `fork_safe: true` -- **Auto-Migration**: Seamless upgrade from v1.x with automatic backups +## Quick Navigation -**Migration:** See `docs/MIGRATION_V2.md` for upgrading from v1.0.0. +- [Skill development](skill/CLAUDE.md) +- [Slash command development](command/CLAUDE.md) +- [Guardian agent development](agent/CLAUDE.md) +- [Installation, testing & release](docs/CLAUDE.md) ---- +Chained context (Claude Code auto-imports these): -## Architecture +@skill/CLAUDE.md +@command/CLAUDE.md +@agent/CLAUDE.md +@docs/CLAUDE.md -### Component Interaction Flow +## Behavioral Guidelines -``` -User Project - ↓ -/enhance-claude-md (Slash Command) - ↓ -[Phase 1: Discovery] → [Phase 2: Analysis] → [Phase 3: Task] - ↓ -claude-md-guardian (Agent) OR Direct Skill Invocation - ↓ -claudeforge-skill (Python Modules) - ↓ -workflow.py → analyzer.py → validator.py → template_selector.py → generator.py - ↓ -CLAUDE.md Created/Updated with 100% Native Format -``` +Behavioural guardrails applied to every coding, review, and refactoring task in this repo. Full skill: `~/.claude/skills/karpathy-guidelines/SKILL.md`. -### Python Module Architecture +1. **Think before coding.** State load-bearing assumptions; if a request has multiple reasonable interpretations, surface them instead of picking silently. Stop and ask when something is genuinely unclear. +2. **Simplicity first.** Write the minimum code that solves the stated problem. No speculative abstractions, no unrequested configuration, no error handling for conditions that cannot occur. +3. **Surgical changes.** Touch only what the task requires. Match surrounding style. Every changed line should trace directly to the user's request. +4. **Goal-driven execution.** Convert vague requests into verifiable success criteria before coding (failing test first), and state a step-by-step plan with per-step verification for multi-step work. -The skill consists of 5 core modules (~2,190 lines): - -**workflow.py (432 lines)** - `InitializationWorkflow` class -- Orchestrates interactive initialization for new projects -- Methods: `check_claude_md_exists()`, `generate_exploration_prompt()`, `analyze_discoveries()` -- Detects: project type, tech stack, team size, development phase, workflows -- Returns: Project context dictionary for template selection - -**analyzer.py (382 lines)** - `CLAUDEMDAnalyzer` class -- Analyzes existing CLAUDE.md files -- Methods: `analyze_file()`, `detect_sections()`, `calculate_quality_score()`, `generate_recommendations()` -- Quality scoring: 0-100 based on length (25pts), completeness (25pts), formatting (20pts), specificity (15pts), modularity (15pts) -- Returns: Analysis report with quality score and actionable recommendations - -**validator.py (429 lines)** - `BestPracticesValidator` class -- Validates against Anthropic guidelines -- Methods: `validate_length()`, `validate_structure()`, `validate_formatting()`, `validate_completeness()`, `validate_all()` -- Checks: file length (20-300 lines), required sections, markdown formatting, anti-patterns -- Returns: Validation report with pass/fail status and detailed issues - -**template_selector.py (467 lines)** - `TemplateSelector` class -- Selects appropriate template based on context -- Methods: `select_template()`, `customize_template()`, `recommend_modular_structure()` -- Logic: Maps project type + team size → template complexity -- Returns: Template configuration with target line count and modular recommendation - -**generator.py (480 lines)** - `ContentGenerator` class -- Generates new or enhanced CLAUDE.md content -- Methods: `generate_root_file()`, `generate_context_file()`, `generate_section()`, `merge_with_existing()` -- Supports: Root files, context-specific files (backend/, frontend/, database/), individual sections -- Returns: Complete CLAUDE.md content with 100% native format compliance - -### Critical Validation Rule - -All generated CLAUDE.md files MUST include: -- Project structure (ASCII tree diagram) -- File structure explanations -- Setup & installation instructions -- Architecture section (for complex projects) -- Validation against `/update-claude-md` slash command format -- Cross-check against reference examples in `skill/examples/` - ---- - -## Installation & Testing - -### Test Installation Scripts - -```bash -# macOS/Linux -./install.sh -# Choose option 1 (user-level) or 2 (project-level) -# Verify installation at ~/.claude/ or ./.claude/ - -# Windows -.\install.ps1 -# Same options as above - -# Verify components installed: -ls -la ~/.claude/skills/claudeforge-skill/ -ls -la ~/.claude/commands/enhance-claude-md/ -ls -la ~/.claude/agents/claude-md-guardian.md -``` - -### Directory Structure After Installation - -``` -~/.claude/ # User-level installation -├── skills/ -│ └── claudeforge-skill/ # Copied from skill/ -│ ├── SKILL.md -│ ├── analyzer.py -│ ├── validator.py -│ ├── generator.py -│ ├── template_selector.py -│ ├── workflow.py -│ └── examples/ # 7 reference templates -├── commands/ -│ └── enhance-claude-md/ # Copied from command/ -│ └── enhance-claude-md.md -└── agents/ - └── claude-md-guardian.md # Copied from agent/ -``` - ---- - -## Development Workflow - -### Modifying Python Modules - -When updating skill modules (analyzer.py, generator.py, etc.): - -1. Edit files in `skill/` directory -2. Test changes by reinstalling: `./install.sh` (choose option 2 for project-level testing) -3. Test skill invocation in Claude Code: `/enhance-claude-md` -4. Validate output against reference examples in `skill/examples/` -5. Update `CHANGELOG.md` with changes - -### Modifying Slash Command - -When updating `/enhance-claude-md` command: - -1. Edit `command/enhance-claude-md.md` -2. Key sections to modify: - - **Phase 1 (Discovery)**: Bash commands that check project state - - **Phase 2 (Analysis)**: Logic that determines initialize vs. enhance - - **Phase 3 (Task)**: Skill/agent invocation logic -3. Test by reinstalling command: `cp command/enhance-claude-md.md ~/.claude/commands/enhance-claude-md/` -4. Restart Claude Code and test: `/enhance-claude-md` - -### Modifying Guardian Agent - -When updating `claude-md-guardian` agent: - -1. Edit `agent/claude-md-guardian.md` -2. Key YAML frontmatter fields: - - `permissions`: [Bash, Read, Write, Edit, Grep, Glob, Skill] - - `model`: Set to `haiku` for token efficiency - - `color`: Visual indicator (purple) - - `fork_safe`: Set to `true` for independent execution - - `hooks`: Array of lifecycle hooks (SessionStart, PreToolUse, PostToolUse) -3. Agent workflow phases: - - Phase 1: Assessment (check git changes) - - Phase 2: Analysis (determine scope) - - Phase 3: Update (invoke skill for targeted updates) -4. Test: `cp agent/claude-md-guardian.md ~/.claude/agents/` - -**Example Agent Definition with v2.0.0 Syntax:** -```yaml ---- -name: claude-md-guardian -permissions: [Bash, Read, Write, Edit, Grep, Glob, Skill] -model: haiku -color: purple -fork_safe: true -hooks: - - SessionStart - - PreToolUse - - PostToolUse ---- -``` - -### Adding New Templates - -To add a new reference template (e.g., Rust, mobile): - -1. Create new template file in `skill/examples/` -2. Follow native format structure: - - Project structure diagram (ASCII tree) - - Setup & installation - - Architecture section - - Tech-specific guidelines -3. Update `skill/examples/README.md` with new template description -4. Update `template_selector.py` logic to detect when to use new template -5. Add test case in `skill/sample_input.json` - ---- - -## Testing & Validation - -### Manual Testing Checklist - -**Test New Project Initialization:** -```bash -# 1. Create test project -mkdir test-project && cd test-project -git init -npm init -y # or create package.json - -# 2. Run slash command -/enhance-claude-md - -# 3. Verify Claude: -# - Explores repository -# - Detects TypeScript/Node project -# - Shows discoveries -# - Asks for confirmation -# - Creates CLAUDE.md with native format -``` - -**Test Existing Project Enhancement:** -```bash -# 1. Create basic CLAUDE.md -echo "# CLAUDE.md\n\n## Tech Stack\n- TypeScript" > CLAUDE.md - -# 2. Run slash command -/enhance-claude-md - -# 3. Verify Claude: -# - Analyzes existing file -# - Calculates quality score (0-100) -# - Identifies missing sections (Project Structure, Setup, etc.) -# - Asks to enhance -# - Adds missing native format sections -``` - -**Test Guardian Agent:** -```bash -# 1. Make significant changes -npm install react # Add new dependency -mkdir src/components # New directory - -# 2. Start new Claude Code session (triggers SessionStart) - -# 3. Verify agent: -# - Detects changes via git diff -# - Updates CLAUDE.md automatically -# - Reports: "Tech Stack: Added react", "Project Structure: Updated diagram" -``` - -### Quality Validation - -All generated CLAUDE.md files should pass these checks: - -```python -# Use validator.py -validator = BestPracticesValidator(content) -results = validator.validate_all() - -# Expected passes: -# - File length: 20-300 lines (or modular if >300) -# - Structure: Required sections present -# - Formatting: Valid markdown, proper heading hierarchy -# - Completeness: Code examples, tech stack, workflows -# - Anti-patterns: No hardcoded secrets, no TODOs/placeholders -``` - ---- - -## File Organization - -### Repository Structure +## Repository Layout (top level) ``` ClaudeForge/ -├── skill/ # Python modules (core capability) -│ ├── analyzer.py # File analysis -│ ├── validator.py # Best practices validation -│ ├── generator.py # Content generation -│ ├── template_selector.py # Template selection logic -│ ├── workflow.py # Interactive initialization -│ ├── SKILL.md # Skill definition (YAML frontmatter) -│ ├── sample_input.json # Test scenarios (6 examples) -│ ├── expected_output.json # Expected outputs -│ └── examples/ # 7 reference templates -│ -├── command/ # Slash command definition -│ ├── enhance-claude-md.md # Multi-phase workflow -│ └── README.md -│ -├── agent/ # Guardian agent definition -│ ├── claude-md-guardian.md # Background maintenance agent -│ └── README.md -│ -├── docs/ # Documentation -│ ├── INSTALLATION.md -│ ├── QUICK_START.md -│ ├── ARCHITECTURE.md -│ ├── TROUBLESHOOTING.md -│ └── CONTRIBUTING.md -│ -├── examples/ # Usage examples (markdown) -├── hooks/ # Quality hooks (pre-commit) -├── .github/ # GitHub templates & workflows -│ ├── workflows/validate.yml # CI/CD validation -│ ├── ISSUE_TEMPLATE/ -│ ├── PULL_REQUEST_TEMPLATE.md -│ └── CODE_OF_CONDUCT.md -│ -├── install.sh # macOS/Linux installer -├── install.ps1 # Windows installer -├── README.md # Project overview -├── CHANGELOG.md # Version history -├── LICENSE # MIT License -└── CLAUDE.md # This file +├── .claude-plugin/plugin.json # plugin manifest +├── skill/ # core Python modules + karpathy-guidelines/ +├── command/ # /enhance-claude-md, /sync-claude-md +├── agent/ # claude-md-guardian +├── docs/ # operational docs (installation, testing, release) +├── examples/ # usage examples +├── hooks/ # quality hooks (pre-commit) +├── .github/ # CI workflows, issue/PR templates +├── install.sh / install.ps1 # installers +├── README.md / CHANGELOG.md / LICENSE +└── CLAUDE.md # this file ``` -### Important: Dual Directory Structure +## Naming Reference -Note the duplication: `claude-md-enhancer/` (legacy) and `skill/` (current). When making changes: -- **Always edit `skill/`** - This is the active version used by installers -- `claude-md-enhancer/` is kept for reference but not actively maintained +- **Project / display name:** ClaudeForge +- **GitHub:** https://github.com/alirezarezvani/ClaudeForge +- **Skill name (frontmatter):** `claude-md-enhancer` (kept for backwards compatibility); installed as `claudeforge-skill/` +- **Slash commands:** `/enhance-claude-md`, `/sync-claude-md` (names fixed by file name) +- **Agent:** `claude-md-guardian` +- **Standalone skill:** `karpathy-guidelines` ---- +## License -## Common Operations - -### Update Reference Templates - -```bash -# Edit template -vim skill/examples/python-api-CLAUDE.md - -# Test template selection -# 1. Create test project matching template criteria -mkdir test-python-api && cd test-python-api -echo "fastapi" > requirements.txt - -# 2. Run slash command and verify template is used -/enhance-claude-md -``` - -### Update Quality Scoring Logic - -```bash -# Edit analyzer.py -vim skill/analyzer.py - -# Update calculate_quality_score() method -# Current scoring breakdown: -# - length_appropriateness: 25 points (20-300 lines ideal) -# - section_completeness: 25 points (required sections present) -# - formatting_quality: 20 points (markdown, headings, code blocks) -# - content_specificity: 15 points (project-specific, not generic) -# - modular_organization: 15 points (context files if needed) - -# Test scoring -python3 -c " -from skill.analyzer import CLAUDEMDAnalyzer -with open('test-CLAUDE.md') as f: - analyzer = CLAUDEMDAnalyzer(f.read()) - report = analyzer.analyze_file() - print(f'Quality Score: {report[\"quality_score\"]}/100') -" -``` - -### Update Installer Scripts - -```bash -# Edit installer -vim install.sh # or install.ps1 - -# Key sections: -# - Installation paths (user-level vs project-level) -# - Component copying (skill, command, agent) -# - Backup logic (existing installations) -# - Quality hooks installation (optional) - -# Test installer -./install.sh -# Choose test option and verify all components copied correctly -``` - ---- - -## Integration Points - -### Skill ↔ Slash Command - -The slash command invokes the skill via: -```markdown -# In command/enhance-claude-md.md, Phase 3: - -I can invoke the `claude-md-enhancer` skill directly to handle the appropriate workflow based on what I discovered above. -``` - -Claude Code recognizes the skill name `claude-md-enhancer` and calls Python modules. - -### Skill ↔ Guardian Agent - -The agent uses the skill as its core capability: -```yaml -# In agent/claude-md-guardian.md: -permissions: [Bash, Read, Write, Edit, Grep, Glob, Skill] -hooks: - - SessionStart # Detects project changes on session start - - PreToolUse # Validates before tool execution - - PostToolUse # Validates after CLAUDE.md updates -``` - -Agent invokes skill with: `Skill: claude-md-enhancer` in agent workflow. - -**Example Hook Usage:** -```markdown -# When SessionStart hook triggers: -1. Check git diff for changes -2. If significant changes detected → invoke skill -3. Update CLAUDE.md automatically - -# When PostToolUse hook triggers after Edit/Write to CLAUDE.md: -1. Validate updated content with validator.py -2. Report quality score -3. Suggest improvements if needed -``` - -### Agent ↔ Git - -Agent detects changes via git commands: -```bash -git diff --name-status HEAD~10 -git log --since="1 week ago" --oneline --no-merges -git diff HEAD~10 -- package.json requirements.txt -``` - -Triggers update when: -- 5+ files modified -- New dependencies added -- New directories created -- Manual invocation after milestone - ---- - -## Tech Stack Detection Logic - -The workflow and template selector detect tech stacks via: - -**Frontend Detection:** -- React: `package.json` contains `"react"` -- Vue: `package.json` contains `"vue"` -- Angular: `angular.json` exists -- TypeScript: `tsconfig.json` exists - -**Backend Detection:** -- Node.js: `package.json` exists -- Python: `requirements.txt`, `pyproject.toml`, `setup.py` -- Go: `go.mod` exists -- Java: `pom.xml`, `build.gradle` -- Rust: `Cargo.toml` exists - -**Database Detection:** -- PostgreSQL: `package.json` or `requirements.txt` contains "pg" or "psycopg2" -- MongoDB: Contains "mongoose" or "pymongo" -- Redis: Contains "redis" or "ioredis" - -Update detection logic in: `skill/workflow.py` → `_detect_tech_stack()` method - ---- - -## Repository Naming - -**Project Name:** ClaudeForge -**GitHub URL:** https://github.com/alirezarezvani/ClaudeForge -**Skill Name:** `claudeforge-skill` (installed as directory name) -**Slash Command:** `/enhance-claude-md` (fixed name, cannot be changed by user) -**Agent Name:** `claude-md-guardian` (file name) - -When updating references: -- `skill/SKILL.md` → YAML frontmatter `name: claude-md-enhancer` (kept for compatibility) -- `README.md` → Use "ClaudeForge" as display name -- `install.sh` → Copies to `claudeforge-skill/` directory -- Internal documentation → Use "ClaudeForge" consistently - ---- - -## Version Management - -**Current Version:** 2.0.0 (see CHANGELOG.md) -**Versioning:** Semantic Versioning (MAJOR.MINOR.PATCH) - -When releasing new version: -1. Update `CHANGELOG.md` with changes under new version header -2. Update version in `README.md` badge -3. Update version in `skill/SKILL.md` bottom section -4. Create git tag: `git tag -a v2.1.0 -m "Release v2.1.0"` -5. Push tag: `git push origin v2.1.0` -6. Create GitHub release with CHANGELOG excerpt - ---- - -## License & Copyright - -**License:** MIT License -**Copyright:** © 2025 Alireza Rezvani - -All files should include appropriate copyright headers. The LICENSE file is authoritative. +MIT — © 2025 Alireza Rezvani. See `LICENSE`. diff --git a/agent/CLAUDE.md b/agent/CLAUDE.md new file mode 100644 index 0000000..18a3a0c --- /dev/null +++ b/agent/CLAUDE.md @@ -0,0 +1,70 @@ +> Parent context: see the root [CLAUDE.md](../CLAUDE.md) for project-wide guidelines and behavioural rules. +> Chained import: `@../CLAUDE.md` + +# Guardian Agent Development + +Guidelines for the `claude-md-guardian` background-maintenance agent. + +## File + +`agent/claude-md-guardian.md` — installs to `~/.claude/agents/claude-md-guardian.md`. + +## Modifying the Agent + +1. Edit `agent/claude-md-guardian.md`. +2. YAML frontmatter fields to preserve: + - `permissions: [Bash, Read, Write, Edit, Grep, Glob, Skill]` + - `model: haiku` — token efficiency for routine sync runs. + - `color: purple` — visual indicator in Claude Code UI. + - `fork_safe: true` — agent runs independently. + - `hooks: [SessionStart, PreToolUse, PostToolUse]`. +3. Workflow phases inside the agent: + - **Assessment** — read `git diff` / `git status` / changed-file counts. + - **Analysis** — decide if changes are significant enough to update CLAUDE.md. + - **Update** — invoke the skill for targeted section updates rather than full regeneration (~70–80% token saving vs. rewrite). +4. Re-install for testing: `cp agent/claude-md-guardian.md ~/.claude/agents/`. + +## v2.0.0+ Frontmatter Reference + +```yaml +--- +name: claude-md-guardian +permissions: [Bash, Read, Write, Edit, Grep, Glob, Skill] +model: haiku +color: purple +fork_safe: true +hooks: + - SessionStart + - PreToolUse + - PostToolUse +--- +``` + +## Skill ↔ Agent Integration + +The agent uses `claude-md-enhancer` (the skill's frontmatter name; installed as `claudeforge-skill/`) as its core capability. Invoke it with `Skill: claude-md-enhancer` inside the agent workflow. + +Hook responsibilities: + +- **SessionStart** — check `git diff`; if significant change is detected, invoke the skill for an incremental update. +- **PreToolUse** — validate before a CLAUDE.md edit lands. +- **PostToolUse** — after Edit/Write to any CLAUDE.md, run `BestPracticesValidator`, report the quality score, suggest improvements. Refuse to leave the file over 150 lines. + +## Agent ↔ Git + +The agent watches for change signals via: + +```bash +git diff --name-status HEAD~10 +git log --since="1 week ago" --oneline --no-merges +git diff HEAD~10 -- package.json requirements.txt pyproject.toml go.mod Cargo.toml +``` + +Triggers an update when any of these hold: + +- 5+ files modified since the last sync. +- New dependencies added to a manifest file. +- New top-level directories created (potential new sub-CLAUDE.md candidates). +- Manual invocation after a milestone or release. + +When the agent runs sync, it follows `command/sync-claude-md.md`: never commit, leave the diff for the user to review. diff --git a/command/CLAUDE.md b/command/CLAUDE.md new file mode 100644 index 0000000..550dff9 --- /dev/null +++ b/command/CLAUDE.md @@ -0,0 +1,38 @@ +> Parent context: see the root [CLAUDE.md](../CLAUDE.md) for project-wide guidelines and behavioural rules. +> Chained import: `@../CLAUDE.md` + +# Slash Command Development + +Guidelines for the `/enhance-claude-md` and `/sync-claude-md` slash commands. + +## Files + +- `command/enhance-claude-md.md` — interactive initialise / enhance workflow. +- `command/sync-claude-md.md` — walks every CLAUDE.md, prunes stale references, enforces the 150-line cap, repairs the root ↔ sub chain. + +Both install as top-level `~/.claude/commands/.md` so they register as `/enhance-claude-md` and `/sync-claude-md`. There is no `enhance-claude-md/` bundle directory anymore — legacy bundles are backed up automatically on upgrade. + +## Modifying `/enhance-claude-md` + +1. Edit `command/enhance-claude-md.md`. +2. Key phases: + - **Phase 1 (Discovery)** — bash inventory + Explore-subagent delegation for deep codebase walks. Keep the calling session's context lean. + - **Phase 2 (Analysis)** — branches initialise (no CLAUDE.md) vs. enhance (CLAUDE.md exists). + - **Phase 3 (Task)** — invokes the `claude-md-enhancer` skill or `claude-md-guardian` agent. +3. Always-on requirement: every generated/enhanced CLAUDE.md must include `## Behavioral Guidelines`. The skill inserts it automatically — do not strip it. +4. Re-install for testing: `./install.sh` (project-level) or copy the file manually to `~/.claude/commands/enhance-claude-md.md`. +5. Restart Claude Code (commands hot-reload, but restart guarantees a clean state) and test. + +## Modifying `/sync-claude-md` + +1. Edit `command/sync-claude-md.md`. +2. Phases: inventory → per-file audit → enforce 150-line cap (split into sub-files via `generator.generate_context_file()`) → re-chain root ↔ subs → cleanup report. +3. Sync should never commit on its own; leave the diff staged-but-uncommitted for the user. + +## Skill ↔ Slash Command Integration + +`command/enhance-claude-md.md` Phase 3 invokes the skill by name: + +> I can invoke the `claude-md-enhancer` skill directly to handle the appropriate workflow based on what I discovered above. + +Claude Code resolves `claude-md-enhancer` from the YAML frontmatter `name:` field in `skill/SKILL.md` (kept for backwards compatibility — the installed directory is `claudeforge-skill/`). diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md new file mode 100644 index 0000000..8e252e9 --- /dev/null +++ b/docs/CLAUDE.md @@ -0,0 +1,109 @@ +> Parent context: see the root [CLAUDE.md](../CLAUDE.md) for project-wide guidelines and behavioural rules. +> Chained import: `@../CLAUDE.md` + +# Installation, Testing & Release + +Operational guidance for installers, smoke tests, and release management. + +## Test Installation Scripts + +```bash +# macOS/Linux +./install.sh +# Choose option 1 (user-level) or 2 (project-level) + +# Windows +.\install.ps1 +# Same options as above + +# Verify after install: +ls -la ~/.claude/skills/claudeforge-skill/ +ls -la ~/.claude/skills/karpathy-guidelines/ +ls -la ~/.claude/commands/enhance-claude-md.md +ls -la ~/.claude/commands/sync-claude-md.md +ls -la ~/.claude/agents/claude-md-guardian.md +``` + +## Directory Layout After Install + +``` +~/.claude/ # user-level (project-level mirrors under ./.claude) +├── skills/ +│ ├── claudeforge-skill/ # from skill/ +│ │ ├── SKILL.md +│ │ ├── analyzer.py +│ │ ├── validator.py +│ │ ├── generator.py +│ │ ├── template_selector.py +│ │ ├── workflow.py +│ │ └── examples/ +│ └── karpathy-guidelines/ # from skill/karpathy-guidelines/ +│ └── SKILL.md +├── commands/ +│ ├── enhance-claude-md.md +│ └── sync-claude-md.md +└── agents/ + └── claude-md-guardian.md +``` + +## Smoke Test (run from repo root) + +```bash +python3 - <<'PY' +import sys; sys.path.insert(0, 'skill') +from validator import BestPracticesValidator +from template_selector import TemplateSelector +from generator import ContentGenerator + +assert BestPracticesValidator.MAX_RECOMMENDED_LINES == 150 +for cfg in TemplateSelector.TEAM_SIZE_TEMPLATES.values(): + assert cfg['target_lines'] <= 150 + +ctx = {'type':'fullstack','tech_stack':['typescript','python'], + 'team_size':'medium','phase':'production','workflows':['cicd']} +out = ContentGenerator(ctx).generate_root_file() +assert len(out.splitlines()) <= 150 +assert '## Behavioral Guidelines' in out +print('smoke ok') +PY +``` + +Run after any change to `skill/`, `command/`, or `agent/`. + +## Manual End-to-End Tests + +**Fresh project init:** +1. `mkdir test-project && cd test-project && git init && npm init -y` +2. Run `/enhance-claude-md`. +3. Confirm generated CLAUDE.md ≤ 150 lines, contains `## Behavioral Guidelines`, has tech detection right. + +**Existing project enhance:** +1. Seed `CLAUDE.md` with one short section. +2. Run `/enhance-claude-md`; confirm quality score reported, missing sections proposed, `## Behavioral Guidelines` appended if absent. + +**Guardian agent sync:** +1. Add a new dependency and create a new directory. +2. Open a new Claude Code session — `SessionStart` fires. +3. Confirm the agent updates Tech Stack / Project Structure and quality re-validates. + +**Sync command:** +1. In a repo with stale CLAUDE.md references, run `/sync-claude-md`. +2. Confirm stale lines flagged, 150-cap enforced via split, root ↔ sub chain repaired, diff left staged for the user. + +## Common Operations + +**Update a reference template:** edit `skill/examples/-CLAUDE.md`, then add a matching scenario to `skill/sample_input.json`. + +**Update quality scoring:** edit `skill/analyzer.py` → `calculate_quality_score()`. Re-run the smoke test. + +**Update installer:** edit `install.sh` / `install.ps1` (paths, copy logic, backup logic, hooks). Test both user-level and project-level on a throwaway directory. + +## Release Process + +1. Update `CHANGELOG.md` under a new version header. +2. Bump the version in `README.md`, `skill/SKILL.md`, and `.claude-plugin/plugin.json`. +3. `git tag -a vX.Y.Z -m "Release vX.Y.Z"`. +4. `git push origin vX.Y.Z`. +5. Create the GitHub release with a CHANGELOG excerpt. + +Versioning is semver. See `docs/MIGRATION_V2.md` for the v1 → v2 upgrade path. diff --git a/skill/CLAUDE.md b/skill/CLAUDE.md new file mode 100644 index 0000000..fecb17a --- /dev/null +++ b/skill/CLAUDE.md @@ -0,0 +1,85 @@ +> Parent context: see the root [CLAUDE.md](../CLAUDE.md) for project-wide guidelines and behavioural rules. +> Chained import: `@../CLAUDE.md` + +# Skill Development + +Guidelines for the `claudeforge-skill` Python modules and the `karpathy-guidelines` skill. + +## Component Interaction Flow + +``` +User Project + ↓ +/enhance-claude-md (Slash Command) → Explore subagent (deep scan) + ↓ +[Discovery] → [Analysis] → [Task] + ↓ +claude-md-guardian (Agent) OR Direct Skill Invocation + ↓ +claudeforge-skill (Python Modules) + ↓ +workflow.py → analyzer.py → validator.py → template_selector.py → generator.py + ↓ +CLAUDE.md ≤ 150 lines, chained via `@path` imports +``` + +## Python Module Architecture + +Five modules live under `skill/`: + +- **`workflow.py`** — `InitializationWorkflow`: orchestrates interactive setup, detects project type / tech stack / team size / phase / workflows, returns a context dict. +- **`analyzer.py`** — `CLAUDEMDAnalyzer`: analyses existing files; quality scoring (0–100) across length, completeness, formatting, specificity, modularity. +- **`validator.py`** — `BestPracticesValidator`: checks file length (hard cap 150, warning at 120), required sections, formatting, anti-patterns. +- **`template_selector.py`** — `TemplateSelector`: maps project type + team size to a template; all team-size targets are ≤ 150 lines. +- **`generator.py`** — `ContentGenerator`: writes root + context files, emits `@path` chain imports, prepends sub-file back-links, idempotent `merge_with_existing`. + +## Required Output Sections + +Every generated CLAUDE.md must contain: + +- Project structure (ASCII tree, for projects that need it) +- Setup & installation +- Architecture (for non-trivial projects) +- `## Behavioral Guidelines` (Karpathy summary — inserted automatically) +- Cross-check against reference examples in `skill/examples/` + +## Modifying Python Modules + +1. Edit files in `skill/`. +2. Run the smoke test (see `docs/CLAUDE.md` → Testing & Validation). +3. Re-install for live testing: `./install.sh` (project-level scope). +4. Test slash command: `/enhance-claude-md`. +5. Validate output against `skill/examples/`. +6. Update `CHANGELOG.md`. + +## Adding Reference Templates + +1. Add a new file under `skill/examples/`. +2. Follow the native format (project structure, setup, architecture, tech guidelines). +3. Update `skill/examples/README.md`. +4. Teach `template_selector.py` how to detect the new template. +5. Add a scenario to `skill/sample_input.json`. + +## Quality Scoring (analyzer.py) + +`calculate_quality_score()` breakdown: + +- length_appropriateness: 25 pts (50–150 lines ideal; the 150-line hard cap is enforced here) +- section_completeness: 25 pts (required sections present) +- formatting_quality: 20 pts (markdown, heading hierarchy, code blocks) +- content_specificity: 15 pts (project-specific, not generic) +- modular_organization: 15 pts (chained sub-files when needed) + +## Tech Stack Detection + +`skill/workflow.py` → `_detect_tech_stack()` reads these signals: + +- **Frontend** — React/Vue/Angular via `package.json`; Angular via `angular.json`; TypeScript via `tsconfig.json`. +- **Backend** — Node (`package.json`), Python (`requirements.txt` / `pyproject.toml` / `setup.py`), Go (`go.mod`), Java (`pom.xml` / `build.gradle`), Rust (`Cargo.toml`). +- **Database** — Postgres (`pg` / `psycopg2`), MongoDB (`mongoose` / `pymongo`), Redis (`redis` / `ioredis`). + +Add new detectors there, not in the template selector. + +## Karpathy Guidelines Skill + +`skill/karpathy-guidelines/SKILL.md` is the standalone skill installed at `~/.claude/skills/karpathy-guidelines/`. Adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repo. The four principles are inserted automatically into every generated CLAUDE.md via `template_selector._generate_karpathy_guidelines()` and `generator._generate_karpathy_guidelines()`. Do not strip the embedded section during enhancement.