Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
Replace project-kickoff + context-manager with /project-health command
Jeremy Dawes36ee5a104c21
diff --git a/plugins/dev-tools/.claude-plugin/plugin.json b/plugins/dev-tools/.claude-plugin/plugin.jsonindex 9280aee5..c3d9d391 100644--- a/plugins/dev-tools/.claude-plugin/plugin.json+++ b/plugins/dev-tools/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "dev-tools",- "description": "Skill creation, project kickoff and permission management, project context, dev sessions, GitHub releases, Gemini peer review and API guide, capabilities reference, UX audits, and responsive layout testing.",+ "description": "Skill creation, project health (permissions, context, docs audit and setup), dev sessions, GitHub releases, Gemini peer review and API guide, capabilities reference, UX audits, and responsive layout testing.","author": {"name": "Jeremy Dawes / Jezweb","email": "[email protected]"diff --git a/plugins/dev-tools/commands/project-health.md b/plugins/dev-tools/commands/project-health.mdnew file mode 100644index 00000000..a40264a9--- /dev/null+++ b/plugins/dev-tools/commands/project-health.md@@ -0,0 +1,20 @@+---+description: Audit and manage project configuration — permissions, context, docs+argument-hint: "[full | setup | tidy | capture | preset | restructure]"+allowed-tools: "*"+---++Run the project-health skill with the specified mode.++Load the `project-health` skill first, then execute based on $ARGUMENTS:++| Argument | Mode |+|----------|------|+| (none) / `full` | Full health check: permissions + context audit |+| `setup` | New project setup (settings.local.json, CLAUDE.md, .gitignore) |+| `tidy` | Tidy permissions file only |+| `capture` | Capture session learnings to CLAUDE.md |+| `preset` | Add a permission preset (will ask which one) |+| `restructure` | Restructure oversized context files |++If no argument provided, run the full health check.diff --git a/plugins/dev-tools/skills/context-manager/SKILL.md b/plugins/dev-tools/skills/context-manager/SKILL.mddeleted file mode 100644index 9eb35919..00000000--- a/plugins/dev-tools/skills/context-manager/SKILL.md+++ /dev/null@@ -1,192 +0,0 @@-----name: context-manager-description: "Audit and manage the full project context landscape: CLAUDE.md memory hierarchy, project documentation, markdown footprint, and content overlap. Detects project type, scores quality, flags stale docs, and reports total context cost. Trigger with 'audit context', 'audit memory', 'update CLAUDE.md', 'restructure memory', 'session capture', 'check project docs', 'markdown footprint', or 'what docs does this project need'."-compatibility: claude-code-only------# Context Manager--Manage the Claude Code memory hierarchy and audit the full markdown landscape of a project. Produces well-organised memory files, detects documentation overlap, and reports the total context footprint.--## Four Context Layers--| Layer | Location | Purpose | What this skill does |-|-------|----------|---------|---------------------|-| **Memory** | `./CLAUDE.md`, subdirs, `.claude/rules/*.md` | Project context, commands, architecture, rules | Audit, score, maintain |-| **Project docs** | `ARCHITECTURE.md`, `DATABASE_SCHEMA.md`, `API_ENDPOINTS.md`, `docs/**/*.md` | Technical documentation | Check existence per project type, flag staleness, detect CLAUDE.md overlap |-| **Session** | `SESSION.md`, `PROJECT_BRIEF.md` | Temporary progress tracking | Report presence + size (managed by dev-session) |-| **Public** | `README.md`, `CONTRIBUTING.md`, other root `.md` | Public-facing docs | Detect CLAUDE.md duplication |--Auto-memory (`~/.claude/projects/*/memory/MEMORY.md`) is also scanned for awareness but managed by Claude automatically.--## Operating Modes--### Mode 1: Session Capture--**When**: End of session, "capture learnings", "update CLAUDE.md with what we learned"--1. Review the conversation for discoveries worth preserving:- - Commands that worked (or didn't)- - Gotchas and workarounds found- - Architecture decisions made- - Configuration quirks discovered- - Patterns that would help future sessions-2. Categorise each discovery using the placement decision tree below-3. Draft all changes as diffs in a single batch-4. Present the batch — apply after a single yes/no confirmation--**Keep it concise**: one line per concept. No verbose explanations, no generic advice.--### Mode 2: Full Audit--**When**: "audit context", "audit memory", "check project docs", periodic maintenance, working in a neglected project--1. Run the audit script:- ```bash- python3 plugins/dev-tools/skills/context-manager/scripts/audit_memory.py [repo-path]- ```-2. Review the output:- - **Memory layer**: CLAUDE.md sizes, quality scores, rules file sizes- - **Project docs**: existence, staleness, overlap with CLAUDE.md- - **Session/public**: presence and size- - **Markdown footprint**: total KB by layer- - **Overlap warnings**: sections duplicated between files-3. Generate changes autonomously — create, update, or flag files as needed-4. Present all changes as a single batch for approval-5. Apply approved changes-6. Check if the commit capture hook is installed — if not, offer to set it up (see [references/commit-hook.md](references/commit-hook.md))--For large repos, delegate to a sub-agent:-```-Task(subagent_type: "general-purpose",- prompt: "Run python3 plugins/dev-tools/skills/context-manager/scripts/audit_memory.py /path/to/repo- and summarise the findings.")-```--### Mode 3: Restructure--**When**: "restructure memory", root CLAUDE.md over 200 lines, first-time memory setup--1. Run full audit (Mode 2) first-2. Split oversized files:- - Extract topic sections from root CLAUDE.md into `.claude/rules/<topic>.md`- - Extract directory-specific content into sub-directory CLAUDE.md files- - Move detailed technical content from CLAUDE.md to `docs/` or `ARCHITECTURE.md` if it's reference material, not operational context-3. Resolve overlaps: if CLAUDE.md duplicates ARCHITECTURE.md or docs/, remove the duplication-4. Create missing documentation files based on project type-5. Present the restructure plan, apply after approval--## Placement Decision Tree--```-Would this still apply if I switched to a completely different project?-├── YES → ~/.claude/rules/<topic>.md-│ (correction rules, API patterns, coding standards)-└── NO → Is it specific to a subdirectory?- ├── YES → <dir>/CLAUDE.md- │ (integrations, directory-specific gotchas)- └── NO → Is it reference documentation or operational context?- ├── Reference → ARCHITECTURE.md or docs/- │ (system design, schemas, detailed flows)- └── Operational → ./CLAUDE.md (project root)- (identity, stack, commands, critical rules)-```--## Size Targets--| File Type | Target | Maximum |-|-----------|--------|---------|-| Root CLAUDE.md | 50-150 lines | 200 |-| Sub-directory CLAUDE.md | 15-50 lines | 80 |-| Rules topic file | 20-80 lines | 120 |--## What Belongs Where--### Root CLAUDE.md-- Project name, purpose, owner-- Tech stack summary-- Build/deploy/test commands (copy-paste ready)-- Directory structure overview-- Critical "never do X" rules-- Key integrations and secrets locations--### Sub-directory CLAUDE.md-- External service integrations for that component-- Non-obvious configuration specific to this area-- Directory-specific commands-- Gotchas when working in this directory--**Don't create when**: parent covers it, directory is self-explanatory, content would be under 10 lines.--### .claude/rules/ topic files-- Correction rules bridging training cutoff (e.g. API changes, deprecated patterns)-- Coding patterns and standards-- Platform-specific formatting rules-- Error prevention patterns--### docs/ and ARCHITECTURE.md-- Detailed system architecture (component diagrams, data flows)-- Database schemas and migration guides-- API endpoint catalogues-- Content that Claude should read on demand, not every session--**Rule of thumb**: If it's needed every session, put it in CLAUDE.md. If it's reference material consulted occasionally, put it in docs/.--### What to delete-- Content Claude already knows from training-- Verbose explanations of standard frameworks-- Changelogs or version history (use git)-- Duplicated content (between CLAUDE.md and docs/, ARCHITECTURE.md, or README.md)-- "TODO" items that were never completed-- Generic advice not specific to the project--## Project Type Detection--The audit script detects project type from file presence and suggests appropriate documentation:--| Indicator | Type | Suggested Docs |-|-----------|------|---------------|-| `wrangler.jsonc` / `wrangler.toml` | Cloudflare Worker | ARCHITECTURE.md |-| `vite.config.*` + `.tsx` files | Vite/React | ARCHITECTURE.md |-| `next.config.*` | Next.js | ARCHITECTURE.md |-| MCP patterns in `src/index.ts` | MCP Server | ARCHITECTURE.md, API_ENDPOINTS.md |-| `src/routes/` or `src/api/` | API Project | API_ENDPOINTS.md, DATABASE_SCHEMA.md |-| Drizzle/Prisma config | Database | DATABASE_SCHEMA.md |--All projects get CLAUDE.md. Additional docs only when the project type warrants them. See [references/project-types.md](references/project-types.md) for full detection heuristics and doc templates.--## Autonomy Rules--- **Just do it**: Run audit, detect project type, identify gaps, draft changes-- **Brief confirmation**: Apply changes (single batch yes/no, not item-by-item)-- **Ask first**: Delete existing content, major restructures (moving 50+ lines), create new project docs from scratch where there's ambiguity about content--## Quality Scoring--The audit script scores each CLAUDE.md on 6 criteria (100 points):--| Criterion | Points | What it measures |-|-----------|--------|-----------------|-| Commands/Workflows | 20 | Build, test, deploy documented |-| Architecture Clarity | 20 | Structure, relationships, entry points |-| Non-Obvious Patterns | 15 | Gotchas, quirks, warnings |-| Conciseness | 15 | Dense content, no filler |-| Currency | 15 | References valid, commands work |-| Actionability | 15 | Copy-paste ready, real paths |--See [references/quality-criteria.md](references/quality-criteria.md) for the full rubric.--## Reference Files--| When | Read |-|------|------|-| Scoring CLAUDE.md quality | [references/quality-criteria.md](references/quality-criteria.md) |-| Detecting project type and expected docs | [references/project-types.md](references/project-types.md) |-| Creating new CLAUDE.md or rules files | [references/templates.md](references/templates.md) |-| Setting up automatic capture on commit | [references/commit-hook.md](references/commit-hook.md) |--## Scripts--- `scripts/audit_memory.py` — Scan all four layers, score quality, detect project type, report footprint and overlap- - `python3 audit_memory.py [repo-path]` — human-readable report- - `python3 audit_memory.py [repo-path] --json` — structured JSON outputdiff --git a/plugins/dev-tools/skills/context-manager/references/commit-hook.md b/plugins/dev-tools/skills/context-manager/references/commit-hook.mddeleted file mode 100644index 25aa8216..00000000--- a/plugins/dev-tools/skills/context-manager/references/commit-hook.md+++ /dev/null@@ -1,43 +0,0 @@-# Recommended Hook: Context Capture on Commit--Automatically remind Claude to capture learnings after every git commit. This pairs with Mode 1 (Session Capture) — the hook triggers the prompt, the skill handles the capture.--## Setup--Create this file at `~/.claude/hookify.context-capture-reminder.local.md` for global coverage, or `project/.claude/hookify.context-capture-reminder.local.md` for a single project:--```markdown-----name: context-capture-reminder-enabled: true-event: bash-pattern: git\s+commit-action: warn------Context check: Were any patterns, gotchas, or commands discovered during this work that should be captured to CLAUDE.md or .claude/rules/? If yes, update them now before moving on. If nothing new was learned, carry on.-```--## How It Works--1. You finish work and commit-2. The hook fires after the `git commit` Bash call-3. Claude pauses to consider whether anything learned during this work should be persisted-4. If yes, Claude updates CLAUDE.md or creates/updates a `.claude/rules/` file-5. If nothing new, Claude continues--## Why Commit Time?--- Context is fresh — you just finished the work-- You're creating a permanent record anyway-- Natural checkpoint before moving to the next task-- Pairs with `git log` for tracing when a pattern was discovered--## Requires--This hook uses the [hookify](https://github.com/jezweb/claude-skills) plugin for Claude Code. If you don't have hookify, you can add the same reminder as a line in your CLAUDE.md:--```markdown-## Workflow-- Before committing: check if any discoveries should be captured to CLAUDE.md or .claude/rules/-```diff --git a/plugins/dev-tools/skills/context-manager/references/project-types.md b/plugins/dev-tools/skills/context-manager/references/project-types.mddeleted file mode 100644index f4dcdf08..00000000--- a/plugins/dev-tools/skills/context-manager/references/project-types.md+++ /dev/null@@ -1,149 +0,0 @@-# Project Types--Detect project type from file presence to determine which documentation files are expected. Only suggest docs that match — no enterprise bloat.--## Detection Heuristics--Check indicators in priority order (first match wins for primary type, but types can stack):--| Indicator Files | Project Type |-|----------------|-------------|-| `wrangler.jsonc` or `wrangler.toml` | cloudflare-worker |-| `vite.config.*` + `src/` with `.tsx` files | vite-react |-| `vite.config.*` without React | vite-app |-| `next.config.*` | nextjs |-| `src/index.ts` + `FastMCP` or `McpAgent` imports | mcp-server |-| `skills/` dir + SKILL.md files within | skills-repo |-| `src/routes/` or `src/api/` or `app/api/` | api-project |-| `drizzle.config.*` or `prisma/schema.prisma` or D1 bindings in wrangler | database-project |-| `.claude/agents/` + operational scripts | claude-ops |-| `package.json` only (generic Node) | node-project |-| `pyproject.toml` or `setup.py` | python-project |--**Stacking**: A Cloudflare Worker with D1 bindings is both `cloudflare-worker` and `database-project`. Union the expected docs.--## Expected Documentation Per Type--### All projects--| Doc | Purpose |-|-----|---------|-| `CLAUDE.md` (root) | Project identity, stack, commands, critical rules |--### cloudflare-worker--| Doc | Purpose |-|-----|---------|-| `ARCHITECTURE.md` | Worker entry point, bindings, routes, middleware |--### vite-react / nextjs--| Doc | Purpose |-|-----|---------|-| `ARCHITECTURE.md` | Component tree, routing, state management, build pipeline |--### mcp-server--| Doc | Purpose |-|-----|---------|-| `ARCHITECTURE.md` | Server structure, tool registration, auth flow |-| `API_ENDPOINTS.md` | Tool catalogue with parameters and return types |--### api-project--| Doc | Purpose |-|-----|---------|-| `API_ENDPOINTS.md` | Routes, methods, request/response schemas, auth requirements |-| `DATABASE_SCHEMA.md` | Tables, relationships, indexes, migration workflow |--### database-project--| Doc | Purpose |-|-----|---------|-| `DATABASE_SCHEMA.md` | Tables, relationships, indexes, migration commands |--### skills-repo--| Doc | Purpose |-|-----|---------|-| Per-skill `SKILL.md` | Each skill directory needs its own SKILL.md |--### claude-ops--No additional docs beyond CLAUDE.md — operational repos are typically self-documenting through their agents and scripts.--## Doc Templates--### ARCHITECTURE.md outline--```markdown-# Architecture--## Overview-[One paragraph: what this project does and how it's structured]--## Stack-[Tech stack with versions]--## Directory Structure-[Tree with purpose annotations]--## Key Flows-[1-3 main data/request flows through the system]--## Deployment-[How to deploy, what happens on deploy]-```--### DATABASE_SCHEMA.md outline--```markdown-# Database Schema--## Tables-[Table per section: name, columns, types, constraints]--## Relationships-[Foreign keys, join patterns]--## Migrations-[How to create/run migrations, local vs remote]--## Indexes-[Non-obvious indexes and why they exist]-```--### API_ENDPOINTS.md outline--```markdown-# API Endpoints--## Authentication-[Auth method, where tokens come from]--## Endpoints-[Per endpoint: method, path, params, response shape, auth required]--## Error Handling-[Standard error format, common error codes]-```--## docs/ Directory--Projects with a `docs/` folder get its contents scanned for staleness and overlap with CLAUDE.md. Common patterns:--| Pattern | Example |-|---------|---------|-| Component docs | `docs/RICH_CONTENT_COMPONENTS.md` |-| API guides | `docs/api-guide.md` |-| Planning briefs | `docs/briefs/feature-x.md` |--The audit doesn't manage docs/ content — it flags staleness (broken file references) and overlap (sections duplicated with CLAUDE.md).--## Rules--- Only suggest docs that match detected project type-- Simple projects (node-project, python-project) just need CLAUDE.md-- Don't create empty template docs — only suggest when there's content to fill-- Prefer one well-maintained doc over three sparse ones-- If CLAUDE.md duplicates ARCHITECTURE.md or docs/, move the content to docs/ and keep CLAUDE.md concisediff --git a/plugins/dev-tools/skills/context-manager/references/quality-criteria.md b/plugins/dev-tools/skills/context-manager/references/quality-criteria.mddeleted file mode 100644index c28561f5..00000000--- a/plugins/dev-tools/skills/context-manager/references/quality-criteria.md+++ /dev/null@@ -1,97 +0,0 @@-# Quality Criteria--Score CLAUDE.md files on a 100-point scale across 6 criteria. Use this when running a full audit (Mode 2) or restructure (Mode 3).--## Scoring Rubric--### Commands/Workflows (20 points)--Build, test, deploy, and dev commands documented with context.--| Score | Meaning |-|-------|---------|-| 20 | All essential commands with context (when to use, flags) |-| 15 | Most commands documented, some missing context |-| 10 | Basic commands only (e.g. `npm run dev`) |-| 5 | Few commands, no context |-| 0 | None documented |--### Architecture Clarity (20 points)--Directory structure, module relationships, entry points, data flow.--| Score | Meaning |-|-------|---------|-| 20 | Clear codebase map with relationships and entry points |-| 15 | Good overview, minor gaps |-| 10 | Basic directory listing only |-| 5 | Vague or incomplete |-| 0 | None |--### Non-Obvious Patterns (15 points)--Gotchas, quirks, edge cases, workarounds, "why" for unusual decisions.--| Score | Meaning |-|-------|---------|-| 15 | Gotchas and quirks captured with explanations |-| 10 | Some patterns documented |-| 5 | Minimal |-| 0 | None |--### Conciseness (15 points)--Dense, valuable content. No filler, no redundancy, each line earns its place.--| Score | Meaning |-|-------|---------|-| 15 | Every line adds value, no filler |-| 10 | Mostly concise, minor bloat |-| 5 | Verbose in places |-| 0 | Mostly filler or generic advice |--### Currency (15 points)--Reflects the actual current codebase. Commands work, files exist, stack is correct.--| Score | Meaning |-|-------|---------|-| 15 | All references valid, commands work, stack current |-| 10 | Mostly current, minor staleness |-| 5 | Several outdated references |-| 0 | Severely outdated |--### Actionability (15 points)--Instructions are executable. Copy-paste ready commands, real paths, concrete steps.--| Score | Meaning |-|-------|---------|-| 15 | Copy-paste ready, concrete, real paths |-| 10 | Mostly actionable |-| 5 | Some vague instructions |-| 0 | Theoretical or generic |--## Grading Scale--| Grade | Score | Meaning |-|-------|-------|---------|-| A | 90-100 | Comprehensive, current, actionable |-| B | 70-89 | Good coverage, minor gaps |-| C | 50-69 | Basic info, missing key sections |-| D | 30-49 | Sparse or outdated |-| F | 0-29 | Missing or severely outdated |--## Red Flags--Flag these during audit — each indicates a quality problem:--- Commands that fail when run-- References to files/directories that don't exist-- Outdated technology versions or deprecated APIs-- Generic advice not specific to the project (e.g. "write clean code")-- Copy-paste templates that weren't customised-- "TODO" items that were never completed-- Duplicated content across multiple CLAUDE.md files-- Verbose explanations of things Claude already knows-- Changelogs or version history (belongs in git, not CLAUDE.md)diff --git a/plugins/dev-tools/skills/context-manager/references/templates.md b/plugins/dev-tools/skills/context-manager/references/templates.mddeleted file mode 100644index 7e05c189..00000000--- a/plugins/dev-tools/skills/context-manager/references/templates.md+++ /dev/null@@ -1,149 +0,0 @@-# Templates--Reference templates for CLAUDE.md files, rules topic files, and sub-directory context. Use these when creating new files or restructuring existing ones.--## Root CLAUDE.md (Minimal)--For simple projects with a single developer:--```markdown-# [Project Name]--[One-line description]--## Stack--[Tech stack summary]--## Commands--| Command | Purpose |-|---------|---------|-| `npm run dev` | Start dev server |-| `npm run build` | Production build |-| `npm run deploy` | Deploy to [platform] |--## Gotchas--- [Non-obvious thing 1]-- [Non-obvious thing 2]-```--Target: 30-60 lines.--## Root CLAUDE.md (Comprehensive)--For projects with external integrations, multiple contributors, or complex workflows:--```markdown-# [Project Name]--**Repository**: [URL]-**Owner**: [Name]--[One-line description]--## Stack--[Tech stack with key decisions noted]--## Directory Structure--[Annotated tree of key directories]--## Commands--| Command | Purpose |-|---------|---------|-| `npm run dev` | Start dev server |-| `npm run build` | Production build |-| `npm run deploy` | Deploy to [platform] |-| `npm test` | Run test suite |--## Key Files--| File | Purpose |-|------|---------|-| `src/index.ts` | Entry point |-| `wrangler.jsonc` | Cloudflare config |--## Critical Rules--- [Never do X because Y]-- [Always do A before B]--## Gotchas--- [Non-obvious thing 1]-- [Non-obvious thing 2]-```--Target: 60-150 lines.--## Sub-Directory CLAUDE.md--For directories with external integrations, non-obvious config, or common gotchas:--```markdown-# [Component Name]--## Key Integrations--- **[Service]**: [endpoint], [auth method], [secret location]--## Commands--[Directory-specific commands if different from root]--## Gotchas--- [Non-obvious thing specific to this directory]-```--Target: 15-50 lines.--**Don't create when**: parent CLAUDE.md covers it, directory is self-explanatory, content would be under 10 lines.--## Rules Topic File (.claude/rules/*.md)--For correction rules, patterns, and technical facts that apply across projects:--```markdown-# [Topic Name]--## [Pattern/Rule Category]--| If Claude suggests... | Use instead... |-|----------------------|----------------|-| [Wrong pattern] | [Correct pattern] |--[Code example if helpful]--**Last Updated**: [date]-```--Target: 20-80 lines per topic file.--## Section Placement Guide--| Content Type | Where It Goes |-|-------------|---------------|-| Project name, owner, purpose | Root CLAUDE.md |-| Tech stack, architecture overview | Root CLAUDE.md |-| Build/deploy/test commands | Root CLAUDE.md |-| Critical "never do X" rules | Root CLAUDE.md |-| Directory structure | Root CLAUDE.md |-| External service integrations | Sub-directory CLAUDE.md (near the code that uses them) |-| Directory-specific gotchas | Sub-directory CLAUDE.md |-| Correction rules (training cutoff) | `.claude/rules/<topic>.md` |-| Coding patterns for this project | `.claude/rules/<topic>.md` or root CLAUDE.md |-| Session-specific discoveries | Auto-memory (managed by Claude Code, not this skill) |--## Anti-Patterns--- Verbose explanations of standard tools or frameworks-- Changelogs or version history (use git)-- Content Claude already knows from training-- Duplicating parent CLAUDE.md content in child files-- Generic best practices not specific to the project-- Empty template sections with placeholder textdiff --git a/plugins/dev-tools/skills/context-manager/scripts/audit_memory.py b/plugins/dev-tools/skills/context-manager/scripts/audit_memory.pydeleted file mode 100644index b3d85f06..00000000--- a/plugins/dev-tools/skills/context-manager/scripts/audit_memory.py+++ /dev/null@@ -1,888 +0,0 @@-#!/usr/bin/env python3-"""Audit project context across all four layers.--Scans CLAUDE.md files, .claude/rules/ topic files, auto-memory,-project documentation, session files, and public markdown.-Reports sizes, quality scores, project type, footprint, and overlap.--Usage:- python3 audit_memory.py [repo-path]- python3 audit_memory.py # uses current directory- python3 audit_memory.py --json # JSON output for programmatic use-"""--import json-import os-import re-import sys-from pathlib import Path--# ----------------------------------------------------------------------------# Configuration-# -----------------------------------------------------------------------------ROOT_TARGET = 150-SUBDIR_TARGET = 50-RULES_TARGET = 80--SKIP_DIRS = {- "node_modules", ".git", "dist", "build", ".wrangler",- ".output", ".vercel", ".cache", "__pycache__", ".venv",- "vendor", ".next", ".nuxt", ".turbo", ".parcel-cache",-}--# Sections that indicate quality (used for scoring)-COMMAND_PATTERNS = re.compile(- r"(##\s*(commands?|scripts?|workflow|usage|quick\s*start))",- re.IGNORECASE,-)-ARCH_PATTERNS = re.compile(- r"(##\s*(architect|directory|structure|stack|overview|layout))",- re.IGNORECASE,-)-GOTCHA_PATTERNS = re.compile(- r"(##\s*(gotcha|caveat|warning|critical|never|important|rules?))",- re.IGNORECASE,-)--# Well-known project docs-PROJECT_DOC_NAMES = {- "ARCHITECTURE.md", "DATABASE_SCHEMA.md", "API_ENDPOINTS.md",- "PROJECT_SPEC.md",-}--# Well-known session files-SESSION_FILE_NAMES = {"SESSION.md", "PROJECT_BRIEF.md"}--# Well-known public files-PUBLIC_MD_NAMES = {"README.md", "CONTRIBUTING.md", "CHANGELOG.md", "LICENSE.md"}--# Project type detection indicators-PROJECT_INDICATORS = {- "cloudflare-worker": {- "files": ["wrangler.jsonc", "wrangler.toml"],- "docs": ["ARCHITECTURE.md"],- },- "mcp-server": {- "content_patterns": [r"FastMCP|McpAgent|mcp.*server"],- "docs": ["ARCHITECTURE.md", "API_ENDPOINTS.md"],- },- "vite-react": {- "files_glob": ["vite.config.*"],- "content_check": {"dir": "src", "ext": ".tsx"},- "docs": ["ARCHITECTURE.md"],- },- "vite-app": {- "files_glob": ["vite.config.*"],- "docs": ["ARCHITECTURE.md"],- },- "nextjs": {- "files_glob": ["next.config.*"],- "docs": ["ARCHITECTURE.md"],- },- "api-project": {- "dirs": ["src/routes", "src/api", "app/api"],- "docs": ["API_ENDPOINTS.md", "DATABASE_SCHEMA.md"],- },- "database-project": {- "files_glob": ["drizzle.config.*", "prisma/schema.prisma"],- "docs": ["DATABASE_SCHEMA.md"],- },- "skills-repo": {- "dirs": ["skills"],- "content_check_dir": {"subdir": "skills", "file": "SKILL.md"},- "docs": [],- },- "claude-ops": {- "dirs": [".claude/agents"],- "docs": [],- },-}--# ----------------------------------------------------------------------------# Core scanning functions-# ------------------------------------------------------------------------------def count_lines(path: Path) -> int:- try:- return len(path.read_text(encoding="utf-8").splitlines())- except (OSError, UnicodeDecodeError):- return -1---def file_size(path: Path) -> int:- """Return file size in bytes."""- try:- return path.stat().st_size- except OSError:- return 0---def read_text(path: Path) -> str:- try:- return path.read_text(encoding="utf-8")- except (OSError, UnicodeDecodeError):- return ""---def find_claude_md(repo: Path) -> list[Path]:- """Find all CLAUDE.md files, skipping ignored directories."""- results = []- for root, dirs, files in os.walk(repo):- dirs[:] = [d for d in dirs if d not in SKIP_DIRS]- for f in files:- if f == "CLAUDE.md":- results.append(Path(root) / f)- return sorted(results)---def find_rules(repo: Path) -> list[Path]:- """Find .claude/rules/ files."""- rules_dir = repo / ".claude" / "rules"- if not rules_dir.is_dir():- return []- return sorted(rules_dir.glob("*.md"))---def find_auto_memory() -> list[Path]:- """Find auto-memory MEMORY.md files in ~/.claude/projects/."""- home = Path.home()- projects_dir = home / ".claude" / "projects"- if not projects_dir.is_dir():- return []- results = []- for project_dir in sorted(projects_dir.iterdir()):- memory_file = project_dir / "memory" / "MEMORY.md"- if memory_file.is_file():- results.append(memory_file)- return results---def find_project_docs(repo: Path) -> list[Path]:- """Find project documentation files (ARCHITECTURE.md, docs/, etc.)."""- results = []- # Check root-level project docs- for name in PROJECT_DOC_NAMES:- path = repo / name- if path.is_file():- results.append(path)- # Check docs/ directory- docs_dir = repo / "docs"- if docs_dir.is_dir():- for md in sorted(docs_dir.rglob("*.md")):- results.append(md)- return sorted(set(results))---def find_session_files(repo: Path) -> list[Path]:- """Find session tracking files (SESSION.md, PROJECT_BRIEF.md)."""- results = []- for name in SESSION_FILE_NAMES:- path = repo / name- if path.is_file():- results.append(path)- return sorted(results)---def find_public_md(repo: Path, already_categorised: set[Path]) -> list[Path]:- """Find public-facing markdown in repo root not already categorised."""- results = []- for name in PUBLIC_MD_NAMES:- path = repo / name- if path.is_file() and path not in already_categorised:- results.append(path)- # Also pick up any other root .md files not yet categorised- for md in sorted(repo.glob("*.md")):- if md not in already_categorised and md not in results:- # Skip CLAUDE.md (handled in memory layer)- if md.name != "CLAUDE.md":- results.append(md)- return sorted(set(results))---def extract_sections(path: Path) -> list[tuple[str, str]]:- """Extract H2 sections with their content."""- lines = read_text(path).splitlines()- sections = []- current_heading = None- current_lines = []- for line in lines:- if line.startswith("## "):- if current_heading is not None:- sections.append((current_heading, "\n".join(current_lines)))- current_heading = line.lstrip("# ").strip()- current_lines = []- elif current_heading is not None:- current_lines.append(line)- if current_heading is not None:- sections.append((current_heading, "\n".join(current_lines)))- return sections---def find_complex_dirs(repo: Path, existing: set[Path]) -> list[Path]:- """Find directories that might benefit from a CLAUDE.md."""- indicators = {- "wrangler.jsonc", "wrangler.toml", ".env.example",- "docker-compose.yml", "Dockerfile", "firebase.json",- "vercel.json", "netlify.toml",- }- suggestions = []- for root, dirs, files in os.walk(repo):- dirs[:] = [d for d in dirs if d not in SKIP_DIRS]- root_path = Path(root)- if root_path in existing:- continue- if root_path == repo:- continue- has_indicator = bool(set(files) & indicators)- src_count = sum(1 for f in files if f.endswith((".ts", ".tsx", ".py", ".go")))- if has_indicator or src_count > 10:- suggestions.append(root_path)- return sorted(suggestions)---# ----------------------------------------------------------------------------# Overlap detection-# ------------------------------------------------------------------------------def normalise_text(text: str) -> str:- """Normalise text for comparison: lowercase, strip whitespace, remove markdown formatting."""- text = text.lower()- text = re.sub(r"[`*_#|>\-]", " ", text)- text = re.sub(r"\s+", " ", text)- return text.strip()---def section_overlap(text_a: str, text_b: str) -> float:- """Calculate word-level overlap between two text blocks. Returns 0.0-1.0."""- words_a = set(normalise_text(text_a).split())- words_b = set(normalise_text(text_b).split())- if not words_a or not words_b:- return 0.0- intersection = words_a & words_b- # Use the smaller set as denominator (Jaccard-like but asymmetric)- smaller = min(len(words_a), len(words_b))- return len(intersection) / smaller if smaller > 0 else 0.0---def detect_overlaps(claude_md_path: Path, other_paths: list[Path], repo: Path, threshold: float = 0.5) -> list[dict]:- """Detect section-level overlap between root CLAUDE.md and other files."""- claude_sections = extract_sections(claude_md_path)- if not claude_sections:- return []-- overlaps = []- for other_path in other_paths:- other_sections = extract_sections(other_path)- if not other_sections:- continue-- for c_heading, c_content in claude_sections:- if len(c_content.strip()) < 50: # Skip tiny sections- continue- for o_heading, o_content in other_sections:- if len(o_content.strip()) < 50:- continue- pct = section_overlap(c_content, o_content)- if pct >= threshold:- overlaps.append({- "claude_section": c_heading,- "other_file": str(other_path.relative_to(repo)),- "other_section": o_heading,- "overlap_pct": round(pct * 100),- })- return overlaps---# ----------------------------------------------------------------------------# Footprint calculation-# ------------------------------------------------------------------------------def calculate_footprint(- claude_files: list[Path],- rules: list[Path],- project_docs: list[Path],- session_files: list[Path],- public_md: list[Path],- auto_memory: list[Path],-) -> dict:- """Calculate total markdown footprint by layer."""-- def sum_bytes(paths: list[Path]) -> int:- return sum(file_size(p) for p in paths)-- memory_bytes = sum_bytes(claude_files) + sum_bytes(rules)- docs_bytes = sum_bytes(project_docs)- session_bytes = sum_bytes(session_files)- public_bytes = sum_bytes(public_md)- auto_bytes = sum_bytes(auto_memory)- total = memory_bytes + docs_bytes + session_bytes + public_bytes + auto_bytes- total_files = len(claude_files) + len(rules) + len(project_docs) + len(session_files) + len(public_md) + len(auto_memory)-- return {- "total_bytes": total,- "total_files": total_files,- "memory_bytes": memory_bytes,- "project_docs_bytes": docs_bytes,- "session_bytes": session_bytes,- "public_bytes": public_bytes,- "auto_memory_bytes": auto_bytes,- }---def format_bytes(b: int) -> str:- """Format bytes as human-readable KB."""- if b < 1024:- return f"{b}B"- return f"{b / 1024:.1f}KB"---# ----------------------------------------------------------------------------# Project type detection-# ------------------------------------------------------------------------------def detect_project_type(repo: Path) -> list[dict]:- """Detect project types from file presence. Returns list of matching types."""- detected = []-- for type_name, indicators in PROJECT_INDICATORS.items():- matched = False-- # Check specific files- if "files" in indicators:- for f in indicators["files"]:- if (repo / f).exists():- matched = True- break-- # Check glob patterns- if not matched and "files_glob" in indicators:- for pattern in indicators["files_glob"]:- if list(repo.glob(pattern)):- matched = True- break-- # Check directories- if not matched and "dirs" in indicators:- for d in indicators["dirs"]:- if (repo / d).is_dir():- matched = True- break-- # Content pattern check (e.g. MCP server detection)- if not matched and "content_patterns" in indicators:- src_index = repo / "src" / "index.ts"- if src_index.exists():- content = read_text(src_index)- for pattern in indicators["content_patterns"]:- if re.search(pattern, content):- matched = True- break-- # Vite-react needs .tsx files in src/- if matched and type_name == "vite-react":- src_dir = repo / "src"- if not src_dir.is_dir() or not list(src_dir.glob("**/*.tsx")):- matched = False-- # Vite-app should not match if vite-react already matched- if type_name == "vite-app" and matched:- if any(d["type"] == "vite-react" for d in detected):- matched = False-- # Skills repo needs SKILL.md files inside skills/- if matched and type_name == "skills-repo":- skills_dir = repo / "skills"- if not list(skills_dir.glob("*/SKILL.md")):- matched = False-- if matched:- detected.append({- "type": type_name,- "docs": indicators.get("docs", []),- })-- return detected if detected else [{"type": "generic", "docs": []}]---def get_expected_docs(project_types: list[dict]) -> list[str]:- """Union all expected docs from detected project types."""- docs = {"CLAUDE.md"}- for pt in project_types:- for d in pt.get("docs", []):- docs.add(d)- return sorted(docs)---def check_missing_docs(repo: Path, expected: list[str]) -> list[str]:- """Check which expected docs are missing."""- missing = []- for doc in expected:- # Check root and docs/ directory- if not (repo / doc).exists() and not (repo / "docs" / doc).exists():- missing.append(doc)- return missing---# ----------------------------------------------------------------------------# Quality scoring-# ------------------------------------------------------------------------------def score_claude_md(path: Path, repo: Path) -> dict:- """Score a CLAUDE.md file on 6 criteria (100 points total)."""- content = read_text(path)- lines = content.splitlines()- line_count = len(lines)-- scores = {}-- # 1. Commands/Workflows (20 pts)- has_commands = bool(COMMAND_PATTERNS.search(content))- has_code_blocks = content.count("```") >= 2- has_table = "|" in content and "---" in content- cmd_score = 0- if has_commands and has_code_blocks:- cmd_score = 20- elif has_commands or has_code_blocks:- cmd_score = 15 if has_table else 10- elif has_table:- cmd_score = 5- scores["commands"] = cmd_score-- # 2. Architecture Clarity (20 pts)- has_arch = bool(ARCH_PATTERNS.search(content))- has_tree = "├" in content or "└" in content- arch_score = 0- if has_arch and has_tree:- arch_score = 20- elif has_arch:- arch_score = 15- elif has_tree:- arch_score = 10- scores["architecture"] = arch_score-- # 3. Non-Obvious Patterns (15 pts)- has_gotchas = bool(GOTCHA_PATTERNS.search(content))- has_never = "never" in content.lower() or "don't" in content.lower()- gotcha_score = 0- if has_gotchas and has_never:- gotcha_score = 15- elif has_gotchas or has_never:- gotcha_score = 10- scores["patterns"] = gotcha_score-- # 4. Conciseness (15 pts)- is_root = path.parent == repo- target = ROOT_TARGET if is_root else SUBDIR_TARGET- ratio = line_count / target if target > 0 else 2.0- if 0.3 <= ratio <= 1.0:- concise_score = 15- elif ratio <= 1.5:- concise_score = 10- elif ratio <= 2.0:- concise_score = 5- else:- concise_score = 0- scores["conciseness"] = concise_score-- # 5. Currency (15 pts) — check for stale references- stale_refs = check_staleness(path, repo)- if not stale_refs:- currency_score = 15- elif len(stale_refs) <= 2:- currency_score = 10- elif len(stale_refs) <= 5:- currency_score = 5- else:- currency_score = 0- scores["currency"] = currency_score-- # 6. Actionability (15 pts)- has_inline_code = "`" in content- actionability_score = 0- if has_code_blocks and has_inline_code and has_table:- actionability_score = 15- elif has_code_blocks and has_inline_code:- actionability_score = 10- elif has_inline_code:- actionability_score = 5- scores["actionability"] = actionability_score-- total = sum(scores.values())- grade = (- "A" if total >= 90 else- "B" if total >= 70 else- "C" if total >= 50 else- "D" if total >= 30 else- "F"- )-- return {- "scores": scores,- "total": total,- "grade": grade,- "stale_refs": stale_refs,- }---# ----------------------------------------------------------------------------# Staleness detection-# ------------------------------------------------------------------------------def check_staleness(path: Path, repo: Path) -> list[str]:- """Check for references to non-existent files/directories."""- content = read_text(path)- stale = []-- # Find file path references (backticked paths, markdown links)- path_patterns = [- r"`([a-zA-Z0-9_./-]+\.[a-zA-Z]{1,5})`", # `path/to/file.ext`- r"\[.*?\]\(([a-zA-Z0-9_./-]+\.[a-zA-Z]{1,5})\)", # [text](path)- r"`([a-zA-Z0-9_/-]+/)`", # `path/to/dir/`- ]-- checked = set()- for pattern in path_patterns:- for match in re.finditer(pattern, content):- ref = match.group(1).rstrip("/")- if ref in checked:- continue- checked.add(ref)-- # Skip URLs, commands, common patterns- if ref.startswith(("http", "//", "npm ", "git ", "$")):- continue- if ref.startswith(("*.", "**/")):- continue- # Skip short refs that are likely code, not file paths- if "/" not in ref and not ref.startswith("."):- continue-- # Check relative to the file's directory and repo root- ref_path = Path(ref)- candidates = [- path.parent / ref_path,- repo / ref_path,- ]- if not any(c.exists() for c in candidates):- stale.append(ref)-- return stale---# ----------------------------------------------------------------------------# Report generation-# ------------------------------------------------------------------------------def print_header(text: str) -> None:- print(f"\n{'=' * 60}")- print(f" {text}")- print(f"{'=' * 60}\n")---def main():- json_output = "--json" in sys.argv- args = [a for a in sys.argv[1:] if a != "--json"]- repo = Path(args[0] if args else ".").resolve()-- if not repo.is_dir():- print(f"Error: {repo} is not a directory", file=sys.stderr)- sys.exit(1)-- report = {- "repo": str(repo),- "project_types": [],- "claude_md_files": [],- "rules_files": [],- "auto_memory_files": [],- "project_docs": [],- "session_files": [],- "public_md": [],- "missing_docs": [],- "suggestions": [],- "footprint": {},- "overlaps": [],- "summary": {},- }-- # --- Project Type Detection ---- project_types = detect_project_type(repo)- report["project_types"] = [pt["type"] for pt in project_types]- expected_docs = get_expected_docs(project_types)- missing_docs = check_missing_docs(repo, expected_docs)- report["missing_docs"] = missing_docs-- if not json_output:- print(f"Auditing: {repo}\n")- type_names = ", ".join(pt["type"] for pt in project_types)- print(f"Project type(s): {type_names}")- print(f"Expected docs: {', '.join(expected_docs)}")- if missing_docs:- print(f"Missing docs: {', '.join(missing_docs)}")- else:- print("Missing docs: none")-- # --- Layer 1: CLAUDE.md Files ---- claude_files = find_claude_md(repo)- existing_dirs = {f.parent for f in claude_files}-- if not json_output:- print_header("Layer 1: CLAUDE.md Hierarchy")-- if not claude_files:- if not json_output:- print(" No CLAUDE.md files found.\n")- else:- if not json_output:- print(f" Found {len(claude_files)} file(s):\n")-- for f in claude_files:- lines = count_lines(f)- rel = str(f.relative_to(repo))- is_root = f.parent == repo- target = ROOT_TARGET if is_root else SUBDIR_TARGET- status = "OK" if lines <= target else "OVER"- quality = score_claude_md(f, repo)-- file_info = {- "path": rel,- "lines": lines,- "target": target,- "status": status,- "quality": quality,- }- report["claude_md_files"].append(file_info)-- if not json_output:- marker = f" <<< +{lines - target} over" if status == "OVER" else ""- print(f" {rel}: {lines} lines (target: {target}){marker}")- print(f" Score: {quality['total']}/100 ({quality['grade']})")- scores = quality["scores"]- parts = [f"{k}={v}" for k, v in scores.items()]- print(f" [{', '.join(parts)}]")- if quality["stale_refs"]:- print(f" Stale refs: {', '.join(quality['stale_refs'])}")- print()-- # --- Layer 2: Rules Files ---- rules = find_rules(repo)-- if not json_output:- print_header("Layer 2: .claude/rules/")-- if rules:- if not json_output:- print(f" Found {len(rules)} rule file(s):\n")- for r in rules:- lines = count_lines(r)- status = "OVER" if lines > RULES_TARGET else "OK"- file_info = {- "path": f".claude/rules/{r.name}",- "lines": lines,- "target": RULES_TARGET,- "status": status,- }- report["rules_files"].append(file_info)- if not json_output:- marker = f" <<< +{lines - RULES_TARGET} over" if status == "OVER" else ""- print(f" {r.name}: {lines} lines{marker}")- else:- if not json_output:- print(" No .claude/rules/ directory found.")-- # --- Layer 3: Auto-Memory ---- auto_memory = find_auto_memory()-- if not json_output:- print_header("Layer 3: Auto-Memory")-- if auto_memory:- if not json_output:- print(f" Found {len(auto_memory)} auto-memory file(s):\n")- for m in auto_memory:- lines = count_lines(m)- # Extract project name from directory- project_name = m.parent.parent.name- file_info = {- "path": str(m),- "project": project_name,- "lines": lines,- "empty": lines <= 1,- }- report["auto_memory_files"].append(file_info)- if not json_output:- empty_note = " (empty)" if lines <= 1 else ""- print(f" {project_name}: {lines} lines{empty_note}")- else:- if not json_output:- print(" No auto-memory files found.")-- # --- Layer 4: Project Documentation ---- project_docs = find_project_docs(repo)- # Track all categorised paths for public_md exclusion- categorised = set(claude_files) | set(rules) | set(project_docs)-- if not json_output:- print_header("Layer 4: Project Documentation")-- if project_docs:- if not json_output:- print(f" Found {len(project_docs)} doc file(s):\n")- for d in project_docs:- lines = count_lines(d)- rel = str(d.relative_to(repo))- stale_refs = check_staleness(d, repo)- file_info = {- "path": rel,- "lines": lines,- "bytes": file_size(d),- "stale_refs": stale_refs,- }- report["project_docs"].append(file_info)- if not json_output:- stale_note = f" ({len(stale_refs)} stale refs)" if stale_refs else ""- print(f" {rel}: {lines} lines ({format_bytes(file_size(d))}){stale_note}")- else:- if not json_output:- print(" No project documentation found.")-- # --- Session Files ---- session_files = find_session_files(repo)- categorised.update(session_files)-- if not json_output:- print_header("Session Files")-- if session_files:- for s in session_files:- lines = count_lines(s)- rel = str(s.relative_to(repo))- file_info = {- "path": rel,- "lines": lines,- "bytes": file_size(s),- }- report["session_files"].append(file_info)- if not json_output:- print(f" {rel}: {lines} lines ({format_bytes(file_size(s))})")- else:- if not json_output:- print(" No session files found.")-- # --- Public Markdown ---- public_md = find_public_md(repo, categorised)- categorised.update(public_md)-- if not json_output:- print_header("Public Markdown")-- if public_md:- for p in public_md:- lines = count_lines(p)- rel = str(p.relative_to(repo))- file_info = {- "path": rel,- "lines": lines,- "bytes": file_size(p),- }- report["public_md"].append(file_info)- if not json_output:- print(f" {rel}: {lines} lines ({format_bytes(file_size(p))})")- else:- if not json_output:- print(" No public markdown files found.")-- # --- Overlap Detection ---- root_claude = repo / "CLAUDE.md"- overlaps = []- if root_claude.is_file():- # Compare root CLAUDE.md against project docs and public md- compare_targets = project_docs + public_md- overlaps = detect_overlaps(root_claude, compare_targets, repo)- report["overlaps"] = overlaps-- if not json_output and overlaps:- print_header("Overlap Warnings")- for o in overlaps:- print(f" CLAUDE.md § {o['claude_section']} ↔ {o['other_file']} § {o['other_section']} ({o['overlap_pct']}% overlap)")-- # --- Suggestions ---- suggestions = find_complex_dirs(repo, existing_dirs)- report["suggestions"] = [str(s.relative_to(repo)) for s in suggestions]-- if suggestions and not json_output:- print_header("Suggestions")- print(f" {len(suggestions)} director(ies) could benefit from a CLAUDE.md:\n")- for s in suggestions:- print(f" {s.relative_to(repo)}/CLAUDE.md")-- # --- Footprint ---- footprint = calculate_footprint(claude_files, rules, project_docs, session_files, public_md, auto_memory)- report["footprint"] = footprint-- if not json_output:- print_header("Markdown Footprint")- print(f" Total: {format_bytes(footprint['total_bytes'])} across {footprint['total_files']} files")- print(f" Memory: {format_bytes(footprint['memory_bytes'])} (CLAUDE.md + {len(rules)} rules)")- print(f" Project docs: {format_bytes(footprint['project_docs_bytes'])} ({len(project_docs)} files)")- print(f" Session: {format_bytes(footprint['session_bytes'])} ({len(session_files)} files)")- print(f" Public: {format_bytes(footprint['public_bytes'])} ({len(public_md)} files)")- if auto_memory:- print(f" Auto-memory: {format_bytes(footprint['auto_memory_bytes'])} ({len(auto_memory)} files)")-- # --- Summary ---- total_claude_lines = sum(count_lines(f) for f in claude_files)- total_rules_lines = sum(count_lines(r) for r in rules)- oversized_count = sum(- 1 for f in report["claude_md_files"] if f["status"] == "OVER"- )- avg_score = 0- if report["claude_md_files"]:- avg_score = round(- sum(f["quality"]["total"] for f in report["claude_md_files"])- / len(report["claude_md_files"])- )-- report["summary"] = {- "claude_md_count": len(claude_files),- "claude_md_total_lines": total_claude_lines,- "claude_md_oversized": oversized_count,- "claude_md_avg_score": avg_score,- "rules_count": len(rules),- "rules_total_lines": total_rules_lines,- "auto_memory_count": len(auto_memory),- "project_docs_count": len(project_docs),- "session_files_count": len(session_files),- "public_md_count": len(public_md),- "overlap_count": len(overlaps),- "missing_docs": len(missing_docs),- "suggestion_count": len(suggestions),- "total_footprint_bytes": footprint["total_bytes"],- }-- if not json_output:- print_header("Summary")- print(f" CLAUDE.md files: {len(claude_files)} ({total_claude_lines} lines, {oversized_count} oversized)")- print(f" Average quality: {avg_score}/100")- print(f" Rules files: {len(rules)} ({total_rules_lines} lines)")- print(f" Auto-memory files: {len(auto_memory)}")- print(f" Project docs: {len(project_docs)}")- print(f" Session files: {len(session_files)}")- print(f" Public markdown: {len(public_md)}")- print(f" Overlaps: {len(overlaps)}")- print(f" Missing docs: {len(missing_docs)}")- print(f" Suggested additions: {len(suggestions)}")- print(f" Total footprint: {format_bytes(footprint['total_bytes'])}")- else:- print(json.dumps(report, indent=2))---if __name__ == "__main__":- main()diff --git a/plugins/dev-tools/skills/project-kickoff/SKILL.md b/plugins/dev-tools/skills/project-kickoff/SKILL.mddeleted file mode 100644index 4150505d..00000000--- a/plugins/dev-tools/skills/project-kickoff/SKILL.md+++ /dev/null@@ -1,178 +0,0 @@-----name: project-kickoff-description: "Bootstrap new projects with curated settings.local.json permissions, CLAUDE.md, and .gitignore. Detects project type and generates comprehensive permission presets so you never get prompted. Auto-discovers connected MCP servers. Also tidies existing messy settings files. Trigger with 'kickoff', 'new project', 'bootstrap', 'setup claude', 'tidy permissions', 'clean settings', or 'init project'."-compatibility: claude-code-only------# Project Kickoff--Bootstrap a new project so Claude Code has the right permissions from the start. The goal is **zero permission prompts** after setup — every command you'd reasonably use should be pre-approved.--**Problem**: Every new project accumulates permission approvals one click at a time. Project `settings.local.json` shadows global settings (does not merge), so each project needs its own complete list. This skill generates that list upfront.--**Output**: `settings.local.json`, `CLAUDE.md`, `.gitignore` (and optionally git init + GitHub repo).--## Operating Modes--### Mode 1: New Project Setup--**When**: Starting a new project, or working in a directory without `.claude/settings.local.json`.--**Steps**:--1. **Detect project type** from files present in the directory:-- | Indicator | Type |- |-----------|------|- | `wrangler.jsonc` or `wrangler.toml` | cloudflare-worker |- | `vercel.json` or `next.config.*` | vercel-app |- | `package.json` (no deploy target) | javascript-typescript |- | `pyproject.toml` or `setup.py` or `requirements.txt` | python |- | `Cargo.toml` | rust |- | `go.mod` | go |- | `Gemfile` or `Rakefile` | ruby |- | `composer.json` or `wp-config.php` | php |- | `Dockerfile` or `docker-compose.yml` | docker |- | `.claude/agents/` or operational scripts | ops-admin |- | Empty directory | Ask the user |-- If ambiguous, ask. Types can stack (e.g. cloudflare-worker + javascript-typescript).--2. **Generate `.claude/settings.local.json`**:-- Read [references/permission-presets.md](references/permission-presets.md) for preset definitions, then:-- a. **Always include Universal Base** — file ops, text processing, network, system, git. These are needed by every project.-- b. **Add detected language presets** — JS/TS, Python, PHP, Go, Rust, Ruby, etc. When in doubt, include more rather than less. Adding `Bash(cargo *)` to a JS project costs nothing if Rust isn't installed.-- c. **Add deployment presets** if detected — Cloudflare Worker, Vercel, Docker, Cloud CLIs.-- d. **Auto-discover MCP servers** — Use `ToolSearch` to find available MCP tools, extract the unique server names from tool names (e.g. `mcp__vault__secret_list` → server is `vault`), and generate `mcp__servername__*` for each. This is necessary because:- - `mcp__*` (single wildcard) does NOT work — wildcard doesn't cross `__` boundary- - `mcp__*__*` (double wildcard) also does NOT work- - Each server must be listed individually: `mcp__vault__*`, `mcp__brain__*`, etc.-- e. **Always include**: `WebSearch`, `WebFetch`-- f. **Always include explicit `gh` subcommands** alongside `Bash(gh *)` — there's a known bug where `Bash(gh *)` doesn't match some subcommands:- ```- "Bash(gh *)",- "Bash(gh repo *)",- "Bash(gh issue *)",- "Bash(gh pr *)",- "Bash(gh api *)",- "Bash(gh search *)",- "Bash(gh run *)",- "Bash(gh release *)",- ```-- g. Write with `//` comment groups for organisation.-- h. Warn the user: **"Project settings.local.json SHADOWS your global settings — it does not merge. A session restart is needed for changes to take effect."**--3. **Generate `CLAUDE.md`**:- - Read [references/claude-md-templates.md](references/claude-md-templates.md) for templates- - Fill in: project name (from directory name or ask), today's date, detected stack- - Pre-fill Jez's defaults (Cloudflare account ID, pnpm, EN-AU)--4. **Generate `.gitignore`**:- - Use the type-appropriate template from [references/claude-md-templates.md](references/claude-md-templates.md)- - Always include `.claude/settings.local.json` and `.dev.vars`--5. **Optionally** (ask first):- - `git init` + first commit- - `gh repo create jezweb/[name] --private` + push--### Mode 2: Tidy Existing Permissions--**When**: User says "tidy permissions", "clean settings", or the existing `settings.local.json` has more than ~50 entries.--**Steps**:--1. Run the tidy script to analyse the current file:- ```bash- python3 ${SKILL_DIR}/scripts/tidy_permissions.py .claude/settings.local.json- ```--2. Review the report. It flags:- - **Leaked secrets**: API keys, tokens, hex strings embedded in approval patterns- - **Shell fragments**: `Bash(do)`, `Bash(fi)`, `Bash(then)`, `Bash(else)`, `Bash(done)`- - **Legacy colon syntax**: `Bash(git:*)` → should be `Bash(git *)`- - **Duplicates**: Entries covered by a broader pattern already present (e.g. `Bash(git add *)` is redundant if `Bash(git *)` exists)- - **One-time entries**: Entire commit messages, hardcoded paths that will never match again- - **Consolidation opportunities**: e.g. 5 separate `Bash(git add:*)`, `Bash(git commit:*)` could become `Bash(git *)`- - **Missing MCP servers**: Compare connected servers vs. what's in the allow list--3. Present the cleaned version with a diff showing what changed.--4. Apply after user confirmation. Recommend the user rotate any leaked secrets.--### Mode 3: Add Preset--**When**: User says "add python permissions", "add MCP permissions", or "add docker permissions" to an existing project.--**Steps**:--1. Read the relevant preset section from [references/permission-presets.md](references/permission-presets.md)-2. Read the existing `.claude/settings.local.json`-3. Merge without duplicating — add new entries, keep existing groups-4. Write the updated file-5. Remind user: **session restart required** for changes to take effect--## MCP Server Auto-Discovery--To discover connected MCP servers, run these ToolSearch queries:--```-ToolSearch("+brain")-ToolSearch("+vault")-ToolSearch("+playwright")-ToolSearch("+gmail")-ToolSearch("+xero")-```--Or search broadly: `ToolSearch("mcp")` and extract unique server prefixes from returned tool names.--Each discovered server gets a wildcard entry: `mcp__servername__*`--## Permission Syntax Quick Reference--| Pattern | Meaning |-|---------|---------|-| `Bash(git *)` | Preferred — space before `*` = word boundary |-| `Bash(nvidia-smi)` | Exact match, no arguments |-| `WebFetch` | Blanket web fetch (all domains) |-| `WebFetch(domain:x.com)` | Domain-scoped web fetch |-| `WebSearch` | Blanket web search |-| `mcp__brain__*` | All tools on one server |-| `mcp__brain__brain_sites` | One specific MCP tool |--### What Does NOT Work--| Pattern | Why |-|---------|-----|-| `mcp__*` | Wildcard doesn't cross `__` boundary |-| `mcp__*__*` | Still doesn't work — segments aren't glob-expanded |-| `Bash(git:*)` | Deprecated colon syntax (still works but prefer space) |--### Important Behaviours--- **Not hot-reloaded**: Edits to `settings.local.json` require a **session restart**-- **"Don't ask again"** injects at runtime (no restart needed) using legacy colon format — this is normal-- **Shadows, not merges**: Project `settings.local.json` completely replaces global allow list-- **Shell safety**: `Bash(git *)` won't match `git add && rm -rf /` — operators are handled safely-- **`gh` bug**: `Bash(gh *)` sometimes doesn't match subcommands — include explicit `Bash(gh issue *)` etc. as workaround--## Autonomy--- **Just do it**: Detect project type, read existing files, auto-discover MCP servers-- **Brief confirmation**: Write settings.local.json, CLAUDE.md, .gitignore (show what will be written)-- **Ask first**: git init, GitHub repo creation, overwriting existing files, applying tidy fixes--## Reference Files--| When | Read |-|------|------|-| Building permission presets | [references/permission-presets.md](references/permission-presets.md) |-| Generating CLAUDE.md and .gitignore | [references/claude-md-templates.md](references/claude-md-templates.md) |diff --git a/plugins/dev-tools/skills/project-kickoff/references/claude-md-templates.md b/plugins/dev-tools/skills/project-kickoff/references/claude-md-templates.mddeleted file mode 100644index bbe9c1b7..00000000--- a/plugins/dev-tools/skills/project-kickoff/references/claude-md-templates.md+++ /dev/null@@ -1,246 +0,0 @@-# CLAUDE.md Templates--Templates for generating project CLAUDE.md files. Each template includes Jez's defaults pre-filled.--## Detection Heuristics--Detect project type from file presence (first match wins, types can stack):--| Indicator | Project Type |-|-----------|-------------|-| `wrangler.jsonc` or `wrangler.toml` | cloudflare-worker |-| `vercel.json` or `next.config.*` | vercel-app |-| `package.json` with no deploy target | node-generic |-| `pyproject.toml` or `setup.py` | python |-| `.claude/agents/` + operational scripts | ops-admin |-------## Cloudflare Worker Template--```markdown-# [Project Name]--**Repository**: https://github.com/jezweb/[repo-name]-**Last Updated**: [date]--## Stack--- Cloudflare Workers + Static Assets-- Vite + React 19 + @cloudflare/vite-plugin-- Tailwind v4 + shadcn/ui (neutral palette)-- D1 (SQLite) + Drizzle ORM-- Hono (API routing)-- pnpm--## Commands--| Command | Purpose |-|---------|---------|-| `pnpm dev` | Local dev server (Vite + Miniflare) |-| `pnpm build` | Production build |-| `pnpm deploy` | Deploy to Cloudflare |-| `pnpm db:migrate:local` | Run D1 migrations locally |-| `pnpm db:migrate:remote` | Run D1 migrations on production |--## Directory Structure--[Fill in after scaffolding]--## Cloudflare--- **Account**: Jezweb Team (`0460574641fdbb98159c98ebf593e2bd`)-- **Compatibility flags**: `nodejs_compat` (never use `node_compat`)-- Always use Workers + Static Assets (never Cloudflare Pages)--## Critical Rules--- Run migrations on BOTH local AND remote before testing-- Set `account_id` in wrangler.jsonc to avoid interactive prompts-- D1 bulk inserts: batch into chunks of ~10 rows (parameter limit)-- `wrangler secret put` does NOT auto-deploy — run `wrangler deploy` after--## Gotchas--[Add as discovered]-```-------## Vercel App Template--```markdown-# [Project Name]--**Repository**: https://github.com/jezweb/[repo-name]-**Last Updated**: [date]--## Stack--- Next.js / Vite + React 19-- Tailwind v4 + shadcn/ui (neutral palette)-- Vercel (Jezweb team account)-- pnpm--## Commands--| Command | Purpose |-|---------|---------|-| `pnpm dev` | Local dev server |-| `pnpm build` | Production build |-| `vercel deploy` | Deploy to Vercel |-| `vercel deploy --prod` | Deploy to production |--## Vercel--- **Team**: jezweb (always use team account)-- Run `vercel switch jezweb` before deploying-- Run `vercel link --yes` to connect project--## Gotchas--[Add as discovered]-```-------## Node Generic Template--```markdown-# [Project Name]--**Repository**: https://github.com/jezweb/[repo-name]-**Last Updated**: [date]--## Stack--- Node.js + TypeScript (ES modules)-- pnpm--## Commands--| Command | Purpose |-|---------|---------|-| `pnpm dev` | Local dev server |-| `pnpm build` | Production build |-| `pnpm test` | Run tests |--## Directory Structure--[Fill in after scaffolding]--## Gotchas--[Add as discovered]-```-------## Python Template--```markdown-# [Project Name]--**Repository**: https://github.com/jezweb/[repo-name]-**Last Updated**: [date]--## Stack--- Python 3.12+-- uv (package management)--## Commands--| Command | Purpose |-|---------|---------|-| `uv run python main.py` | Run the application |-| `uv sync` | Install dependencies |-| `uv run pytest` | Run tests |--## Directory Structure--[Fill in after scaffolding]--## Gotchas--[Add as discovered]-```-------## Ops / Admin Template--```markdown-# [Project Name]--**Repository**: https://github.com/jezweb/[repo-name]-**Last Updated**: [date]--## Purpose--[What this operational project does]--## MCP Servers--This project uses the following MCP integrations:--| Server | Purpose |-|--------|---------|-| Brain | Client/site/contact CRM |-| Vault | Secrets and knowledge store |-| Rocket.net | WordPress hosting management |-| Synergy Wholesale | Domain registration and DNS |-| Gmail (Jez + Anthro) | Email management |-| Google Chat (Jez + Anthro) | Team messaging |-| Google Docs/Sheets | Document management |-| Calendar | Event management |--## Anthro Persona--When communicating with Jezweb staff via Google Chat or email, use the Anthro persona. See `~/Documents/anthro/ANTHRO.md` for full briefing.--## Gotchas--[Add as discovered]-```-------## .gitignore Templates--### Cloudflare Worker / Node--```-node_modules/-.wrangler/-dist/-.dev.vars-*.log-.DS_Store-.env-.env.local-.claude/settings.local.json-```--### Python--```-__pycache__/-*.pyc-.venv/-dist/-*.egg-info/-.env-.env.local-.DS_Store-.claude/settings.local.json-```--### Ops / Admin--```-.DS_Store-.env-.env.local-.claude/settings.local.json-```diff --git a/plugins/dev-tools/skills/project-kickoff/references/permission-presets.md b/plugins/dev-tools/skills/project-kickoff/references/permission-presets.mddeleted file mode 100644index 48c92362..00000000--- a/plugins/dev-tools/skills/project-kickoff/references/permission-presets.md+++ /dev/null@@ -1,408 +0,0 @@-# Permission Presets--Curated permission presets for `settings.local.json`. Each preset is a JSON array of permission strings grouped with `//` comments. Compose presets by stacking: Universal Base + language preset + deployment preset + extras.--## Syntax Reference--| Pattern | Meaning |-|---------|---------|-| `Bash(git *)` | Space before `*` = word boundary. Matches `git status` but not `gitk`. **Preferred syntax.** |-| `Bash(git*)` | No space = prefix match. Matches `git status` AND `gitk`. |-| `Bash(nvidia-smi)` | Exact match — no arguments. Use for bare commands. |-| `WebFetch` | Blanket web fetch (all domains) |-| `WebFetch(domain:example.com)` | Domain-scoped web fetch |-| `WebSearch` | Blanket web search |-| `mcp__brain__*` | All tools on one MCP server |-| `mcp__brain__brain_sites` | One specific MCP tool |--### Format Notes--- **Deprecated**: `Bash(git:*)` colon syntax still works but prefer space syntax `Bash(git *)`-- **"Don't ask again"** prompt uses legacy colon format (e.g. `node:*`) — it's equivalent but looks different-- **Comments**: `"// --- Section ---"` strings in the allow array are ignored and useful for organisation-- **Not hot-reloaded**: Changes to `settings.local.json` require a session restart. "Don't ask again" bypasses this because it injects into the running session directly.--**Critical**: Project `settings.local.json` **SHADOWS** global settings (does not merge). If a project has its own allow list, the global allow list is ignored entirely for that project.--Shell operators (`&&`, `||`, `;`) are handled safely — `Bash(git *)` won't match `git add && rm -rf /`.-------## Universal Base--Every project gets these. Version control, file operations, and basic tools needed for all development.--```json-"// --- Version Control ---",-"Bash(git *)",-"Bash(gh *)",-"Bash(gh repo *)",-"Bash(gh issue *)",-"Bash(gh pr *)",-"Bash(gh api *)",-"Bash(gh search *)",-"Bash(gh run *)",-"Bash(gh release *)",--"// --- File Operations ---",-"Bash(ls *)",-"Bash(cat *)",-"Bash(head *)",-"Bash(tail *)",-"Bash(wc *)",-"Bash(sort *)",-"Bash(mkdir *)",-"Bash(cp *)",-"Bash(mv *)",-"Bash(touch *)",-"Bash(chmod *)",-"Bash(find *)",-"Bash(tree *)",-"Bash(du *)",-"Bash(df *)",--"// --- Archives ---",-"Bash(tar *)",-"Bash(zip *)",-"Bash(unzip *)",-"Bash(gzip *)",--"// --- Text Processing ---",-"Bash(grep *)",-"Bash(rg *)",-"Bash(awk *)",-"Bash(sed *)",-"Bash(diff *)",-"Bash(jq *)",-"Bash(echo *)",-"Bash(printf *)",-"Bash(tee *)",--"// --- System ---",-"Bash(which *)",-"Bash(whereis *)",-"Bash(type *)",-"Bash(ps *)",-"Bash(env *)",-"Bash(date *)",-"Bash(uname *)",-"Bash(make *)",--"// --- Network ---",-"Bash(curl *)",-"Bash(wget *)",-"Bash(ssh *)",-"Bash(scp *)",-"Bash(rsync *)",-"Bash(dig *)",--"// --- Web ---",-"WebSearch",-"WebFetch"-```-------## JavaScript / TypeScript--For any JS/TS project. Add to Universal Base.--```json-"// --- Node.js ---",-"Bash(node *)",-"Bash(npm *)",-"Bash(npx *)",--"// --- Alternative Runtimes ---",-"Bash(bun *)",-"Bash(bunx *)",-"Bash(deno *)",--"// --- Package Managers ---",-"Bash(pnpm *)",-"Bash(yarn *)",--"// --- TypeScript ---",-"Bash(tsc *)",-"Bash(tsx *)",--"// --- Bundlers ---",-"Bash(esbuild *)",-"Bash(vite *)",-"Bash(turbo *)",--"// --- Testing ---",-"Bash(jest *)",-"Bash(vitest *)",-"Bash(playwright *)",-"Bash(cypress *)",--"// --- Linting / Formatting ---",-"Bash(eslint *)",-"Bash(prettier *)",-"Bash(biome *)"-```-------## Python--For Python projects. Add to Universal Base.--```json-"// --- Python Runtime ---",-"Bash(python *)",-"Bash(python3 *)",--"// --- Package Managers ---",-"Bash(pip *)",-"Bash(pip3 *)",-"Bash(uv *)",-"Bash(poetry *)",-"Bash(pipx *)",-"Bash(conda *)",--"// --- Testing / Quality ---",-"Bash(pytest *)",-"Bash(mypy *)",-"Bash(ruff *)",-"Bash(black *)",-"Bash(flake8 *)",-"Bash(isort *)",--"// --- Dev Servers ---",-"Bash(flask *)",-"Bash(uvicorn *)",-"Bash(gunicorn *)",-"Bash(django-admin *)",--"// --- Notebooks ---",-"Bash(jupyter *)"-```-------## PHP--For PHP projects including WordPress and Laravel. Add to Universal Base.--```json-"// --- PHP Runtime ---",-"Bash(php *)",-"Bash(composer *)",--"// --- WordPress ---",-"Bash(wp *)",--"// --- Testing / Quality ---",-"Bash(phpunit *)",-"Bash(phpstan *)",-"Bash(phpcs *)",-"Bash(phpcbf *)",-"Bash(pest *)",--"// --- Laravel ---",-"Bash(artisan *)",-"Bash(sail *)"-```-------## Go--For Go projects. Add to Universal Base.--```json-"// --- Go ---",-"Bash(go *)",-"Bash(golangci-lint *)"-```-------## Rust--For Rust projects. Add to Universal Base.--```json-"// --- Rust ---",-"Bash(cargo *)",-"Bash(rustc *)",-"Bash(rustup *)"-```-------## Ruby--For Ruby / Rails projects. Add to Universal Base.--```json-"// --- Ruby ---",-"Bash(ruby *)",-"Bash(gem *)",-"Bash(bundle *)",-"Bash(bundler *)",-"Bash(rails *)",-"Bash(rake *)",-"Bash(rspec *)"-```-------## Cloudflare Worker--Deployment preset. Add to Universal Base + JavaScript/TypeScript.--```json-"// --- Wrangler ---",-"Bash(wrangler *)",-"Bash(npx wrangler *)"-```-------## Vercel--Deployment preset. Add to Universal Base + JavaScript/TypeScript.--```json-"// --- Vercel ---",-"Bash(vercel *)",-"Bash(npx vercel *)",--"// --- Prisma (common with Vercel) ---",-"Bash(prisma *)",-"Bash(npx prisma *)"-```-------## Docker / Containers--For containerised projects. Add to any stack.--```json-"// --- Docker ---",-"Bash(docker *)",-"Bash(docker-compose *)",--"// --- Kubernetes ---",-"Bash(kubectl *)",-"Bash(helm *)",--"// --- IaC ---",-"Bash(terraform *)",-"Bash(pulumi *)"-```-------## Database--For projects that interact with databases directly. Add to any stack.--```json-"// --- SQL ---",-"Bash(psql *)",-"Bash(mysql *)",-"Bash(sqlite3 *)",--"// --- NoSQL ---",-"Bash(redis-cli *)",-"Bash(mongosh *)"-```-------## Cloud CLIs--For cloud-deployed projects. Add to any stack.--```json-"// --- AWS ---",-"Bash(aws *)",--"// --- Google Cloud ---",-"Bash(gcloud *)",-"Bash(gsutil *)",--"// --- Azure ---",-"Bash(az *)"-```-------## AI / GPU--For AI/ML workloads. Add to any stack.--```json-"// --- Local LLM ---",-"Bash(ollama *)",--"// --- GPU ---",-"Bash(nvidia-smi *)",-"Bash(nvidia-smi)"-```--Note: `Bash(nvidia-smi)` (no wildcard) matches the bare command with no arguments, which is the most common usage.-------## MCP Servers--MCP (Model Context Protocol) servers provide tool access to external services. Permission patterns use the format `mcp__servername__toolname`.--### Per-Server Wildcards (Recommended)--Allow all tools on each MCP server you trust. You must list each server individually — `mcp__*` does NOT work as a blanket (the wildcard only matches within the last segment, not across the `__` boundary).--```json-"mcp__brain__*",-"mcp__playwright__*",-"mcp__vault__*"-```--### Individual Tools--For maximum control, allow specific tools only:--```json-"mcp__brain__brain_sites",-"mcp__brain__brain_recall"-```-------## Combining Presets--Presets stack. Examples:--| Project Type | Presets to Combine |-|-------------|-------------------|-| Next.js on Vercel | Universal + JavaScript/TypeScript + Vercel |-| Cloudflare Worker | Universal + JavaScript/TypeScript + Cloudflare Worker |-| Django app | Universal + Python + Database + Docker |-| WordPress plugin | Universal + PHP |-| Rust CLI | Universal + Rust |-| ML project | Universal + Python + AI/GPU |-| Full-stack ops | Universal + JavaScript/TypeScript + Python + Docker + Database + MCP (blanket) |--When merging, deduplicate and keep the grouped `//` comment structure. The final `settings.local.json` should look like:--```json-{- "permissions": {- "allow": [- "// --- Version Control ---",- "Bash(git *)",- "Bash(gh *)",- "// --- Node.js ---",- "Bash(node *)",- "..."- ],- "deny": []- }-}-```diff --git a/plugins/dev-tools/skills/project-kickoff/scripts/tidy_permissions.py b/plugins/dev-tools/skills/project-kickoff/scripts/tidy_permissions.pydeleted file mode 100755index b9148a5d..00000000--- a/plugins/dev-tools/skills/project-kickoff/scripts/tidy_permissions.py+++ /dev/null@@ -1,285 +0,0 @@-#!/usr/bin/env python3-"""Analyse and tidy a Claude Code settings.local.json permissions file.--Usage:- python3 tidy_permissions.py <path> # Report mode (default)- python3 tidy_permissions.py <path> --fix # Output cleaned JSON- python3 tidy_permissions.py <path> --json # Report as JSON-"""--import json-import re-import sys-from pathlib import Path---# Patterns that indicate leaked secrets-SECRET_PATTERNS = [- r"sk-ant-api\d+-[A-Za-z0-9_-]{20,}", # Anthropic API keys- r"[A-Za-z0-9_-]{32,}", # Long tokens/keys (32+ chars)- r"Bearer [A-Za-z0-9_-]{20,}", # Bearer tokens- r"ANTHROPIC_API_KEY='[^']+", # Explicit key assignments- r"CLOUDFLARE_API_TOKEN=\"[^\"]+", # Cloudflare tokens- r"Authorization: [A-Za-z]+ [A-Za-z0-9_-]{20,}", # Auth headers with tokens-]--# Shell fragments that get accidentally approved-SHELL_FRAGMENTS = {- "Bash(do)", "Bash(done)", "Bash(fi)", "Bash(then)", "Bash(else)",- "Bash(break)", "Bash(if)", "Bash(for)", "Bash(while)",-}--# Deprecated MCP references-DEPRECATED_MCP = [- "mcp__bitwarden__",- "mcp__google-chat__", # Old format (not claude_ai_ prefixed)- "mcp__google-docs__", # Old format- "mcp__google-drive__", # Old format- "mcp__google-sheets__", # Old format- "mcp__gmail__", # Old format (not gmail-jez or gmail-anthro)-]--# Patterns that can be consolidated into broader ones-CONSOLIDATION_MAP = {- "Bash(git *)": [- r"Bash\(git (add|commit|push|pull|fetch|checkout|branch|merge|stash|rm|reset|log|diff|status|remote|revert|mv|check-ignore|ls-tree|merge-tree)",- ],- "Bash(gh *)": [- r"Bash\(gh (repo|issue|pr|api|search|run|release|label|workflow|gist|auth|project)",- ],- "Bash(pnpm *)": [- r"Bash\(pnpm (install|add|remove|build|dev|test|deploy|list|ls|why|run|exec|update|audit|tsc|vitest|dlx|--filter)",- ],- "Bash(npm *)": [- r"Bash\(npm (install|run|view|audit|init|info|ls)",- ],- "Bash(npx *)": [- r"Bash\(npx (wrangler|vercel|tsc|tsx|prettier|vitest|shadcn|prisma|vite)",- ],-}---def strip_json_comments(text: str) -> str:- """Remove // comments from JSON (Claude Code JSON5-style)."""- lines = text.split("\n")- cleaned = []- for line in lines:- stripped = line.strip()- # Keep lines that are comment-only strings in arrays (like "// --- Git ---")- if stripped.startswith('"//'):- cleaned.append(line)- else:- # Remove inline comments (not inside strings)- cleaned.append(line)- return "\n".join(cleaned)---def load_settings(path: Path) -> dict:- """Load settings.local.json, handling // comments."""- text = path.read_text()- # Try parsing as-is first- try:- return json.loads(text)- except json.JSONDecodeError:- pass- # Strip comments and retry- cleaned = strip_json_comments(text)- return json.loads(cleaned)---def check_secrets(entry: str) -> bool:- """Check if a permission entry contains a suspected secret."""- # MCP tool names and WebFetch/WebSearch/Skill entries aren't secrets- if entry.startswith(("mcp__", "WebFetch", "WebSearch", "Skill")):- return False- # Only check Bash entries and other patterns- for pattern in SECRET_PATTERNS:- if re.search(pattern, entry):- return True- return False---def check_shell_fragment(entry: str) -> bool:- """Check if an entry is a shell fragment."""- return entry in SHELL_FRAGMENTS or entry.startswith("Bash(__NEW_LINE_")---def check_deprecated_mcp(entry: str) -> bool:- """Check if an entry references a deprecated MCP server."""- for prefix in DEPRECATED_MCP:- if entry.startswith(prefix):- return True- return False---def check_one_time(entry: str) -> bool:- """Check if an entry looks like a one-time command that won't match again."""- # Entries with embedded commit messages- if "EOF" in entry and "git commit" in entry:- return True- # Entries with hardcoded absolute paths to specific files- if re.search(r"Bash\(git -C /[^\s]+", entry):- return True- # Entries with hardcoded for-loop values- if entry.startswith("Bash(for ") and "in " in entry:- return True- # Entries with specific file copies- if "cp " in entry and "/" in entry and entry.count("/") > 3:- return True- return False---def find_consolidations(entries: list[str]) -> dict[str, list[str]]:- """Find entries that could be consolidated into broader patterns."""- consolidations = {}- for broad, patterns in CONSOLIDATION_MAP.items():- # Skip if the broad pattern already exists- if broad in entries:- continue- matches = []- for entry in entries:- for pattern in patterns:- if re.match(pattern, entry):- matches.append(entry)- break- if len(matches) >= 2:- consolidations[broad] = matches- return consolidations---def find_duplicates(entries: list[str]) -> list[str]:- """Find duplicate entries."""- seen = set()- dupes = []- for entry in entries:- if entry in seen:- dupes.append(entry)- seen.add(entry)- return dupes---def analyse(settings: dict) -> dict:- """Analyse permissions and return a report."""- entries = settings.get("permissions", {}).get("allow", [])-- # Filter out comment strings- real_entries = [e for e in entries if not e.startswith("//")]- comments = [e for e in entries if e.startswith("//")]-- report = {- "total_entries": len(real_entries),- "comment_lines": len(comments),- "secrets": [e for e in real_entries if check_secrets(e)],- "shell_fragments": [e for e in real_entries if check_shell_fragment(e)],- "deprecated_mcp": [e for e in real_entries if check_deprecated_mcp(e)],- "one_time": [e for e in real_entries if check_one_time(e)],- "duplicates": find_duplicates(real_entries),- "consolidations": find_consolidations(real_entries),- }-- issues = (- len(report["secrets"])- + len(report["shell_fragments"])- + len(report["deprecated_mcp"])- + len(report["one_time"])- + len(report["duplicates"])- )- report["total_issues"] = issues- report["consolidation_count"] = sum(- len(v) for v in report["consolidations"].values()- )-- return report---def print_report(report: dict, path: str) -> None:- """Print human-readable report."""- print(f"\n=== Permission Tidy Report: {path} ===\n")- print(f"Total entries: {report['total_entries']} ({report['comment_lines']} comment lines)")- print(f"Issues found: {report['total_issues']}")- print(f"Consolidation opportunities: {report['consolidation_count']} entries -> {len(report['consolidations'])} broad patterns")- print()-- if report["secrets"]:- print(f"LEAKED SECRETS ({len(report['secrets'])}):")- for s in report["secrets"]:- # Truncate to avoid printing full secrets- display = s[:60] + "..." if len(s) > 60 else s- print(f" - {display}")- print()-- if report["shell_fragments"]:- print(f"Shell fragments ({len(report['shell_fragments'])}):")- for s in report["shell_fragments"]:- print(f" - {s}")- print()-- if report["deprecated_mcp"]:- print(f"Deprecated MCP refs ({len(report['deprecated_mcp'])}):")- for s in report["deprecated_mcp"]:- print(f" - {s}")- print()-- if report["one_time"]:- print(f"One-time entries ({len(report['one_time'])}):")- for s in report["one_time"]:- display = s[:80] + "..." if len(s) > 80 else s- print(f" - {display}")- print()-- if report["duplicates"]:- print(f"Duplicates ({len(report['duplicates'])}):")- for s in report["duplicates"]:- print(f" - {s}")- print()-- if report["consolidations"]:- print("Consolidation opportunities:")- for broad, specifics in report["consolidations"].items():- print(f" {broad} would replace {len(specifics)} entries:")- for s in specifics[:5]:- print(f" - {s}")- if len(specifics) > 5:- print(f" ... and {len(specifics) - 5} more")- print()---def main():- if len(sys.argv) < 2:- print(__doc__)- sys.exit(1)-- path = Path(sys.argv[1])- if not path.exists():- print(f"Error: {path} not found")- sys.exit(1)-- mode = sys.argv[2] if len(sys.argv) > 2 else "--report"-- settings = load_settings(path)- report = analyse(settings)-- if mode == "--json":- # Don't include full secret values in JSON output- safe_report = report.copy()- safe_report["secrets"] = [s[:40] + "..." for s in report["secrets"]]- print(json.dumps(safe_report, indent=2))- elif mode == "--fix":- # Output a cleaned version- entries = settings.get("permissions", {}).get("allow", [])- remove = set()- remove.update(report["secrets"])- remove.update(report["shell_fragments"])- remove.update(report["deprecated_mcp"])- remove.update(report["one_time"])- remove.update(report["duplicates"])-- cleaned = [e for e in entries if e not in remove]- settings["permissions"]["allow"] = cleaned- print(json.dumps(settings, indent=2))- else:- print_report(report, str(path))---if __name__ == "__main__":- main()