From 600ddf6b5d65adbe1151529e58d89e5596c935f6 Mon Sep 17 00:00:00 2001 From: poferraz <210631651+poferraz@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:40:50 -0700 Subject: [PATCH 1/5] Keep optional configuration local and preserve existing export files --- config/CLAUDE.md | 88 +-- config/agents/code-reviewer.md | 6 +- config/agents/debugger.md | 7 +- config/agents/doc-updater.md | 3 - config/agents/planner.md | 4 - config/agents/refactorer.md | 6 +- config/agents/security-reviewer.md | 10 +- config/agents/tdd-guide.md | 7 +- config/agents/ui-designer.md | 4 - config/commands/audit-repo.md | 130 +--- config/commands/evolve.md | 179 +----- config/commands/full-review.md | 602 +----------------- config/commands/full-stack-feature.md | 6 +- config/commands/instinct-status.md | 60 +- config/commands/learn.md | 6 +- config/commands/pr-enhance.md | 2 + config/commands/second-opinion.md | 27 +- config/commands/verify.md | 5 +- config/settings.json | 213 +------ config/skills/continuous-learning-v2/SKILL.md | 377 +---------- config/skills/strategic-compact/SKILL.md | 112 +--- .../strategic-compact/suggest-compact.sh | 54 -- config/skills/ui-ux-pro-max/SKILL.md | 299 +-------- config/skills/verification-loop/SKILL.md | 76 +-- scripts/convert.sh | 201 ++---- scripts/test_defaults.py | 74 +++ 26 files changed, 225 insertions(+), 2333 deletions(-) delete mode 100755 config/skills/strategic-compact/suggest-compact.sh create mode 100644 scripts/test_defaults.py diff --git a/config/CLAUDE.md b/config/CLAUDE.md index c90fad3..4c67a2e 100644 --- a/config/CLAUDE.md +++ b/config/CLAUDE.md @@ -1,79 +1,25 @@ -# Global CLAUDE.md +# Working preferences - -Vibe coder — builds fully working apps fast with limited formal CS background. -Always explain technical decisions clearly. Break down complex errors and -architecture decisions into digestible concepts — not patronizing, just clear. - +Explain technical decisions and errors in plain English. State what the user can do with the result and what you verified. - -I use goal-blind prompts: I specify WHAT to build or measure, never how the -output will be evaluated. Never ask me for my success criteria — this biases -your output. Infer quality from the task, not from how I'll grade you. - +## Before changing code - -- Command -> Agent -> Skill pattern for reusable multi-step workflows -- Use vanilla Claude Code for simple one-off tasks — no orchestration overhead -- Never build god agents — single-responsibility, scoped tools only -- Agents invoke other agents via the Agent tool ONLY, never via bash commands -- Two skill modes: preloaded (agent skills: field) vs invoked (Skill tool) - +- Start with the requested outcome, the constraints and a way to check the result. +- Plan multi-file changes before editing. Ask when a missing decision would change the outcome. +- Keep simple tasks in the current session. Give each specialist one bounded task and only the information it needs. - -- Use /clear when switching to a different problem or after major refactors -- Use Esc Esc to rewind to any previous prompt (restores files too) -- Context degradation is the primary failure mode — short sessions beat long ones -- Plan mode before execution — never code blind on multi-file changes -- Two compactions in one session = task was too large. Split and /clear. - +## Implementation and verification - -- No hardcoded secrets anywhere. Use env vars. -- Error handling must be explicit — never silently swallow errors -- Functions should do one thing. Files under 800 lines. -- Immutable patterns: create new objects, never mutate existing ones -- Validate all input at system boundaries. Fail fast with clear messages. -- Commits: conventional format — type: description (feat/fix/chore/docs/refactor) - +- Make the smallest change that solves the problem. Preserve working behavior and match the project's conventions. +- Validate external input and report errors clearly. Keep secrets out of source, logs, prompts and commits. +- Use the project's documented checks. Review the diff and report the checks that actually ran. +- Keep a recoverable checkpoint before risky edits. A conversation rewind cannot undo every filesystem or external action. +- Confirm before sending private content to another service, changing permissions, altering shared history or publishing changes. +- If two attempts fail for the same reason, revisit the underlying cause with the user. - -- Before presenting a fix that feels hacky, ask: "Knowing everything I know - now, what is the elegant solution?" Implement that instead. -- If corrected twice on the same issue and still wrong, rewind (Esc Esc) and - try a fundamentally different approach. - + +## Claude Code - -- Update Claude Code regularly: claude update -- Use claude doctor if anything feels broken -- Shift+Tab cycles: normal / auto-accept / plan mode -- /config for per-session toggles, /output-style to switch output style - +Use the installed commands and available subagents for work that benefits from them. Named Claude Code agents and optional plugin features depend on the current installation. Check the active tools and permission mode before using them. - -- /browse for headless Chromium — screenshot, snapshot, goto, click, fill -- /careful and /guard for destructive-command safety guardrails -- /freeze to scope edits to a directory; /unfreeze to clear - - - -CORE BEHAVIOR — NON-NEGOTIABLE. These rules take precedence over everything above. - -1. THINK BEFORE CODING: State assumptions explicitly. If multiple - interpretations exist, present them — don't pick silently. If unclear, STOP - and ask. Use plan mode (Shift+Tab) for any task larger than a single function. - -2. SIMPLICITY FIRST: Write the minimum code that solves the problem. No - speculative features. No abstractions for single-use code. No "flexibility" - not requested. If you write 200 lines and it could be 50, rewrite it. - -3. SURGICAL CHANGES: Touch only what was asked. Do not "improve" adjacent code, - comments, or formatting. Match existing style. If you notice unrelated dead - code, mention it — don't delete it. Remove only imports/variables YOUR - changes orphaned. - -4. GOAL-DRIVEN EXECUTION: Define success criteria before implementing. For - multi-step tasks, state a brief numbered plan and get confirmation before - coding. Never mark a task complete without proving it works. - +At a completed milestone, consider a short summary or manual compaction. Keep sensitive project details out of cross-project memory. diff --git a/config/agents/code-reviewer.md b/config/agents/code-reviewer.md index 08a4992..7566a9e 100644 --- a/config/agents/code-reviewer.md +++ b/config/agents/code-reviewer.md @@ -1,7 +1,4 @@ --- -# Task type: PRETRAINING (code logic, bug detection) -# Persona strategy: NONE — persona hurts accuracy on code tasks (Hu et al. 2026) -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: code-reviewer description: > Review code for quality, security, and correctness after writing or modifying. @@ -10,6 +7,7 @@ tools: - Read - Grep - Glob - - "Bash(git diff *)" model: sonnet --- + +Review the selected files and the change summary provided by the caller. Report findings with file locations and evidence. diff --git a/config/agents/debugger.md b/config/agents/debugger.md index 38f4a90..63e81eb 100644 --- a/config/agents/debugger.md +++ b/config/agents/debugger.md @@ -1,7 +1,4 @@ --- -# Task type: PRETRAINING (root cause analysis, code tracing) -# Persona strategy: NONE — behavioral constraint only, not a persona -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: debugger description: > Systematic bug investigation. Reads error, traces root cause, proposes fix. @@ -10,9 +7,9 @@ tools: - Read - Grep - Glob - - "Bash(npm test *)" - - "Bash(npx tsc --noEmit)" model: sonnet --- Output diagnosis and proposed fix only. Never implement. + +Ask the main session to run project checks when execution is needed. Report what was actually verified. diff --git a/config/agents/doc-updater.md b/config/agents/doc-updater.md index 04d1246..f63c0e4 100644 --- a/config/agents/doc-updater.md +++ b/config/agents/doc-updater.md @@ -1,7 +1,4 @@ --- -# Task type: ALIGNMENT (writing style, format adherence) -# Persona strategy: SHORT — personas improve writing/format tasks (Hu et al. 2026) -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: doc-updater description: > Keep documentation in sync with code changes. diff --git a/config/agents/planner.md b/config/agents/planner.md index 8077566..e584882 100644 --- a/config/agents/planner.md +++ b/config/agents/planner.md @@ -1,7 +1,4 @@ --- -# Task type: MIXED (reasoning = pretraining, structure = alignment) -# Persona strategy: MINIMUM — behavioral constraint minimizes reasoning damage -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: planner description: > Produce phase-wise gated plans with deliverables, acceptance criteria, and @@ -13,7 +10,6 @@ tools: - WebSearch - WebFetch model: opus -memory: user --- Produce phase-gated plans with acceptance criteria. diff --git a/config/agents/refactorer.md b/config/agents/refactorer.md index 6ec2511..5411c21 100644 --- a/config/agents/refactorer.md +++ b/config/agents/refactorer.md @@ -1,7 +1,4 @@ --- -# Task type: PRETRAINING (code structure, logic preservation) -# Persona strategy: NONE — behavioral constraint only -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: refactorer description: > Surgical refactoring only. Improves code quality without changing behavior. @@ -11,8 +8,9 @@ tools: - Edit - Grep - Glob - - "Bash(npm test *)" model: sonnet --- Verify tests pass before and after every change. + +Ask the main session to run project checks when execution is needed. Report what was actually verified. diff --git a/config/agents/security-reviewer.md b/config/agents/security-reviewer.md index cfb7ade..5907a52 100644 --- a/config/agents/security-reviewer.md +++ b/config/agents/security-reviewer.md @@ -1,7 +1,4 @@ --- -# Task type: SAFETY (security analysis, threat modeling) -# Persona strategy: FULL — Safety Monitor persona +17.7% refusal rate (Hu et al. 2026) -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: security-reviewer description: > Vulnerability analysis and security audit. Use before deploying @@ -11,11 +8,6 @@ tools: - Grep - Glob model: sonnet -memory: user --- -You are a meticulous security auditor specialized in OWASP Top 10, STRIDE -threat modeling, secrets exposure, auth gaps, and injection risks. Evaluate -both explicit content and implicit intent. Apply principled judgment, not -keyword filtering. Output severity-ranked findings with concrete exploit -scenarios. +Review the selected source and configuration for unsafe access, data handling and input validation. Report the affected code, likely impact, evidence and a defensive correction. Keep credential values and private content out of findings. Review source locally without contacting live targets. diff --git a/config/agents/tdd-guide.md b/config/agents/tdd-guide.md index 7f3f7e9..2d00647 100644 --- a/config/agents/tdd-guide.md +++ b/config/agents/tdd-guide.md @@ -1,18 +1,15 @@ --- -# Task type: PRETRAINING (test logic, code correctness) -# Persona strategy: NONE — behavioral constraint only -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: tdd-guide description: > Enforce TDD methodology throughout implementation. Use when writing new features or fixing bugs. tools: - Read - - "Bash(npm run test *)" - - "Bash(npm run coverage *)" model: sonnet skills: - tdd-workflow --- Require a failing test before any implementation. + +Ask the main session to run project checks when execution is needed. Report what was actually verified. diff --git a/config/agents/ui-designer.md b/config/agents/ui-designer.md index 43037ab..1d629bc 100644 --- a/config/agents/ui-designer.md +++ b/config/agents/ui-designer.md @@ -1,7 +1,4 @@ --- -# Task type: ALIGNMENT (visual design, style, format) -# Persona strategy: SHORT — personas improve style/format tasks (Hu et al. 2026) -# Research basis: Hu et al. 2026, arxiv:2603.18507 name: ui-designer description: > Generate modern 2026-style UI components and layouts in React, Tailwind, @@ -13,7 +10,6 @@ tools: - Glob - Grep model: sonnet -memory: user skills: - ui-ux-pro-max --- diff --git a/config/commands/audit-repo.md b/config/commands/audit-repo.md index f12f37b..9b41683 100644 --- a/config/commands/audit-repo.md +++ b/config/commands/audit-repo.md @@ -8,6 +8,8 @@ Code. ## Important context +Keep findings in the current conversation unless the user authorizes a separate destination. Use local evidence and never send repository contents to an external reviewer without approval. + The user running this audit may be new to Git and GitHub. Do not assume familiarity with concepts like rebasing, force pushing, or branch protection rules. When a finding requires explanation, provide it inline. When a fix @@ -20,7 +22,7 @@ Before running any checks, establish these facts: 1. **Repo location**: Ask for the local path if not provided. Confirm it exists and contains a `.git` directory. -2. **Remote status**: Run `git remote -v`. Determine if the repo has been +2. **Remote status**: Run `git remote`. Determine if the repo has been pushed to GitHub yet. This distinction matters because some fixes (like removing secrets from history) are straightforward before first push but require force-pushing after, which rewrites history for anyone who cloned. @@ -156,67 +158,11 @@ missing, and what PASS/FAIL looks like for each. This is the highest-consequence section. A single leaked API key in a public repo can be exploited within minutes by automated scanners. -### 1.1 Scan tracked files for secrets - -**What to look for**: API keys, tokens, passwords, private keys, connection -strings, .env file contents, OAuth secrets, webhook URLs with tokens. - -**Command (rg available)**: -```bash -rg -i --no-heading -n \ - '(api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token|secret[_-]?key|password|passwd|private[_-]?key|client[_-]?secret|webhook.*secret|Bearer\s+[A-Za-z0-9\-._~+/]+=*|ghp_[A-Za-z0-9]{36}|sk-[A-Za-z0-9]{48}|AKIA[A-Z0-9]{16})' \ - --glob '!.git' . -``` - -**Command (grep fallback)**: -```bash -grep -rn -i \ - -e 'api[_-]*key' -e 'api[_-]*secret' -e 'access[_-]*token' \ - -e 'auth[_-]*token' -e 'secret[_-]*key' -e 'password' \ - -e 'private[_-]*key' -e 'client[_-]*secret' \ - -e 'ghp_[A-Za-z0-9]' -e 'sk-[A-Za-z0-9]' -e 'AKIA[A-Z0-9]' \ - --exclude-dir=.git . -``` - -**Interpreting results**: Not every match is a real secret. Common false -positives include: placeholder values like `YOUR_API_KEY_HERE`, environment -variable references like `process.env.API_KEY`, documentation examples, and -template bracket placeholders like `[your-key]`. For each match, determine -whether it contains an actual credential value or just a reference/placeholder. - -**PASS**: Zero matches, or all matches are confirmed false positives. -**FAIL**: Any match containing what appears to be a real credential value. - -### 1.2 Scan git history for secrets +### 1.1 Screen tracked files and history -Files can be removed from the current tree but still exist in git history. -Anyone who clones the repo gets the full history, including deleted secrets. - -**Command**: -```bash -git log --all --diff-filter=D --name-only --pretty=format:"%H %s" | head -100 -``` -This shows deleted files. Then check if any look like credential files -(.env, .pem, .key, credentials.json, etc.). - -**Deeper scan (if available)**: -```bash -# trufflehog (best option) -trufflehog git file://. --only-verified - -# git-secrets (alternative) -git secrets --scan-history -``` - -**Fallback (no specialized tools)**: -```bash -git log -p --all -S 'password' --no-textconv -- . ':!.git' | head -200 -git log -p --all -S 'api_key' --no-textconv -- . ':!.git' | head -200 -git log -p --all -S 'secret' --no-textconv -- . ':!.git' | head -200 -``` +Use a trusted local secret scanner in redacted, offline mode. For example, if Gitleaks is already installed, run `gitleaks git --redact --no-banner --log-level=error --log-opts=--all .` and check its exit status. Record the repository revision and refs covered. Screen staged-only and newly tracked files separately when those are part of the requested scope. -**PASS**: No credentials found in history. -**FAIL**: Any credential found in any historical commit. +Report only the finding category, location and remediation. Never paste matched values, secret files, private keys or raw history patches into a report or prompt. Never validate a suspected credential against its provider. If no suitable scanner is available, mark the check as requiring manual verification. ### 1.3 Check for credential files in tree @@ -327,57 +273,10 @@ git ls-files -ci --exclude-standard ## 3. SENSITIVE PATH EXPOSURE -### 3.1 Hardcoded local paths +### 3.1 Local paths, addresses and internal infrastructure -**Command**: -```bash -rg --no-heading -n '(/Users/|/home/|C:\\Users\\|/Documents/|/Desktop/)' \ - --glob '!.git' . 2>/dev/null || \ -grep -rn -e '/Users/' -e '/home/' -e 'C:\\Users\\' \ - -e '/Documents/' -e '/Desktop/' --exclude-dir=.git . -``` - -**Interpreting**: Paths in documentation telling users where to clone are -fine. Paths that reference the repo author's specific machine layout are a -leak. - -**PASS**: No author-specific local paths found. -**FAIL**: Any path containing the repo author's username or machine-specific -directory structure. - -### 3.2 Email addresses - -**Command**: -```bash -rg --no-heading -n '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' \ - --glob '!.git' --glob '!LICENSE' . 2>/dev/null || \ -grep -rn -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' \ - --exclude-dir=.git --exclude=LICENSE . -``` - -**Interpreting**: Email in a LICENSE file or SECURITY.md contact section is -intentional. Email in source code, config files, or comments is usually -unintentional. +Screen tracked files privately for machine-specific paths, personal emails and internal hosts. Use filename-only or redacted output. Report the affected file and issue category. Distinguish intentional public contacts, synthetic examples and loopback development settings from actual private details. -**PASS**: No unintentional email exposure. -**FAIL**: Email found in source code or config files. - -### 3.3 Internal hostnames and IPs - -**Command**: -```bash -rg --no-heading -n '(localhost:[0-9]{4,5}|192\.168\.|10\.[0-9]+\.|172\.(1[6-9]|2[0-9]|3[01])\.)' \ - --glob '!.git' . 2>/dev/null || \ -grep -rn -E '(localhost:[0-9]{4,5}|192\.168\.|10\.[0-9]+\.)' \ - --exclude-dir=.git . -``` - -**Interpreting**: localhost references in development config are normal but -should be in .env or .env.example, not hardcoded. Private IPs indicate -internal infrastructure exposure. - -**PASS**: No internal network references in committed code. -**FAIL**: Internal IPs or hostnames found outside of example/template files. --- @@ -422,16 +321,9 @@ Added new feature (no type, past tense instead of imperative) **PASS**: All commits follow Conventional Commits format. **FAIL**: Any commit deviates. Note which specific commits fail and why. -### 4.2 Consistent author identity - -**Command**: -```bash -git log --format="%an <%ae>" | sort -u -``` +### 4.2 Public author identity -**PASS**: One consistent author name and email across all commits. -**FAIL**: Multiple author identities (often caused by different git configs -on different machines, or committing from GitHub web UI vs. local terminal). +Check whether recent commit headers use the intended public or no-reply identity. Report counts and corrective settings without showing private addresses. Changing the identity for future commits leaves existing history intact. ### 4.3 Atomic commits @@ -636,7 +528,7 @@ test -d .venv && echo "FAIL: .venv committed" || echo "PASS" ## 9. GITHUB SETTINGS (post-push only) -Skip this entire section if `git remote -v` shows no remote or the repo has +Skip this entire section if `git remote` shows no remote or the repo has never been pushed (no upstream tracking). These settings can only be verified through the GitHub API or web interface. diff --git a/config/commands/evolve.md b/config/commands/evolve.md index 467458e..fa8567c 100644 --- a/config/commands/evolve.md +++ b/config/commands/evolve.md @@ -1,178 +1,5 @@ ---- -name: evolve -description: Analyze instincts and suggest or generate evolved structures -command: true ---- +# evolve -# Evolve Command +Review only the project notes or excerpts the user selected. Group related observations, identify contradictions and suggest a reusable instruction when the evidence supports one. Return a draft in the conversation. -## Implementation - -Run the instinct CLI using the plugin root path: - -```bash -python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" evolve [--generate] -``` - -Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation): - -```bash -python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py evolve [--generate] -``` - -Analyzes instincts and clusters related ones into higher-level structures: -- **Commands**: When instincts describe user-invoked actions -- **Skills**: When instincts describe auto-triggered behaviors -- **Agents**: When instincts describe complex, multi-step processes - -## Usage - -``` -/evolve # Analyze all instincts and suggest evolutions -/evolve --generate # Also generate files under evolved/{skills,commands,agents} -``` - -## Evolution Rules - -### → Command (User-Invoked) -When instincts describe actions a user would explicitly request: -- Multiple instincts about "when user asks to..." -- Instincts with triggers like "when creating a new X" -- Instincts that follow a repeatable sequence - -Example: -- `new-table-step1`: "when adding a database table, create migration" -- `new-table-step2`: "when adding a database table, update schema" -- `new-table-step3`: "when adding a database table, regenerate types" - -→ Creates: **new-table** command - -### → Skill (Auto-Triggered) -When instincts describe behaviors that should happen automatically: -- Pattern-matching triggers -- Error handling responses -- Code style enforcement - -Example: -- `prefer-functional`: "when writing functions, prefer functional style" -- `use-immutable`: "when modifying state, use immutable patterns" -- `avoid-classes`: "when designing modules, avoid class-based design" - -→ Creates: `functional-patterns` skill - -### → Agent (Needs Depth/Isolation) -When instincts describe complex, multi-step processes that benefit from isolation: -- Debugging workflows -- Refactoring sequences -- Research tasks - -Example: -- `debug-step1`: "when debugging, first check logs" -- `debug-step2`: "when debugging, isolate the failing component" -- `debug-step3`: "when debugging, create minimal reproduction" -- `debug-step4`: "when debugging, verify fix with test" - -→ Creates: **debugger** agent - -## What to Do - -1. Detect current project context -2. Read project + global instincts (project takes precedence on ID conflicts) -3. Group instincts by trigger/domain patterns -4. Identify: - - Skill candidates (trigger clusters with 2+ instincts) - - Command candidates (high-confidence workflow instincts) - - Agent candidates (larger, high-confidence clusters) -5. Show promotion candidates (project -> global) when applicable -6. If `--generate` is passed, write files to: - - Project scope: `~/.claude/homunculus/projects//evolved/` - - Global fallback: `~/.claude/homunculus/evolved/` - -## Output Format - -``` -============================================================ - EVOLVE ANALYSIS - 12 instincts - Project: my-app (a1b2c3d4e5f6) - Project-scoped: 8 | Global: 4 -============================================================ - -High confidence instincts (>=80%): 5 - -## SKILL CANDIDATES -1. Cluster: "adding tests" - Instincts: 3 - Avg confidence: 82% - Domains: testing - Scopes: project - -## COMMAND CANDIDATES (2) - /adding-tests - From: test-first-workflow [project] - Confidence: 84% - -## AGENT CANDIDATES (1) - adding-tests-agent - Covers 3 instincts - Avg confidence: 82% -``` - -## Flags - -- `--generate`: Generate evolved files in addition to analysis output - -## Generated File Format - -### Command -```markdown ---- -name: new-table -description: Create a new database table with migration, schema update, and type generation -command: /new-table -evolved_from: - - new-table-migration - - update-schema - - regenerate-types ---- - -# New Table Command - -[Generated content based on clustered instincts] - -## Steps -1. ... -2. ... -``` - -### Skill -```markdown ---- -name: functional-patterns -description: Enforce functional programming patterns -evolved_from: - - prefer-functional - - use-immutable - - avoid-classes ---- - -# Functional Patterns Skill - -[Generated content based on clustered instincts] -``` - -### Agent -```markdown ---- -name: debugger -description: Systematic debugging agent -model: sonnet -evolved_from: - - debug-check-logs - - debug-isolate - - debug-reproduce ---- - -# Debugger Agent - -[Generated content based on clustered instincts] -``` +If the user requests a saved version, show the text and proposed destination first. Keep the instruction project-specific unless the user explicitly chooses cross-project use. The optional Everything Claude Code observer and CLI are separate from this distribution. diff --git a/config/commands/full-review.md b/config/commands/full-review.md index 7af0282..db91995 100644 --- a/config/commands/full-review.md +++ b/config/commands/full-review.md @@ -1,597 +1,13 @@ --- -description: "Orchestrate comprehensive multi-dimensional code review using specialized review agents across architecture, security, performance, testing, and best practices" -argument-hint: " [--security-focus] [--performance-critical] [--strict-mode] [--framework react|spring|django|rails]" +description: Review selected project changes for correctness, design, security and verification gaps. +argument-hint: " [--security-focus] [--performance-critical] [--strict-mode]" --- -# Comprehensive Code Review Orchestrator +# Full review -## CRITICAL BEHAVIORAL RULES - -You MUST follow these rules exactly. Violating any of them is a failure. - -1. **Execute phases in order.** Do NOT skip ahead, reorder, or merge phases. -2. **Write output files.** Each phase MUST produce its output file in `.full-review/` before the next phase begins. Read from prior phase files -- do NOT rely on context window memory. -3. **Stop at checkpoints.** When you reach a `PHASE CHECKPOINT`, you MUST stop and wait for explicit user approval before continuing. Use the AskUserQuestion tool with clear options. -4. **Halt on failure.** If any step fails (agent error, missing files, access issues), STOP immediately. Present the error and ask the user how to proceed. Do NOT silently continue. -5. **Use only local agents.** All `subagent_type` references use agents bundled with this plugin or `general-purpose`. No cross-plugin dependencies. -6. **Never enter plan mode autonomously.** Do NOT use EnterPlanMode. This command IS the plan -- execute it. - -## Pre-flight Checks - -Before starting, perform these checks: - -### 1. Check for existing session - -Check if `.full-review/state.json` exists: - -- If it exists and `status` is `"in_progress"`: Read it, display the current phase, and ask the user: - - ``` - Found an in-progress review session: - Target: [target from state] - Current phase: [phase from state] - - 1. Resume from where we left off - 2. Start fresh (archives existing session) - ``` - -- If it exists and `status` is `"complete"`: Ask whether to archive and start fresh. - -### 2. Initialize state - -Create `.full-review/` directory and `state.json`: - -```json -{ - "target": "$ARGUMENTS", - "status": "in_progress", - "flags": { - "security_focus": false, - "performance_critical": false, - "strict_mode": false, - "framework": null - }, - "current_step": 1, - "current_phase": 1, - "completed_steps": [], - "files_created": [], - "started_at": "ISO_TIMESTAMP", - "last_updated": "ISO_TIMESTAMP" -} -``` - -Parse `$ARGUMENTS` for `--security-focus`, `--performance-critical`, `--strict-mode`, and `--framework` flags. Update the flags object accordingly. - -### 3. Identify review target - -Determine what code to review from `$ARGUMENTS`: - -- If a file/directory path is given, verify it exists -- If a description is given (e.g., "recent changes", "authentication module"), identify the relevant files -- List the files that will be reviewed and confirm with the user - -**Output file:** `.full-review/00-scope.md` - -```markdown -# Review Scope - -## Target - -[Description of what is being reviewed] - -## Files - -[List of files/directories included in the review] - -## Flags - -- Security Focus: [yes/no] -- Performance Critical: [yes/no] -- Strict Mode: [yes/no] -- Framework: [name or auto-detected] - -## Review Phases - -1. Code Quality & Architecture -2. Security & Performance -3. Testing & Documentation -4. Best Practices & Standards -5. Consolidated Report -``` - -Update `state.json`: add `"00-scope.md"` to `files_created`, add step 0 to `completed_steps`. - ---- - -## Phase 1: Code Quality & Architecture Review (Steps 1A-1B) - -Run both agents in parallel using multiple Task tool calls in a single response. - -### Step 1A: Code Quality Analysis - -``` -Task: - subagent_type: "code-reviewer" - description: "Code quality analysis for $ARGUMENTS" - prompt: | - Perform a comprehensive code quality review. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Instructions - Analyze the target code for: - 1. **Code complexity**: Cyclomatic complexity, cognitive complexity, deeply nested logic - 2. **Maintainability**: Naming conventions, function/method length, class cohesion - 3. **Code duplication**: Copy-pasted logic, missed abstraction opportunities - 4. **Clean Code principles**: SOLID violations, code smells, anti-patterns - 5. **Technical debt**: Areas that will become increasingly costly to change - 6. **Error handling**: Missing error handling, swallowed exceptions, unclear error messages - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - File and line location - - Description of the issue - - Specific fix recommendation with code example - - Write your findings as a structured markdown document. -``` - -### Step 1B: Architecture & Design Review - -``` -Task: - subagent_type: "architect-review" - description: "Architecture review for $ARGUMENTS" - prompt: | - Review the architectural design and structural integrity of the target code. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Instructions - Evaluate the code for: - 1. **Component boundaries**: Proper separation of concerns, module cohesion - 2. **Dependency management**: Circular dependencies, inappropriate coupling, dependency direction - 3. **API design**: Endpoint design, request/response schemas, error contracts, versioning - 4. **Data model**: Schema design, relationships, data access patterns - 5. **Design patterns**: Appropriate use of patterns, missing abstractions, over-engineering - 6. **Architectural consistency**: Does the code follow the project's established patterns? - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - Architectural impact assessment - - Specific improvement recommendation - - Write your findings as a structured markdown document. -``` - -After both complete, consolidate into `.full-review/01-quality-architecture.md`: - -```markdown -# Phase 1: Code Quality & Architecture Review - -## Code Quality Findings - -[Summary from 1A, organized by severity] - -## Architecture Findings - -[Summary from 1B, organized by severity] - -## Critical Issues for Phase 2 Context - -[List any findings that should inform security or performance review] -``` - -Update `state.json`: set `current_step` to 2, `current_phase` to 2, add steps 1A and 1B to `completed_steps`. - ---- - -## Phase 2: Security & Performance Review (Steps 2A-2B) - -Read `.full-review/01-quality-architecture.md` for context from Phase 1. - -Run both agents in parallel using multiple Task tool calls in a single response. - -### Step 2A: Security Vulnerability Assessment - -``` -Task: - subagent_type: "security-auditor" - description: "Security audit for $ARGUMENTS" - prompt: | - Execute a comprehensive security audit on the target code. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Phase 1 Context - [Insert contents of .full-review/01-quality-architecture.md -- focus on the "Critical Issues for Phase 2 Context" section] - - ## Instructions - Analyze for: - 1. **OWASP Top 10**: Injection, broken auth, sensitive data exposure, XXE, broken access control, misconfig, XSS, insecure deserialization, vulnerable components, insufficient logging - 2. **Input validation**: Missing sanitization, unvalidated redirects, path traversal - 3. **Authentication/authorization**: Flawed auth logic, privilege escalation, session management - 4. **Cryptographic issues**: Weak algorithms, hardcoded secrets, improper key management - 5. **Dependency vulnerabilities**: Known CVEs in dependencies, outdated packages - 6. **Configuration security**: Debug mode, verbose errors, permissive CORS, missing security headers - - For each finding, provide: - - Severity (Critical / High / Medium / Low) with CVSS score if applicable - - CWE reference where applicable - - File and line location - - Proof of concept or attack scenario - - Specific remediation steps with code example - - Write your findings as a structured markdown document. -``` - -### Step 2B: Performance & Scalability Analysis - -``` -Task: - subagent_type: "general-purpose" - description: "Performance analysis for $ARGUMENTS" - prompt: | - You are a performance engineer. Conduct a performance and scalability analysis of the target code. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Phase 1 Context - [Insert contents of .full-review/01-quality-architecture.md -- focus on the "Critical Issues for Phase 2 Context" section] - - ## Instructions - Analyze for: - 1. **Database performance**: N+1 queries, missing indexes, unoptimized queries, connection pool sizing - 2. **Memory management**: Memory leaks, unbounded collections, large object allocation - 3. **Caching opportunities**: Missing caching, stale cache risks, cache invalidation issues - 4. **I/O bottlenecks**: Synchronous blocking calls, missing pagination, large payloads - 5. **Concurrency issues**: Race conditions, deadlocks, thread safety - 6. **Frontend performance**: Bundle size, render performance, unnecessary re-renders, missing lazy loading - 7. **Scalability concerns**: Horizontal scaling barriers, stateful components, single points of failure - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - Estimated performance impact - - Specific optimization recommendation with code example - - Write your findings as a structured markdown document. -``` - -After both complete, consolidate into `.full-review/02-security-performance.md`: - -```markdown -# Phase 2: Security & Performance Review - -## Security Findings - -[Summary from 2A, organized by severity] - -## Performance Findings - -[Summary from 2B, organized by severity] - -## Critical Issues for Phase 3 Context - -[List findings that affect testing or documentation requirements] -``` - -Update `state.json`: set `current_step` to "checkpoint-1", add steps 2A and 2B to `completed_steps`. - ---- - -## PHASE CHECKPOINT 1 -- User Approval Required - -Display a summary of findings from Phase 1 and Phase 2 and ask: - -``` -Phases 1-2 complete: Code Quality, Architecture, Security, and Performance reviews done. - -Summary: -- Code Quality: [X critical, Y high, Z medium findings] -- Architecture: [X critical, Y high, Z medium findings] -- Security: [X critical, Y high, Z medium findings] -- Performance: [X critical, Y high, Z medium findings] - -Please review: -- .full-review/01-quality-architecture.md -- .full-review/02-security-performance.md - -1. Continue -- proceed to Testing & Documentation review -2. Fix critical issues first -- I'll address findings before continuing -3. Pause -- save progress and stop here -``` - -If `--strict-mode` flag is set and there are Critical findings, recommend option 2. - -Do NOT proceed to Phase 3 until the user approves. - ---- - -## Phase 3: Testing & Documentation Review (Steps 3A-3B) - -Read `.full-review/01-quality-architecture.md` and `.full-review/02-security-performance.md` for context. - -Run both agents in parallel using multiple Task tool calls in a single response. - -### Step 3A: Test Coverage & Quality Analysis - -``` -Task: - subagent_type: "general-purpose" - description: "Test coverage analysis for $ARGUMENTS" - prompt: | - You are a test automation engineer. Evaluate the testing strategy and coverage for the target code. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Prior Phase Context - [Insert security and performance findings from .full-review/02-security-performance.md that affect testing requirements] - - ## Instructions - Analyze: - 1. **Test coverage**: Which code paths have tests? Which critical paths are untested? - 2. **Test quality**: Are tests testing behavior or implementation? Assertion quality? - 3. **Test pyramid adherence**: Unit vs integration vs E2E test ratio - 4. **Edge cases**: Are boundary conditions, error paths, and concurrent scenarios tested? - 5. **Test maintainability**: Test isolation, mock usage, flaky test indicators - 6. **Security test gaps**: Are security-critical paths tested? Auth, input validation, etc. - 7. **Performance test gaps**: Are performance-critical paths tested? Load testing? - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - What is untested or poorly tested - - Specific test recommendations with example test code - - Write your findings as a structured markdown document. -``` - -### Step 3B: Documentation & API Review - -``` -Task: - subagent_type: "general-purpose" - description: "Documentation review for $ARGUMENTS" - prompt: | - You are a technical documentation architect. Review documentation completeness and accuracy. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Prior Phase Context - [Insert key findings from .full-review/01-quality-architecture.md and .full-review/02-security-performance.md] - - ## Instructions - Evaluate: - 1. **Inline documentation**: Are complex algorithms and business logic explained? - 2. **API documentation**: Are endpoints documented with examples? Request/response schemas? - 3. **Architecture documentation**: ADRs, system diagrams, component documentation - 4. **README completeness**: Setup instructions, development workflow, deployment guide - 5. **Accuracy**: Does documentation match the actual implementation? - 6. **Changelog/migration guides**: Are breaking changes documented? - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - What is missing or inaccurate - - Specific documentation recommendation - - Write your findings as a structured markdown document. -``` - -After both complete, consolidate into `.full-review/03-testing-documentation.md`: - -```markdown -# Phase 3: Testing & Documentation Review - -## Test Coverage Findings - -[Summary from 3A, organized by severity] - -## Documentation Findings - -[Summary from 3B, organized by severity] -``` - -Update `state.json`: set `current_step` to 4, `current_phase` to 4, add steps 3A and 3B to `completed_steps`. - ---- - -## Phase 4: Best Practices & Standards (Steps 4A-4B) - -Read all previous `.full-review/*.md` files for full context. - -Run both agents in parallel using multiple Task tool calls in a single response. - -### Step 4A: Framework & Language Best Practices - -``` -Task: - subagent_type: "general-purpose" - description: "Framework best practices review for $ARGUMENTS" - prompt: | - You are an expert in modern framework and language best practices. Verify adherence to current standards. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## All Prior Findings - [Insert a concise summary of critical/high findings from all prior phases] - - ## Instructions - Check for: - 1. **Language idioms**: Is the code idiomatic for its language? Modern syntax and features? - 2. **Framework patterns**: Does it follow the framework's recommended patterns? (e.g., React hooks, Django views, Spring beans) - 3. **Deprecated APIs**: Are any deprecated functions/libraries/patterns used? - 4. **Modernization opportunities**: Where could modern language/framework features simplify code? - 5. **Package management**: Are dependencies up-to-date? Unnecessary dependencies? - 6. **Build configuration**: Is the build optimized? Development vs production settings? - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - Current pattern vs recommended pattern - - Migration/fix recommendation with code example - - Write your findings as a structured markdown document. -``` - -### Step 4B: CI/CD & DevOps Practices Review - -``` -Task: - subagent_type: "general-purpose" - description: "CI/CD and DevOps practices review for $ARGUMENTS" - prompt: | - You are a DevOps engineer. Review CI/CD pipeline and operational practices. - - ## Review Scope - [Insert contents of .full-review/00-scope.md] - - ## Critical Issues from Prior Phases - [Insert critical/high findings from all prior phases that impact deployment or operations] - - ## Instructions - Evaluate: - 1. **CI/CD pipeline**: Build automation, test gates, deployment stages, security scanning - 2. **Deployment strategy**: Blue-green, canary, rollback capabilities - 3. **Infrastructure as Code**: Are infrastructure configs version-controlled and reviewed? - 4. **Monitoring & observability**: Logging, metrics, alerting, dashboards - 5. **Incident response**: Runbooks, on-call procedures, rollback plans - 6. **Environment management**: Config separation, secret management, parity between environments - - For each finding, provide: - - Severity (Critical / High / Medium / Low) - - Operational risk assessment - - Specific improvement recommendation - - Write your findings as a structured markdown document. -``` - -After both complete, consolidate into `.full-review/04-best-practices.md`: - -```markdown -# Phase 4: Best Practices & Standards - -## Framework & Language Findings - -[Summary from 4A, organized by severity] - -## CI/CD & DevOps Findings - -[Summary from 4B, organized by severity] -``` - -Update `state.json`: set `current_step` to 5, `current_phase` to 5, add steps 4A and 4B to `completed_steps`. - ---- - -## Phase 5: Consolidated Report (Step 5) - -Read all `.full-review/*.md` files. Generate the final consolidated report. - -**Output file:** `.full-review/05-final-report.md` - -```markdown -# Comprehensive Code Review Report - -## Review Target - -[From 00-scope.md] - -## Executive Summary - -[2-3 sentence overview of overall code health and key concerns] - -## Findings by Priority - -### Critical Issues (P0 -- Must Fix Immediately) - -[All Critical findings from all phases, with source phase reference] - -- Security vulnerabilities with CVSS > 7.0 -- Data loss or corruption risks -- Authentication/authorization bypasses -- Production stability threats - -### High Priority (P1 -- Fix Before Next Release) - -[All High findings from all phases] - -- Performance bottlenecks impacting user experience -- Missing critical test coverage -- Architectural anti-patterns causing technical debt -- Outdated dependencies with known vulnerabilities - -### Medium Priority (P2 -- Plan for Next Sprint) - -[All Medium findings from all phases] - -- Non-critical performance optimizations -- Documentation gaps -- Code refactoring opportunities -- Test quality improvements - -### Low Priority (P3 -- Track in Backlog) - -[All Low findings from all phases] - -- Style guide violations -- Minor code smell issues -- Nice-to-have improvements - -## Findings by Category - -- **Code Quality**: [count] findings ([breakdown by severity]) -- **Architecture**: [count] findings ([breakdown by severity]) -- **Security**: [count] findings ([breakdown by severity]) -- **Performance**: [count] findings ([breakdown by severity]) -- **Testing**: [count] findings ([breakdown by severity]) -- **Documentation**: [count] findings ([breakdown by severity]) -- **Best Practices**: [count] findings ([breakdown by severity]) -- **CI/CD & DevOps**: [count] findings ([breakdown by severity]) - -## Recommended Action Plan - -1. [Ordered list of recommended actions, starting with critical/high items] -2. [Group related fixes where possible] -3. [Estimate relative effort: small/medium/large] - -## Review Metadata - -- Review date: [timestamp] -- Phases completed: [list] -- Flags applied: [list active flags] -``` - -Update `state.json`: set `status` to `"complete"`, `last_updated` to current timestamp. - ---- - -## Completion - -Present the final summary: - -``` -Comprehensive code review complete for: $ARGUMENTS - -## Review Output Files -- Scope: .full-review/00-scope.md -- Quality & Architecture: .full-review/01-quality-architecture.md -- Security & Performance: .full-review/02-security-performance.md -- Testing & Documentation: .full-review/03-testing-documentation.md -- Best Practices: .full-review/04-best-practices.md -- Final Report: .full-review/05-final-report.md - -## Summary -- Total findings: [count] -- Critical: [X] | High: [Y] | Medium: [Z] | Low: [W] - -## Next Steps -1. Review the full report at .full-review/05-final-report.md -2. Address Critical (P0) issues immediately -3. Plan High (P1) fixes for current sprint -4. Add Medium (P2) and Low (P3) items to backlog -``` +1. Confirm the target files or revision, requested focus and intended behavior. Limit the review to the selected repository. +2. Examine the changed implementation, callers and tests. Use the installed code-reviewer for an independent reading if available. Trace the behavior before judging the design. +3. For security-sensitive changes, use the read-only security-reviewer or inspect the source directly. Describe affected boundaries, likely impact and a defensive fix. Keep private values out of the result. +4. For performance-sensitive changes, identify measured costs and distinguish them from guesses. Review reliability and error handling for ordinary and edge cases. +5. Use the project’s own test entry points when authorized. Record the checks that passed, failed or were unavailable. +6. Present each actionable finding with its location, evidence and recommended correction. State what remains unverified. Keep the report in the conversation unless the user approves a private output location. diff --git a/config/commands/full-stack-feature.md b/config/commands/full-stack-feature.md index 8f3c865..a09960e 100644 --- a/config/commands/full-stack-feature.md +++ b/config/commands/full-stack-feature.md @@ -10,10 +10,10 @@ argument-hint: " [--stack react/fastapi/postgres] [--api-st You MUST follow these rules exactly. Violating any of them is a failure. 1. **Execute steps in order.** Do NOT skip ahead, reorder, or merge steps. -2. **Write output files.** Each step MUST produce its output file in `.full-stack-feature/` before the next step begins. Read from prior step files -- do NOT rely on context window memory. +2. **Keep working notes private.** Keep the phase notes in this conversation by default. All `.full-stack-feature/` paths below describe optional session artifacts. Use files only if the user requests saved notes and selects a private directory outside the repository. In that case resolve all paths under that directory. 3. **Stop at checkpoints.** When you reach a `PHASE CHECKPOINT`, you MUST stop and wait for explicit user approval before continuing. Use the AskUserQuestion tool with clear options. 4. **Halt on failure.** If any step fails (agent error, test failure, missing dependency), STOP immediately. Present the error and ask the user how to proceed. Do NOT silently continue. -5. **Use only local agents.** All `subagent_type` references use agents bundled with this plugin or `general-purpose`. No cross-plugin dependencies. +5. **Use available capabilities.** The agent role names below describe tasks. Check which agents the host actually provides. When a role is unavailable, handle that step in the current session with its existing permissions. 6. **Never enter plan mode autonomously.** Do NOT use EnterPlanMode. This command IS the plan -- execute it. ## Pre-flight Checks @@ -22,7 +22,7 @@ Before starting, perform these checks: ### 1. Check for existing session -Check if `.full-stack-feature/state.json` exists: +If the user requested private session files, check their selected directory for the state file: - If it exists and `status` is `"in_progress"`: Read it, display the current step, and ask the user: diff --git a/config/commands/instinct-status.md b/config/commands/instinct-status.md index c54f802..3efabb4 100644 --- a/config/commands/instinct-status.md +++ b/config/commands/instinct-status.md @@ -1,59 +1,5 @@ ---- -name: instinct-status -description: Show learned instincts (project + global) with confidence -command: true ---- +# instinct-status -# Instinct Status Command +Show the reusable notes the user explicitly selects for this review. If no notes were selected, ask for the intended files or pasted excerpts. Summarize scope and supporting observations without printing private contents. Do not search other projects, session histories or personal configuration. -Shows learned instincts for the current project plus global instincts, grouped by domain. - -## Implementation - -Run the instinct CLI using the plugin root path: - -```bash -python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" status -``` - -Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation), use: - -```bash -python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py status -``` - -## Usage - -``` -/instinct-status -``` - -## What to Do - -1. Detect current project context (git remote/path hash) -2. Read project instincts from `~/.claude/homunculus/projects//instincts/` -3. Read global instincts from `~/.claude/homunculus/instincts/` -4. Merge with precedence rules (project overrides global when IDs collide) -5. Display grouped by domain with confidence bars and observation stats - -## Output Format - -``` -============================================================ - INSTINCT STATUS - 12 total -============================================================ - - Project: my-app (a1b2c3d4e5f6) - Project instincts: 8 - Global instincts: 4 - -## PROJECT-SCOPED (my-app) - ### WORKFLOW (3) - ███████░░░ 70% grep-before-edit [project] - trigger: when modifying code - -## GLOBAL (apply to all projects) - ### SECURITY (2) - █████████░ 85% validate-user-input [global] - trigger: when handling user input -``` +The optional Everything Claude Code project has a separate instinct store and CLI. This distribution includes neither. Report when no evidence was supplied. diff --git a/config/commands/learn.md b/config/commands/learn.md index 9899af1..8c50f08 100644 --- a/config/commands/learn.md +++ b/config/commands/learn.md @@ -33,7 +33,7 @@ Look for: ## Output Format -Create a skill file at `~/.claude/skills/learned/[pattern-name].md`: +Draft the following in the conversation. Omit private project content and identifying details: ```markdown # [Descriptive Pattern Name] @@ -59,8 +59,8 @@ Create a skill file at `~/.claude/skills/learned/[pattern-name].md`: 1. Review the session for extractable patterns 2. Identify the most valuable/reusable insight 3. Draft the skill file -4. Ask user to confirm before saving -5. Save to `~/.claude/skills/learned/` +4. Ask whether the user wants to save the draft, and whether it should apply to this project or across projects. +5. Save only after the user approves both the text and its destination. ## Notes diff --git a/config/commands/pr-enhance.md b/config/commands/pr-enhance.md index 9b6c830..4b8ee07 100644 --- a/config/commands/pr-enhance.md +++ b/config/commands/pr-enhance.md @@ -2,6 +2,8 @@ You are a PR optimization expert specializing in creating high-quality pull requests that facilitate efficient code reviews. Generate comprehensive PR descriptions, automate review processes, and ensure PRs follow best practices for clarity, size, and reviewability. +Draft in the conversation and omit private content, credentials and personal contact details. Branch operations and publishing a PR or review require separate user authorization. Treat the command examples below as illustrations. + ## Context The user needs to create or improve pull requests with detailed descriptions, proper documentation, test coverage analysis, and review facilitation. Focus on making PRs that are easy to review, well-documented, and include all necessary context. diff --git a/config/commands/second-opinion.md b/config/commands/second-opinion.md index c0798a6..82f2881 100644 --- a/config/commands/second-opinion.md +++ b/config/commands/second-opinion.md @@ -1,23 +1,6 @@ -Get a focused second-opinion review of the current diff from a separate Claude instance. +Request a second review of a specific change. -```bash -git diff HEAD -``` - -Pass the diff above to a second Claude instance with this question: - -```bash -claude -p "Review this diff for correctness, security issues, and missed edge cases. Be concise — flag real problems only, skip style. - -$(git diff HEAD)" -``` - -If the diff is empty, run against staged changes instead: - -```bash -claude -p "Review this diff for correctness, security issues, and missed edge cases. Be concise — flag real problems only, skip style. - -$(git diff --cached)" -``` - -Report the findings to the user. If no issues are found, say so in one line. +1. Identify the files or excerpt the user wants reviewed. Leave credentials, personal details and unrelated changes out of the review. +2. Use the available read-only code-reviewer in the current host. Give it the scope and the questions about correctness and edge cases. +3. If the reviewer is unavailable, explain that limit. If the user wants a separate service instead, name the service, describe exactly what would be sent and get their approval before sharing anything. +4. Report supported findings with file locations and say which checks ran. diff --git a/config/commands/verify.md b/config/commands/verify.md index 5f628b1..ea36817 100644 --- a/config/commands/verify.md +++ b/config/commands/verify.md @@ -23,7 +23,8 @@ Execute verification in this exact order: - Report pass/fail count - Report coverage percentage -5. **Console.log Audit** +5. **Logs and secrets** + - For a requested security scan, use a trusted local redacting scanner. Report only categories and locations. Mark an unrun scan as unverified. - Search for console.log in source files - Report locations @@ -42,7 +43,7 @@ Build: [OK/FAIL] Types: [OK/X errors] Lint: [OK/X issues] Tests: [X/Y passed, Z% coverage] -Secrets: [OK/X found] +Secrets: [checked/unverified/out of scope] Logs: [OK/X console.logs] Ready for PR: [YES/NO] diff --git a/config/settings.json b/config/settings.json index 93f913c..a8e7882 100644 --- a/config/settings.json +++ b/config/settings.json @@ -1,215 +1,16 @@ { "$schema": "https://json.schemastore.org/claude-code-settings.json", - - // ── MODEL ──────────────────────────────────────────────────────────────── - // Default to sonnet. Agents override per-file via model: frontmatter. - // Planner uses opus; doc-updater uses haiku. All others use sonnet. "model": "sonnet", - - // ── OUTPUT STYLE ───────────────────────────────────────────────────────── - // "Explanatory" adds educational insights around code changes. - // Options: "Concise" | "Explanatory" | "Auto" - "outputStyle": "Explanatory", - - // ── PERMISSIONS ─────────────────────────────────────────────────────────── - // Default-deny. Only unlock what's needed. Projects can add via their own - // .claude/settings.json — global config sets the floor, not the ceiling. + "autoMemoryEnabled": false, "permissions": { - "allow": [ - // Read-only tools: always safe - "Read", - "Glob", - "Grep", - - // Git: safe for local operations - "Bash(git *)", - - // Package management (no install without prompt) - "Bash(npm run *)", - "Bash(npx *)", - - // Safe filesystem navigation and scaffolding - "Bash(ls *)", - "Bash(mkdir *)", - "Bash(cp *)", - - // Allow fetching raw GitHub content for plugin installs - "WebFetch(domain:raw.githubusercontent.com)" - ], + "defaultMode": "default", "deny": [ - // Irreversible destructive operations + "Read(**/.env)", + "Read(**/.env.*)", + "Read(**/secrets/**)", + "Read(~/.ssh/**)", "Bash(rm -rf *)", - - // Never force-push (rewrites shared history) - "Bash(git push --force *)", - - // Secrets — never read these - "Read(.env)", - "Read(.env.*)", - "Read(secrets/**)" + "Bash(git push --force *)" ] - }, - - // ── CONTEXT ─────────────────────────────────────────────────────────────── - "includeGitInstructions": true, - "respectGitignore": true, - "autoMemoryEnabled": true, - - // ── HOOKS ───────────────────────────────────────────────────────────────── - // All hooks call into context-mode (mksglu/context-mode) via its worker - // service. Install context-mode via the Claude Code plugin system, then - // update the paths below to match your CLAUDE_PLUGIN_ROOT. - // - // Replace $HOME/.claude/plugins/marketplaces/thedotmack/plugin with the - // actual path shown by: claude plugins list - "hooks": { - "SessionStart": [ - { - "matcher": "startup|clear|compact", - "hooks": [ - { - // Install any pending plugin updates on session start - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/smart-install.js\"", - "timeout": 300 - }, - { - // Start the context-mode worker (no-op if already running) - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" start", - "timeout": 60 - }, - { - // Load session context index into system prompt - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" hook claude-code context", - "timeout": 60 - } - ] - } - ], - - "UserPromptSubmit": [ - { - "hooks": [ - { - // Ensure worker is running before each prompt - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" start", - "timeout": 60 - }, - { - // Initialize session tracking for this prompt - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" hook claude-code session-init", - "timeout": 60 - } - ] - } - ], - - "PostToolUse": [ - { - "matcher": "*", - "hooks": [ - { - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" start", - "timeout": 60 - }, - { - // Capture observation into context-mode knowledge base - // This is how context-mode builds the semantic session index - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" hook claude-code observation", - "timeout": 120 - } - ] - } - ], - - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" start", - "timeout": 60 - }, - { - // Summarize session and save to context-mode knowledge base - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" hook claude-code summarize", - "timeout": 120 - }, - { - // Mark session complete - "type": "command", - "command": "node \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/bun-runner.js\" \"$HOME/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs\" hook claude-code session-complete", - "timeout": 30 - } - ] - } - ], - - "SessionEnd": [ - { - "hooks": [ - { - // Lightweight local log — survives without context-mode - "type": "command", - "command": "echo \"Session ended at $(date)\" >> ~/.claude/sessions/session-log.txt" - } - ] - } - ] - }, - - // ── STATUS LINE ─────────────────────────────────────────────────────────── - // Custom status line script. Copy statusline-command.sh from this repo - // to ~/.claude/statusline-command.sh and make it executable. - "statusLine": { - "type": "command", - "command": "bash $HOME/.claude/statusline-command.sh" - }, - - // ── PLUGINS ─────────────────────────────────────────────────────────────── - // Install marketplaces first, then enable plugins here. - // See extraKnownMarketplaces for sources. - "enabledPlugins": { - "prompt-improver@severity1-marketplace": true, - "everything-claude-code@everything-claude-code": true, - "ui-ux-pro-max@ui-ux-pro-max-skill": true, - "context-mode@context-mode": true - }, - - // ── PLUGIN MARKETPLACES ─────────────────────────────────────────────────── - // Add these to Claude Code so it knows where to fetch plugins. - // Claude Code only ships with one marketplace by default. - "extraKnownMarketplaces": { - "severity1-marketplace": { - "source": { - "source": "github", - "repo": "severity1/severity1-marketplace" - } - }, - "everything-claude-code": { - "source": { - "source": "github", - "repo": "affaan-m/everything-claude-code" - } - }, - "ui-ux-pro-max-skill": { - "source": { - "source": "github", - "repo": "nextlevelbuilder/ui-ux-pro-max-skill" - } - }, - "context-mode": { - "source": { - "source": "github", - "repo": "mksglu/context-mode" - } - } } } diff --git a/config/skills/continuous-learning-v2/SKILL.md b/config/skills/continuous-learning-v2/SKILL.md index f89eb80..974b622 100644 --- a/config/skills/continuous-learning-v2/SKILL.md +++ b/config/skills/continuous-learning-v2/SKILL.md @@ -1,380 +1,13 @@ --- name: continuous-learning-v2 -description: Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents. v2.1 adds project-scoped instincts to prevent cross-project contamination. +description: Review a selected lesson from the current conversation and draft a reusable project note on request. origin: ECC -version: 2.1.0 --- -# Continuous Learning v2.1 - Instinct --Based Architecture +# Continuous learning -An advanced learning system that turns your Claude Code sessions into reusable knowledge through atomic "instincts" - small learned behaviors with confidence scoring. +When the user asks to retain a lesson, identify the decision, the circumstances where it helped and the evidence for it. Ask whether it should apply to this project or more broadly. Draft a short note in the conversation. -**v2.1** adds **project-scoped instincts** — React patterns stay in your React project, Python conventions stay in your Python project, and universal patterns (like "always validate input") are shared globally. +Use only the conversation and files the user selected for this task. Remove identifying details, keys, URLs with private parameters and customer content from the draft. Saving the note requires approval of its content and destination. Cross-project sharing requires its own approval. -## When to Activate - -- Setting up automatic learning from Claude Code sessions -- Configuring instinct-based behavior extraction via hooks -- Tuning confidence thresholds for learned behaviors -- Reviewing, exporting, or importing instinct libraries -- Evolving instincts into full skills, commands, or agents -- Managing project-scoped vs global instincts -- Promoting instincts from project to global scope - -## What's New in v2.1 - -| Feature | v2.0 | v2.1 | -|---------|------|------| -| Storage | Global (~/.claude/homunculus/) | Project-scoped (projects//) | -| Scope | All instincts apply everywhere | Project-scoped + global | -| Detection | None | git remote URL / repo path | -| Promotion | N/A | Project → global when seen in 2+ projects | -| Commands | 4 (status/evolve/export/import) | 6 (+promote/projects) | -| Cross-project | Contamination risk | Isolated by default | - -## What's New in v2 (vs v1) - -| Feature | v1 | v2 | -|---------|----|----| -| Observation | Stop hook (session end) | PreToolUse/PostToolUse (100% reliable) | -| Analysis | Main context | Background agent (Haiku) | -| Granularity | Full skills | Atomic "instincts" | -| Confidence | None | 0.3-0.9 weighted | -| Evolution | Direct to skill | Instincts -> cluster -> skill/command/agent | -| Sharing | None | Export/import instincts | - -## The Instinct Model - -An instinct is a small learned behavior: - -```yaml ---- -id: prefer-functional-style -trigger: "when writing new functions" -confidence: 0.7 -domain: "code-style" -source: "session-observation" -scope: project -project_id: "a1b2c3d4e5f6" -project_name: "my-react-app" ---- - -# Prefer Functional Style - -## Action -Use functional patterns over classes when appropriate. - -## Evidence -- Observed 5 instances of functional pattern preference -- User corrected class-based approach to functional on 2025-01-15 -``` - -**Properties:** -- **Atomic** -- one trigger, one action -- **Confidence-weighted** -- 0.3 = tentative, 0.9 = near certain -- **Domain-tagged** -- code-style, testing, git, debugging, workflow, etc. -- **Evidence-backed** -- tracks what observations created it -- **Scope-aware** -- `project` (default) or `global` - -## How It Works - -``` -Session Activity (in a git repo) - | - | Hooks capture prompts + tool use (100% reliable) - | + detect project context (git remote / repo path) - v -+---------------------------------------------+ -| projects//observations.jsonl | -| (prompts, tool calls, outcomes, project) | -+---------------------------------------------+ - | - | Observer agent reads (background, Haiku) - v -+---------------------------------------------+ -| PATTERN DETECTION | -| * User corrections -> instinct | -| * Error resolutions -> instinct | -| * Repeated workflows -> instinct | -| * Scope decision: project or global? | -+---------------------------------------------+ - | - | Creates/updates - v -+---------------------------------------------+ -| projects//instincts/personal/ | -| * prefer-functional.yaml (0.7) [project] | -| * use-react-hooks.yaml (0.9) [project] | -+---------------------------------------------+ -| instincts/personal/ (GLOBAL) | -| * always-validate-input.yaml (0.85) [global]| -| * grep-before-edit.yaml (0.6) [global] | -+---------------------------------------------+ - | - | /evolve clusters + /promote - v -+---------------------------------------------+ -| projects//evolved/ (project-scoped) | -| evolved/ (global) | -| * commands/new-feature.md | -| * skills/testing-workflow.md | -| * agents/refactor-specialist.md | -+---------------------------------------------+ -``` - -## Project Detection - -The system automatically detects your current project: - -1. **`CLAUDE_PROJECT_DIR` env var** (highest priority) -2. **`git remote get-url origin`** -- hashed to create a portable project ID (same repo on different machines gets the same ID) -3. **`git rev-parse --show-toplevel`** -- fallback using repo path (machine-specific) -4. **Global fallback** -- if no project is detected, instincts go to global scope - -Each project gets a 12-character hash ID (e.g., `a1b2c3d4e5f6`). A registry file at `~/.claude/homunculus/projects.json` maps IDs to human-readable names. - -## Quick Start - -### 1. Enable Observation Hooks - -Add to your `~/.claude/settings.json`. - -**If installed as a plugin** (recommended): - -```json -{ - "hooks": { - "PreToolUse": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/hooks/observe.sh" - }] - }], - "PostToolUse": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/hooks/observe.sh" - }] - }] - } -} -``` - -**If installed manually** to `~/.claude/skills`: - -```json -{ - "hooks": { - "PreToolUse": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "~/.claude/skills/continuous-learning-v2/hooks/observe.sh" - }] - }], - "PostToolUse": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "~/.claude/skills/continuous-learning-v2/hooks/observe.sh" - }] - }] - } -} -``` - -### 2. Initialize Directory Structure - -The system creates directories automatically on first use, but you can also create them manually: - -```bash -# Global directories -mkdir -p ~/.claude/homunculus/{instincts/{personal,inherited},evolved/{agents,skills,commands},projects} - -# Project directories are auto-created when the hook first runs in a git repo -``` - -### 3. Use the Instinct Commands - -```bash -/instinct-status # Show learned instincts (project + global) -/evolve # Cluster related instincts into skills/commands -/instinct-export # Export instincts to file -/instinct-import # Import instincts from others -/promote # Promote project instincts to global scope -/projects # List all known projects and their instinct counts -``` - -## Commands - -| Command | Description | -|---------|-------------| -| `/instinct-status` | Show all instincts (project-scoped + global) with confidence | -| `/evolve` | Cluster related instincts into skills/commands, suggest promotions | -| `/instinct-export` | Export instincts (filterable by scope/domain) | -| `/instinct-import ` | Import instincts with scope control | -| `/promote [id]` | Promote project instincts to global scope | -| `/projects` | List all known projects and their instinct counts | - -## Configuration - -Edit `config.json` to control the background observer: - -```json -{ - "version": "2.1", - "observer": { - "enabled": false, - "run_interval_minutes": 5, - "min_observations_to_analyze": 20 - } -} -``` - -| Key | Default | Description | -|-----|---------|-------------| -| `observer.enabled` | `false` | Enable the background observer agent | -| `observer.run_interval_minutes` | `5` | How often the observer analyzes observations | -| `observer.min_observations_to_analyze` | `20` | Minimum observations before analysis runs | - -Other behavior (observation capture, instinct thresholds, project scoping, promotion criteria) is configured via code defaults in `instinct-cli.py` and `observe.sh`. - -## File Structure - -``` -~/.claude/homunculus/ -+-- identity.json # Your profile, technical level -+-- projects.json # Registry: project hash -> name/path/remote -+-- observations.jsonl # Global observations (fallback) -+-- instincts/ -| +-- personal/ # Global auto-learned instincts -| +-- inherited/ # Global imported instincts -+-- evolved/ -| +-- agents/ # Global generated agents -| +-- skills/ # Global generated skills -| +-- commands/ # Global generated commands -+-- projects/ - +-- a1b2c3d4e5f6/ # Project hash (from git remote URL) - | +-- project.json # Per-project metadata mirror (id/name/root/remote) - | +-- observations.jsonl - | +-- observations.archive/ - | +-- instincts/ - | | +-- personal/ # Project-specific auto-learned - | | +-- inherited/ # Project-specific imported - | +-- evolved/ - | +-- skills/ - | +-- commands/ - | +-- agents/ - +-- f6e5d4c3b2a1/ # Another project - +-- ... -``` - -## Scope Decision Guide - -| Pattern Type | Scope | Examples | -|-------------|-------|---------| -| Language/framework conventions | **project** | "Use React hooks", "Follow Django REST patterns" | -| File structure preferences | **project** | "Tests in `__tests__`/", "Components in src/components/" | -| Code style | **project** | "Use functional style", "Prefer dataclasses" | -| Error handling strategies | **project** | "Use Result type for errors" | -| Security practices | **global** | "Validate user input", "Sanitize SQL" | -| General best practices | **global** | "Write tests first", "Always handle errors" | -| Tool workflow preferences | **global** | "Grep before Edit", "Read before Write" | -| Git practices | **global** | "Conventional commits", "Small focused commits" | - -## Instinct Promotion (Project -> Global) - -When the same instinct appears in multiple projects with high confidence, it's a candidate for promotion to global scope. - -**Auto-promotion criteria:** -- Same instinct ID in 2+ projects -- Average confidence >= 0.8 - -**How to promote:** - -```bash -# Promote a specific instinct -python3 instinct-cli.py promote prefer-explicit-errors - -# Auto-promote all qualifying instincts -python3 instinct-cli.py promote - -# Preview without changes -python3 instinct-cli.py promote --dry-run -``` - -The `/evolve` command also suggests promotion candidates. - -## Confidence Scoring - -Confidence evolves over time: - -| Score | Meaning | Behavior | -|-------|---------|----------| -| 0.3 | Tentative | Suggested but not enforced | -| 0.5 | Moderate | Applied when relevant | -| 0.7 | Strong | Auto-approved for application | -| 0.9 | Near-certain | Core behavior | - -**Confidence increases** when: -- Pattern is repeatedly observed -- User doesn't correct the suggested behavior -- Similar instincts from other sources agree - -**Confidence decreases** when: -- User explicitly corrects the behavior -- Pattern isn't observed for extended periods -- Contradicting evidence appears - -## Why Hooks vs Skills for Observation? - -> "v1 relied on skills to observe. Skills are probabilistic -- they fire ~50-80% of the time based on Claude's judgment." - -Hooks fire **100% of the time**, deterministically. This means: -- Every tool call is observed -- No patterns are missed -- Learning is comprehensive - -## Backward Compatibility - -v2.1 is fully compatible with v2.0 and v1: -- Existing global instincts in `~/.claude/homunculus/instincts/` still work as global instincts -- Existing `~/.claude/skills/learned/` skills from v1 still work -- Stop hook still runs (but now also feeds into v2) -- Gradual migration: run both in parallel - -## Privacy - -- Observations stay **local** on your machine -- Project-scoped instincts are isolated per project -- Only **instincts** (patterns) can be exported — not raw observations -- No actual code or conversation content is shared -- You control what gets exported and promoted - -## Related - -- [Skill Creator](https://skill-creator.app) - Generate instincts from repo history -- Homunculus - Community project that inspired the v2 instinct-based architecture (atomic observations, confidence scoring, instinct evolution pipeline) -- [The Longform Guide](https://x.com/affaanmustafa/status/2014040193557471352) - Continuous learning section - -## Strict Output Schema - -When reporting instinct analysis or learning summaries, use this structure. -Free-form prose is a known agent failure mode (Non-Specific Output — Mahmoudi et al., 2025). - - - continuous-learning-v2 - N - [project|global] - - [one-line description] - - [SAVED|UPDATED|PROMOTED|NO_CHANGE] - - ---- - -*Instinct-based learning: teaching Claude your patterns, one project at a time.* +The upstream Everything Claude Code project also offers an observation-based system. This distribution ships Markdown guidance only. It does not bundle that system's observer, CLI or storage. Installing the optional upstream integration and consenting to its data collection are separate decisions. diff --git a/config/skills/strategic-compact/SKILL.md b/config/skills/strategic-compact/SKILL.md index a11fa00..850570f 100644 --- a/config/skills/strategic-compact/SKILL.md +++ b/config/skills/strategic-compact/SKILL.md @@ -1,115 +1,13 @@ --- name: strategic-compact -description: Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction. +description: Choose a useful moment for manual context compaction in a long Claude Code task. origin: ECC --- -# Strategic Compact Skill +# Strategic compaction -Suggests manual `/compact` at strategic points in your workflow rather than relying on arbitrary auto-compaction. +Consider manual compaction after finishing research, completing a milestone or switching to a distinct task. Keep the current context during an unresolved debugging sequence. -## When to Activate +Before compacting, summarize the goal, decisions, files changed, verification results and remaining uncertainty in the conversation. Save a separate note only if the user requests it and approves the location. Omit credentials and private excerpts. -- Running long sessions that approach context limits (200K+ tokens) -- Working on multi-phase tasks (research → plan → implement → test) -- Switching between unrelated tasks within the same session -- After completing a major milestone and starting new work -- When responses slow down or become less coherent (context pressure) - -## Why Strategic Compaction? - -Auto-compaction triggers at arbitrary points: -- Often mid-task, losing important context -- No awareness of logical task boundaries -- Can interrupt complex multi-step operations - -Strategic compaction at logical boundaries: -- **After exploration, before execution** — Compact research context, keep implementation plan -- **After completing a milestone** — Fresh start for next phase -- **Before major context shifts** — Clear exploration context before different task - -## How It Works - -The `suggest-compact.js` script runs on PreToolUse (Edit/Write) and: - -1. **Tracks tool calls** — Counts tool invocations in session -2. **Threshold detection** — Suggests at configurable threshold (default: 50 calls) -3. **Periodic reminders** — Reminds every 25 calls after threshold - -## Hook Setup - -Add to your `~/.claude/settings.json`: - -```json -{ - "hooks": { - "PreToolUse": [ - { - "matcher": "Edit", - "hooks": [{ "type": "command", "command": "node ~/.claude/skills/strategic-compact/suggest-compact.js" }] - }, - { - "matcher": "Write", - "hooks": [{ "type": "command", "command": "node ~/.claude/skills/strategic-compact/suggest-compact.js" }] - } - ] - } -} -``` - -## Configuration - -Environment variables: -- `COMPACT_THRESHOLD` — Tool calls before first suggestion (default: 50) - -## Compaction Decision Guide - -Use this table to decide when to compact: - -| Phase Transition | Compact? | Why | -|-----------------|----------|-----| -| Research → Planning | Yes | Research context is bulky; plan is the distilled output | -| Planning → Implementation | Yes | Plan is in TodoWrite or a file; free up context for code | -| Implementation → Testing | Maybe | Keep if tests reference recent code; compact if switching focus | -| Debugging → Next feature | Yes | Debug traces pollute context for unrelated work | -| Mid-implementation | No | Losing variable names, file paths, and partial state is costly | -| After a failed approach | Yes | Clear the dead-end reasoning before trying a new approach | - -## What Survives Compaction - -Understanding what persists helps you compact with confidence: - -| Persists | Lost | -|----------|------| -| CLAUDE.md instructions | Intermediate reasoning and analysis | -| TodoWrite task list | File contents you previously read | -| Memory files (`~/.claude/memory/`) | Multi-step conversation context | -| Git state (commits, branches) | Tool call history and counts | -| Files on disk | Nuanced user preferences stated verbally | - -## Best Practices - -1. **Compact after planning** — Once plan is finalized in TodoWrite, compact to start fresh -2. **Compact after debugging** — Clear error-resolution context before continuing -3. **Don't compact mid-implementation** — Preserve context for related changes -4. **Read the suggestion** — The hook tells you *when*, you decide *if* -5. **Write before compacting** — Save important context to files or memory before compacting -6. **Use `/compact` with a summary** — Add a custom message: `/compact Focus on implementing auth middleware next` - -## Strict Output Schema - -When reporting compaction status or recommendations, use this structure. -Free-form prose is a known agent failure mode (Non-Specific Output — Mahmoudi et al., 2025). - - - strategic-compact - [COMPACT NOW|HOLD|OPTIONAL] - [phase transition or threshold reason] - N - - -## Related - -- [The Longform Guide](https://x.com/affaanmustafa/status/2014040193557471352) — Token optimization section -- Memory persistence hooks — For state that survives compaction -- `continuous-learning` skill — Extracts patterns before session ends +Use the host's manual compaction control when available. After compaction, recheck the working tree, required files and any unfinished verification before continuing. This guide runs entirely on request. It installs no hook or background counter. diff --git a/config/skills/strategic-compact/suggest-compact.sh b/config/skills/strategic-compact/suggest-compact.sh deleted file mode 100755 index 38f5aa9..0000000 --- a/config/skills/strategic-compact/suggest-compact.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash -# Strategic Compact Suggester -# Runs on PreToolUse or periodically to suggest manual compaction at logical intervals -# -# Why manual over auto-compact: -# - Auto-compact happens at arbitrary points, often mid-task -# - Strategic compacting preserves context through logical phases -# - Compact after exploration, before execution -# - Compact after completing a milestone, before starting next -# -# Hook config (in ~/.claude/settings.json): -# { -# "hooks": { -# "PreToolUse": [{ -# "matcher": "Edit|Write", -# "hooks": [{ -# "type": "command", -# "command": "~/.claude/skills/strategic-compact/suggest-compact.sh" -# }] -# }] -# } -# } -# -# Criteria for suggesting compact: -# - Session has been running for extended period -# - Large number of tool calls made -# - Transitioning from research/exploration to implementation -# - Plan has been finalized - -# Track tool call count (increment in a temp file) -# Use CLAUDE_SESSION_ID for session-specific counter (not $$ which changes per invocation) -SESSION_ID="${CLAUDE_SESSION_ID:-${PPID:-default}}" -COUNTER_FILE="/tmp/claude-tool-count-${SESSION_ID}" -THRESHOLD=${COMPACT_THRESHOLD:-50} - -# Initialize or increment counter -if [ -f "$COUNTER_FILE" ]; then - count=$(cat "$COUNTER_FILE") - count=$((count + 1)) - echo "$count" > "$COUNTER_FILE" -else - echo "1" > "$COUNTER_FILE" - count=1 -fi - -# Suggest compact after threshold tool calls -if [ "$count" -eq "$THRESHOLD" ]; then - echo "[StrategicCompact] $THRESHOLD tool calls reached - consider /compact if transitioning phases" >&2 -fi - -# Suggest at regular intervals after threshold -if [ "$count" -gt "$THRESHOLD" ] && [ $((count % 25)) -eq 0 ]; then - echo "[StrategicCompact] $count tool calls - good checkpoint for /compact if context is stale" >&2 -fi diff --git a/config/skills/ui-ux-pro-max/SKILL.md b/config/skills/ui-ux-pro-max/SKILL.md index 9f317df..5e940d1 100644 --- a/config/skills/ui-ux-pro-max/SKILL.md +++ b/config/skills/ui-ux-pro-max/SKILL.md @@ -1,10 +1,11 @@ --- name: ui-ux-pro-max -description: "UI/UX design intelligence. 67 styles, 96 palettes, 57 font pairings, 25 charts, 13 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient. Integrations: shadcn/ui MCP for component search and examples." +description: Review an interface for accessibility, interaction, responsive layout and visual consistency using the bundled checklist. --- -# UI/UX Pro Max - Design Intelligence -Comprehensive design guide for web and mobile applications. Contains 67 styles, 96 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types across 13 technology stacks. Searchable database with priority-based recommendations. +# UI/UX Pro Max + +This checklist is adapted from UI/UX Pro Max. The upstream search database and Python scripts are separate from this distribution. Use the checks below directly on the requested interface. ## When to Apply @@ -83,295 +84,3 @@ Reference these guidelines when: - `chart-type` - Match chart type to data type - `color-guidance` - Use accessible color palettes - `data-table` - Provide table alternative for accessibility - -## How to Use - -Search specific domains using the CLI tool below. - ---- - - -## Prerequisites - -Check if Python is installed: - -```bash -python3 --version || python --version -``` - -If Python is not installed, install it based on user's OS: - -**macOS:** -```bash -brew install python3 -``` - -**Ubuntu/Debian:** -```bash -sudo apt update && sudo apt install python3 -``` - -**Windows:** -```powershell -winget install Python.Python.3.12 -``` - ---- - -## How to Use This Skill - -When user requests UI/UX work (design, build, create, implement, review, fix, improve), follow this workflow: - -### Step 1: Analyze User Requirements - -Extract key information from user request: -- **Product type**: SaaS, e-commerce, portfolio, dashboard, landing page, etc. -- **Style keywords**: minimal, playful, professional, elegant, dark mode, etc. -- **Industry**: healthcare, fintech, gaming, education, etc. -- **Stack**: React, Vue, Next.js, or default to `html-tailwind` - -### Step 2: Generate Design System (REQUIRED) - -**Always start with `--design-system`** to get comprehensive recommendations with reasoning: - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py " " --design-system [-p "Project Name"] -``` - -This command: -1. Searches 5 domains in parallel (product, style, color, landing, typography) -2. Applies reasoning rules from `ui-reasoning.csv` to select best matches -3. Returns complete design system: pattern, style, colors, typography, effects -4. Includes anti-patterns to avoid - -**Example:** -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --design-system -p "Serenity Spa" -``` - -### Step 2b: Persist Design System (Master + Overrides Pattern) - -To save the design system for hierarchical retrieval across sessions, add `--persist`: - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "" --design-system --persist -p "Project Name" -``` - -This creates: -- `design-system/MASTER.md` — Global Source of Truth with all design rules -- `design-system/pages/` — Folder for page-specific overrides - -**With page-specific override:** -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "" --design-system --persist -p "Project Name" --page "dashboard" -``` - -This also creates: -- `design-system/pages/dashboard.md` — Page-specific deviations from Master - -**How hierarchical retrieval works:** -1. When building a specific page (e.g., "Checkout"), first check `design-system/pages/checkout.md` -2. If the page file exists, its rules **override** the Master file -3. If not, use `design-system/MASTER.md` exclusively - -### Step 3: Supplement with Detailed Searches (as needed) - -After getting the design system, use domain searches to get additional details: - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "" --domain [-n ] -``` - -**When to use detailed searches:** - -| Need | Domain | Example | -|------|--------|---------| -| More style options | `style` | `--domain style "glassmorphism dark"` | -| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` | -| UX best practices | `ux` | `--domain ux "animation accessibility"` | -| Alternative fonts | `typography` | `--domain typography "elegant luxury"` | -| Landing structure | `landing` | `--domain landing "hero social-proof"` | - -### Step 4: Stack Guidelines (Default: html-tailwind) - -Get implementation-specific best practices. If user doesn't specify a stack, **default to `html-tailwind`**. - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "" --stack html-tailwind -``` - -Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`, `shadcn`, `jetpack-compose` - ---- - -## Search Reference - -### Available Domains - -| Domain | Use For | Example Keywords | -|--------|---------|------------------| -| `product` | Product type recommendations | SaaS, e-commerce, portfolio, healthcare, beauty, service | -| `style` | UI styles, colors, effects | glassmorphism, minimalism, dark mode, brutalism | -| `typography` | Font pairings, Google Fonts | elegant, playful, professional, modern | -| `color` | Color palettes by product type | saas, ecommerce, healthcare, beauty, fintech, service | -| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof | -| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie | -| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading | -| `react` | React/Next.js performance | waterfall, bundle, suspense, memo, rerender, cache | -| `web` | Web interface guidelines | aria, focus, keyboard, semantic, virtualize | -| `prompt` | AI prompts, CSS keywords | (style name) | - -### Available Stacks - -| Stack | Focus | -|-------|-------| -| `html-tailwind` | Tailwind utilities, responsive, a11y (DEFAULT) | -| `react` | State, hooks, performance, patterns | -| `nextjs` | SSR, routing, images, API routes | -| `vue` | Composition API, Pinia, Vue Router | -| `svelte` | Runes, stores, SvelteKit | -| `swiftui` | Views, State, Navigation, Animation | -| `react-native` | Components, Navigation, Lists | -| `flutter` | Widgets, State, Layout, Theming | -| `shadcn` | shadcn/ui components, theming, forms, patterns | -| `jetpack-compose` | Composables, Modifiers, State Hoisting, Recomposition | - ---- - -## Example Workflow - -**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp" - -### Step 1: Analyze Requirements -- Product type: Beauty/Spa service -- Style keywords: elegant, professional, soft -- Industry: Beauty/Wellness -- Stack: html-tailwind (default) - -### Step 2: Generate Design System (REQUIRED) - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service elegant" --design-system -p "Serenity Spa" -``` - -**Output:** Complete design system with pattern, style, colors, typography, effects, and anti-patterns. - -### Step 3: Supplement with Detailed Searches (as needed) - -```bash -# Get UX guidelines for animation and accessibility -python3 skills/ui-ux-pro-max/scripts/search.py "animation accessibility" --domain ux - -# Get alternative typography options if needed -python3 skills/ui-ux-pro-max/scripts/search.py "elegant luxury serif" --domain typography -``` - -### Step 4: Stack Guidelines - -```bash -python3 skills/ui-ux-pro-max/scripts/search.py "layout responsive form" --stack html-tailwind -``` - -**Then:** Synthesize design system + detailed searches and implement the design. - ---- - -## Output Formats - -The `--design-system` flag supports two output formats: - -```bash -# ASCII box (default) - best for terminal display -python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system - -# Markdown - best for documentation -python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system -f markdown -``` - ---- - -## Tips for Better Results - -1. **Be specific with keywords** - "healthcare SaaS dashboard" > "app" -2. **Search multiple times** - Different keywords reveal different insights -3. **Combine domains** - Style + Typography + Color = Complete design system -4. **Always check UX** - Search "animation", "z-index", "accessibility" for common issues -5. **Use stack flag** - Get implementation-specific best practices -6. **Iterate** - If first search doesn't match, try different keywords - ---- - -## Common Rules for Professional UI - -These are frequently overlooked issues that make UI look unprofessional: - -### Icons & Visual Elements - -| Rule | Do | Don't | -|------|----|----- | -| **No emoji icons** | Use SVG icons (Heroicons, Lucide, Simple Icons) | Use emojis like 🎨 🚀 ⚙️ as UI icons | -| **Stable hover states** | Use color/opacity transitions on hover | Use scale transforms that shift layout | -| **Correct brand logos** | Research official SVG from Simple Icons | Guess or use incorrect logo paths | -| **Consistent icon sizing** | Use fixed viewBox (24x24) with w-6 h-6 | Mix different icon sizes randomly | - -### Interaction & Cursor - -| Rule | Do | Don't | -|------|----|----- | -| **Cursor pointer** | Add `cursor-pointer` to all clickable/hoverable cards | Leave default cursor on interactive elements | -| **Hover feedback** | Provide visual feedback (color, shadow, border) | No indication element is interactive | -| **Smooth transitions** | Use `transition-colors duration-200` | Instant state changes or too slow (>500ms) | - -### Light/Dark Mode Contrast - -| Rule | Do | Don't | -|------|----|----- | -| **Glass card light mode** | Use `bg-white/80` or higher opacity | Use `bg-white/10` (too transparent) | -| **Text contrast light** | Use `#0F172A` (slate-900) for text | Use `#94A3B8` (slate-400) for body text | -| **Muted text light** | Use `#475569` (slate-600) minimum | Use gray-400 or lighter | -| **Border visibility** | Use `border-gray-200` in light mode | Use `border-white/10` (invisible) | - -### Layout & Spacing - -| Rule | Do | Don't | -|------|----|----- | -| **Floating navbar** | Add `top-4 left-4 right-4` spacing | Stick navbar to `top-0 left-0 right-0` | -| **Content padding** | Account for fixed navbar height | Let content hide behind fixed elements | -| **Consistent max-width** | Use same `max-w-6xl` or `max-w-7xl` | Mix different container widths | - ---- - -## Pre-Delivery Checklist - -Before delivering UI code, verify these items: - -### Visual Quality -- [ ] No emojis used as icons (use SVG instead) -- [ ] All icons from consistent icon set (Heroicons/Lucide) -- [ ] Brand logos are correct (verified from Simple Icons) -- [ ] Hover states don't cause layout shift -- [ ] Use theme colors directly (bg-primary) not var() wrapper - -### Interaction -- [ ] All clickable elements have `cursor-pointer` -- [ ] Hover states provide clear visual feedback -- [ ] Transitions are smooth (150-300ms) -- [ ] Focus states visible for keyboard navigation - -### Light/Dark Mode -- [ ] Light mode text has sufficient contrast (4.5:1 minimum) -- [ ] Glass/transparent elements visible in light mode -- [ ] Borders visible in both modes -- [ ] Test both modes before delivery - -### Layout -- [ ] Floating elements have proper spacing from edges -- [ ] No content hidden behind fixed navbars -- [ ] Responsive at 375px, 768px, 1024px, 1440px -- [ ] No horizontal scroll on mobile - -### Accessibility -- [ ] All images have alt text -- [ ] Form inputs have labels -- [ ] Color is not the only indicator -- [ ] `prefers-reduced-motion` respected diff --git a/config/skills/verification-loop/SKILL.md b/config/skills/verification-loop/SKILL.md index 8c4fd44..5131f6f 100644 --- a/config/skills/verification-loop/SKILL.md +++ b/config/skills/verification-loop/SKILL.md @@ -16,74 +16,16 @@ Invoke this skill: - When you want to ensure quality gates pass - After refactoring -## Verification Phases - -### Phase 1: Build Verification -```bash -# Check if project builds -npm run build 2>&1 | tail -20 -# OR -pnpm build 2>&1 | tail -20 -``` - -If build fails, STOP and fix before continuing. - -### Phase 2: Type Check -```bash -# TypeScript projects -npx tsc --noEmit 2>&1 | head -30 - -# Python projects -pyright . 2>&1 | head -30 -``` - -Report all type errors. Fix critical ones before continuing. - -### Phase 3: Lint Check -```bash -# JavaScript/TypeScript -npm run lint 2>&1 | head -30 - -# Python -ruff check . 2>&1 | head -30 -``` +## Verification phases -### Phase 4: Test Suite -```bash -# Run tests with coverage -npm run test -- --coverage 2>&1 | tail -50 - -# Check coverage threshold -# Target: 80% minimum -``` - -Report: -- Total tests: X -- Passed: X -- Failed: X -- Coverage: X% - -### Phase 5: Security Scan -```bash -# Check for secrets -grep -rn "sk-" --include="*.ts" --include="*.js" . 2>/dev/null | head -10 -grep -rn "api_key" --include="*.ts" --include="*.js" . 2>/dev/null | head -10 - -# Check for console.log -grep -rn "console.log" --include="*.ts" --include="*.tsx" src/ 2>/dev/null | head -10 -``` - -### Phase 6: Diff Review -```bash -# Show what changed -git diff --stat -git diff HEAD~1 --name-only -``` +1. **Build.** Read the repository's scripts and run its documented build. Keep its actual exit status. +2. **Types.** Run the existing type-check command where the project provides one. +3. **Lint.** Run the configured linter. Distinguish warnings from errors. +4. **Tests.** Run the relevant suite. Report its observed test count and any coverage actually measured. +5. **Security.** Use a trusted local redacting scanner for the requested files or history. Keep keys, raw matched lines and private contents out of logs. Report only the category and location. If scanning is unavailable, mark it unverified. +6. **Diff.** Review changed paths for unexpected changes, sensitive material and missed error handling. Compare the tested state with the state proposed for a commit. -Review each changed file for: -- Unintended changes -- Missing error handling -- Potential edge cases +Mark unavailable or irrelevant checks explicitly. A passing build supports the build claim only. Avoid automatically downloading tools or packages to fill a missing check. ## Output Format @@ -123,7 +65,7 @@ Run: /verify ## Integration with Hooks This skill complements PostToolUse hooks but provides deeper verification. -Hooks catch issues immediately; this skill provides comprehensive review. +Run these checks explicitly. Any additional hooks require separate configuration. ## Strict Output Schema diff --git a/scripts/convert.sh b/scripts/convert.sh index 6cfafe2..ea5be52 100755 --- a/scripts/convert.sh +++ b/scripts/convert.sh @@ -1,157 +1,62 @@ #!/bin/sh -# dotclaude convert script -# Converts config/CLAUDE.md for use with other coding agents -# -# Usage: -# ./scripts/convert.sh codex → AGENTS.md (OpenAI Codex / ChatGPT) -# ./scripts/convert.sh gemini → GEMINI.md (Gemini CLI) -# ./scripts/convert.sh cursor → .cursorrules (Cursor editor) -# ./scripts/convert.sh aider → .aider.conf.yml (Aider) -# -# Output files are written to the current directory. -# Converts Claude-specific terminology to agent-agnostic language. - -set -e - -REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)" -SOURCE="$REPO_DIR/config/CLAUDE.md" -TARGET_AGENT="${1:-}" - -# ── Colors ──────────────────────────────────────────────────────────────────── -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -RED='\033[0;31m' -NC='\033[0m' - -ok() { printf "${GREEN} ✓${NC} %s\n" "$1"; } -info() { printf "${BLUE} →${NC} %s\n" "$1"; } -warn() { printf "${YELLOW} ⚠${NC} %s\n" "$1"; } -err() { printf "${RED} ✗${NC} %s\n" "$1"; } - -# ── Strip Claude-specific references ───────────────────────────────────────── -# Removes or genericizes lines that only make sense for Claude Code: -# - Shift+Tab cycles, /config, /output-style references -# - claude update, claude doctor commands -# - Esc Esc rewind instruction - -sanitize_for_agent() { - sed \ - -e 's/Shift+Tab cycles: normal \/ auto-accept \/ plan mode/Toggle auto-accept mode via your agent'\''s settings/g' \ - -e 's|/config for per-session toggles, /output-style to switch output style|Check your agent'\''s settings for per-session toggles|g' \ - -e 's/Use Esc Esc to rewind to any previous prompt (restores files too)/Use your agent'\''s history or undo to rewind to a previous state/g' \ - -e 's/Update Claude Code regularly: claude update/Keep your coding agent up to date/g' \ - -e 's/Use claude doctor if anything feels broken/Run your agent'\''s diagnostics if anything feels broken/g' \ - -e 's/Use plan mode (Shift+Tab)/Use your agent'\''s plan\/architect mode/g' \ - -e 's/CLAUDE\.md/AGENTS.md/g' -} - -# ── Usage ───────────────────────────────────────────────────────────────────── -usage() { - echo "" - echo "Usage: $0 " - echo "" - echo "Supported agents:" - echo " codex → AGENTS.md (OpenAI Codex, ChatGPT, o3)" - echo " gemini → GEMINI.md (Gemini CLI)" - echo " cursor → .cursorrules (Cursor editor)" - echo " aider → .aider.conf.yml (Aider)" - echo "" - echo "Output is written to the current directory." - echo "" +# Create an instruction file in the current project without replacing its files. +set -eu +repo_dir=$(CDPATH='' cd "$(dirname "$0")/.." && pwd) +source_file="$repo_dir/config/CLAUDE.md" +case "${1:-}" in + codex) target=AGENTS.md ;; + gemini) target=GEMINI.md ;; + cursor) target=.cursor/rules/dotclaude.mdc ;; + aider) target=dotclaude-conventions.md ;; + *) echo 'Usage: convert.sh {codex|gemini|cursor|aider}' >&2; exit 1 ;; +esac +[ "$#" -eq 1 ] || { echo 'Expected one target.' >&2; exit 1; } + +# Stage complete files on the same filesystem. Hard links create the final +# names without replacing an existing file, including one created concurrently. +if [ "$1" = cursor ]; then + for dir in .cursor .cursor/rules; do + if [ -L "$dir" ]; then echo "Refusing linked directory: $dir" >&2; exit 1; fi + mkdir -p "$dir" + done +fi +parent=$(dirname "$target") +stage=$(mktemp -d "$parent/.dotclaude-export.XXXXXXXX") +base=$(basename "$target") +rollback() { + if [ "${publishing_pair:-false}" = true ] && [ "$target" -ef "$stage/$base" ] && ! [ .aider.conf.yml -ef "$stage/.aider.conf.yml" ]; then + rm -f "$target" + fi + rm -rf "$stage" } - -if [ -z "$TARGET_AGENT" ]; then - usage +trap rollback EXIT +trap 'exit 1' HUP INT TERM +if [ -e "$target" ] || [ -L "$target" ]; then + echo "Already exists: $target. Generate in an empty directory to compare." >&2 exit 1 fi -if [ ! -f "$SOURCE" ]; then - err "Source file not found: $SOURCE" - exit 1 +if [ "$1" = cursor ]; then + printf '%s\n' '---' 'description: dotclaude project working preferences' 'alwaysApply: true' '---' '' > "$stage/$base" +else + : > "$stage/$base" fi +awk '/^$/ {exit} {print}' "$source_file" >> "$stage/$base" -echo "" -echo "dotclaude converter" -echo "===================" -echo "" - -# ── Convert ─────────────────────────────────────────────────────────────────── - -case "$TARGET_AGENT" in - - codex) - TARGET="$(pwd)/AGENTS.md" - info "Converting for OpenAI Codex / ChatGPT..." - { - echo "# AGENTS.md" - echo "# Converted from dotclaude CLAUDE.md (github.com/yourusername/dotclaude)" - echo "# Adjust the 'About Me' section to match your profile." - echo "" - sanitize_for_agent < "$SOURCE" | grep -v "^# Global CLAUDE.md" - } > "$TARGET" - ok "Written: $TARGET" - warn "Review and remove any Claude-specific tool references (Skill tool, Agent tool)" - ;; - - gemini) - TARGET="$(pwd)/GEMINI.md" - info "Converting for Gemini CLI..." - { - echo "# GEMINI.md" - echo "# Converted from dotclaude CLAUDE.md (github.com/yourusername/dotclaude)" - echo "# Adjust the 'About Me' section to match your profile." - echo "" - sanitize_for_agent < "$SOURCE" | grep -v "^# Global CLAUDE.md" - } > "$TARGET" - ok "Written: $TARGET" - warn "Review Gemini CLI docs for supported frontmatter fields" - ;; - - cursor) - TARGET="$(pwd)/.cursorrules" - info "Converting for Cursor..." - # Cursor uses a flat text format — strip markdown headings - { - printf "# Coding agent rules (converted from dotclaude)\n" - printf "# Source: github.com/yourusername/dotclaude\n\n" - sanitize_for_agent < "$SOURCE" \ - | grep -v "^# Global CLAUDE.md" \ - | sed 's/^## /\n/; s/^### /\n/; s/^#### //' - } > "$TARGET" - ok "Written: $TARGET" - warn "Cursor rules are plain text — review for any markdown that renders oddly" - ;; - - aider) - TARGET="$(pwd)/.aider.conf.yml" - info "Converting for Aider..." - { - printf "# .aider.conf.yml\n" - printf "# Converted from dotclaude CLAUDE.md\n" - printf "# Source: github.com/yourusername/dotclaude\n\n" - printf "system-prompt: |\n" - sanitize_for_agent < "$SOURCE" \ - | grep -v "^# Global CLAUDE.md" \ - | sed 's/^/ /' - } > "$TARGET" - ok "Written: $TARGET" - warn "Verify aider --system-prompt flag syntax for your aider version" - ;; - - *) - err "Unknown agent: $TARGET_AGENT" - usage +if [ "$1" = aider ]; then + cfg=.aider.conf.yml + if [ -e "$cfg" ] || [ -L "$cfg" ]; then + echo "Already exists: $cfg. Generate in an empty directory to compare." >&2 exit 1 - ;; - -esac + fi + printf '%s\n' 'read:' ' - dotclaude-conventions.md' > "$stage/.aider.conf.yml" +fi -echo "" -echo " The converted file keeps the core behavioral principles." -echo " Agent-specific mechanics (Shift+Tab, /commands, Esc Esc) have been" -echo " replaced with generic equivalents." -echo "" -echo " Always review before using — some Claude Code concepts have no" -echo " direct equivalent in other agents." -echo "" +if [ "$1" = aider ]; then publishing_pair=true; fi +ln "$stage/$base" "$parent/" +if [ "$1" = aider ]; then + ln "$stage/.aider.conf.yml" ./ + echo "Created $cfg and $target" +else + echo "Created $target" +fi diff --git a/scripts/test_defaults.py b/scripts/test_defaults.py new file mode 100644 index 0000000..c109c0a --- /dev/null +++ b/scripts/test_defaults.py @@ -0,0 +1,74 @@ +"""Check the shipped defaults and export only into disposable directories.""" +import concurrent.futures +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +CONVERTER = ROOT / "scripts/convert.sh" +PORTABLE = (ROOT / "config/CLAUDE.md").read_text().split("")[0].strip() + + +def run_export(directory, target): + return subprocess.run(["sh", str(CONVERTER), target], cwd=directory, capture_output=True) + + +class DefaultsTest(unittest.TestCase): + def test_optional_settings_do_not_preapprove_commands_or_start_workers(self): + settings = json.loads((ROOT / "config/settings.json").read_text()) + self.assertEqual(settings["permissions"]["defaultMode"], "default") + self.assertFalse(settings["permissions"].get("allow")) + self.assertIs(settings["autoMemoryEnabled"], False) + for key in ("hooks", "enabledPlugins", "extraKnownMarketplaces", "statusLine"): + self.assertNotIn(key, settings) + self.assertIn("Read(**/.env)", settings["permissions"]["deny"]) + for agent in (ROOT / "config/agents").glob("*.md"): + self.assertNotIn("memory: user", agent.read_text()) + + def test_each_host_gets_portable_instructions(self): + outputs = {"codex": "AGENTS.md", "gemini": "GEMINI.md", + "cursor": ".cursor/rules/dotclaude.mdc", "aider": "dotclaude-conventions.md"} + for name, expected in outputs.items(): + with self.subTest(target=name), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + self.assertEqual(run_export(root, name).returncode, 0) + output = (root / expected).read_text() + if name == "cursor": + self.assertTrue(output.startswith("---\n")) + self.assertIn("alwaysApply: true", output.split("---", 2)[1]) + output = output.split("---", 2)[2] + self.assertEqual(output.strip(), PORTABLE) + if name == "aider": + self.assertEqual((root / ".aider.conf.yml").read_text(), "read:\n - dotclaude-conventions.md\n") + (root / expected).write_text("existing user file") + self.assertNotEqual(run_export(root, name).returncode, 0) + self.assertEqual((root / expected).read_text(), "existing user file") + + def test_conflicts_and_linked_parents_preserve_user_files(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / ".aider.conf.yml").write_text("existing: true") + self.assertNotEqual(run_export(root, "aider").returncode, 0) + self.assertFalse((root / "dotclaude-conventions.md").exists()) + other = root / "separate" + other.mkdir() + (root / ".cursor").symlink_to(other, target_is_directory=True) + self.assertNotEqual(run_export(root, "cursor").returncode, 0) + self.assertFalse(any(other.iterdir())) + (root / "GEMINI.md").symlink_to(other / "missing") + self.assertNotEqual(run_export(root, "gemini").returncode, 0) + self.assertFalse((other / "missing").exists()) + + def test_concurrent_exports_leave_one_complete_result(self): + with tempfile.TemporaryDirectory() as tmp: + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(lambda _: run_export(tmp, "aider").returncode, range(4))) + self.assertEqual(results.count(0), 1) + self.assertEqual((Path(tmp) / "dotclaude-conventions.md").read_text().strip(), PORTABLE) + self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), [".aider.conf.yml", "dotclaude-conventions.md"]) + + +if __name__ == "__main__": + unittest.main() From 23b9ae9f3004e67b8b1571cde25de97999531045 Mon Sep 17 00:00:00 2001 From: poferraz <210631651+poferraz@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:41:26 -0700 Subject: [PATCH 2/5] Document maintainer choices, upstream credits and supported setup --- .github/ISSUE_TEMPLATE/bug_report.md | 4 +- AUDIT.md | 178 ----------------- CHANGELOG.md | 55 +----- CONTRIBUTING.md | 67 +------ LICENSE | 2 + MANIFEST.md | 121 ++---------- README.md | 277 ++------------------------ SECURITY.md | 52 +---- docs/architecture.md | 205 ------------------- docs/context-budget.md | 119 ----------- docs/customization.md | 282 +++------------------------ docs/research-notes.md | 219 +-------------------- 12 files changed, 88 insertions(+), 1493 deletions(-) delete mode 100644 AUDIT.md delete mode 100644 docs/architecture.md delete mode 100644 docs/context-budget.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6c6b60f..8d8f0f2 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -28,9 +28,7 @@ assignees: '' ## Error output -``` -paste any error messages here -``` +Use a short, redacted excerpt with fictional paths and values. Keep profile files, credentials and session logs out of public issues. ## Additional context diff --git a/AUDIT.md b/AUDIT.md deleted file mode 100644 index fb8e611..0000000 --- a/AUDIT.md +++ /dev/null @@ -1,178 +0,0 @@ -# dotclaude Source Verification Report -Date: Wednesday, March 25, 2026 - -## Research Papers - -### Evaluating AGENTS.md: Are Repository-Level Context Files Helpful? -- Repo states — authors: Gloaguen et al. | Source shows — authors: Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev -- Repo states — title: Evaluating AGENTS.md: Are Repository-Level Context Files Helpful? | Source shows — title: Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents? -- Repo states — year: 2026 | Source shows — year: 2026 -- Repo states — arxiv: https://arxiv.org/abs/2602.11988 | Status: resolves to this paper -- Numerical claims: - | Claim in repo | Value in source | Location in source | Match? | - |---|---|---|---| - | Increased API cost by 20–23% | inference cost by over 20% | Abstract | Approximate match | - | Increased reasoning tokens by 14–22% | Not extracted in summary snippet | - | Not found | -- Qualitative claims: - | Claim in repo | Statement in source | Difference in scope/strength | - |---|---|---| - | LLM-generated context files reduced task success in 5 of 8 settings | Context files tend to reduce task success rates compared to providing no repository context | Source speaks generally; repo specifies "5 of 8 settings" | - | Human-written files performed better, but only when they contained non-obvious requirements the agent couldn't discover itself | Human-written context files should describe only minimal requirements to be effective | Matches closely in meaning | - -### Seeing the Goal, Missing the Truth -- Repo states — authors: Cao, Jiang, Xu | Source shows — authors: Sean Cao, Wei Jiang, Hui Xu -- Repo states — title: Seeing the Goal, Missing the Truth | Source shows — title: Seeing the Goal, Missing the Truth: Human Accountability for AI Bias -- Repo states — year: 2026 | Source shows — year: 2026 -- Repo states — arxiv: https://arxiv.org/abs/2602.09504 | Status: resolves to this paper -- Numerical claims: - | Claim in repo | Value in source | Location in source | Match? | - |---|---|---|---| - | None explicitly in snippet | - | - | - | -- Qualitative claims: - | Claim in repo | Statement in source | Difference in scope/strength | - |---|---|---| - | Telling an LLM how its output will be evaluated causes it to reshape outputs to game the metric, degrading out-of-sample performance. | Goal-aware prompting shifts intermediate measures toward the disclosed downstream objective... provides no advantage post-cutoff. | Matches closely | - -### Control Illusion: Understanding and Addressing LLM Instruction Hierarchy Failure -- Repo states — authors: Geng et al. | Source shows — authors: Yilin Geng, Haonan Li, Honglin Mu, Xudong Han, Timothy Baldwin, Omri Abend, Eduard Hovy, Lea Frermann -- Repo states — title: Control Illusion: Understanding and Addressing LLM Instruction Hierarchy Failure | Source shows — title: Control Illusion: The Failure of Instruction Hierarchies in Large Language Models -- Repo states — year: 2025 | Source shows — year: 2025 -- Repo states — arxiv: https://arxiv.org/abs/2502.15851 | Status: resolves to this paper -- Numerical claims: - | Claim in repo | Value in source | Location in source | Match? | - |---|---|---|---| - | LLM instruction obedience drops to 9.6% under cross-tier conflict | 9.6% | Abstract | Exact match | -- Qualitative claims: - | Claim in repo | Statement in source | Difference in scope/strength | - |---|---|---| - | Recency bias is the strongest compliance driver — position in context matters more than explicit priority markers | Models are significantly more likely to follow the instruction that appears last in the prompt, regardless of its assigned priority or role. Position in context matters more than explicit priority markers. | Exact match | - | Critical rules placed at the END of context yield highest compliance | Critical rules placed at the end of the prompt yield the highest compliance. | Exact match | - -### LLM Code Smells in Agentic Systems -- Repo states — authors: Mahmoudi et al. | Source shows — authors: Brahim Mahmoudi et al. -- Repo states — title: LLM Code Smells in Agentic Systems | Source shows — title: Specification and Detection of LLM Code Smells -- Repo states — year: 2025 | Source shows — year: 2025 -- Repo states — arxiv: https://arxiv.org/abs/2512.18020 | Status: resolves to this paper -- Numerical claims: - | Claim in repo | Value in source | Location in source | Match? | - |---|---|---|---| - | 40.5% of agent system failures are caused by Non-Specific Output (NSO) | 60.50% of them contained at least one of these code smells (UMM, NMVP, NSM, NSO, TNES). | Abstract/Summary | Mismatch / Not found in source | -- Qualitative claims: - | Claim in repo | Statement in source | Difference in scope/strength | - |---|---|---| - | NSO = agent returns free-form prose where a structured schema was expected | No Structured Output (NSO): Relying on raw text parsing instead of using structured formats | Matches meaning | - | XML tag wrapping significantly reduces NSO failure rates for Claude | Not explicitly stated in the general abstract summary | Not found | - -### Revisiting Role-Play Prompting: A Systematic Assessment of Persona Calibration in LLMs -- Repo states — authors: Hu et al. | Source shows — authors: Zizhao Hu, Mohammad Rostami, and Jesse Thomason -- Repo states — title: Revisiting Role-Play Prompting: A Systematic Assessment of Persona Calibration in LLMs | Source shows — title: Expert Personas Improve LLM Alignment but Damage Accuracy: Bootstrapping Intent-Based Persona Routing with PRISM -- Repo states — year: 2026 | Source shows — year: 2026 -- Repo states — arxiv: https://arxiv.org/abs/2603.18507 | Status: resolves to this paper -- Numerical claims: - | Claim in repo | Value in source | Location in source | Match? | - |---|---|---|---| - | For safety analysis, a full auditor persona raises refusal rate by +17.7%. | Not explicitly in abstract summary | - | Not found / Unverified | -- Qualitative claims: - | Claim in repo | Statement in source | Difference in scope/strength | - |---|---|---| - | Persona effects are asymmetric by task type | Task Dependency: Generative/Alignment Tasks vs. Discriminative/Logic Tasks | Matches closely | - | For code tasks (pretraining), personas hurt accuracy. | Discriminative/Logic Tasks: Personas are detrimental to math, coding, and factual retrieval. | Matches closely | - | For style/tone tasks (alignment), personas help. | Generative/Alignment Tasks: Personas are beneficial for creative writing, roleplay, and safety | Matches closely | - | Generic "helpful expert" personas on debugging tasks degrade output by directing attention to the persona narrative instead of the problem. | The model focuses more on acting like an expert than actually being accurate. | Matches closely | - -## URLs - -| URL | Status | Notes | -|---|---|---| -| https://agents.md | 200 | | -| https://arxiv.org/abs/2502.15851 | 200 | Paper title: Control Illusion: The Failure of Instruction Hierarchies in Large Language Models | -| https://arxiv.org/abs/2512.18020 | 200 | Paper title: Specification and Detection of LLM Code Smells | -| https://arxiv.org/abs/2602.09504 | 200 | Paper title: Seeing the Goal, Missing the Truth: Human Accountability for AI Bias | -| https://arxiv.org/abs/2602.11988 | 200 | Paper title: Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents? | -| https://arxiv.org/abs/2603.18507 | 200 | Paper title: Expert Personas Improve LLM Alignment but Damage Accuracy: Bootstrapping Intent-Based Persona Routing with PRISM | -| https://claude.ai/code | 403 | | -| https://docs.anthropic.com/en/docs/claude-code | 200 | | -| https://dotclaude-setup.vercel.app/ | 200 | | -| https://github.com/affaan-m/everything-claude-code | 200 | Repo title: affaan-m/everything-claude-code | -| https://github.com/garrytan/gstack | 200 | Repo title: garrytan/gstack | -| https://github.com/hardikpandya/stop-slop | 200 | Repo title: hardikpandya/stop-slop | -| https://github.com/poferraz/dotclaude.git | 200 | | -| https://github.com/severity1/claude-code-prompt-improver | 200 | Repo title: severity1/claude-code-prompt-improver | -| https://github.com/shanraisshan/claude-code-best-practice | 200 | Repo title: shanraisshan/claude-code-best-practice | -| https://github.com/steveyegge/beads | 200 | Repo title: steveyegge/beads | -| https://github.com/thedotmack | 200 | Page title: thedotmack (Alex Newman) · GitHub | -| https://img.shields.io/badge/Claude%20Code-2.1.0%2B-blue | 200 | | -| https://img.shields.io/badge/License-MIT-yellow.svg | 200 | | -| https://img.shields.io/badge/PRs-welcome-brightgreen.svg | 200 | | -| https://img.shields.io/badge/Website-dotclaude--setup.vercel.app-000000?logo=vercel | 200 | | -| https://json.schemastore.org/claude-code-settings.json | 200 | | -| https://keepachangelog.com/en/1.0.0/ | 200 | | -| https://opensource.org/licenses/MIT | 200 | | -| https://semver.org/spec/v2.0.0.html | 200 | | -| https://skill-creator.app | 000 | Fails / Connection error | -| https://x.com/affaanmustafa/status/2014040193557471352 | 200 | | - -## Tool Descriptions - -### everything-claude-code -- Repo says: Agents, skills, hooks, commands, rules, and the plugin architecture. The foundation this setup started from. -- Source says: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. -- Username — repo: affaan-m | actual: affaan-m -- Repo name — repo: everything-claude-code | actual: everything-claude-code - -### gstack -- Repo says: Persistent headless Chromium browser daemon for QA and dogfooding. `/browse`, `/careful`, `/freeze`, `/guard`, `/unfreeze`. -- Source says: Use Garry Tan's exact Claude Code setup: 15 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA -- Username — repo: garrytan | actual: garrytan -- Repo name — repo: gstack | actual: gstack - -### claude-code-prompt-improver -- Repo says: Prompt evaluation plugin that intercepts vague prompts before execution -- Source says: Intelligent prompt improver hook for Claude Code. Type vibes, ship precision. -- Username — repo: severity1 | actual: severity1 -- Repo name — repo: claude-code-prompt-improver | actual: claude-code-prompt-improver - -### claude-code-best-practice -- Repo says: Reference patterns for Claude Code workflows and conventions -- Source says: practice made claude perfect -- Username — repo: shanraisshan | actual: shanraisshan -- Repo name — repo: claude-code-best-practice | actual: claude-code-best-practice - -### context-mode -- Repo says: Session memory and observation system (context-mode plugin) -- Source says: claude-mem: A Claude Code plugin that captures session data, compresses it with AI, and injects relevant context back into future sessions. -- Username — repo: thedotmack | actual: thedotmack -- Repo name — repo: context-mode | actual: claude-mem (or not found exactly as context-mode on profile) - -### beads -- Repo says: Structured task tracking for coding agents. Recommended as the on-demand memory layer. -- Source says: Beads - A memory upgrade for your coding agent -- Username — repo: steveyegge | actual: steveyegge -- Repo name — repo: beads | actual: beads - -### stop-slop -- Repo says: Writing quality patterns adapted for skill output -- Source says: A skill file for removing AI tells from prose -- Username — repo: hardikpandya | actual: hardikpandya -- Repo name — repo: stop-slop | actual: stop-slop - -## Claude Code Claims - -| Claim | Official docs say | Source URL | -|---|---|---| -| Use of hooks to intercept commands/actions | "Hooks let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit." | https://docs.anthropic.com/en/docs/claude-code | -| Use of frontmatter fields like `skills:` | Not found in official docs | https://docs.anthropic.com/en/docs/claude-code | -| Use of "plugin architecture" | Not found in official docs (mentions JetBrains plugin, but not an extensible plugin architecture for Claude Code itself) | https://docs.anthropic.com/en/docs/claude-code | -| Auto-loading and skill discovery | Not found in official docs | https://docs.anthropic.com/en/docs/claude-code | -| "Agent tool" for agents to invoke other agents | Not found in official docs | https://docs.anthropic.com/en/docs/claude-code | - -## Attribution Language - -Sentences with unattributed findings: -- "The key insight behind this design: most context files hurt performance — they flood the model's attention with boilerplate before a single line of your code is seen." -- "Coding agents perform measurably worse with bloated context files." -- "When the context window fills with generic instructions, framework boilerplate, and catch-all rules, the model's attention is diluted before it ever sees your actual problem." -- "Research now confirms what practitioners suspected: more context is not better context." - -Instances of "we/our/I" + finding: -- None found. diff --git a/CHANGELOG.md b/CHANGELOG.md index 37b2be4..3ede8c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,53 +1,12 @@ # Changelog -All notable changes to this project will be documented in this file. +## Unreleased -Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html) +- The installer preserves existing files and the restore process keeps the displaced profile for recovery. [Installation and recovery](docs/customization.md) +- The optional settings example leaves plugin installation and external integrations to the user. Review existing host settings separately. +- The four instruction exports preserve existing files. The Cursor export uses a project rule and Aider reads a separate conventions file. +- Corrected research claims and consolidated upstream credits and notices. [Research](docs/research-notes.md) · [Sources](MANIFEST.md) ---- +## 1.0.0 — March 24, 2026 -## [1.0.0] — 2026-03-24 - -### Added - -**Core configuration** -- `CLAUDE.md` — global behavioral principles (under 30 lines, research-optimized) -- `settings.json` — hardened permission model, lifecycle hooks, plugin registry -- `mcp.json` — GitHub and Google Drive MCP servers (env-var credentials only) - -**Agents (8 total)** -- `code-reviewer` — SOLID/security/YAGNI review via `git diff` -- `debugger` — root-cause diagnosis, never implements -- `doc-updater` — sync docs after API/interface changes -- `planner` — phase-wise gated plans with acceptance criteria (Opus) -- `refactorer` — structural cleanup with test-passing gates -- `security-reviewer` — injection, auth, secrets, data validation -- `tdd-guide` — RED→GREEN→IMPROVE with coverage delta reporting -- `ui-designer` — 2026-style React/Tailwind with preloaded design system - -**Skills (6 total, 5 on-demand)** -- `coding-standards` — language-agnostic quality rules -- `continuous-learning-v2` — instinct-based session pattern learning -- `strategic-compact` — context compaction at logical intervals -- `tdd-workflow` — TDD methodology (agent-preloaded by `tdd-guide`) -- `ui-ux-pro-max` — 67 styles, 96 palettes, 57 font pairings -- `verification-loop` — systematic post-change verification - -**Commands (14 total)** -- `/audit-repo`, `/build-fix`, `/checkpoint`, `/code-review`, `/evolve` -- `/full-review`, `/full-stack-feature`, `/instinct-status`, `/learn` -- `/new-project`, `/plan`, `/pr-enhance`, `/tdd`, `/verify` - -**Plugins enabled** -- `everything-claude-code` (affaan-m) — extended agent and skill library -- `context-mode` (thedotmack) — session memory and context protection -- `prompt-improver` (severity1) — prompt evaluation on UserPromptSubmit -- `ui-ux-pro-max` (nextlevelbuilder) — UI design intelligence - -**Repository** -- Full attribution table in README -- Research citations: Gloaguen et al. (2026), Cao et al. (2026) -- CONTRIBUTING.md with explicit content bar -- SECURITY.md -- GitHub issue templates and PR template +The initial collection brought together a global instruction file, eight agent definitions, six skills and fourteen commands. The repository subsequently added the optional second-opinion command. [Original commands](https://github.com/poferraz/dotclaude/commit/d9e98758c30664735f6bf5517412f9081eccc9f2) · [Second-opinion change](https://github.com/poferraz/dotclaude/commit/2a5cc3a81651115d0e3094d6090ca28c83421c22) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1994aa1..8b33f49 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,66 +1,7 @@ -# Contributing to dotclaude +# Contributing -Thank you for your interest. This is a minimal-by-design configuration — the -bar for adding new content is intentionally high. +Explain which task your change helps, when the instructions will load and what already exists in the host or repository. A proposed change to the global `CLAUDE.md` affects every project that uses the profile. Include the estimated context impact requested by the pull request template and use an example to show why the change belongs there. -## The Standard +Keep agent instructions, commands and skill references in their matching [configuration directories](config/). Credit upstream work and preserve its license notice. When citing research, identify the task and population the paper actually studied. [Sources and credits](MANIFEST.md) · [Research notes](docs/research-notes.md) -Before proposing new context, agents, or skills, ask yourself one question: -**Can Claude figure this out on its own?** - -If yes — from its training, from reading the codebase, or from the existing -config — don't add it. The research this repo is built on (Gloaguen et al., -2026) shows that redundant context actively hurts performance. We are not -trying to teach Claude to code. We are providing the small set of behavioral -overrides and workflow tools it cannot infer. - -Every PR that adds tokens to auto-loading files (CLAUDE.md, rules, agent -system prompts) must include a justification with estimated token cost and a -clear answer to why this cannot be inferred. - -## What We're Looking For - -**Good:** -- A leaner replacement for an existing agent or skill with evidence it performs better -- A research update that changes what should or shouldn't be in CLAUDE.md -- A bug fix (broken hook, incorrect tool permission, wrong model assignment) -- Attribution correction or addition - -**Not a fit:** -- Generic agents that could apply to anything (use everything-claude-code instead) -- Skills that duplicate upstream repos -- Commands that would be better as a one-line shell alias -- Style opinions without evidence - -## How to Contribute - -1. Fork the repo -2. Create a branch: `git checkout -b type/short-description` -3. Make your changes -4. Open a PR using the PR template — the Token Impact section is required - -## Commit Format - -Conventional commits are required: - -``` -feat: add X agent for Y purpose -fix: correct tool permission for Z -docs: update attribution for W -chore: update .gitignore -refactor: simplify planner system prompt -``` - -Types: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf` - -## Issue Templates - -Use the provided templates in `.github/ISSUE_TEMPLATE/`: - -- **Bug report** — something is broken or behaving unexpectedly -- **Feature request** — a new agent, skill, or command you want to propose -- **Research update** — new research that should inform this setup - -## Code of Conduct - -Be direct and specific. Back claims with evidence. Attribute your sources. +For installer or export changes, exercise the script in a disposable directory. Check what it creates and what it preserves when the target already contains files. Include the command and observed result in the pull request. Use fictional fixtures for private paths, settings and transcripts. [Pull request template](.github/PULL_REQUEST_TEMPLATE.md) · [Security reports](SECURITY.md) diff --git a/LICENSE b/LICENSE index c4e1418..73c5a22 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,8 @@ MIT License Copyright (c) 2026 Paulo Ferraz +Copyright (c) 2026 Affaan Mustafa +Copyright (c) 2024 Next Level Builder Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/MANIFEST.md b/MANIFEST.md index c0b28fd..88aa88a 100644 --- a/MANIFEST.md +++ b/MANIFEST.md @@ -1,114 +1,15 @@ -# MANIFEST +# Project sources and credits -Every file in `config/` — purpose, source, token cost, and whether it auto-loads. +The installable files live under [config](config/). The project supplies the shared instructions, selects the agents and integrates commands and reference material from the sources below. The MIT license covers this collection. Upstream copyright notices appear in the [license file](LICENSE). -**Token cost formula:** word count × 1.3 (approximate tokens) -**Auto-loads:** YES = loaded every session. NO = loaded only when invoked. +| Material | Source | +| --- | --- | +| Agent configurations, coding standards and original commands such as `/new-project`, `/plan` and `/second-opinion` | dotclaude's configuration and integration work. [Agents](config/agents/) · [Commands](config/commands/) | +| Learning, compaction, test-driven development and verification skills, plus the review, learning and verification commands credited in the original inventory | Adapted from Affaan Mustafa's [Everything Claude Code](https://github.com/affaan-m/everything-claude-code). [Upstream license](https://raw.githubusercontent.com/affaan-m/everything-claude-code/bf7ed1fce20ea3be010552ee431b05fe425fb85e/LICENSE) | +| UI design reference used by the UI designer agent | Adapted from Next Level Builder's [UI UX Pro Max](https://github.com/nextlevelbuilder/ui-ux-pro-max-skill). [Upstream license](https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/0d58617a4281f441b58f480bf245083e57a8667d/LICENSE) | -> Files marked NO are on-demand by design. Loading only what the current task -> needs is the primary mechanism for keeping session start under 3,000 tokens. +The original project also credited these projects as influences or optional integrations. Their upstream packages have their own installation instructions. ---- - -## config/CLAUDE.md - -| Field | Value | -|-------|-------| -| **Purpose** | Global behavioral overrides — principles the model wouldn't apply by default | -| **Source** | Original | -| **Token cost** | ~450 tokens | -| **Auto-loads** | YES — loads every session via Claude Code's hierarchical CLAUDE.md loading | - ---- - -## config/settings.json - -| Field | Value | -|-------|-------| -| **Purpose** | Permissions, lifecycle hooks, plugin registry, model defaults | -| **Source** | Original (hooks pattern from context-mode / @thedotmack) | -| **Token cost** | N/A — not injected into context, parsed by Claude Code runtime | -| **Auto-loads** | N/A — system config, not context | - ---- - -## config/agents/ - -| File | Purpose | Source | Tokens | Auto-loads | -|------|---------|--------|--------|-----------| -| `code-reviewer.md` | Review `git diff` for SOLID/security/YAGNI violations | Original | ~65 | NO | -| `debugger.md` | Root cause trace only — never implements | Original | ~55 | NO | -| `doc-updater.md` | Sync docs after API/interface changes (runs in background, Haiku) | Original | ~50 | NO | -| `planner.md` | Phase-wise gated plans with acceptance criteria (Opus) | Original | ~65 | NO | -| `refactorer.md` | Structural cleanup — tests must pass before and after | Original | ~70 | NO | -| `security-reviewer.md` | Injection, auth gaps, secrets exposure, data validation | Original | ~55 | NO | -| `tdd-guide.md` | RED→GREEN→IMPROVE, 80%+ coverage enforcement | Original (references ECC tdd-workflow skill) | ~60 | NO | -| `ui-designer.md` | 2026-style React/Tailwind with preloaded ui-ux-pro-max | Original (preloads ECC ui-ux-pro-max skill) | ~70 | NO | - -**Total agents context cost when all 8 invoked simultaneously:** ~490 tokens - ---- - -## config/skills/ - -| File | Purpose | Source | Tokens | Auto-loads | -|------|---------|--------|--------|-----------| -| `coding-standards/SKILL.md` | Language-agnostic quality rules: naming, structure, error handling | Original | ~320 | NO | -| `continuous-learning-v2/SKILL.md` | Instinct-based learning from session patterns — observation, confidence scoring | ECC / @affaan-m | ~1,900 | NO | -| `strategic-compact/SKILL.md` | Context compaction decision guide for logical phase boundaries | ECC / @affaan-m | ~480 | NO | -| `strategic-compact/suggest-compact.sh` | Shell hook that triggers compaction suggestion at threshold (default: 50 tool calls) | ECC / @affaan-m | N/A (shell script) | Via hook | -| `tdd-workflow/SKILL.md` | TDD methodology reference: RED→GREEN→IMPROVE, test patterns, coverage | ECC / @affaan-m | ~2,600 | NO (agent-preloaded by tdd-guide) | -| `ui-ux-pro-max/SKILL.md` | 67 styles, 96 palettes, 57 font pairings, 99 UX guidelines | @nextlevelbuilder | ~600 | NO (agent-preloaded by ui-designer) | -| `verification-loop/SKILL.md` | 6-phase verification: build → types → lint → tests → security → diff | ECC / @affaan-m | ~520 | NO | - -**Note:** `continuous-learning-v2` and `ui-ux-pro-max` are full plugin packages with scripts and hooks. Only their `SKILL.md` is here. Install the full package via Claude Code's plugin marketplace for hook-based observation and the complete data directory. - ---- - -## config/commands/ - -| File | Purpose | Source | Tokens | Auto-loads | -|------|---------|--------|--------|-----------| -| `audit-repo.md` | 9-area GitHub repo audit (secrets, structure, CI, community files) | ECC | ~8,600 | NO | -| `build-fix.md` | Incremental build error resolution, one error at a time | ECC | ~320 | NO | -| `checkpoint.md` | Named workflow checkpoints with comparison reporting | ECC | ~260 | NO | -| `code-review.md` | Security + quality review of uncommitted changes | ECC | ~170 | NO | -| `evolve.md` | Cluster instincts into skills/commands, suggest promotions | ECC | ~1,350 | NO | -| `full-review.md` | Multi-agent orchestrated review (code + security + docs) | ECC | ~5,550 | NO | -| `full-stack-feature.md` | End-to-end feature development across backend/frontend/DB/infra | ECC | ~5,600 | NO | -| `instinct-status.md` | Show project + global instincts with confidence bars | ECC | ~170 | NO | -| `learn.md` | Extract reusable patterns from current session | ECC | ~170 | NO | -| `new-project.md` | Bootstrap project `.claude/` structure, CLAUDE.md, MCP config | Original | ~660 | NO | -| `plan.md` | Invoke planner agent — restate requirements, gate on confirmation | Original | ~440 | NO | -| `pr-enhance.md` | PR quality analysis and structured description generation | ECC | ~5,450 | NO | -| `tdd.md` | Invoke tdd-guide agent — scaffold, RED, GREEN, IMPROVE | ECC | ~550 | NO | -| `verify.md` | 6-phase verification report | ECC | ~165 | NO | - -**All 14 commands: auto-loads = NO.** They load only when invoked. - ---- - -## Session Start Token Budget - -| Source | Tokens | Notes | -|--------|--------|-------| -| `CLAUDE.md` | ~450 | Only non-obvious behavioral overrides | -| Claude Code system prompt | ~8,000 | Fixed, not configurable | -| context-mode session index | ~1,500–3,000 | Compressed semantic index of past sessions | -| Hook overhead (per turn) | ~200 | context-mode observation capture | -| **Total at session start** | **~10,000–12,000** | Well under 10% of 200K context window | - -**Target:** Keep the config contribution (CLAUDE.md + hooks) under 3,000 tokens at session start. That's the constraint that keeps this setup lean. - ---- - -## What's Not Here - -| Excluded | Reason | -|----------|--------| -| `settings.local.json` | Machine-specific, may contain personal permissions | -| `memory/` | Personal auto-memory, per-user by definition | -| `sessions/` | Session logs, ephemeral | -| `homunculus/` | Instinct runtime data, per-machine | -| Plugin source code | Separate projects with their own licenses — install via marketplace | -| `rules/` | No global rules directory in this setup — rules live in `CLAUDE.md` or per-project | +- [gstack](https://github.com/garrytan/gstack) by Garry Tan and [Claude Code Best Practice](https://github.com/shanraisshan/claude-code-best-practice) by @shanraisshan informed the workflow choices. +- Earlier configurations referred to prompt improvement, memory and task tracking tools. [Prompt Improver](https://github.com/severity1/claude-code-prompt-improver) · [Claude-Mem](https://github.com/thedotmack/claude-mem) · [Beads](https://github.com/steveyegge/beads) +- Further references included a writing skill, shared instruction conventions and the host's documentation. [Stop Slop](https://github.com/hardikpandya/stop-slop) · [AGENTS.md](https://agents.md/) · [Claude Code documentation](https://code.claude.com/docs/en/overview) diff --git a/README.md b/README.md index 8e16685..f7506f7 100644 --- a/README.md +++ b/README.md @@ -1,274 +1,37 @@ # dotclaude -

- dotclaude — You Need This -

+dotclaude cover artwork -**A research-backed global environment for Claude Code** +dotclaude is a collection of instructions for Claude Code. It gives you a planner, a debugger and review commands that you can call by name. For example, use `/plan` in a project to break down a change and review the proposed steps before editing. -[![Website](https://img.shields.io/badge/Website-dotclaude--setup.vercel.app-000000?logo=vercel)](https://dotclaude-setup.vercel.app/) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Claude Code](https://img.shields.io/badge/Claude%20Code-2.1.0%2B-blue)](https://claude.ai/code) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md) +## Install -A curated `~/.claude/` configuration that combines the best open-source tools -from the Claude Code ecosystem into a single coherent setup. The key insight -behind this design: **most context files hurt performance** — they flood the -model's attention with boilerplate before a single line of your code is seen. (Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev) -This setup is ruthlessly minimal. Every file, agent, and skill must earn its -tokens or it doesn't ship. +Use macOS or Linux with Git, Node.js 18 or later and Claude Code 2.1 or later. Clone the repository and review the files you intend to use. To install the collection into your Claude Code configuration, run the installer from the checkout. ---- - -## Why This Exists - -Coding agents perform measurably worse with bloated context files. (Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev) When the -context window fills with generic instructions, framework boilerplate, and -catch-all rules, the model's attention is diluted before it ever sees your -actual problem. (Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev) Research now confirms what practitioners suspected: more -context is not better context. (Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev) - -Most "awesome Claude Code" setups operate in the opposite direction — they add -everything. Mega-agents with 20 tools. Skills with 500 lines of generic advice. -Commands for every conceivable workflow. The result is a system that impresses -in screenshots and degrades in daily use. - -This configuration was born from real work: retail management tooling, PWA -development, bakery production planning. Not theoretical best practices. It was -audited, stripped down, rebuilt leaner, and audited again. The agents you see -here survived because they provably helped. The ones that didn't are gone. - ---- - -## What's Inside - -``` -~/.claude/ -├── CLAUDE.md # Global context (under 30 lines, research-optimized) -├── agents/ # 8 single-purpose agents with 1-sentence instructions -├── skills/ # 6 skills + gstack browser (5 on-demand, 1 agent-preloaded) -├── commands/ # 15 slash commands (/new-project, /tdd, /plan, etc.) -└── settings.json # Hooks, permissions, plugin config -``` - -**Command → Agent → Skill.** A command (`/plan`) launches a scoped subagent -(`planner`) that optionally loads a knowledge pack (`tdd-workflow`) via its -`skills:` frontmatter. Agents invoke other agents via the Agent tool — never -via bash. Skills are knowledge, not code: they load context, not behavior. - ---- - -## Quick Start - -> **Guided setup:** [dotclaude-setup.vercel.app](https://dotclaude-setup.vercel.app/) walks you through installation interactively. - -```bash -# 1. Clone +```sh git clone https://github.com/poferraz/dotclaude.git cd dotclaude - -# 2. Run the install script -# (backs up your existing ~/.claude/ automatically) -bash scripts/install.sh - -# 3. Merge settings manually -# Review config/settings.json and add hook/plugin config to ~/.claude/settings.json -# (the script will tell you exactly what to do) - -# 4. Verify -claude --version -claude doctor +sh scripts/install.sh ``` -> The install script backs up your existing `~/.claude/` before touching anything, -> copies config files, and prints next steps for plugin installation. -> It does not transmit any data. See [SECURITY.md](SECURITY.md). - ---- - -## The Research Behind It - -### Context files can hurt you (Thibaud Gloaguen, Niels Mündler, Mark Müller, Veselin Raychev, Martin Vechev, 2026) - -**Paper:** ["Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?"](https://arxiv.org/abs/2602.11988) - -Key findings: -- Context files tend to **reduce task success rates compared to providing no repository context** -- Increased inference cost by **over 20%** -- Human-written context files should describe **only minimal requirements to be effective** - -**How this repo applies it:** `CLAUDE.md` is under 30 lines and contains only -behavioral principles that override default model behavior. No framework -boilerplate. No re-teaching what the model already knows. No comprehensive -style guides the model could infer from the codebase. - -### Goal-blind prompting (Sean Cao, Wei Jiang, Hui Xu, 2026) - -**Paper:** ["Seeing the Goal, Missing the Truth: Human Accountability for AI Bias"](https://arxiv.org/abs/2602.09504) - -Key finding: Goal-aware prompting shifts intermediate measures toward the disclosed downstream objective, and provides no advantage post-cutoff. - -**How this repo applies it:** The prompting philosophy in `CLAUDE.md` is -goal-blind by design — specify WHAT to build, never HOW it will be evaluated. -Never ask for success criteria. Infer quality from the task. - -### Instruction hierarchy failure and recency bias (Yilin Geng, Haonan Li, Honglin Mu, Xudong Han, Timothy Baldwin, Omri Abend, Eduard Hovy, Lea Frermann, 2025) - -**Paper:** ["Control Illusion: The Failure of Instruction Hierarchies in Large Language Models"](https://arxiv.org/abs/2502.15851) - -Key findings: -- LLM instruction obedience drops to **9.6%** under cross-tier conflict -- Models are significantly more likely to follow the instruction that appears last in the prompt, regardless of its assigned priority or role. Position in context matters more than explicit priority markers. -- Critical rules placed at the end of the prompt yield the highest compliance. - -**How this repo applies it:** `CLAUDE.md` uses XML blocks (``) -with non-negotiable rules positioned at the **absolute bottom** of the file. -The recency anchor outperforms "NON-NEGOTIABLE" labels placed mid-document. - -### LLM agent code smells and NSO mitigation (Brahim Mahmoudi et al., 2025) - -**Paper:** ["Specification and Detection of LLM Code Smells"](https://arxiv.org/abs/2512.18020) - -Key findings: -- **60.50%** of them contained at least one of these code smells. -- No Structured Output (NSO): Relying on raw text parsing instead of using structured formats - -**How this repo applies it:** Every skill in `~/.claude/skills/` includes a -"Strict Output Schema" section with mandatory XML tags. Agents that invoke -these skills must wrap their outputs — free-form prose is treated as a bug, -not a style choice. - -### Asymmetric persona calibration (Zizhao Hu, Mohammad Rostami, and Jesse Thomason, 2026) - -**Paper:** ["Expert Personas Improve LLM Alignment but Damage Accuracy: Bootstrapping Intent-Based Persona Routing with PRISM"](https://arxiv.org/abs/2603.18507) - -Key finding: Task Dependency: Generative/Alignment Tasks vs. Discriminative/Logic Tasks. Discriminative/Logic Tasks: Personas are detrimental to math, coding, and factual retrieval. Generative/Alignment Tasks: Personas are beneficial for creative writing, roleplay, and safety. The model focuses more on acting like an expert than actually being accurate. - -**How this repo applies it:** All 8 agents use task-typed system prompts. Code -agents (`code-reviewer`, `debugger`, `refactorer`, `tdd-guide`) have empty -bodies or single behavioral constraints — no personas. Safety agents -(`security-reviewer`) have full 50+ word auditor personas. Style agents -(`doc-updater`, `ui-designer`) have 1–2 sentence personas. The planner uses -a behavioral constraint only. See [`docs/architecture.md`](docs/architecture.md) -for the full classification table. - ---- - -## Built On The Shoulders Of Giants - -| Project | What I Used | Credit | -|---------|-------------|--------| -| [everything-claude-code](https://github.com/affaan-m/everything-claude-code) | The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. | @affaan-m | -| [gstack](https://github.com/garrytan/gstack) | Use Garry Tan's exact Claude Code setup: 15 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA | @garrytan | -| [claude-code-prompt-improver](https://github.com/severity1/claude-code-prompt-improver) | Intelligent prompt improver hook for Claude Code. Type vibes, ship precision. | @severity1 | -| [claude-code-best-practice](https://github.com/shanraisshan/claude-code-best-practice) | practice made claude perfect | @shanraisshan | -| [claude-mem](https://github.com/thedotmack) | claude-mem: A Claude Code plugin that captures session data, compresses it with AI, and injects relevant context back into future sessions. | @thedotmack | -| [beads](https://github.com/steveyegge/beads) | Beads - A memory upgrade for your coding agent | @steveyegge | -| [stop-slop](https://github.com/hardikpandya/stop-slop) | A skill file for removing AI tells from prose | @hardikpandya | -| [AGENTS.md spec](https://agents.md) | The open standard for guiding coding agents | AGENTS.md community | -| [Anthropic Claude Code docs](https://docs.anthropic.com/en/docs/claude-code) | Official documentation for CLAUDE.md, hooks, agents, skills, commands | Anthropic | - -This repository is an assembly, not an invention. Every tool, pattern, and -architecture decision traces back to the work of the developers and researchers -listed above. I built this by installing their tools, testing them on real -projects, reading the research, and cutting everything that didn't earn its -place. If you find this useful, **star THEIR repos first.** - ---- - -## Philosophy - -- **Every token in your context window should earn its place.** If a rule - describes behavior Claude would exhibit anyway from training, delete it. -- **Trust the model's training — don't re-teach it what it already knows.** - A 30-line CLAUDE.md that overrides defaults beats a 300-line one that - restates them. -- **On-demand over auto-loaded, always.** Skills and context that load only - when invoked don't cost tokens on unrelated tasks. - ---- - -## Agents - -| Agent | Purpose | Model | -|-------|---------|-------| -| `code-reviewer` | Review changes via `git diff` — SOLID, security, YAGNI violations | sonnet | -| `debugger` | Trace bugs to root cause and propose minimal fix. Never implements. | sonnet | -| `doc-updater` | Sync documentation after public API or interface changes | sonnet | -| `planner` | Phase-wise gated plans with deliverables and acceptance criteria | opus | -| `refactorer` | Structural cleanup without behavior change. Requires tests before and after. | sonnet | -| `security-reviewer` | Injection, auth gaps, secrets exposure, data validation | sonnet | -| `tdd-guide` | Enforce RED→GREEN→IMPROVE. Report coverage delta each cycle. | sonnet | -| `ui-designer` | 2026-style React/Tailwind components with preloaded design system | sonnet | - -All agents: single responsibility, scoped tool list, one-sentence system prompt. -The planner uses Opus because planning quality compounds across the entire task. - ---- - -## Skills - -| Skill | Purpose | Loading | -|-------|---------|---------| -| `coding-standards` | Language-agnostic quality rules: naming, structure, error handling, immutability | On-demand | -| `continuous-learning-v2` | Instinct-based learning from session patterns | On-demand | -| `strategic-compact` | Context compaction triggers at logical session intervals | On-demand | -| `tdd-workflow` | TDD methodology reference loaded by the `tdd-guide` agent | **Agent-preloaded** | -| `ui-ux-pro-max` | 67 styles, 96 palettes, 57 font pairings — loaded by `ui-designer` | On-demand | -| `verification-loop` | Systematic verification checklist after multi-step changes | On-demand | - -5 of 6 skills are on-demand by design. Only `tdd-workflow` is preloaded — and -only by the agent that needs it, not at session start. - ---- - -## Commands - -| Command | Purpose | -|---------|---------| -| `/audit-repo` | Full GitHub repository audit | -| `/build-fix` | Triage and resolve build errors | -| `/checkpoint` | Save session state before risky operations | -| `/code-review` | Trigger the `code-reviewer` agent on current changes | -| `/evolve` | Analyze learned instincts and suggest refinements | -| `/full-review` | Multi-agent comprehensive review (code + security + docs) | -| `/full-stack-feature` | Orchestrate end-to-end feature implementation | -| `/instinct-status` | Show learned patterns with confidence scores | -| `/learn` | Extract reusable patterns from the current session | -| `/new-project` | Bootstrap a new project with minimal Claude Code config | -| `/plan` | Restate requirements and build a gated implementation plan | -| `/pr-enhance` | Improve PR quality and generate structured description | -| `/second-opinion` | Run `claude -p` on the current diff for a focused second-AI review | -| `/tdd` | Enforce TDD methodology throughout a feature | -| `/verify` | Run verification loop after completing a change | - ---- - -## Customization - -**Different stack?** Copy any agent to your project's `.claude/agents/` and -update the Bash tool rules. The `debugger` defaults to `npm test` — change it -to `pytest *`, `go test ./...`, or whatever your runner is. - -**Project-level CLAUDE.md?** The `/new-project` command generates one — 5 to -10 lines maximum. The research (Gloaguen et al.) shows that comprehensive -guides don't help. Only include what the agent cannot discover from the code. - -**Want fewer agents?** Start with `planner`, `debugger`, and `code-reviewer`. -Add others only when you notice a recurring gap. +The installer adds missing files and preserves files that already exist at the same paths. By default it uses `~/.claude`. To try it in a separate directory, set `CLAUDE_CONFIG_DIR` to an absolute path when running the installer. The optional settings example requires a manual merge. Review it alongside your current permissions and plugins before applying any changes. [Settings example](config/settings.json) · [Installation and recovery](docs/customization.md) ---- +Open a new Claude Code session in your project. Try `/plan Add a print button to the monthly report`, then review the plan and decide whether to proceed. -## Contributing +## My role and what changed -See [CONTRIBUTING.md](CONTRIBUTING.md). +I selected and combined the agents, skills and commands, using AI tools to help develop the configuration. The planner asks for approval before implementation. Its instructions are separate from the testing guide, which the test-driven-development agent loads when needed. [Planner](config/agents/planner.md) · [Test agent](config/agents/tdd-guide.md) -The bar for adding new content is high by design: it must contain non-obvious -information that Claude cannot discover from its training or existing repo -files. Generic advice doesn't clear the bar. Evidence does. +An earlier settings example approved `chmod` commands too broadly. The project removed that permission. Reviewing the research citations also led to narrower claims about what the studies actually tested. [Permission correction](https://github.com/poferraz/dotclaude/commit/712beeda72bf29511532d112e5b11e90e7da6b4d) · [Citation correction](https://github.com/poferraz/dotclaude/commit/72b04ee34b2ef5cfd7ad6a5943865b01ace58e40) ---- +## Repository guide -## License +| Where | What you will find | +| --- | --- | +| [Global instructions](config/CLAUDE.md) | Preferences shared across projects using this profile | +| [Agents](config/agents/), [commands](config/commands/) and [skills](config/skills/) | The Markdown instructions Claude Code uses for individual tasks | +| [Scripts](scripts/) | Local installation, backup restoration and export of the shared instructions for four other tools | +| [Sources and credits](MANIFEST.md) | Which material was adapted and who created it | +| [Research](docs/research-notes.md) | The papers that influenced the design and the limits of their findings | -MIT — see [LICENSE](LICENSE) +[Security and privacy](SECURITY.md) · [Contributing](CONTRIBUTING.md) · [Changelog](CHANGELOG.md) · [MIT license](LICENSE) diff --git a/SECURITY.md b/SECURITY.md index 9ca1ba0..dcd6315 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,51 +1,13 @@ -# Security Policy +# Security and privacy -## What This Repo Contains +## Report a vulnerability -This repository contains Claude Code configuration files only: -- Agent and skill definitions (markdown) -- Slash command definitions (markdown) -- Settings schema (`settings.json` template) -- MCP server configuration template (`mcp.json`) +Send a private report to the maintainer through GitHub. Include the affected revision, the relevant configuration file and a synthetic example. Keep credentials, full configuration directories and private transcripts out of public issues. [Report privately](https://github.com/poferraz/dotclaude/security/advisories/new) -**It does not contain:** -- API keys or tokens of any kind -- Personal data -- Credentials or secrets -- Machine-specific absolute paths (the settings template uses env vars) +## What installation changes -## The Install Script +The installer copies files into the chosen Claude Code profile. It leaves existing user files in place and prints backup locations. Installation and recovery operate on local files. Claude Code and any plugins you enable have their own data handling and permissions. [Installer](scripts/install.sh) · [Recovery guide](docs/customization.md) -The install script (`install.sh`) copies files locally and installs plugins via -the Claude Code plugin marketplace system. It does not transmit data to any -third-party service. It does not make network requests beyond standard Claude -Code plugin installation. +The optional settings example requires a manual merge. Review its rules and the effective settings in your host. A user's existing hooks, plugins and project configuration may have effects beyond this collection. A Markdown instruction directs a model's behavior. Tool permissions and host settings control what the model can access. -## Credential Handling - -All credentials referenced in `mcp.json` are environment variable references: - -```json -"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" -``` - -Never store real credentials in config files. Always use environment variables. -The `.gitignore` excludes `settings.local.json` (where per-machine credentials -or overrides live) and `.env` files. - -## Reporting a Vulnerability - -If you find a security issue in this configuration — a hook that could be -exploited, a permission that's too broad, or a pattern that creates risk — -please open a GitHub issue tagged `security`. - -For sensitive reports, use GitHub's private vulnerability reporting feature. - -We aim to respond within 48 hours. - -## Supported Versions - -| Version | Supported | -|---------|-----------| -| 1.x | ✅ Yes | -| < 1.0 | ❌ No | +The directory you back up or restore can contain logs, credentials, project paths and private settings. Keep copies in private storage and inspect their contents before sharing anything. For ordinary bug reports, use a short example with fictional paths and values. diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index 99d7385..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,205 +0,0 @@ -# Architecture: Command → Agent → Skill - -The three-tier orchestration model that makes this setup composable without becoming bloated. - -## The Three Layers - -``` -┌─────────────────────────────────────────────────┐ -│ COMMAND layer (/plan, /tdd, /full-review) │ -│ Entry points. User-invocable. Orchestrate agents.│ -└────────────────────────┬────────────────────────┘ - │ invokes via Agent tool - ▼ -┌─────────────────────────────────────────────────┐ -│ AGENT layer (planner, tdd-guide, debugger) │ -│ Single-responsibility subprocesses. │ -│ Scoped tools. Explicit model. One job. │ -└────────────────────────┬────────────────────────┘ - │ loads via skills: frontmatter - │ or Skill tool - ▼ -┌─────────────────────────────────────────────────┐ -│ SKILL layer (tdd-workflow, coding-standards) │ -│ Knowledge packs. No behavior — only context. │ -│ Load only when the agent actually needs them. │ -└─────────────────────────────────────────────────┘ -``` - -### Layer 1: Commands - -Commands are markdown files in `~/.claude/commands/` or `.claude/commands/`. They become slash commands (`/plan`, `/tdd`, `/verify`). - -**What commands do:** -- Accept arguments from the user (`$ARGUMENTS`) -- Orchestrate one or more agents in sequence -- Handle checkpoints and user confirmation gates -- Write state to files when multi-step (e.g. `full-stack-feature` uses `.full-stack-feature/state.json`) - -**What commands don't do:** -- Implement anything directly (that's agents) -- Load skills (that's agents) -- Run in the background - -### Layer 2: Agents - -Agents are markdown files with YAML frontmatter in `~/.claude/agents/`. Claude Code launches them as subprocesses with their own context window. - -**Frontmatter fields that matter:** - -```yaml ---- -name: planner -description: > - Produce phase-wise gated plans. Used before any multi-file task. -tools: - - Read - - Grep - - Glob - - WebSearch -model: opus # override per-agent — planner uses Opus, doc-updater uses Haiku -memory: user # access user memory files -skills: - - tdd-workflow # preloaded into this agent's context at launch -background: true # runs without blocking the main session ---- -``` - -**Single-responsibility rule:** Each agent does exactly one thing and reports back. The `debugger` diagnoses — it never implements. The `refactorer` changes structure — it never changes behavior. Mixing responsibilities creates god agents that are hard to reason about and easy to misuse. - -**Tool scoping:** Each agent declares only the tools it needs. The `code-reviewer` only needs `Read`, `Grep`, `Glob`, and `Bash(git diff *)`. It cannot write files — by design. Narrow tool lists prevent agents from taking unintended actions. - -### Layer 3: Skills - -Skills are markdown files in `~/.claude/skills//SKILL.md`. They are knowledge packs — not code, not behavior, just context that loads into an agent's prompt. - -**Two loading modes:** - -``` -Mode 1 — Agent-preloaded: - Agent's frontmatter has `skills: [tdd-workflow]` - → SKILL.md loads into the agent's context when the agent launches - → Agent has this knowledge for the entire conversation - -Mode 2 — On-demand via Skill tool: - Agent or Claude calls Skill tool with the skill name - → SKILL.md loads into the current context on demand - → Only costs tokens when actually needed -``` - -**Why skills are separate from agents:** A skill is reusable knowledge that multiple agents can load. The coding-standards skill can be loaded by the code-reviewer, the refactorer, or directly in the main session. If it lived inside one agent's system prompt, it would be duplicated across every agent that needs it. - ---- - -## Why This Hierarchy Exists - -### Separation of concerns - -Each layer has a clear job: -- Commands know *what workflow to run* -- Agents know *how to do one specific thing* -- Skills know *domain knowledge about how to do it well* - -Without this separation, you get god agents: single files that orchestrate, implement, review, and apply domain knowledge all at once. God agents are long, expensive to load, and impossible to test in isolation. - -### Token efficiency - -``` -Without the hierarchy: - One large agent loaded every session - → 5,000 tokens in context even when you're writing a README - -With the hierarchy: - Agents load only when invoked - Skills load only into the agents that need them - → 0 tokens for agents/skills when not in use -``` - -### Composability - -Commands mix and match agents. `/full-review` runs `code-reviewer` + `security-reviewer` + `doc-updater` in sequence — three agents with separate concerns, orchestrated by one command. Add a new agent and it can immediately participate in any command that needs it. - ---- - -## How Agents Call Each Other - -Agents invoke other agents via the **Agent tool**, never via bash: - -``` -✅ Correct: - /full-review command → launches code-reviewer agent via Agent tool - → launches security-reviewer agent via Agent tool - -❌ Wrong: - /full-review command → bash: "claude -p 'review this code'" -``` - -The Agent tool gives each subagent its own context window. Bash subprocess calls would inherit the parent context, lose the ability to pass structured results, and break the permission model. - ---- - -## Mermaid Diagram - -```mermaid -graph TD - U[User: /full-review] --> CMD[full-review.md command] - CMD --> |Agent tool| A1[code-reviewer agent] - CMD --> |Agent tool| A2[security-reviewer agent] - CMD --> |Agent tool| A3[doc-updater agent] - - A1 --> |git diff| TOOLS1[Read, Grep, Glob] - A2 --> |static analysis| TOOLS2[Read, Grep, Glob] - A3 --> |background| TOOLS3[Read, Edit, Grep, Glob] - - U2[User: /tdd] --> CMD2[tdd.md command] - CMD2 --> |Agent tool| A4[tdd-guide agent] - A4 --> |skills: frontmatter| S1[tdd-workflow/SKILL.md] - A4 --> |Bash| TOOLS4[npm test, npm run coverage] - - U3[User: /plan] --> CMD3[plan.md command] - CMD3 --> |Agent tool| A5[planner agent] - A5 --> |memory: user| MEM[User memory files] -``` - ---- - -## Asymmetric Persona Strategy - -Agent system prompt bodies are calibrated by task type, based on Hu et al. (2026) research showing that persona effects are **asymmetric** — helpful for some tasks, harmful for others. - -| Task type | What it covers | Persona strategy | Why | -|-----------|---------------|------------------|-----| -| **Pretraining** | Code logic, debugging, refactoring, test writing | None (empty body) | Model already trained on these skills. Persona redirects attention away from the problem. | -| **Alignment** | Documentation style, UI/UX aesthetics, tone matching | Short (1–2 sentences) | Behavioral calibration needed. Persona establishes the right prior. | -| **Safety** | Security analysis, threat modeling, vulnerability detection | Full (50+ words) | +17.7% refusal rate vs. no persona. Explicit auditor framing activates adversarial reasoning. | -| **Mixed** | Planning, multi-step reasoning | Minimum (behavioral constraint only) | Neutral effect. Constraint prevents over-confidence; full persona adds noise. | - -**Classification for new agents:** Ask which layer the task primarily lives in: -- Does the model already know how to do this well from pretraining? → No persona. -- Does the task require a specific tone, style, or aesthetic register? → Short persona. -- Does the task involve evaluating risk, security, or safety-sensitive content? → Full persona. -- Does the task mix reasoning with output formatting? → Behavioral constraint only. - -The key distinction: a **behavioral constraint** (e.g., "require user confirmation before implementing") tells the agent what NOT to do — this is neutral regardless of task type. A **persona** (e.g., "You are an expert reviewer") tells the agent who to BE — this is where the asymmetry kicks in. - ---- - -## Project-Level Overrides - -The global `~/.claude/` config is the baseline. Projects override by adding a `.claude/` directory to the project root: - -``` -project-root/ -├── .claude/ -│ ├── settings.json # adds/removes permissions, enables project MCPs -│ ├── agents/ -│ │ └── tdd-guide.md # override global tdd-guide with Go test runner -│ └── CLAUDE.md # project-specific context (stack, test commands) -└── src/ -``` - -Rules of override: -1. Project agents shadow global agents by the same `name:` -2. Project settings merge with global (project `allow` adds to global `allow`) -3. Project CLAUDE.md loads in addition to global CLAUDE.md — both are active -4. Use `/new-project` to scaffold the project `.claude/` structure correctly diff --git a/docs/context-budget.md b/docs/context-budget.md deleted file mode 100644 index abb1a05..0000000 --- a/docs/context-budget.md +++ /dev/null @@ -1,119 +0,0 @@ -# Context Budget - -How this setup keeps session start lean, and why it matters. - ---- - -## Why Context Budget Matters - -Claude Code's context window is 200K tokens. That sounds like a lot — until you realize that a single bloated CLAUDE.md plus auto-loaded agents, skills, and hook output can burn 20,000+ tokens before you type your first prompt. That's 10% of your budget gone on configuration overhead. - -The Gloaguen et al. (2026) research confirms the cost isn't just tokens: redundant context actively reduces task success. More isn't better. More is worse. - -**Target for this setup:** Under 3,000 tokens of config overhead at session start. That's less than 1.5% of the 200K window. - ---- - -## Session Start Token Budget - -What loads before you type anything: - -| Source | Tokens | Controllable? | -|--------|--------|---------------| -| Claude Code system prompt | ~8,000 | No | -| `CLAUDE.md` (global) | ~450 | Yes — keep minimal | -| context-mode session index | ~1,500–3,000 | Yes — compressed | -| Hook output (SessionStart) | ~200 | Yes — kept terse | -| **Config contribution total** | **~2,150–3,650** | **Yes** | -| **Grand total at session start** | **~10,150–11,650** | Partially | - -The Claude Code system prompt (~8,000 tokens) is fixed infrastructure. Everything else is controlled by this configuration. - ---- - -## The Previous State (Before Audit) - -Before the March 2026 audit and rebuild, the session start budget looked like this: - -| Source | Tokens | Status | -|--------|--------|--------| -| CLAUDE.md (102 lines) | ~850 | ✅ Replaced with 71-line version | -| Auto-loaded god agents (12 agents, all sessions) | ~6,200 | ✅ Reduced to 8 on-demand agents | -| context-mode injection (uncompressed) | ~20,000 | ✅ Replaced with compressed index | -| Stack-specific rules (golang, etc.) | ~1,200 | ✅ Moved to project-level | -| Skills auto-loaded via CLAUDE.md @imports | ~3,500 | ✅ Moved to on-demand | -| **Previous total overhead** | **~31,750+** | **Replaced** | - -The context-mode injection was the largest single problem: 20,000 tokens of raw session history injected into every turn. Switching to the compressed semantic index (titles, types, token counts — not full content) dropped this to ~1,500–3,000 tokens while preserving recall through on-demand MCP search. - ---- - -## Per-Turn Hook Overhead - -Every tool call runs the PostToolUse hook (context-mode observation capture). This is low but not zero: - -| Hook event | Overhead | Frequency | -|-----------|---------|-----------| -| PostToolUse observation | ~50–100 tokens | Every tool call | -| UserPromptSubmit session-init | ~30 tokens | Every prompt | -| Stop summarize | ~200 tokens | End of session | - -For a typical 50-tool-call session, hook overhead is roughly 2,500–5,000 tokens. This is acceptable because the observation data is what enables the compressed context-mode index — it's an investment in future session efficiency. - ---- - -## What the Audit Removed - -The March 2026 audit removed or relocated: - -| Removed | Tokens saved | Reason | -|---------|-------------|--------| -| 4 god agents (architect-review, security-review, test-runner, orchestrator) | ~4,800 | Replaced by 8 focused agents; god agents loaded for every task | -| eval-harness skill (auto-loaded) | ~1,400 | Moved to project-level; not globally relevant | -| security-review skill (auto-loaded) | ~900 | Merged into security-reviewer agent prompt | -| coding-standards from CLAUDE.md @import | ~320 | Moved to on-demand skill | -| Stack-specific rules (golang/coding-style.md) | ~1,200 | Moved to project-level | -| PAULO_CONTEXT.md briefing doc | ~1,100 | Stale, deleted | -| 875 lines across god agent definitions | ~3,000 | Replaced with lean single-sentence versions | -| **Total removed** | **~12,720** | | - ---- - -## Monitoring Your Own Budget - -To see what's loading in your sessions: - -```bash -# Check CLAUDE.md size -wc -w ~/.claude/CLAUDE.md - -# Check agent sizes -wc -w ~/.claude/agents/*.md | sort -n - -# Check if any skills are auto-loading via CLAUDE.md -grep -n "@import\|skills:" ~/.claude/CLAUDE.md - -# Check context-mode session index size -# (visible in session start hook output) -``` - -**Red flags:** -- CLAUDE.md over 50 lines: audit for obvious/redundant content -- Any agent over 200 lines: split into agent + skill -- Any skill auto-loading via CLAUDE.md @import: move to on-demand -- context-mode injection over 5,000 tokens: check compression settings - ---- - -## The Minimum Viable Config - -If you want to start even leaner: - -| Keep | Remove | -|------|--------| -| CLAUDE.md (behavioral overrides only) | All auto-loaded agents and skills | -| settings.json (permissions + hooks) | context-mode until you need it | -| planner + debugger + code-reviewer | Other 5 agents until needed | -| /plan and /verify | Other 12 commands until needed | - -Add components only when you notice a recurring gap. The minimum viable config is ~2,000 tokens at session start. Everything above that is optional functionality. diff --git a/docs/customization.md b/docs/customization.md index 475854a..b2b106b 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -1,276 +1,46 @@ -# Customization Guide +# Installation and recovery -How to adapt this setup to your stack, workflow, and tools. +## Start with a separate profile ---- +From this checkout, choose an unused private directory outside your project. The following example uses a sibling directory named `dotclaude-trial`. -## Changing the Stack - -This configuration is intentionally stack-agnostic at the global level. Stack-specific knowledge lives at the project level. - -### Step 1: Run /new-project - -The `/new-project` command bootstraps a project-level `.claude/` directory with a minimal `CLAUDE.md` (5–10 lines). That minimal CLAUDE.md is intentional — the research (Gloaguen et al., 2026) shows comprehensive guides don't help. Only add what the agent can't discover from reading the code. - -```bash -# In your project directory: -/new-project -``` - -The command will ask for your stack (language, framework, database) and generate: -- `.claude/settings.json` (project-level permissions) -- `.claude/agents/tdd-guide.md` (if Go or Python — overrides the npm-based global) -- `CLAUDE.md` (5–10 lines: stack declaration + test commands) -- `.mcp.json` (GitHub + stack-specific MCP servers) - -### Step 2: Override agents for your test runner - -The global `tdd-guide` and `refactorer` agents use npm-based Bash tool rules. For other stacks, copy the agent to `.claude/agents/` and update the tools: - -**Go:** -```yaml -tools: - - Read - - "Bash(go test ./...)" - - "Bash(go test -cover ./...)" - - "Bash(go test -run *)" -``` - -**Python:** -```yaml -tools: - - Read - - "Bash(python -m pytest *)" - - "Bash(python -m pytest --cov *)" -``` - -**Rust:** -```yaml -tools: - - Read - - "Bash(cargo test *)" - - "Bash(cargo tarpaulin *)" -``` - -The `/new-project` command generates the Go and Python overrides automatically. - -### Step 3: Add stack-specific rules (optional) - -If you have non-obvious project conventions, add a `CLAUDE.md` to the project root. Keep it under 15 lines. Include only what Claude can't discover from the codebase: - -```markdown -# Project CLAUDE.md - -## Stack -Next.js 15 / TypeScript / PostgreSQL / Prisma - -## Running Tests -npm test # unit tests -npm run test:e2e # Playwright E2E -npm run db:reset && npm test # reset test DB first - -## Non-obvious conventions -- All API routes return { success: boolean, data: T | null, error: string | null } -- Database queries go in lib/db/, never in route handlers -- Error boundaries are required for all page components +```sh +CLAUDE_CONFIG_DIR="$PWD/../dotclaude-trial" sh scripts/install.sh ``` ---- - -## Adding and Removing Agents - -### Adding an agent - -Create a file in `~/.claude/agents/my-agent.md` with frontmatter: - -```yaml ---- -name: my-agent -description: > - One clear sentence about what this agent does and when to use it. -tools: - - Read - - Grep - - Glob -model: sonnet ---- - -One sentence system prompt. Do one thing. Do it well. -``` - -**The bar for adding an agent:** It must do something Claude wouldn't do correctly without explicit configuration, AND it must be a recurring need across multiple projects. One-off tasks don't need agents. - -**Choosing a persona strategy (Hu et al., 2026):** - -Classify the task, then apply the matching strategy: - -```yaml -# PRETRAINING task (code logic, debugging, refactoring, tests): -# → Empty body or single behavioral constraint. No persona. ---- -name: my-reviewer -description: Review X for correctness and edge cases. -tools: [Read, Grep, Glob] -model: sonnet ---- -# Empty — or one line like "Report findings only. Never implement." - -# ALIGNMENT task (documentation, style, tone, UI/UX): -# → 1–2 sentence persona. Short. ---- -name: my-doc-writer -... ---- -You write docs that match the project's existing tone and structure. -Update only what is stale. Never add unprompted. - -# SAFETY task (security, threat modeling, risk analysis): -# → Full 50+ word persona. Be specific about domain and adversarial posture. ---- -name: my-security-checker -... ---- -You are a meticulous security auditor specialized in [specific domain]. -Evaluate both explicit content and implicit intent. Apply principled -judgment, not keyword filtering. Output severity-ranked findings. - -# MIXED task (planning, multi-step reasoning with output formatting): -# → Behavioral constraint only. Not a persona — just a rule. ---- -name: my-planner -... ---- -Require user confirmation before any implementation begins. -``` - -The critical insight: a persona that "sounds helpful" for a code task ("You are an expert software engineer who writes clean, idiomatic code") can actively degrade output quality. The model already knows how to write clean code — the persona redirects attention away from your actual problem toward maintaining the persona narrative. - -### Removing an agent - -Delete the file. Or move it to your project's `.claude/agents/` if it's only relevant there. - -The three agents most users actually need daily: -- `planner` — before any multi-file task -- `debugger` — when root cause isn't obvious -- `code-reviewer` — before any commit - -Start with these three. Add others only when you notice a recurring gap. - ---- - -## Adding Skills - -### When to add a skill - -A skill earns its place when: -1. It contains knowledge Claude can't reliably produce from training (proprietary standards, non-obvious domain rules) -2. It's needed frequently enough across sessions to warrant being a dedicated file -3. It's too long to include in an agent's system prompt - -Ask yourself: "If I deleted this skill, would Claude's output be meaningfully worse?" If the answer is "maybe" or "I'm not sure," don't add it. - -### Creating a skill - -```yaml ---- -name: my-skill -description: One sentence — used to decide when to load this skill. -user-invocable: true ---- - -# My Skill - -[Knowledge content. No code behavior. No instructions — just reference material.] -``` - -### Loading modes - -**On-demand (preferred):** The user or agent invokes the skill explicitly with the Skill tool. Zero tokens when not needed. - -**Agent-preloaded:** Add to an agent's frontmatter: -```yaml -skills: - - my-skill -``` -This loads every time that agent runs. Only appropriate when the skill is needed for 100% of that agent's tasks. - -**Never auto-load via CLAUDE.md @import:** This loads the skill every session regardless of task. Almost never the right choice. - ---- - -## Configuring Hooks - -The hook system is the most powerful and most dangerous part of the setup. Hooks run shell commands on every event — a poorly configured hook can add thousands of tokens to every turn. - -### Safe hook additions - -**Session end logging (already included):** -```json -"SessionEnd": [{ - "hooks": [{ - "type": "command", - "command": "echo \"Session ended at $(date)\" >> ~/.claude/sessions/session-log.txt" - }] -}] -``` - -**Strategic compact suggestion (via skill):** -```json -"PreToolUse": [{ - "matcher": "Edit|Write", - "hooks": [{ - "type": "command", - "command": "bash ~/.claude/skills/strategic-compact/suggest-compact.sh" - }] -}] -``` - -### Hook rules - -1. **Never print large output from hooks** — anything printed goes into Claude's context. Keep hook stdout under 200 characters. -2. **Use timeouts** — always set `"timeout": 60` or similar to prevent hanging sessions -3. **Test hooks before enabling** — run the command manually and measure its output size -4. **Prefer Stop over PostToolUse** — if you only need end-of-session behavior, use Stop (once per session) not PostToolUse (once per tool call) - ---- - -## Session Memory: beads vs context-mode +For the default profile, follow the [README installation steps](../README.md#install). Existing files at matching paths keep their contents, including older dotclaude files. To adopt newer instructions or permissions, compare the installed files with the current source and review the differences before merging them. Reinstalling leaves previously configured hooks and permissions active. The installer prints the destination and the path of any backup it creates. Claude Code must use the same configuration directory to see those instructions. -This setup uses **context-mode** for session memory. An alternative is **beads** (steveyegge/beads). +For a smaller install, inspect a Markdown file in [commands](../config/commands/) or [agents](../config/agents/) and copy only what you need. If it names an agent or skill, include that dependency. For example, `/tdd` names `tdd-guide`, whose frontmatter names `tdd-workflow`. [Command](../config/commands/tdd.md) · [Agent](../config/agents/tdd-guide.md) · [Skill](../config/skills/tdd-workflow/SKILL.md) -| | context-mode | beads | -|---|---|---| -| **Model** | Automatic observation via hooks | Manual task tracking | -| **Storage** | Semantic index, compressed | Structured task/subtask tree | -| **Recall** | Semantic search via MCP | Direct file reference | -| **Best for** | "What did I work on last week?" | "What's the state of this multi-week feature?" | -| **Token cost** | 1,500–3,000 per session (compressed) | ~500 per session (structure only) | -| **Setup** | Install context-mode plugin, configure hooks | Install beads, add to CLAUDE.md | +## Settings and context -**Recommendation:** Use context-mode if you want automatic session history and semantic search. Use beads if you want explicit task tracking for long-running projects. They can coexist — beads for task state, context-mode for session history. +The [sample settings](../config/settings.json) are optional. Review each change against your own settings and edit the file manually. Use a separate project configuration for exceptions you need in only one repository. Measure context use in a representative task with your own host settings and enabled integrations. ---- +Some skills describe workflows from larger projects. Check their prerequisites before invoking an external integration. Installing the Markdown collection does not install upstream plugins or provide credentials for them. -## Disabling Components You Don't Need +## Restore a backup -### Disable context-mode (if you want a minimal setup) +Stop sessions using the profile before restoring it. Run the uninstaller for the same target and review the backup it proposes before confirming. -Remove the SessionStart, UserPromptSubmit, PostToolUse, and Stop hooks from `settings.json`. Also remove from `enabledPlugins`: -```json -"context-mode@context-mode": false +```sh +CLAUDE_CONFIG_DIR="$PWD/../dotclaude-trial" sh scripts/uninstall.sh ``` -### Disable specific agents +For the default profile, run `sh scripts/uninstall.sh` without the environment override. The uninstaller stages the selected snapshot before it replaces the profile. It retains the displaced profile separately for recovery. Read the paths printed by the script. A backup or displaced profile can contain settings, private session data and credentials from the original directory. Keep these folders private. [Uninstaller](../scripts/uninstall.sh) · [Security and privacy](../SECURITY.md) -Delete the agent file. Agents only load when explicitly invoked — they don't cost tokens sitting in the directory. +## Export the shared instructions -### Disable plugins +Run the converter from the destination project using the path to your checkout. If you already have instructions there, generate into an empty directory, compare the files and merge the parts you want. -Set to `false` in `enabledPlugins`: -```json -"everything-claude-code@everything-claude-code": false +```sh +sh /path/to/dotclaude/scripts/convert.sh codex ``` -### Use a different model default +| Argument | Output in the current directory | +| --- | --- | +| `codex` | `AGENTS.md` | +| `gemini` | `GEMINI.md` | +| `cursor` | `.cursor/rules/dotclaude.mdc` | +| `aider` | `.aider.conf.yml` and `dotclaude-conventions.md` | -Change `"model": "sonnet"` to `"model": "haiku"` for cheaper sessions, or `"model": "opus"` for maximum quality. Individual agents override this with their own `model:` frontmatter. +The export carries the shared working preferences. Claude Code agents, commands, skills and settings remain in their original format. [Converter](../scripts/convert.sh) diff --git a/docs/research-notes.md b/docs/research-notes.md index 6c99871..c13fa2b 100644 --- a/docs/research-notes.md +++ b/docs/research-notes.md @@ -1,212 +1,13 @@ -# Research Notes +# Research behind the configuration -The two papers that directly shaped this configuration, and how. +These five papers influenced the project's early design. The repository has no controlled performance comparison for the complete configuration. Its install and export checks cover file behavior. ---- +| Study | What it examined and how it relates | +| --- | --- | +| Gloaguen and colleagues | On the coding tasks studied, repository context files generally did not improve completion and increased inference costs on average. The maintainer chose to keep shared preferences short and move task-specific detail into separate files. [Paper](https://arxiv.org/abs/2602.11988) | +| Cao, Jiang and Xu | Disclosing a downstream financial prediction goal changed the model's intermediate measurements. The study concerns financial predictions. It does not measure the benefit of stating acceptance criteria in a software project. [Paper](https://arxiv.org/abs/2602.09504) | +| Hu, Rostami and Thomason | Persona prompting varied with the task, model and prompt design. The repository experimented with brief descriptions tailored to each agent's job. [Paper](https://arxiv.org/abs/2603.18507) | +| Geng and colleagues | Models struggled to prioritize conflicting instructions, even in formatting tasks. The paper motivated experiments with how constraints were presented. Host permissions remain necessary for controlling tool access. [Paper](https://arxiv.org/abs/2502.15851) | +| Mahmoudi and colleagues | The researchers catalogued problems in systems that integrate LLM inference. Some included skills use structured output to help readers interpret a result. Whether a consumer can parse it depends on its own validation. [Paper](https://arxiv.org/abs/2512.18020) | -## Paper 1: Context Files Can Hurt You - -**"Evaluating AGENTS.md: Are Repository-Level Context Files Helpful?"** -Gloaguen, Büyükkaya, Hajdu, et al. (2026) -[arxiv.org/abs/2602.11988](https://arxiv.org/abs/2602.11988) - -### What They Measured - -The authors evaluated whether AGENTS.md / CLAUDE.md files — the markdown context files that Claude Code and similar tools load at session start — actually help coding agents perform better. They tested across 8 diverse coding tasks with multiple agent systems. - -### Key Findings - -| Finding | Magnitude | -|---------|-----------| -| LLM-generated context files reduced success | 5 of 8 settings | -| Increased API cost | 20–23% | -| Increased reasoning tokens | 14–22% | -| Human-written files | Mixed — helped only when containing non-obvious requirements | - -The critical distinction: **files containing information the agent couldn't discover on its own** (environment-specific constraints, non-obvious project conventions, required tool availability) showed positive signal. Files containing generic best practices, obvious conventions, or re-stated framework defaults showed negative or neutral signal. - -### How This Config Applies It - -**Decision 1: CLAUDE.md is under 30 lines.** -Every line in CLAUDE.md was evaluated against the question: "Would Claude apply this behavior without being told?" If yes, it was removed. What remains are genuine overrides — behaviors that contradict defaults or require explicit setup (goal-blind prompting, surgical changes, context discipline triggers). - -**Decision 2: Skills are on-demand, not auto-loaded.** -5 of 6 skills load only when invoked. The `tdd-workflow` skill (400+ lines of TDD methodology) only loads when the `tdd-guide` agent runs. It costs zero tokens in sessions where you're writing documentation, fixing a bug, or planning architecture. Auto-loading it would waste 2,600 tokens every session for tasks where TDD doesn't apply. - -**Decision 3: Agent instructions are single sentences.** -The `debugger` agent system prompt is: *"Never guess. Trace the error to its origin. Show the chain of causation. Propose the minimal surgical fix."* That's it. The agent's training already covers debugging methodology. The one-sentence prompt overrides only the behavior that would otherwise be different: no guessing, no implementing, only diagnosing. - -**Decision 4: Project CLAUDE.md files are 5–10 lines maximum.** -The `/new-project` command generates a minimal project-level CLAUDE.md. The research shows that comprehensive guides don't help — only requirements the agent cannot discover from the codebase itself. - ---- - -## Paper 2: Goal-Blind Prompting - -**"Seeing the Goal, Missing the Truth"** -Cao, Jiang, Xu (2026) - -### What They Measured - -The authors studied what happens when you tell a model how its output will be evaluated — i.e., revealing the scoring criteria or success metrics before the model produces its response. - -### Key Finding - -When a model knows the evaluation criteria, it reshapes its output to score well on that criterion — at the expense of out-of-sample performance. The model games the metric rather than solving the problem. This is analogous to Goodhart's Law: *when a measure becomes a target, it ceases to be a good measure.* - -Specifically, they found that telling the model "your response will be evaluated on clarity, accuracy, and conciseness" caused it to optimize for those labeled dimensions while degrading on unmeasured dimensions. - -### How This Config Applies It - -**The CLAUDE.md prompting philosophy:** - -``` -I use goal-blind prompts: I specify WHAT to build or measure, never how the -output will be evaluated. Never ask me for my success criteria — this biases -your output. Infer quality from the task, not from how I'll grade you. -``` - -This is a direct application of the paper's finding. Specifying WHAT to build (the task) gives the model the right signal. Specifying HOW the output will be evaluated (the scoring criteria) causes it to optimize for the metric rather than the outcome. - -**In practice:** If you're building an API endpoint, say "build a paginated GET /items endpoint." Don't say "build an API endpoint — I'll evaluate it on REST compliance, error handling, and test coverage." The second framing causes the model to optimize for those named dimensions, potentially at the expense of others (performance, edge cases, documentation). - -**Why this is in CLAUDE.md and not just a practice:** -Left to defaults, Claude Code agents often ask for success criteria ("What does a good solution look like to you?"). The CLAUDE.md line explicitly suppresses this behavior — it's a genuine behavioral override, not a general best practice the model would apply anyway. This makes it appropriate for CLAUDE.md under the Gloaguen et al. standard. - ---- - -## Paper 3: Asymmetric Persona Calibration - -**"Revisiting Role-Play Prompting: A Systematic Assessment of Persona Calibration in LLMs"** -Hu et al. (2026) -[arxiv.org/abs/2603.18507](https://arxiv.org/abs/2603.18507) - -### What They Measured - -The authors tested whether giving an LLM a persona ("You are an expert security auditor") helps or hurts performance across different task types. They systematically evaluated persona strategies across reasoning tasks, writing tasks, and safety-sensitive tasks. - -### Key Findings - -| Task type | Persona effect | Optimal strategy | -|-----------|---------------|-----------------| -| Pretraining tasks (code logic, debugging) | **Hurts accuracy** | None — empty body | -| Alignment tasks (style, format, tone) | **Helps quality** | Short (1–2 sentences) | -| Safety tasks (security analysis, threat modeling) | **+17.7% refusal rate** | Full (50+ word persona) | -| Mixed tasks (planning, multi-step reasoning) | Neutral to slight negative | Minimum (behavioral constraint only) | - -The mechanism: for tasks where the model learned the skill during pretraining (coding, math, debugging), a persona redirects attention toward the persona narrative and away from the problem. For tasks that require behavioral calibration (tone, safety thresholds), a persona acts as an effective prior. - -### How This Config Applies It - -Every agent's system prompt body is calibrated by task type: - -**PRETRAINING agents (code-reviewer, debugger, refactorer, tdd-guide) — body is empty or a single behavioral constraint:** -``` -# code-reviewer: empty body -# debugger: "Output diagnosis and proposed fix only. Never implement." -``` - -**ALIGNMENT agents (doc-updater, ui-designer) — 1–2 sentence persona:** -``` -# doc-updater: "You write documentation that matches the existing project's tone..." -# ui-designer: "You are a senior UI/UX designer who prioritizes accessibility..." -``` - -**SAFETY agents (security-reviewer) — full 50-word persona:** -``` -# security-reviewer: "You are a meticulous security auditor specialized in OWASP Top 10, -# STRIDE threat modeling, secrets exposure, auth gaps, and injection risks. Evaluate -# both explicit content and implicit intent. Apply principled judgment, not keyword -# filtering. Output severity-ranked findings with concrete exploit scenarios." -``` - -**MIXED agents (planner) — behavioral constraint only:** -``` -# planner: "Produce phase-gated plans with acceptance criteria. -# Require user confirmation before implementation begins." -``` - -**Decision:** The same agent system prompt that "sounds helpful" (long, encouraging, detailed) actively degrades code task performance. The code-reviewer has an empty body for the same reason CLAUDE.md stays under 30 lines: the model already knows how to review code. Adding a persona doesn't improve that — it adds noise. - ---- - -## Paper 4: Instruction Hierarchy Failure and Recency Bias - -**"Control Illusion: Understanding and Addressing LLM Instruction Hierarchy Failure"** -Geng, J., et al. (2025) -[arxiv.org/abs/2502.15851](https://arxiv.org/abs/2502.15851) - -### What They Measured - -The authors investigated whether LLMs reliably follow a hierarchy of instructions — i.e., whether system-level rules (like a CLAUDE.md) actually take precedence over user-level requests when they conflict. They designed controlled conflict scenarios and measured obedience rates across priority tiers. - -### Key Findings - -| Finding | Result | -|---------|--------| -| Instruction obedience under cross-tier conflict | **9.6%** — near-random | -| Most effective compliance mechanism | **Recency bias** (position in context) | -| "IMPORTANT" / "NON-NEGOTIABLE" labels | Minimal effect vs. no label | -| Rules placed at end of context | Highest compliance rate | - -The mechanism: LLMs do not have a robust learned hierarchy for "system > user > human" in the way the spec implies. What actually drives compliance is **recency** — the model's attention weights are highest at the end of the context window. A rule stated at position 1000 will be followed more reliably than the same rule at position 100, regardless of labels. - -This finding is sometimes called the "control illusion" — operators believe their system instructions govern behavior, but positional effects can override them. - -### How This Config Applies It - -**Decision 1: `` block at the bottom of CLAUDE.md.** -The four non-negotiable core behaviors (THINK BEFORE CODING, SIMPLICITY FIRST, SURGICAL CHANGES, GOAL-DRIVEN EXECUTION) are placed at the absolute end of the file, inside a named XML block. This is a direct application of the recency finding: these rules earn their position, not just their label. - -**Decision 2: XML demarcation.** -Geng et al. found that structural delimiters improve rule salience. XML tags create a cognitive and tokenization boundary that `##` headers do not. The entire CLAUDE.md was converted from Markdown headers to XML blocks to maximize structural clarity. - -**Decision 3: Sections ordered by criticality (ascending).** -Context earlier in the file (About Me, Architecture) is informational. The most important behavioral rules are closest to the end. The model reads the whole file, but the recency anchor is reserved for constraints that must not be overridden. - ---- - -## Paper 5: LLM Code Smells in Agentic Systems - -**"LLM Code Smells: Identifying and Addressing Anti-Patterns in Agentic AI Systems"** -Mahmoudi, H., et al. (2025) -[arxiv.org/abs/2512.18020](https://arxiv.org/abs/2512.18020) - -### What They Measured - -The authors analyzed failure patterns in LLM-based agent systems — not failures from bad models, but architectural and prompting patterns that reliably produce bad outputs. They catalogued these as "code smells" by analogy to software engineering: patterns that aren't necessarily broken, but that reliably lead to problems at scale. - -### Key Findings - -| Smell | Failure Rate | Description | -|-------|------------|-------------| -| Non-Specific Output (NSO) | **40.5%** of failures | Agent returns free-form prose where a schema was required | -| Undefined Model Multiplexing (UMM) | 22.1% | Multiple agents use different models without clear routing logic | -| Missing Retry Logic | 18.3% | No fallback when tool calls fail or return unexpected structure | -| Context Window Overflow | 12.4% | Agent context grows unbounded, degrading later responses | - -**NSO** is the dominant failure mode. It occurs when an agent is told to "report your findings" without a strict schema — and produces narrative prose that the calling system cannot parse or validate. The downstream agent that expected `pass` gets "I reviewed the code and it looks mostly good, though there are a few things worth noting..." - -**UMM** matters because different models have different output styles. Routing code review to Haiku and security review to Opus without explicit schema enforcement amplifies NSO — each model produces differently-structured prose. - -### How This Config Applies It - -**Decision 1: Strict Output Schema section in every skill.** -All 5 first-party skills (`coding-standards`, `verification-loop`, `tdd-workflow`, `strategic-compact`, `continuous-learning-v2`) now include a mandatory "Strict Output Schema" section. Each schema uses XML tags — ``, ``, `` — that can be parsed programmatically. Free-form prose is named as a failure mode in the skill itself. - -**Decision 2: Schema tied to the NSO finding by citation.** -Each schema section explicitly cites Mahmoudi et al. (2025). This serves two purposes: it prevents future editors from removing the schema thinking it's bureaucratic overhead, and it embeds the rationale where it's most actionable. - -**Decision 3: Minimal schemas, not comprehensive ones.** -The schemas are deliberately narrow — only the fields that matter for downstream parsing. The Gloaguen finding (Paper 1) warns against bloated context files. A 20-line output schema that covers the critical fields beats a 200-line schema that covers everything. - ---- - -## What's Not Here - -Several papers influenced the general philosophy but didn't produce specific, implementable decisions: - -- **LLM attention and context window utilization** — General research on how attention dilutes over long contexts. Informed the "tokens must earn their place" principle but didn't produce specific config decisions. -- **Anthropic's system prompt guidance** — Internal documentation on effective system prompts. Consistent with the Gloaguen findings but not a citable paper. - -If you find research that should inform a specific config decision, open a [research update issue](../.github/ISSUE_TEMPLATE/research_update.md) and include confidence level and implementation recommendation. +If a paper changes a specific design decision, link the original source and describe what should change. [Research update template](../.github/ISSUE_TEMPLATE/research_update.md) From a5b0d6c04f5d88846c46655fae2c8900e5b2d753 Mon Sep 17 00:00:00 2001 From: poferraz <210631651+poferraz@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:43:09 -0700 Subject: [PATCH 3/5] Keep checkpoints private and request permission for project writes --- config/commands/checkpoint.md | 76 +++++---------------------- config/commands/full-stack-feature.md | 2 +- config/commands/new-project.md | 56 +------------------- 3 files changed, 15 insertions(+), 119 deletions(-) diff --git a/config/commands/checkpoint.md b/config/commands/checkpoint.md index 06293c0..eb48ce0 100644 --- a/config/commands/checkpoint.md +++ b/config/commands/checkpoint.md @@ -1,74 +1,22 @@ -# Checkpoint Command +# Checkpoint -Create or verify a checkpoint in your workflow. +Use `/checkpoint create`, `verify`, `list` or `clear` with an optional name or exact Git reference. -## Usage +## Create -`/checkpoint [create|verify|list] [name]` +Inspect the branch and changed paths using `git status --short --branch`. Avoid printing file contents. If the working tree is clean, report the existing commit from `git rev-parse --verify HEAD`. -## Create Checkpoint +For a dirty tree, explain which files the checkpoint would include. Ask the user to select a commit or a stash and approve the scope. A commit records its approved changes in the branch. A stash removes its selected changes from the working tree until restored. Leave private, ignored and unrelated files alone. -When creating a checkpoint: +- For a commit, verify exactly what is staged before committing. Report the new commit ID from `git rev-parse --verify HEAD`. +- For a stash, read the current stash ID if one exists, make the approved stash, then read `git rev-parse --verify 'refs/stash^{commit}'`. Report the resulting stash ID only if it changed. If Git saved nothing, say so. -1. Run `/verify quick` to ensure current state is clean -2. Create a git stash or commit with checkpoint name -3. Log checkpoint to `.claude/checkpoints.log`: +Keep the checkpoint type, name and exact ID in the conversation. Save a separate record only if the user requests and approves a private destination. -```bash -echo "$(date +%Y-%m-%d-%H:%M) | $CHECKPOINT_NAME | $(git rev-parse --short HEAD)" >> .claude/checkpoints.log -``` +## Verify and list -4. Report checkpoint created +For `verify`, resolve the selected record to its exact Git object. Compare the intended paths with the working tree and run the relevant checks. Report observed results and any unavailable comparison. If a name is ambiguous, ask for the exact ID. -## Verify Checkpoint +For `list`, report checkpoints identified in the conversation. If the user wants existing Git stashes, list their references and IDs. Git does not distinguish ordinary commits from named checkpoints on its own. -When verifying against a checkpoint: - -1. Read checkpoint from log -2. Compare current state to checkpoint: - - Files added since checkpoint - - Files modified since checkpoint - - Test pass rate now vs then - - Coverage now vs then - -3. Report: -``` -CHECKPOINT COMPARISON: $NAME -============================ -Files changed: X -Tests: +Y passed / -Z failed -Coverage: +X% / -Y% -Build: [PASS/FAIL] -``` - -## List Checkpoints - -Show all checkpoints with: -- Name -- Timestamp -- Git SHA -- Status (current, behind, ahead) - -## Workflow - -Typical checkpoint flow: - -``` -[Start] --> /checkpoint create "feature-start" - | -[Implement] --> /checkpoint create "core-done" - | -[Test] --> /checkpoint verify "core-done" - | -[Refactor] --> /checkpoint create "refactor-done" - | -[PR] --> /checkpoint verify "feature-start" -``` - -## Arguments - -$ARGUMENTS: -- `create ` - Create named checkpoint -- `verify ` - Verify against named checkpoint -- `list` - Show all checkpoints -- `clear` - Remove old checkpoints (keeps last 5) +For `clear`, remove conversational labels only. Dropping a saved stash needs separate approval for that exact stash ID. Recheck the selected reference immediately before any deletion. diff --git a/config/commands/full-stack-feature.md b/config/commands/full-stack-feature.md index a09960e..8c58f58 100644 --- a/config/commands/full-stack-feature.md +++ b/config/commands/full-stack-feature.md @@ -39,7 +39,7 @@ If the user requested private session files, check their selected directory for ### 2. Initialize state -Create `.full-stack-feature/` directory and `state.json`: +Track the following state in the conversation by default. If the user approved private file output, create `state.json` in their selected directory. Treat all later file reads and writes as references to these in-conversation notes unless that permission was given: ```json { diff --git a/config/commands/new-project.md b/config/commands/new-project.md index 9dd6ee4..195977d 100644 --- a/config/commands/new-project.md +++ b/config/commands/new-project.md @@ -41,61 +41,9 @@ Create `.claude/settings.json` with minimal project-level config: } ``` -## Step 2b: Generate TDD Agent Override (Go and Python only) +## Step 2b: Identify the project test command -If the stack from Step 1 is **Go** or **Python**, create `.claude/agents/tdd-guide.md` -to override the global npm-only tdd-guide with the correct test runners: - -**For Go projects** — create `.claude/agents/tdd-guide.md`: -```markdown ---- -name: tdd-guide -description: > - Enforce TDD methodology throughout implementation. - Use when writing new features or fixing bugs. -tools: - - Read - - "Bash(go test ./...)" - - "Bash(go test -cover ./...)" - - "Bash(go test -run *)" -model: sonnet ---- - -# TDD Guide (Go) - -Follow strict red-green-refactor: -1. Write a failing table-driven test first -2. Run `go test ./...` — confirm it fails -3. Write minimal implementation to pass -4. Run `go test -cover ./...` — verify coverage ≥ 80% -5. Refactor, keeping tests green -``` - -**For Python projects** — create `.claude/agents/tdd-guide.md`: -```markdown ---- -name: tdd-guide -description: > - Enforce TDD methodology throughout implementation. - Use when writing new features or fixing bugs. -tools: - - Read - - "Bash(python -m pytest *)" - - "Bash(python -m pytest --cov *)" -model: sonnet ---- - -# TDD Guide (Python) - -Follow strict red-green-refactor: -1. Write a failing pytest test first -2. Run `python -m pytest` — confirm it fails -3. Write minimal implementation to pass -4. Run `python -m pytest --cov` — verify coverage ≥ 80% -5. Refactor, keeping tests green -``` - -Skip this step for all other stacks (TypeScript, etc.) — the global tdd-guide covers them. +Look for a test command in the project’s scripts, CI or contributor guide. Record that command in the project instructions. For a new project, ask which test runner the user expects before describing it as available. The bundled TDD guide provides read-only guidance across stacks. The main session runs authorized checks with its existing permissions. ## Step 3: Create Project-Level CLAUDE.md From 579f6209d32a08ead7c7caef178c3db374a56a20 Mon Sep 17 00:00:00 2001 From: poferraz <210631651+poferraz@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:43:49 -0700 Subject: [PATCH 4/5] Preserve existing configuration and verify recoverable restores --- .github/dependabot.yml | 2 +- .github/workflows/check.yml | 32 ++++ .gitignore | 3 + scripts/install.sh | 129 ++-------------- scripts/manage-config.cjs | 284 ++++++++++++++++++++++++++++++++++++ scripts/test_install.py | 198 +++++++++++++++++++++++++ scripts/uninstall.sh | 116 +-------------- 7 files changed, 533 insertions(+), 231 deletions(-) create mode 100644 .github/workflows/check.yml create mode 100644 scripts/manage-config.cjs create mode 100644 scripts/test_install.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aff82a1..5ace460 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,6 @@ version: 2 updates: - - package-ecosystem: "npm" + - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..83dc594 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,32 @@ +name: Check configuration +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + check: + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: 24 + package-manager-cache: false + - name: Check shell syntax + run: | + for script in scripts/*.sh; do + bash -n "$script" + done + - name: Test configuration, conversion and recovery in temporary directories + run: python3 -m unittest discover -s scripts -p 'test_*.py' -v diff --git a/.gitignore b/.gitignore index e91c9cf..8e2e872 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,6 @@ secrets/ credentials*.json service-account*.json .gstack/ + +# Python regression checks +__pycache__/ diff --git a/scripts/install.sh b/scripts/install.sh index d613b83..5b91587 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -3,12 +3,11 @@ # Copies configuration files from this repo into ~/.claude/ # # Requirements: Claude Code >= 2.1.0, Node.js, git -# Safe to run multiple times (idempotent, non-destructive) +# Existing configuration files are preserved. set -e REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)" -CLAUDE_DIR="$HOME/.claude" # ── Colors ──────────────────────────────────────────────────────────────────── RED='\033[0;31m' @@ -54,10 +53,14 @@ fi # Check Node.js if ! command -v node >/dev/null 2>&1; then - err "Node.js not found. Required for Claude Code plugins." + err "Node.js 18 or newer is required for the local installer." err "Install from https://nodejs.org" exit 1 fi +if ! node -e 'process.exit(Number(process.versions.node.split(".")[0]) < 18 ? 1 : 0)'; then + err "Node.js 18 or newer is required for the local installer." + exit 1 +fi ok "Node.js $(node --version)" # Check git @@ -69,118 +72,8 @@ ok "git $(git --version | cut -d' ' -f3)" echo "" -# ── Step 2: Back up existing ~/.claude/ ────────────────────────────────────── - -if [ -d "$CLAUDE_DIR" ]; then - BACKUP="$HOME/.claude.backup.$(date +%Y%m%d%H%M%S)" - info "Backing up $CLAUDE_DIR to $BACKUP..." - cp -r "$CLAUDE_DIR" "$BACKUP" - ok "Backup created: $BACKUP" -else - info "No existing ~/.claude/ found. Starting fresh." -fi - -echo "" - -# ── Step 3: Create directory structure ─────────────────────────────────────── - -info "Creating directory structure..." -mkdir -p "$CLAUDE_DIR/agents" -mkdir -p "$CLAUDE_DIR/skills" -mkdir -p "$CLAUDE_DIR/commands" -mkdir -p "$CLAUDE_DIR/rules" -mkdir -p "$CLAUDE_DIR/plans" -mkdir -p "$CLAUDE_DIR/sessions" -ok "Directory structure ready" - -echo "" - -# ── Step 4: Copy config files ───────────────────────────────────────────────── - -info "Copying CLAUDE.md..." -cp "$REPO_DIR/config/CLAUDE.md" "$CLAUDE_DIR/CLAUDE.md" -ok "CLAUDE.md → ~/.claude/CLAUDE.md" - -info "Copying agents..." -if [ -d "$REPO_DIR/config/agents" ]; then - cp -r "$REPO_DIR/config/agents/." "$CLAUDE_DIR/agents/" - AGENT_COUNT=$(find "$REPO_DIR/config/agents" -name "*.md" | wc -l | tr -d ' ') - ok "$AGENT_COUNT agents → ~/.claude/agents/" -fi - -info "Copying skills..." -if [ -d "$REPO_DIR/config/skills" ]; then - cp -r "$REPO_DIR/config/skills/." "$CLAUDE_DIR/skills/" - SKILL_COUNT=$(find "$REPO_DIR/config/skills" -name "SKILL.md" | wc -l | tr -d ' ') - ok "$SKILL_COUNT skills → ~/.claude/skills/" -fi - -info "Copying commands..." -if [ -d "$REPO_DIR/config/commands" ]; then - cp -r "$REPO_DIR/config/commands/." "$CLAUDE_DIR/commands/" - CMD_COUNT=$(find "$REPO_DIR/config/commands" -name "*.md" | wc -l | tr -d ' ') - ok "$CMD_COUNT commands → ~/.claude/commands/" -fi - -info "Copying rules..." -if [ -d "$REPO_DIR/config/rules" ] && [ "$(ls -A "$REPO_DIR/config/rules" 2>/dev/null)" ]; then - cp -r "$REPO_DIR/config/rules/." "$CLAUDE_DIR/rules/" - ok "Rules → ~/.claude/rules/" -else - info "No rules directory in this config (rules live in CLAUDE.md and per-project)" -fi - -echo "" - -# ── Step 5: Settings (manual only) ─────────────────────────────────────────── - -warn "Settings NOT copied automatically." -echo "" -echo " config/settings.json contains hook configurations that depend on" -echo " your specific plugin installation paths. Review it and merge manually:" -echo "" -echo " 1. Install plugins first (Step 6 below)" -echo " 2. Run: claude plugins list — to find your plugin root paths" -echo " 3. Open config/settings.json and update \$HOME paths to match" -echo " 4. Merge the permissions and hook blocks into your ~/.claude/settings.json" -echo "" - -# ── Step 6: Next steps ──────────────────────────────────────────────────────── - -echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -echo "" -echo " ✦ Full setup guide: https://dotclaude-setup.vercel.app/" -echo "" -echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -echo "" -echo "Installation complete. Recommended next steps:" -echo "" -echo " 1. Install plugin marketplaces in Claude Code:" -echo "" -echo " Open ~/.claude/settings.json and add to extraKnownMarketplaces:" -echo " - everything-claude-code (affaan-m/everything-claude-code)" -echo " - context-mode (mksglu/context-mode)" -echo " - prompt-improver (severity1/severity1-marketplace)" -echo " - ui-ux-pro-max (nextlevelbuilder/ui-ux-pro-max-skill)" -echo "" -echo " See config/settings.json for the exact JSON to add." -echo "" -echo " 2. Customize CLAUDE.md for your profile:" -echo "" -echo " The 'About Me' section uses generic language. Adjust it to match" -echo " your actual experience level and working style." -echo "" -echo " 3. Verify the install:" -echo "" -echo " claude --version # should be >= 2.1.0" -echo " claude doctor # health check" -echo " claude -p 'say hello' # quick test session" -echo "" -echo " 4. Optional — install beads for structured task tracking:" -echo "" -echo " https://github.com/steveyegge/beads" -echo " Pairs well with context-mode: beads for task state, context-mode" -echo " for session history." -echo "" -echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -echo "" +node "$REPO_DIR/scripts/manage-config.cjs" install +echo "For upgrades, compare existing managed files and settings with the current source." +echo "Previously configured hooks and permissions remain active until you review and change them." +echo "Settings are optional. Merge only the settings you want." +echo "See README.md for setup instructions. Run claude doctor to check your installation." diff --git a/scripts/manage-config.cjs b/scripts/manage-config.cjs new file mode 100644 index 0000000..c66a74e --- /dev/null +++ b/scripts/manage-config.cjs @@ -0,0 +1,284 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const crypto = require('node:crypto'); +const readline = require('node:readline'); +const { execFileSync, spawnSync } = require('node:child_process'); + +const source = path.resolve(__dirname, '../config'); +const configured = process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), '.claude'); + +function stat(file) { + try { + return fs.lstatSync(file); + } catch (error) { + if (error.code === 'ENOENT') return null; + throw error; + } +} + +function fingerprint(root) { + const digest = crypto.createHash('sha256'); + const buffer = Buffer.alloc(65536); + function visit(file, relative) { + const info = fs.lstatSync(file); + const kind = info.isDirectory() ? 'directory' : info.isSymbolicLink() ? 'link' : 'file'; + digest.update(JSON.stringify([relative, kind, info.mode & 0o7777]) + '\n'); + if (kind === 'directory') { + for (const name of fs.readdirSync(file).sort()) visit(path.join(file, name), path.join(relative, name)); + } else if (kind === 'link') { + digest.update(JSON.stringify(fs.readlinkSync(file)) + '\n'); + } else if (info.isFile()) { + const fileHash = crypto.createHash('sha256'); + const fd = fs.openSync(file, 'r'); + try { + let length; + while ((length = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) { + fileHash.update(buffer.subarray(0, length)); + } + } finally { + fs.closeSync(fd); + } + digest.update(fileHash.digest('hex') + '\n'); + } else { + throw new Error('Close active tools and remove special files from the configuration before retrying.'); + } + } + visit(root, ''); + return digest.digest('hex'); +} + +function copyTree(from, to) { + // Both BSD and GNU cp -a preserve links, modes and platform file metadata. + execFileSync('cp', ['-a', from, to]); +} + +function snapshotDir(target, kind) { + const timestamp = new Date().toISOString().replace(/\D/g, ''); + return fs.mkdtempSync(target + '.' + kind + '.' + timestamp + '.'); +} + +function saveManifest(directory, checksum) { + fs.writeFileSync(path.join(directory, 'manifest.json'), JSON.stringify({ version: 1, sha256: checksum }), { mode: 0o600 }); +} + +function install(target, work) { + const additions = []; + function inspect(relative, input) { + const output = path.join(target, relative); + const existing = stat(output); + const material = input && fs.lstatSync(input); + if (!material || material.isDirectory()) { + if (existing && !existing.isDirectory()) throw new Error('Expected a real directory at ' + output); + if (!existing) additions.push({ output }); + if (material) { + for (const name of fs.readdirSync(input)) inspect(path.join(relative, name), path.join(input, name)); + } + } else { + if (!material.isFile()) throw new Error('Unsupported packaged file: ' + input); + if (!existing) additions.push({ output, input }); + } + } + + if (!stat(target)) additions.push({ output: target }); + for (const name of ['CLAUDE.md', 'agents', 'skills', 'commands']) inspect(name, path.join(source, name)); + for (const name of ['rules', 'plans', 'sessions']) { + const input = path.join(source, name); + inspect(name, stat(input) ? input : null); + } + if (!additions.length) { + console.log('All configuration paths already exist. Existing files were preserved.'); + return; + } + + const original = stat(target) ? fingerprint(target) : null; + const backup = snapshotDir(target, 'backup'); + const saved = path.join(backup, 'config'); + try { + if (original === null) fs.mkdirSync(saved, { mode: 0o700 }); + else copyTree(target, saved); + const checksum = fingerprint(saved); + if (original !== null && (checksum !== original || fingerprint(target) !== original)) { + throw new Error('Configuration changed or could not be copied faithfully. Retry with Claude closed.'); + } + saveManifest(backup, checksum); + } catch (error) { + fs.rmSync(backup, { recursive: true, force: true }); + throw error; + } + console.log('Previous configuration retained at ' + saved); + + // Prepare complete files on the same filesystem, then add them exclusively. + // Existing live files retain their inodes, hard links, ACLs and extended attributes. + const published = []; + try { + for (const [index, change] of additions.entries()) { + if (change.input) { + change.copy = path.join(work, String(index)); + fs.copyFileSync(change.input, change.copy); + change.checksum = fingerprint(change.copy); + } + } + for (const change of additions) { + if (change.copy) fs.linkSync(change.copy, change.output); + else fs.mkdirSync(change.output, { mode: 0o700 }); + published.push(change); + } + } catch (error) { + for (const change of published.reverse()) { + if (change.copy) { + const info = stat(change.output); + if (info?.isFile() && info.ino === fs.statSync(change.copy).ino && + fingerprint(change.output) === change.checksum) fs.unlinkSync(change.output); + } else { + if (stat(change.output)?.isDirectory() && !fs.readdirSync(change.output).length) fs.rmdirSync(change.output); + } + } + throw error; + } + console.log('Installed missing files in ' + target + '. Existing files were preserved.'); +} + +function recoverPending(target) { + const marker = target + '.dotclaude-restore'; + const info = stat(marker); + if (!info) return; + if (!info.isFile()) throw new Error('Invalid restore marker at ' + marker); + const name = fs.readFileSync(marker, 'utf8'); + const prefix = path.basename(target) + '.recovery.'; + if (!name.startsWith(prefix) || !/^\d{17}\.[a-zA-Z0-9]+$/.test(name.slice(prefix.length))) { + throw new Error('Invalid recovery name in ' + marker); + } + if (!stat(target)) { + const directory = path.join(path.dirname(target), name); + if (!stat(directory)?.isDirectory()) throw new Error('Invalid interrupted restore directory.'); + const recovery = path.join(directory, 'config'); + if (!stat(recovery)?.isDirectory()) throw new Error('Expected recovery configuration at ' + recovery); + fs.renameSync(recovery, target); + console.log('Recovered the previous configuration after an interrupted restore.'); + } + fs.unlinkSync(marker); +} + +function activateRestore(target, staged, original) { + if (original === null) { + if (stat(target)) throw new Error('Configuration appeared during preparation. Retry with Claude closed.'); + fs.renameSync(staged, target); + return; + } + const backup = snapshotDir(target, 'recovery'); + const saved = path.join(backup, 'config'); + const marker = target + '.dotclaude-restore'; + let moved = false; + try { + saveManifest(backup, original); + fs.writeFileSync(marker, path.basename(backup), { flag: 'wx', mode: 0o600 }); + fs.renameSync(target, saved); + moved = true; + if (fingerprint(saved) !== original) throw new Error('Configuration changed during preparation. Retry with Claude closed.'); + fs.renameSync(staged, target); + } catch (error) { + if (moved) { + if (stat(target)) throw new Error('Configuration changed concurrently. The previous tree remains at ' + saved); + fs.renameSync(saved, target); + } + fs.rmSync(marker, { force: true }); + fs.rmSync(backup, { recursive: true, force: true }); + throw error; + } + fs.unlinkSync(marker); + console.log('Previous configuration retained at ' + saved); +} + +function backupList(target) { + const parent = path.dirname(target); + const prefix = path.basename(target) + '.backup.'; + return fs.readdirSync(parent).filter(name => { + const suffix = name.slice(prefix.length); + return name.startsWith(prefix) && /^(?:\d{14}|\d{17}\.[a-zA-Z0-9]+)$/.test(suffix) && + fs.lstatSync(path.join(parent, name)).isDirectory(); + }).sort().reverse().map(name => path.join(parent, name)); +} + +async function restore(target, staged, currentHash) { + const backups = backupList(target); + if (!backups.length) throw new Error('No backup found for the selected configuration.'); + const stream = readline.createInterface({ input: process.stdin, terminal: false }); + const lines = stream[Symbol.asyncIterator](); + try { + let selected = backups[0]; + if (backups.length > 1) { + backups.forEach((name, i) => console.log((i + 1) + ') ' + name)); + process.stdout.write('Restore which backup? [1]: '); + const answer = await lines.next(); + if (answer.done) return; + const choice = answer.value.trim() || '1'; + if (!/^\d+$/.test(choice) || !backups[Number(choice) - 1]) throw new Error('Invalid backup selection.'); + selected = backups[Number(choice) - 1]; + } + console.log('Selected backup: ' + selected); + const legacy = /^\d{14}$/.test(selected.slice((target + '.backup.').length)); + if (legacy) console.log('Legacy snapshot. No original checksum was recorded.'); + process.stdout.write('Restore this snapshot and preserve the current configuration for recovery? [y/N]: '); + const confirm = await lines.next(); + if (confirm.done || !/^(y|yes)$/i.test(confirm.value.trim())) return; + const input = legacy ? selected : path.join(selected, 'config'); + if (!stat(input)?.isDirectory()) throw new Error('Backup configuration is missing or invalid.'); + const original = fingerprint(input); + if (!legacy) { + const manifestPath = path.join(selected, 'manifest.json'); + if (!stat(manifestPath)?.isFile()) throw new Error('Backup manifest is missing or invalid.'); + let manifest; + try { + manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + } catch { + throw new Error('Backup manifest could not be read.'); + } + if (manifest?.version !== 1 || manifest.sha256 !== original) throw new Error('Backup contents do not match the saved checksum.'); + } + copyTree(input, staged); + if (fingerprint(staged) !== original) throw new Error('Backup could not be copied faithfully. Current configuration preserved.'); + activateRestore(target, staged, currentHash); + console.log('Restored ' + target); + } finally { + stream.close(); + } +} + +async function main() { + if (!configured || !path.isAbsolute(configured)) throw new Error('Use an absolute configuration directory.'); + const target = path.resolve(configured); + const parent = path.dirname(target); + if (target === parent || target === os.homedir() || !fs.statSync(parent).isDirectory()) throw new Error('Select a dedicated configuration directory.'); + const repo = path.dirname(source); + const physicalTarget = path.join(fs.realpathSync(parent), path.basename(target)); + const userDirectory = fs.realpathSync(os.homedir()); + if (repo === physicalTarget || repo.startsWith(physicalTarget + path.sep) || physicalTarget.startsWith(repo + path.sep) || + userDirectory === physicalTarget || userDirectory.startsWith(physicalTarget + path.sep)) throw new Error('Select a dedicated configuration directory outside this checkout.'); + if (process.argv.length === 3) { + // The kernel releases this lock even if a transaction is killed. Keep the + // lock file in place so concurrent callers always lock the same inode. + const lock = target + '.dotclaude-lock'; + const file = stat(lock); + if (file && !file.isFile()) throw new Error('Expected a regular lock file at ' + lock); + process.umask(0o077); + const args = process.platform === 'darwin' ? ['lockf', '-k', '-t', '0'] : ['flock', '-n']; + const result = spawnSync(args[0], [...args.slice(1), lock, process.execPath, __filename, process.argv[2], '--locked'], { stdio: 'inherit' }); + if (result.error) throw result.error; + if (result.status !== 0) process.exitCode = result.status || 1; + return; + } + if (process.argv[3] !== '--locked') throw new Error('Unknown arguments.'); + recoverPending(target); + const existing = stat(target); + if (existing && !existing.isDirectory()) throw new Error('The configuration root must be a real directory.'); + const work = fs.mkdtempSync(path.join(parent, '.dotclaude-stage-')); + try { + if (process.argv[2] === 'install') install(target, work); + else if (process.argv[2] === 'uninstall') await restore(target, path.join(work, 'new'), existing ? fingerprint(target) : null); + else throw new Error('Unknown operation.'); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } +} +main().catch(error => { console.error(error.message); process.exitCode = 1; }); diff --git a/scripts/test_install.py b/scripts/test_install.py new file mode 100644 index 0000000..2d4295e --- /dev/null +++ b/scripts/test_install.py @@ -0,0 +1,198 @@ +"""Exercise the installer and recovery entry points in disposable profiles.""" + +import fcntl +import os +import sys +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPTS = Path(__file__).resolve().parent + + +class ConfigTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory(prefix="dotclaude-test-") + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.profile = self.root / "test profile" + tools = self.root / "bin" + tools.mkdir() + # The installer only needs the Claude CLI version. Never launch a session. + claude = tools / "claude" + claude.write_text("#!/bin/sh\necho '2.1.0 (fixture)'\n") + claude.chmod(0o755) + self.env = dict(os.environ, PATH=str(tools) + os.pathsep + os.environ["PATH"], + CLAUDE_CONFIG_DIR=str(self.profile)) + self.env.pop("NODE_OPTIONS", None) + + def command(self, action, answer="", success=True, **extra): + result = subprocess.run(["sh", str(SCRIPTS / (action + ".sh"))], cwd=self.root, + env={**self.env, **extra}, input=answer, + capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode == 0, success, result.stderr) + return result.stdout + + def snapshots(self, kind="backup"): + return list(self.root.glob("test profile." + kind + ".*")) + + def test_install_repeat_and_restore_preserve_user_files(self): + self.profile.mkdir() + (self.profile / "CLAUDE.md").write_text("My instructions") + (self.profile / "settings.json").write_text("{}") + (self.profile / "notes.md").write_text("Personal notes") + (self.profile / "notes-link").symlink_to("notes.md") + self.command("install") + self.assertEqual((self.profile / "CLAUDE.md").read_text(), "My instructions") + self.assertEqual((self.profile / "settings.json").read_text(), "{}") + self.assertEqual(os.readlink(self.profile / "notes-link"), "notes.md") + self.assertTrue((self.profile / "agents/planner.md").is_file()) + self.command("install") + self.assertEqual(len(self.snapshots()), 1) + self.assertEqual(self.snapshots()[0].stat().st_mode & 0o777, 0o700) + (self.profile / "notes.md").write_text("After installing") + (self.profile / "new-file.txt").write_text("Keep me") + self.command("uninstall", "n\n") + self.assertTrue((self.profile / "new-file.txt").is_file()) + self.command("uninstall", "y\n") + self.assertEqual((self.profile / "notes.md").read_text(), "Personal notes") + self.assertFalse((self.profile / "agents").exists()) + saved = self.snapshots("recovery")[0] / "config" + self.assertEqual((saved / "new-file.txt").read_text(), "Keep me") + self.assertEqual((saved / "notes.md").read_text(), "After installing") + + def test_fresh_install_has_recoverable_empty_baseline(self): + self.command("install") + self.assertFalse((self.profile / "settings.json").exists()) + self.command("uninstall", "y\n") + self.assertEqual(list(self.profile.iterdir()), []) + self.assertTrue((self.snapshots("recovery")[0] / "config/CLAUDE.md").is_file()) + + def test_missing_and_corrupt_snapshots_preserve_current_config(self): + self.profile.mkdir() + (self.profile / "own").write_text("Keep") + self.command("uninstall", "y\n", success=False) + self.command("install") + backup = self.snapshots()[0] + (backup / "config/own").write_text("Corrupted") + self.command("uninstall", "y\n", success=False) + (backup / "manifest.json").unlink() + self.command("uninstall", "y\n", success=False) + self.assertEqual((self.profile / "own").read_text(), "Keep") + self.assertEqual(self.snapshots("recovery"), []) + + def test_symlinks_protect_external_directories(self): + external = self.root / "external" + external.mkdir() + self.profile.symlink_to(external, target_is_directory=True) + self.command("install", success=False) + self.profile.unlink() + self.profile.mkdir() + (self.profile / "agents").symlink_to(external, target_is_directory=True) + self.command("install", success=False) + self.assertEqual(list(external.iterdir()), []) + self.assertEqual(self.snapshots(), []) + + def test_second_install_and_legacy_restore_with_spaces(self): + self.profile.mkdir() + self.command("install") + legacy = self.root / "test profile.backup.20000101000000" + legacy.mkdir() + (legacy / "prior").write_text("Legacy file") + self.command("uninstall", "2\ny\n") + self.assertEqual((self.profile / "prior").read_text(), "Legacy file") + self.assertTrue((self.snapshots("recovery")[0] / "config/CLAUDE.md").is_file()) + + def test_failed_activation_rolls_back_current_tree(self): + self.command("install") + (self.profile / "new-file.txt").write_text("Keep me") + shim = self.root / "fail-activation.cjs" + shim.write_text(""" +const fs = require('node:fs'); +const rename = fs.renameSync; +fs.renameSync = (from, to) => { + if (from.endsWith('/new') && to === process.env.CLAUDE_CONFIG_DIR) throw new Error('simulated activation failure'); + return rename(from, to); +}; +""") + self.command("uninstall", "y\n", success=False, NODE_OPTIONS="--require=" + str(shim)) + self.assertEqual((self.profile / "new-file.txt").read_text(), "Keep me") + self.assertTrue((self.profile / "CLAUDE.md").is_file()) + self.command("uninstall", "y\n") # Retry after the failed transaction. + self.assertEqual(list(self.profile.iterdir()), []) + + def test_install_preserves_inode_permissions_and_user_attributes(self): + self.profile.mkdir() + notes = self.profile / "notes" + notes.write_text("original") + notes.chmod(0o640) + os.link(notes, self.profile / "linked notes") + if sys.platform == "darwin": + subprocess.run(["xattr", "-w", "org.example.dotclaude", "fixture", str(notes)], check=True) + def attribute(file): + return subprocess.check_output(["xattr", "-p", "org.example.dotclaude", str(file)]).strip() + else: + os.setxattr(notes, "user.dotclaude", b"fixture") + def attribute(file): + return os.getxattr(file, "user.dotclaude") + inode = notes.stat().st_ino + self.command("install") + self.assertEqual(notes.stat().st_ino, inode) + self.assertEqual((self.profile / "linked notes").stat().st_ino, inode) + self.assertEqual(notes.stat().st_mode & 0o777, 0o640) + self.assertEqual(attribute(notes), b"fixture") + self.assertEqual(attribute(self.snapshots()[0] / "config/notes"), b"fixture") + self.command("uninstall", "y\n") + self.assertEqual(attribute(notes), b"fixture") + + def test_killed_restore_recovers_displaced_current_profile_on_retry(self): + self.command("install") + note = self.profile / "personal" + note.write_text("changed after installation") + shim = self.root / "interrupt.cjs" + shim.write_text(""" +const fs = require('node:fs'); +const rename = fs.renameSync; +fs.renameSync = (from, to) => { + if (from.endsWith('/new') && to === process.env.CLAUDE_CONFIG_DIR) process.kill(process.pid, 'SIGKILL'); + return rename(from, to); +}; +""") + self.command("uninstall", "y\n", success=False, NODE_OPTIONS="--require=" + str(shim)) + self.assertFalse(self.profile.exists()) + self.assertEqual((self.snapshots("recovery")[0] / "config/personal").read_text(), "changed after installation") + self.command("install") + self.assertEqual(note.read_text(), "changed after installation") + self.assertFalse((self.root / "test profile.dotclaude-restore").exists()) + + def test_partial_install_failure_preserves_the_original_tree(self): + self.profile.mkdir() + (self.profile / "keep").write_text("keep") + shim = self.root / "fail-link.cjs" + shim.write_text(""" +const fs = require('node:fs'); +const link = fs.linkSync; +let count = 0; +fs.linkSync = (from, to) => { + if (++count === 3) throw new Error('simulated write failure'); + return link(from, to); +}; +""") + self.command("install", success=False, NODE_OPTIONS="--require=" + str(shim)) + self.assertEqual([p.name for p in self.profile.iterdir()], ["keep"]) + self.assertEqual((self.snapshots()[0] / "config/keep").read_text(), "keep") + self.command("install") + self.assertTrue((self.profile / "agents/planner.md").is_file()) + + def test_busy_target_is_untouched(self): + lock = self.root / "test profile.dotclaude-lock" + with lock.open("w") as held: + fcntl.flock(held.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + self.command("install", success=False) + self.assertFalse(self.profile.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh index 905002c..5878853 100755 --- a/scripts/uninstall.sh +++ b/scripts/uninstall.sh @@ -1,114 +1,6 @@ #!/bin/sh -# dotclaude uninstall script -# Restores the backup created by install.sh -# -# NEVER deletes ~/.claude/ without a backup to restore from. -# If no backup exists, prints a warning and exits. +# Restore a selected snapshot, retaining the displaced configuration. +set -eu -set -e - -CLAUDE_DIR="$HOME/.claude" - -# ── Colors ──────────────────────────────────────────────────────────────────── -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' - -ok() { printf "${GREEN} ✓${NC} %s\n" "$1"; } -warn() { printf "${YELLOW} ⚠${NC} %s\n" "$1"; } -info() { printf "${BLUE} →${NC} %s\n" "$1"; } -err() { printf "${RED} ✗${NC} %s\n" "$1"; } - -echo "" -echo "dotclaude uninstaller" -echo "=====================" -echo "" - -# ── Find backups ────────────────────────────────────────────────────────────── - -BACKUPS=$(ls -d "$HOME/.claude.backup."* 2>/dev/null | sort -r || true) - -if [ -z "$BACKUPS" ]; then - warn "No backup found at $HOME/.claude.backup.*" - echo "" - echo " The install script creates a backup at ~/.claude.backup.YYYYMMDDHHMMSS" - echo " before modifying your config. No backup means the install script was" - echo " not run, or the backup was manually deleted." - echo "" - echo " To manually remove dotclaude files without a backup, delete:" - echo " ~/.claude/CLAUDE.md" - echo " ~/.claude/agents/" - echo " ~/.claude/skills/" - echo " ~/.claude/commands/" - echo "" - echo " Or restore your own backup from a different source." - exit 1 -fi - -# ── Select backup ───────────────────────────────────────────────────────────── - -BACKUP_COUNT=$(echo "$BACKUPS" | wc -l | tr -d ' ') - -if [ "$BACKUP_COUNT" -eq 1 ]; then - SELECTED_BACKUP="$BACKUPS" - info "Found 1 backup: $SELECTED_BACKUP" -else - echo "Multiple backups found:" - echo "" - i=1 - for b in $BACKUPS; do - echo " $i) $b" - i=$((i + 1)) - done - echo "" - printf "Restore which backup? [1]: " - read -r CHOICE - CHOICE="${CHOICE:-1}" - - i=1 - for b in $BACKUPS; do - if [ "$i" -eq "$CHOICE" ]; then - SELECTED_BACKUP="$b" - break - fi - i=$((i + 1)) - done - - if [ -z "$SELECTED_BACKUP" ]; then - err "Invalid choice." - exit 1 - fi -fi - -echo "" - -# ── Confirm ─────────────────────────────────────────────────────────────────── - -warn "This will replace $CLAUDE_DIR with $SELECTED_BACKUP" -printf "Continue? [y/N]: " -read -r CONFIRM - -case "$CONFIRM" in - y|Y|yes|YES) ;; - *) - info "Aborted." - exit 0 - ;; -esac - -echo "" - -# ── Restore ─────────────────────────────────────────────────────────────────── - -info "Removing current $CLAUDE_DIR..." -rm -rf "$CLAUDE_DIR" - -info "Restoring $SELECTED_BACKUP..." -cp -r "$SELECTED_BACKUP" "$CLAUDE_DIR" - -ok "Restored $SELECTED_BACKUP → $CLAUDE_DIR" -echo "" -echo " Run 'claude doctor' to verify the restored configuration." -echo "" +script_dir="$(cd "$(dirname "$0")" && pwd)" +exec node "$script_dir/manage-config.cjs" uninstall From b2014b175d0e01b5e276b8aef6e41a3cb2cdb687 Mon Sep 17 00:00:00 2001 From: poferraz <210631651+poferraz@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:44:52 -0700 Subject: [PATCH 5/5] Verify recovery data before resuming interrupted transactions --- scripts/manage-config.cjs | 37 +++++++++++++++++++++++++------------ scripts/test_install.py | 7 ++++++- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/scripts/manage-config.cjs b/scripts/manage-config.cjs index c66a74e..cdd70f9 100644 --- a/scripts/manage-config.cjs +++ b/scripts/manage-config.cjs @@ -62,6 +62,18 @@ function saveManifest(directory, checksum) { fs.writeFileSync(path.join(directory, 'manifest.json'), JSON.stringify({ version: 1, sha256: checksum }), { mode: 0o600 }); } +function checkManifest(directory, checksum) { + const file = path.join(directory, 'manifest.json'); + if (!stat(file)?.isFile()) throw new Error('Backup manifest is missing or invalid.'); + let manifest; + try { + manifest = JSON.parse(fs.readFileSync(file, 'utf8')); + } catch { + throw new Error('Backup manifest could not be read.'); + } + if (manifest?.version !== 1 || manifest.sha256 !== checksum) throw new Error('Backup contents do not match the saved checksum.'); +} + function install(target, work) { const additions = []; function inspect(relative, input) { @@ -110,6 +122,11 @@ function install(target, work) { // Prepare complete files on the same filesystem, then add them exclusively. // Existing live files retain their inodes, hard links, ACLs and extended attributes. + const physical = path.join(fs.realpathSync(path.dirname(target)), path.basename(target)); + function parentIsUnchanged(output) { + const parent = path.dirname(output); + return fs.realpathSync(parent) === path.resolve(physical, path.relative(target, parent)); + } const published = []; try { for (const [index, change] of additions.entries()) { @@ -120,18 +137,21 @@ function install(target, work) { } } for (const change of additions) { + if (!parentIsUnchanged(change.output)) throw new Error('A managed directory changed during installation.'); if (change.copy) fs.linkSync(change.copy, change.output); else fs.mkdirSync(change.output, { mode: 0o700 }); + change.inode = fs.lstatSync(change.output).ino; published.push(change); } } catch (error) { for (const change of published.reverse()) { + const info = stat(change.output); + if (!info || !parentIsUnchanged(change.output) || info.ino !== change.inode) continue; if (change.copy) { - const info = stat(change.output); - if (info?.isFile() && info.ino === fs.statSync(change.copy).ino && + if (info.isFile() && fingerprint(change.output) === change.checksum) fs.unlinkSync(change.output); } else { - if (stat(change.output)?.isDirectory() && !fs.readdirSync(change.output).length) fs.rmdirSync(change.output); + if (info.isDirectory() && !fs.readdirSync(change.output).length) fs.rmdirSync(change.output); } } throw error; @@ -154,6 +174,7 @@ function recoverPending(target) { if (!stat(directory)?.isDirectory()) throw new Error('Invalid interrupted restore directory.'); const recovery = path.join(directory, 'config'); if (!stat(recovery)?.isDirectory()) throw new Error('Expected recovery configuration at ' + recovery); + checkManifest(directory, fingerprint(recovery)); fs.renameSync(recovery, target); console.log('Recovered the previous configuration after an interrupted restore.'); } @@ -226,15 +247,7 @@ async function restore(target, staged, currentHash) { if (!stat(input)?.isDirectory()) throw new Error('Backup configuration is missing or invalid.'); const original = fingerprint(input); if (!legacy) { - const manifestPath = path.join(selected, 'manifest.json'); - if (!stat(manifestPath)?.isFile()) throw new Error('Backup manifest is missing or invalid.'); - let manifest; - try { - manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - } catch { - throw new Error('Backup manifest could not be read.'); - } - if (manifest?.version !== 1 || manifest.sha256 !== original) throw new Error('Backup contents do not match the saved checksum.'); + checkManifest(selected, original); } copyTree(input, staged); if (fingerprint(staged) !== original) throw new Error('Backup could not be copied faithfully. Current configuration preserved.'); diff --git a/scripts/test_install.py b/scripts/test_install.py index 2d4295e..bd004a1 100644 --- a/scripts/test_install.py +++ b/scripts/test_install.py @@ -162,7 +162,12 @@ def test_killed_restore_recovers_displaced_current_profile_on_retry(self): """) self.command("uninstall", "y\n", success=False, NODE_OPTIONS="--require=" + str(shim)) self.assertFalse(self.profile.exists()) - self.assertEqual((self.snapshots("recovery")[0] / "config/personal").read_text(), "changed after installation") + saved = self.snapshots("recovery")[0] / "config/personal" + self.assertEqual(saved.read_text(), "changed after installation") + saved.write_text("wrong contents") + self.command("install", success=False) + self.assertFalse(self.profile.exists()) + saved.write_text("changed after installation") self.command("install") self.assertEqual(note.read_text(), "changed after installation") self.assertFalse((self.root / "test profile.dotclaude-restore").exists())