From 188a3e17d049388c0f9bb46299de377447d92d20 Mon Sep 17 00:00:00 2001 From: Peter Svensson Date: Tue, 7 Apr 2026 09:04:34 +0200 Subject: [PATCH] =?UTF-8?q?refactor:=20restructure=20claude=20config=20?= =?UTF-8?q?=E2=80=94=20agents,=20rules,=20skills?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update agent definitions, simplify rules tree by removing common/* and language-specific hooks/security/testing files, drop bundled skills in favor of plugin-provided ones, update settings.json and CLAUDE.md. Add intersolia infrastructure dot_claude settings. --- dot_claude/CLAUDE.md | 139 ++--- dot_claude/agents/architect.md | 25 - dot_claude/agents/code-reviewer.md | 30 +- dot_claude/agents/go-reviewer.md | 2 +- dot_claude/agents/planner.md | 81 +-- dot_claude/agents/python-reviewer.md | 2 +- dot_claude/agents/security-reviewer.md | 4 - dot_claude/agents/tdd-guide.md | 2 +- dot_claude/rules/README.md | 83 +-- dot_claude/rules/common/agents.md | 49 -- dot_claude/rules/common/coding-style.md | 48 -- dot_claude/rules/common/git-workflow.md | 23 +- dot_claude/rules/common/hooks.md | 30 - dot_claude/rules/common/patterns.md | 31 - dot_claude/rules/common/performance.md | 55 -- dot_claude/rules/common/security.md | 29 - dot_claude/rules/common/testing.md | 29 - dot_claude/rules/golang/coding-style.md | 1 - dot_claude/rules/golang/hooks.md | 17 - dot_claude/rules/golang/patterns.md | 1 - dot_claude/rules/golang/security.md | 34 -- dot_claude/rules/golang/testing.md | 1 - dot_claude/rules/typescript/coding-style.md | 1 - dot_claude/rules/typescript/hooks.md | 22 - dot_claude/rules/typescript/patterns.md | 1 - dot_claude/rules/typescript/security.md | 28 - dot_claude/rules/typescript/testing.md | 18 - dot_claude/settings.json | 20 +- dot_claude/skills/coding-standards/SKILL.md | 529 ------------------ .../skills/continuous-learning/SKILL.md | 118 ---- .../skills/continuous-learning/config.json | 18 - .../continuous-learning/evaluate-session.sh | 69 --- dot_claude/skills/security-review/SKILL.md | 494 ---------------- .../cloud-infrastructure-security.md | 361 ------------ dot_claude/skills/tdd-workflow/SKILL.md | 409 -------------- dot_claude/skills/verification-loop/SKILL.md | 125 ----- .../{config_home => private_config_home} | 0 private_dot_ssh/{config => private_config} | 0 .../dot_claude/settings.local.json | 117 ++++ 39 files changed, 207 insertions(+), 2839 deletions(-) delete mode 100644 dot_claude/rules/common/agents.md delete mode 100644 dot_claude/rules/common/coding-style.md delete mode 100644 dot_claude/rules/common/hooks.md delete mode 100644 dot_claude/rules/common/patterns.md delete mode 100644 dot_claude/rules/common/performance.md delete mode 100644 dot_claude/rules/common/security.md delete mode 100644 dot_claude/rules/common/testing.md delete mode 100644 dot_claude/rules/golang/hooks.md delete mode 100644 dot_claude/rules/golang/security.md delete mode 100644 dot_claude/rules/typescript/hooks.md delete mode 100644 dot_claude/rules/typescript/security.md delete mode 100644 dot_claude/rules/typescript/testing.md delete mode 100644 dot_claude/skills/coding-standards/SKILL.md delete mode 100644 dot_claude/skills/continuous-learning/SKILL.md delete mode 100644 dot_claude/skills/continuous-learning/config.json delete mode 100755 dot_claude/skills/continuous-learning/evaluate-session.sh delete mode 100644 dot_claude/skills/security-review/SKILL.md delete mode 100644 dot_claude/skills/security-review/cloud-infrastructure-security.md delete mode 100644 dot_claude/skills/tdd-workflow/SKILL.md delete mode 100644 dot_claude/skills/verification-loop/SKILL.md rename private_dot_ssh/config.d/{config_home => private_config_home} (100%) rename private_dot_ssh/{config => private_config} (100%) create mode 100644 source/intersolia/infrastructure/dot_claude/settings.local.json diff --git a/dot_claude/CLAUDE.md b/dot_claude/CLAUDE.md index bf4168e..273358f 100644 --- a/dot_claude/CLAUDE.md +++ b/dot_claude/CLAUDE.md @@ -1,63 +1,41 @@ -- always unzip files to a temporary directory -- Always add all files to git before running pre-commit since it stashes all unstaged files when running -- I use GNU versions of rm and cp which ask for confirmation on replace and remove. -- My shell is fish. All suggested shell commands and scripts must use fish-compatible syntax (no bash-isms like `while read`, `$()` subshells in pipes, `export FOO=bar`, etc.). Use fish idioms: `for x in (command)`, `set -x FOO bar`, etc. -- Files managed by chezmoi must not be edited directly in the home directory. Edit the source files in the chezmoi source directory instead (`chezmoi source-path` to find it). -- Always explicitly specify the context when running `kubectl` commands using `--context `. Check the project's `.buildtools.yaml` or `.envrc` for the expected k8s context. Never rely on the current default context — it may point to a different cluster (e.g., production instead of local). For local development, the context typically follows the pattern: `kind-` -- Never use quote characters (`'` or `"`) inside `#` comments in Bash tool commands. The shell parser cannot distinguish quotes in comments from actual shell quoting, triggering a "desync quote tracking" warning that forces manual approval. Rephrase or move explanations to text output. +- Always unzip files to a temporary directory +- Always add all files to git before running pre-commit (it stashes unstaged files) +- I use GNU versions of rm and cp which ask for confirmation on replace and remove +- My shell is fish. All shell commands must use fish syntax (no bash-isms). Use fish idioms: `for x in (command)`, `set -x FOO bar`, etc. +- Files managed by chezmoi must not be edited directly. Edit source files in the chezmoi source directory (`chezmoi source-path`) +- Always specify `--context ` for kubectl. Check `.buildtools.yaml` or `.envrc` for the expected context. Never rely on the default. +- Never use quote characters in # comments in Bash tool commands (triggers desync quote tracking warning) ## Workflow Orchestration ### Plan Mode - Enter plan mode for ANY non-trivial task (3+ steps or architectural decisions) -- If something goes sideways, STOP and re-plan immediately — don't keep pushing -- Use plan mode for verification steps, not just building -- Write detailed specs upfront to reduce ambiguity -- Pour energy into the plan so implementation can be done in one shot - -### Subagent Strategy -- Use subagents liberally to keep main context window clean -- Offload research, exploration, and parallel analysis to subagents -- For complex problems, throw more compute at it via subagents -- One task per subagent for focused execution +- If something goes sideways, STOP and re-plan immediately +- Write detailed specs upfront so implementation can be done in one shot ### Self-Improvement Loop -- After ANY correction from the user: update auto-memory or the relevant CLAUDE.md with the pattern -- Write rules for yourself that prevent the same mistake -- Ruthlessly iterate on these rules until mistake rate drops -- Keep migration tracking, plan, and memory files up to date at the end of every session that completes meaningful work -- Before starting phased or migration work: read the memory/plan file, then verify it against actual codebase state (check which files exist, which tests pass, git log). Update the file if outdated. Never trust stale docs — they cost entire sessions of wasted exploration +- After ANY correction: update auto-memory or CLAUDE.md with the pattern +- Before starting phased work: read memory/plan files, verify against actual codebase state, update if outdated ### Verification Before Done - Never mark a task complete without proving it works -- Before creating PRs: run the full lint and test suite if available -- Re-read your changes for unnecessary complexity, redundant code, and unclear naming +- Before creating PRs: run the full lint and test suite +- Re-read changes for unnecessary complexity and unclear naming - Diff behavior between main and your changes when relevant -- Ask yourself: "Would a staff engineer approve this?" - -### Demand Elegance (Balanced) -- For non-trivial changes: pause and ask "is there a more elegant way?" -- If a fix feels hacky: rethink and implement the elegant solution -- Skip this for simple, obvious fixes — don't over-engineer ### Autonomous Bug Fixing -- When given a bug report: just fix it — don't ask for hand-holding -- Point at logs, errors, failing tests — then resolve them -- Go fix failing CI tests without being told how +- When given a bug report: just fix it. Point at logs, errors, failing tests, then resolve them. ## Core Principles -- **Simplicity First**: Make every change as simple as possible. Minimal code impact. -- **No Laziness**: Find root causes. No temporary fixes. Senior developer standards. -- **Minimal Impact**: Changes should only touch what's necessary. Avoid introducing bugs. If you identify something that seems like it should change but wasn't requested, mention it and wait for approval — do not modify it. -- **Replace, don't deprecate**: When new replaces old, remove the old entirely. No backward-compat shims, dual config formats, or migration paths. Proactively flag dead code. +- **Minimal Impact**: Only touch what's necessary. If something seems like it should change but wasn't requested, mention it and wait for approval. +- **Replace, don't deprecate**: Remove the old entirely. No backward-compat shims or migration paths. - **No phantom features**: Don't document or validate features that aren't implemented. -- **Justify new dependencies**: Each dependency is attack surface and maintenance burden. Justify before adding. -- **No premature abstraction**: Don't create utilities until the same code is written three times. -- **Bias toward action**: Decide and move for anything easily reversed; state the assumption. Ask before committing to interfaces, data models, architecture, or destructive ops. When assigned a task, proceed directly to implementation — do not spend the session exploring and asking clarifying questions unless explicitly asked to plan first. -- **Finish the job**: Handle edge cases you can see. Clean up what you touched. Flag broken adjacent things. But don't invent new scope — thoroughness is not gold-plating. -- **Verify at every level**: Prefer structure-aware tools (ast-grep, LSPs, compilers) over text pattern matching when searching for code structure. Review your own output critically. -- **Look up versions**: When adding dependencies, CI actions, or tool versions, always look up the current stable version — never assume from memory. +- **Justify new dependencies**: Each is attack surface and maintenance burden. +- **Bias toward action**: Decide and move for anything easily reversed; state the assumption. Ask before committing to interfaces, data models, architecture, or destructive ops. +- **Finish the job**: Handle edge cases you can see. Clean up what you touched. Flag broken adjacent things. Don't invent new scope. +- **Verify at every level**: Prefer ast-grep, LSPs, compilers over text pattern matching for code structure. +- **Look up versions**: When adding dependencies, CI actions, or tool versions, always look up the current stable version. ## Code Discipline @@ -66,73 +44,54 @@ - ≤5 positional parameters — use options objects/structs beyond that ### Zero Warnings Policy -Fix every warning from every tool — linters, type checkers, compilers, tests. If a warning truly can't be fixed, add an inline ignore with a justification comment. Never leave warnings unaddressed. - -### Comments -No commented-out code — delete it. If you need a comment to explain WHAT the code does, refactor the code instead. Comments explain WHY, not WHAT. - -### Error Handling -- Fail fast with clear, actionable messages -- Never swallow exceptions silently -- Include context: what operation failed, what input caused it, suggested fix - -### Testing Philosophy -- **Test behavior, not implementation** — if a refactor breaks tests but not code, the tests were wrong -- **Test edges and errors**, not just the happy path — bugs live in boundaries and error paths -- **Mock boundaries, not logic** — only mock slow, non-deterministic, or external things -- **Verify tests catch failures** — break the code, confirm the test fails, then fix +Fix every warning from every tool. If unfixable, add an inline ignore with justification. ### Code Review Order -Evaluate: architecture → code quality → tests → performance. For each issue: describe concretely with file:line references, present options with tradeoffs, recommend one. +Evaluate: architecture → code quality → tests → performance. For each issue: describe concretely with file:line, present options with tradeoffs, recommend one. ### PR Descriptions -Describe what the code does now — not discarded approaches, prior iterations, or alternatives. Use plain, factual language. Avoid hype words: critical, crucial, essential, significant, comprehensive, robust, elegant. +Describe what the code does now — not discarded approaches. Avoid hype words: critical, crucial, essential, significant, comprehensive, robust, elegant. ## CLI Tools -Prefer these over slower defaults: - | Tool | Replaces | Usage | |------|----------|-------| -| `rg` (ripgrep) | grep | `rg "pattern"` — fast regex search | -| `fd` | find | `fd "*.py"` — fast file finder | -| `ast-grep` | — | `ast-grep --pattern '$FUNC($$$)' --lang py` — AST-based code search | -| `shellcheck` | — | `shellcheck script.sh` — shell script linter | -| `shfmt` | — | `shfmt -i 2 -w script.sh` — shell formatter | -| `actionlint` | — | `actionlint .github/workflows/` — GitHub Actions linter | -| `zizmor` | — | `zizmor .github/workflows/` — Actions security audit | -| `prek` | pre-commit | `prek run --all-files` — fast pre-commit runner | -| `trash` | rm | `trash file` — moves to macOS Trash (recoverable). **Never use `rm -rf`** | - -Prefer `ast-grep` over ripgrep when searching for code structure (function calls, class definitions, imports). Use ripgrep for literal strings and log messages. +| `rg` | grep | `rg "pattern"` | +| `fd` | find | `fd "*.py"` | +| `ast-grep` | — | `ast-grep --pattern '$FUNC($$$)' --lang py` | +| `shellcheck` | — | `shellcheck script.sh` | +| `shfmt` | — | `shfmt -i 2 -w script.sh` | +| `actionlint` | — | `actionlint .github/workflows/` | +| `zizmor` | — | `zizmor .github/workflows/` | +| `prek` | pre-commit | `prek run --all-files` | +| `trash` | rm | `trash file` — **never use `rm -rf`** | + +Prefer `ast-grep` over ripgrep for code structure. Use ripgrep for literal strings. ## Shell & CI ### Shell Scripts -- All bash scripts must start with `set -euo pipefail` -- Lint with `shellcheck` and format with `shfmt` before committing +- All bash scripts: `set -euo pipefail` +- Lint with `shellcheck`, format with `shfmt` ### GitHub Actions -- Pin actions to SHA hashes with version comments: `actions/checkout@ # vX.Y.Z` -- Use `persist-credentials: false` on checkout actions -- Scan workflows with `actionlint` and `zizmor` before committing +- Pin actions to SHA hashes: `actions/checkout@ # vX.Y.Z` +- `persist-credentials: false` on checkout +- Scan with `actionlint` and `zizmor` ### GitHub API -- NEVER use the `mcp__github__create_or_update_file` tool (or the GitHub Contents API) to create/update files. It creates unsigned commits server-side, bypassing local git signing. Always commit and push from the local machine instead. +- NEVER use `mcp__github__create_or_update_file` — it creates unsigned commits. Always commit locally. ### Worktrees (Plain Git Repos) -When NOT on a `gitbutler/workspace` branch and the task involves code changes: -- Before editing files in any git repo, create a worktree: `wt switch -c ` -- Use `wt` (worktrunk) commands, not raw `git worktree` commands -- One worktree per repo per task — reuse it for subsequent edits in the same repo -- Parallel subagents require worktrees — each subagent MUST work in its own worktree -- List worktrees: `wt list` -- Clean up is the user's responsibility (via `wt remove`) +When NOT on `gitbutler/workspace` and the task involves code changes: +- Create a worktree first: `wt switch -c ` +- Use `wt` commands, not raw `git worktree` +- One worktree per repo per task +- Parallel subagents require separate worktrees +- Clean up after PR: `wt remove ` ### prek (Git Hooks) -Install prek in every repo that has a `.pre-commit-config.yaml`: -- `prek install` — installs git hooks -- `prek run` — run hooks before committing -- Configure auto-updates: `prek auto-update --cooldown-days 7` +For repos with `.pre-commit-config.yaml`: +- `prek install` / `prek run` / `prek auto-update --cooldown-days 7` diff --git a/dot_claude/agents/architect.md b/dot_claude/agents/architect.md index c499e3e..d7ea914 100644 --- a/dot_claude/agents/architect.md +++ b/dot_claude/agents/architect.md @@ -183,29 +183,4 @@ Watch for these architectural anti-patterns: - **Tight Coupling**: Components too dependent - **God Object**: One class/component does everything -## Project-Specific Architecture (Example) - -Example architecture for an AI-powered SaaS platform: - -### Current Architecture -- **Frontend**: Next.js 15 (Vercel/Cloud Run) -- **Backend**: FastAPI or Express (Cloud Run/Railway) -- **Database**: PostgreSQL (Supabase) -- **Cache**: Redis (Upstash/Railway) -- **AI**: Claude API with structured output -- **Real-time**: Supabase subscriptions - -### Key Design Decisions -1. **Hybrid Deployment**: Vercel (frontend) + Cloud Run (backend) for optimal performance -2. **AI Integration**: Structured output with Pydantic/Zod for type safety -3. **Real-time Updates**: Supabase subscriptions for live data -4. **Immutable Patterns**: Spread operators for predictable state -5. **Many Small Files**: High cohesion, low coupling - -### Scalability Plan -- **10K users**: Current architecture sufficient -- **100K users**: Add Redis clustering, CDN for static assets -- **1M users**: Microservices architecture, separate read/write databases -- **10M users**: Event-driven architecture, distributed caching, multi-region - **Remember**: Good architecture enables rapid development, easy maintenance, and confident scaling. The best architecture is simple, clear, and follows established patterns. diff --git a/dot_claude/agents/code-reviewer.md b/dot_claude/agents/code-reviewer.md index dec0e06..357079e 100644 --- a/dot_claude/agents/code-reviewer.md +++ b/dot_claude/agents/code-reviewer.md @@ -31,37 +31,11 @@ When invoked: ### Security (CRITICAL) -These MUST be flagged — they can cause real damage: - -- **Hardcoded credentials** — API keys, passwords, tokens, connection strings in source -- **SQL injection** — String concatenation in queries instead of parameterized queries -- **XSS vulnerabilities** — Unescaped user input rendered in HTML/JSX -- **Path traversal** — User-controlled file paths without sanitization -- **CSRF vulnerabilities** — State-changing endpoints without CSRF protection -- **Authentication bypasses** — Missing auth checks on protected routes -- **Insecure dependencies** — Known vulnerable packages -- **Exposed secrets in logs** — Logging sensitive data (tokens, passwords, PII) - -```typescript -// BAD: SQL injection via string concatenation -const query = `SELECT * FROM users WHERE id = ${userId}`; - -// GOOD: Parameterized query -const query = `SELECT * FROM users WHERE id = $1`; -const result = await db.query(query, [userId]); -``` - -```typescript -// BAD: Rendering raw user HTML without sanitization -// Always sanitize user content with DOMPurify.sanitize() or equivalent - -// GOOD: Use text content or sanitize -
{userComment}
-``` +Flag hardcoded credentials, SQL injection, XSS, path traversal, CSRF, auth bypasses, insecure dependencies, and secrets in logs. For detailed security review, delegate to the `security-reviewer` agent. ### Code Quality (HIGH) -- **Large functions** (>50 lines) — Split into smaller, focused functions +- **Large functions** (>100 lines) — Split into smaller, focused functions - **Large files** (>800 lines) — Extract modules by responsibility - **Deep nesting** (>4 levels) — Use early returns, extract helpers - **Missing error handling** — Unhandled promise rejections, empty catch blocks diff --git a/dot_claude/agents/go-reviewer.md b/dot_claude/agents/go-reviewer.md index 1e994c9..e294307 100644 --- a/dot_claude/agents/go-reviewer.md +++ b/dot_claude/agents/go-reviewer.md @@ -37,7 +37,7 @@ When invoked: - **Mutex misuse**: Not using `defer mu.Unlock()` ### HIGH -- Code Quality -- **Large functions**: Over 50 lines +- **Large functions**: Over 100 lines - **Deep nesting**: More than 4 levels - **Non-idiomatic**: `if/else` instead of early return - **Package-level variables**: Mutable global state diff --git a/dot_claude/agents/planner.md b/dot_claude/agents/planner.md index 4150bd6..68cb3d1 100644 --- a/dot_claude/agents/planner.md +++ b/dot_claude/agents/planner.md @@ -98,85 +98,6 @@ Create detailed steps with: 6. **Think Incrementally**: Each step should be verifiable 7. **Document Decisions**: Explain why, not just what -## Worked Example: Adding Stripe Subscriptions - -Here is a complete plan showing the level of detail expected: - -```markdown -# Implementation Plan: Stripe Subscription Billing - -## Overview -Add subscription billing with free/pro/enterprise tiers. Users upgrade via -Stripe Checkout, and webhook events keep subscription status in sync. - -## Requirements -- Three tiers: Free (default), Pro ($29/mo), Enterprise ($99/mo) -- Stripe Checkout for payment flow -- Webhook handler for subscription lifecycle events -- Feature gating based on subscription tier - -## Architecture Changes -- New table: `subscriptions` (user_id, stripe_customer_id, stripe_subscription_id, status, tier) -- New API route: `app/api/checkout/route.ts` — creates Stripe Checkout session -- New API route: `app/api/webhooks/stripe/route.ts` — handles Stripe events -- New middleware: check subscription tier for gated features -- New component: `PricingTable` — displays tiers with upgrade buttons - -## Implementation Steps - -### Phase 1: Database & Backend (2 files) -1. **Create subscription migration** (File: supabase/migrations/004_subscriptions.sql) - - Action: CREATE TABLE subscriptions with RLS policies - - Why: Store billing state server-side, never trust client - - Dependencies: None - - Risk: Low - -2. **Create Stripe webhook handler** (File: src/app/api/webhooks/stripe/route.ts) - - Action: Handle checkout.session.completed, customer.subscription.updated, - customer.subscription.deleted events - - Why: Keep subscription status in sync with Stripe - - Dependencies: Step 1 (needs subscriptions table) - - Risk: High — webhook signature verification is critical - -### Phase 2: Checkout Flow (2 files) -3. **Create checkout API route** (File: src/app/api/checkout/route.ts) - - Action: Create Stripe Checkout session with price_id and success/cancel URLs - - Why: Server-side session creation prevents price tampering - - Dependencies: Step 1 - - Risk: Medium — must validate user is authenticated - -4. **Build pricing page** (File: src/components/PricingTable.tsx) - - Action: Display three tiers with feature comparison and upgrade buttons - - Why: User-facing upgrade flow - - Dependencies: Step 3 - - Risk: Low - -### Phase 3: Feature Gating (1 file) -5. **Add tier-based middleware** (File: src/middleware.ts) - - Action: Check subscription tier on protected routes, redirect free users - - Why: Enforce tier limits server-side - - Dependencies: Steps 1-2 (needs subscription data) - - Risk: Medium — must handle edge cases (expired, past_due) - -## Testing Strategy -- Unit tests: Webhook event parsing, tier checking logic -- Integration tests: Checkout session creation, webhook processing -- E2E tests: Full upgrade flow (Stripe test mode) - -## Risks & Mitigations -- **Risk**: Webhook events arrive out of order - - Mitigation: Use event timestamps, idempotent updates -- **Risk**: User upgrades but webhook fails - - Mitigation: Poll Stripe as fallback, show "processing" state - -## Success Criteria -- [ ] User can upgrade from Free to Pro via Stripe Checkout -- [ ] Webhook correctly syncs subscription status -- [ ] Free users cannot access Pro features -- [ ] Downgrade/cancellation works correctly -- [ ] All tests pass with 80%+ coverage -``` - ## When Planning Refactors 1. Identify code smells and technical debt @@ -198,7 +119,7 @@ Each phase should be mergeable independently. Avoid plans that require all phase ## Red Flags to Check -- Large functions (>50 lines) +- Large functions (>100 lines) - Deep nesting (>4 levels) - Duplicated code - Missing error handling diff --git a/dot_claude/agents/python-reviewer.md b/dot_claude/agents/python-reviewer.md index 98e250d..20b5636 100644 --- a/dot_claude/agents/python-reviewer.md +++ b/dot_claude/agents/python-reviewer.md @@ -40,7 +40,7 @@ When invoked: - **Mutable default arguments**: `def f(x=[])` — use `def f(x=None)` ### HIGH — Code Quality -- Functions > 50 lines, > 5 parameters (use dataclass) +- Functions > 100 lines, > 5 parameters (use dataclass) - Deep nesting (> 4 levels) - Duplicate code patterns - Magic numbers without named constants diff --git a/dot_claude/agents/security-reviewer.md b/dot_claude/agents/security-reviewer.md index 6486afd..0b12ea5 100644 --- a/dot_claude/agents/security-reviewer.md +++ b/dot_claude/agents/security-reviewer.md @@ -99,10 +99,6 @@ If you find a CRITICAL vulnerability: - Dependencies up to date - Security checklist complete -## Reference - -For detailed vulnerability patterns, code examples, report templates, and PR review templates, see skill: `security-review`. - --- **Remember**: Security is not optional. One vulnerability can cost users real financial losses. Be thorough, be paranoid, be proactive. diff --git a/dot_claude/agents/tdd-guide.md b/dot_claude/agents/tdd-guide.md index bea2dd2..94d036d 100644 --- a/dot_claude/agents/tdd-guide.md +++ b/dot_claude/agents/tdd-guide.md @@ -77,4 +77,4 @@ npm run test:coverage - [ ] Assertions are specific and meaningful - [ ] Coverage is 80%+ -For detailed mocking patterns and framework-specific examples, see `skill: tdd-workflow`. +For Go-specific testing patterns, see `skill: golang-testing`. diff --git a/dot_claude/rules/README.md b/dot_claude/rules/README.md index 57de9d3..fd367b0 100644 --- a/dot_claude/rules/README.md +++ b/dot_claude/rules/README.md @@ -2,81 +2,22 @@ ## Structure -Rules are organized into a **common** layer plus **language-specific** directories: - ``` rules/ -├── common/ # Language-agnostic principles (always install) -│ ├── coding-style.md -│ ├── git-workflow.md -│ ├── testing.md -│ ├── performance.md -│ ├── patterns.md -│ ├── hooks.md -│ ├── agents.md -│ └── security.md +├── common/ # Language-agnostic (git workflow) +│ └── git-workflow.md ├── typescript/ # TypeScript/JavaScript specific -├── python/ # Python specific +│ ├── coding-style.md +│ └── patterns.md └── golang/ # Go specific + ├── coding-style.md + ├── testing.md + └── patterns.md ``` -- **common/** contains universal principles — no language-specific code examples. -- **Language directories** extend the common rules with framework-specific patterns, tools, and code examples. Each file references its common counterpart. - -## Installation - -### Option 1: Install Script (Recommended) - -```bash -# Install common + one or more language-specific rule sets -./install.sh typescript -./install.sh python -./install.sh golang - -# Install multiple languages at once -./install.sh typescript python -``` - -### Option 2: Manual Installation - -> **Important:** Copy entire directories — do NOT flatten with `/*`. -> Common and language-specific directories contain files with the same names. -> Flattening them into one directory causes language-specific files to overwrite -> common rules, and breaks the relative `../common/` references used by -> language-specific files. - -```bash -# Install common rules (required for all projects) -cp -r rules/common ~/.claude/rules/common - -# Install language-specific rules based on your project's tech stack -cp -r rules/typescript ~/.claude/rules/typescript -cp -r rules/python ~/.claude/rules/python -cp -r rules/golang ~/.claude/rules/golang - -# Attention ! ! ! Configure according to your actual project requirements; the configuration here is for reference only. -``` - -## Rules vs Skills - -- **Rules** define standards, conventions, and checklists that apply broadly (e.g., "80% test coverage", "no hardcoded secrets"). -- **Skills** (`skills/` directory) provide deep, actionable reference material for specific tasks (e.g., `python-patterns`, `golang-testing`). - -Language-specific rule files reference relevant skills where appropriate. Rules tell you *what* to do; skills tell you *how* to do it. - -## Adding a New Language - -To add support for a new language (e.g., `rust/`): +- **common/** contains workflow rules that apply across all languages. +- **Language directories** contain language-specific coding style, patterns, and testing rules. +- **Agents** (`agents/` directory) handle review and enforcement (code-reviewer, security-reviewer, etc.). +- **Skills** (`skills/` directory) provide deep reference material for specific tasks (golang-patterns, postgres-patterns, etc.). -1. Create a `rules/rust/` directory -2. Add files that extend the common rules: - - `coding-style.md` — formatting tools, idioms, error handling patterns - - `testing.md` — test framework, coverage tools, test organization - - `patterns.md` — language-specific design patterns - - `hooks.md` — PostToolUse hooks for formatters, linters, type checkers - - `security.md` — secret management, security scanning tools -3. Each file should start with: - ``` - > This file extends [common/xxx.md](../common/xxx.md) with specific content. - ``` -4. Reference existing skills if available, or create new ones under `skills/`. +Rules tell you *what* to do; skills tell you *how* to do it; agents enforce both. diff --git a/dot_claude/rules/common/agents.md b/dot_claude/rules/common/agents.md deleted file mode 100644 index e284331..0000000 --- a/dot_claude/rules/common/agents.md +++ /dev/null @@ -1,49 +0,0 @@ -# Agent Orchestration - -## Available Agents - -Located in `~/.claude/agents/`: - -| Agent | Purpose | When to Use | -|-------|---------|-------------| -| planner | Implementation planning | Complex features, refactoring | -| architect | System design | Architectural decisions | -| tdd-guide | Test-driven development | New features, bug fixes | -| code-reviewer | Code review | After writing code | -| security-reviewer | Security analysis | Before commits | -| build-error-resolver | Fix build errors | When build fails | -| e2e-runner | E2E testing | Critical user flows | -| refactor-cleaner | Dead code cleanup | Code maintenance | -| doc-updater | Documentation | Updating docs | - -## Immediate Agent Usage - -No user prompt needed: -1. Complex feature requests - Use **planner** agent -2. Code just written/modified - Use **code-reviewer** agent -3. Bug fix or new feature - Use **tdd-guide** agent -4. Architectural decision - Use **architect** agent - -## Parallel Task Execution - -ALWAYS use parallel Task execution for independent operations: - -```markdown -# GOOD: Parallel execution -Launch 3 agents in parallel: -1. Agent 1: Security analysis of auth module -2. Agent 2: Performance review of cache system -3. Agent 3: Type checking of utilities - -# BAD: Sequential when unnecessary -First agent 1, then agent 2, then agent 3 -``` - -## Multi-Perspective Analysis - -For complex problems, use split role sub-agents: -- Factual reviewer -- Senior engineer -- Security expert -- Consistency reviewer -- Redundancy checker diff --git a/dot_claude/rules/common/coding-style.md b/dot_claude/rules/common/coding-style.md deleted file mode 100644 index 2ee4fde..0000000 --- a/dot_claude/rules/common/coding-style.md +++ /dev/null @@ -1,48 +0,0 @@ -# Coding Style - -## Immutability (CRITICAL) - -ALWAYS create new objects, NEVER mutate existing ones: - -``` -// Pseudocode -WRONG: modify(original, field, value) → changes original in-place -CORRECT: update(original, field, value) → returns new copy with change -``` - -Rationale: Immutable data prevents hidden side effects, makes debugging easier, and enables safe concurrency. - -## File Organization - -MANY SMALL FILES > FEW LARGE FILES: -- High cohesion, low coupling -- 200-400 lines typical, 800 max -- Extract utilities from large modules -- Organize by feature/domain, not by type - -## Error Handling - -ALWAYS handle errors comprehensively: -- Handle errors explicitly at every level -- Provide user-friendly error messages in UI-facing code -- Log detailed error context on the server side -- Never silently swallow errors - -## Input Validation - -ALWAYS validate at system boundaries: -- Validate all user input before processing -- Use schema-based validation where available -- Fail fast with clear error messages -- Never trust external data (API responses, user input, file content) - -## Code Quality Checklist - -Before marking work complete: -- [ ] Code is readable and well-named -- [ ] Functions are small (<50 lines) -- [ ] Files are focused (<800 lines) -- [ ] No deep nesting (>4 levels) -- [ ] Proper error handling -- [ ] No hardcoded values (use constants or config) -- [ ] No mutation (immutable patterns used) diff --git a/dot_claude/rules/common/git-workflow.md b/dot_claude/rules/common/git-workflow.md index 81251b3..2c7fbfe 100644 --- a/dot_claude/rules/common/git-workflow.md +++ b/dot_claude/rules/common/git-workflow.md @@ -10,8 +10,6 @@ Types: feat, fix, refactor, docs, test, chore, perf, ci -Note: Attribution disabled globally via ~/.claude/settings.json. - ## Pull Request Workflow When creating PRs: @@ -23,25 +21,14 @@ When creating PRs: ## Feature Implementation Workflow -1. **Plan First** - - Use **planner** agent to create implementation plan +1. **Plan First** (for non-trivial features) + - Use **planner** agent for complex features - Identify dependencies and risks - Break down into phases -2. **TDD Approach** - - Use **tdd-guide** agent - - Write tests first (RED) - - Implement to pass tests (GREEN) - - Refactor (IMPROVE) - - Verify 80%+ coverage - -3. **Code Review** - - Use **code-reviewer** agent immediately after writing code - - Address CRITICAL and HIGH issues - - Fix MEDIUM issues when possible - -4. **Commit & Push** - - Detailed commit messages +2. **Implement** + - Bias toward action for straightforward work + - Use **tdd-guide** agent when the user requests TDD or the feature has complex edge cases - Follow conventional commits format ## GitButler Workflow (when on gitbutler/workspace branch) diff --git a/dot_claude/rules/common/hooks.md b/dot_claude/rules/common/hooks.md deleted file mode 100644 index 5439408..0000000 --- a/dot_claude/rules/common/hooks.md +++ /dev/null @@ -1,30 +0,0 @@ -# Hooks System - -## Hook Types - -- **PreToolUse**: Before tool execution (validation, parameter modification) -- **PostToolUse**: After tool execution (auto-format, checks) -- **Stop**: When session ends (final verification) - -## Auto-Accept Permissions - -Use with caution: -- Enable for trusted, well-defined plans -- Disable for exploratory work -- Never use dangerously-skip-permissions flag -- Configure `allowedTools` in `~/.claude.json` instead - -## TodoWrite Best Practices - -Use TodoWrite tool to: -- Track progress on multi-step tasks -- Verify understanding of instructions -- Enable real-time steering -- Show granular implementation steps - -Todo list reveals: -- Out of order steps -- Missing items -- Extra unnecessary items -- Wrong granularity -- Misinterpreted requirements diff --git a/dot_claude/rules/common/patterns.md b/dot_claude/rules/common/patterns.md deleted file mode 100644 index 959939f..0000000 --- a/dot_claude/rules/common/patterns.md +++ /dev/null @@ -1,31 +0,0 @@ -# Common Patterns - -## Skeleton Projects - -When implementing new functionality: -1. Search for battle-tested skeleton projects -2. Use parallel agents to evaluate options: - - Security assessment - - Extensibility analysis - - Relevance scoring - - Implementation planning -3. Clone best match as foundation -4. Iterate within proven structure - -## Design Patterns - -### Repository Pattern - -Encapsulate data access behind a consistent interface: -- Define standard operations: findAll, findById, create, update, delete -- Concrete implementations handle storage details (database, API, file, etc.) -- Business logic depends on the abstract interface, not the storage mechanism -- Enables easy swapping of data sources and simplifies testing with mocks - -### API Response Format - -Use a consistent envelope for all API responses: -- Include a success/status indicator -- Include the data payload (nullable on error) -- Include an error message field (nullable on success) -- Include metadata for paginated responses (total, page, limit) diff --git a/dot_claude/rules/common/performance.md b/dot_claude/rules/common/performance.md deleted file mode 100644 index 8d9bfd5..0000000 --- a/dot_claude/rules/common/performance.md +++ /dev/null @@ -1,55 +0,0 @@ -# Performance Optimization - -## Model Selection Strategy - -**Haiku 4.5** (90% of Sonnet capability, 3x cost savings): -- Lightweight agents with frequent invocation -- Pair programming and code generation -- Worker agents in multi-agent systems - -**Sonnet 4.6** (Best coding model): -- Main development work -- Orchestrating multi-agent workflows -- Complex coding tasks - -**Opus 4.6** (Deepest reasoning): -- Complex architectural decisions -- Maximum reasoning requirements -- Research and analysis tasks - -## Context Window Management - -Avoid last 20% of context window for: -- Large-scale refactoring -- Feature implementation spanning multiple files -- Debugging complex interactions - -Lower context sensitivity tasks: -- Single-file edits -- Independent utility creation -- Documentation updates -- Simple bug fixes - -## Extended Thinking + Plan Mode - -Extended thinking is enabled by default, reserving up to 31,999 tokens for internal reasoning. - -Control extended thinking via: -- **Toggle**: Option+T (macOS) / Alt+T (Windows/Linux) -- **Config**: Set `alwaysThinkingEnabled` in `~/.claude/settings.json` -- **Budget cap**: `export MAX_THINKING_TOKENS=10000` -- **Verbose mode**: Ctrl+O to see thinking output - -For complex tasks requiring deep reasoning: -1. Ensure extended thinking is enabled (on by default) -2. Enable **Plan Mode** for structured approach -3. Use multiple critique rounds for thorough analysis -4. Use split role sub-agents for diverse perspectives - -## Build Troubleshooting - -If build fails: -1. Use **build-error-resolver** agent -2. Analyze error messages -3. Fix incrementally -4. Verify after each fix diff --git a/dot_claude/rules/common/security.md b/dot_claude/rules/common/security.md deleted file mode 100644 index 49624c0..0000000 --- a/dot_claude/rules/common/security.md +++ /dev/null @@ -1,29 +0,0 @@ -# Security Guidelines - -## Mandatory Security Checks - -Before ANY commit: -- [ ] No hardcoded secrets (API keys, passwords, tokens) -- [ ] All user inputs validated -- [ ] SQL injection prevention (parameterized queries) -- [ ] XSS prevention (sanitized HTML) -- [ ] CSRF protection enabled -- [ ] Authentication/authorization verified -- [ ] Rate limiting on all endpoints -- [ ] Error messages don't leak sensitive data - -## Secret Management - -- NEVER hardcode secrets in source code -- ALWAYS use environment variables or a secret manager -- Validate that required secrets are present at startup -- Rotate any secrets that may have been exposed - -## Security Response Protocol - -If security issue found: -1. STOP immediately -2. Use **security-reviewer** agent -3. Fix CRITICAL issues before continuing -4. Rotate any exposed secrets -5. Review entire codebase for similar issues diff --git a/dot_claude/rules/common/testing.md b/dot_claude/rules/common/testing.md deleted file mode 100644 index fdcd949..0000000 --- a/dot_claude/rules/common/testing.md +++ /dev/null @@ -1,29 +0,0 @@ -# Testing Requirements - -## Minimum Test Coverage: 80% - -Test Types (ALL required): -1. **Unit Tests** - Individual functions, utilities, components -2. **Integration Tests** - API endpoints, database operations -3. **E2E Tests** - Critical user flows (framework chosen per language) - -## Test-Driven Development - -MANDATORY workflow: -1. Write test first (RED) -2. Run test - it should FAIL -3. Write minimal implementation (GREEN) -4. Run test - it should PASS -5. Refactor (IMPROVE) -6. Verify coverage (80%+) - -## Troubleshooting Test Failures - -1. Use **tdd-guide** agent -2. Check test isolation -3. Verify mocks are correct -4. Fix implementation, not tests (unless tests are wrong) - -## Agent Support - -- **tdd-guide** - Use PROACTIVELY for new features, enforces write-tests-first diff --git a/dot_claude/rules/golang/coding-style.md b/dot_claude/rules/golang/coding-style.md index 20bd449..23d2a93 100644 --- a/dot_claude/rules/golang/coding-style.md +++ b/dot_claude/rules/golang/coding-style.md @@ -6,7 +6,6 @@ paths: --- # Go Coding Style -> This file extends [common/coding-style.md](../common/coding-style.md) with Go specific content. ## Formatting diff --git a/dot_claude/rules/golang/hooks.md b/dot_claude/rules/golang/hooks.md deleted file mode 100644 index 71f888e..0000000 --- a/dot_claude/rules/golang/hooks.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -paths: - - "**/*.go" - - "**/go.mod" - - "**/go.sum" ---- -# Go Hooks - -> This file extends [common/hooks.md](../common/hooks.md) with Go specific content. - -## PostToolUse Hooks - -Configure in `~/.claude/settings.json`: - -- **gofumpt/goimports**: Auto-format `.go` files after edit -- **go vet**: Run static analysis after editing `.go` files -- **staticcheck**: Run extended static checks on modified packages diff --git a/dot_claude/rules/golang/patterns.md b/dot_claude/rules/golang/patterns.md index 282d8f9..93dff2c 100644 --- a/dot_claude/rules/golang/patterns.md +++ b/dot_claude/rules/golang/patterns.md @@ -6,7 +6,6 @@ paths: --- # Go Patterns -> This file extends [common/patterns.md](../common/patterns.md) with Go specific content. ## Functional Options diff --git a/dot_claude/rules/golang/security.md b/dot_claude/rules/golang/security.md deleted file mode 100644 index 372b754..0000000 --- a/dot_claude/rules/golang/security.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -paths: - - "**/*.go" - - "**/go.mod" - - "**/go.sum" ---- -# Go Security - -> This file extends [common/security.md](../common/security.md) with Go specific content. - -## Secret Management - -```go -apiKey := os.Getenv("OPENAI_API_KEY") -if apiKey == "" { - log.Fatal("OPENAI_API_KEY not configured") -} -``` - -## Security Scanning - -- Use **gosec** for static security analysis: - ```bash - gosec ./... - ``` - -## Context & Timeouts - -Always use `context.Context` for timeout control: - -```go -ctx, cancel := context.WithTimeout(ctx, 5*time.Second) -defer cancel() -``` diff --git a/dot_claude/rules/golang/testing.md b/dot_claude/rules/golang/testing.md index a834b31..7806f2e 100644 --- a/dot_claude/rules/golang/testing.md +++ b/dot_claude/rules/golang/testing.md @@ -6,7 +6,6 @@ paths: --- # Go Testing -> This file extends [common/testing.md](../common/testing.md) with Go specific content. ## Framework diff --git a/dot_claude/rules/typescript/coding-style.md b/dot_claude/rules/typescript/coding-style.md index db62a9b..56f4b42 100644 --- a/dot_claude/rules/typescript/coding-style.md +++ b/dot_claude/rules/typescript/coding-style.md @@ -7,7 +7,6 @@ paths: --- # TypeScript/JavaScript Coding Style -> This file extends [common/coding-style.md](../common/coding-style.md) with TypeScript/JavaScript specific content. ## Immutability diff --git a/dot_claude/rules/typescript/hooks.md b/dot_claude/rules/typescript/hooks.md deleted file mode 100644 index cd4754b..0000000 --- a/dot_claude/rules/typescript/hooks.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -paths: - - "**/*.ts" - - "**/*.tsx" - - "**/*.js" - - "**/*.jsx" ---- -# TypeScript/JavaScript Hooks - -> This file extends [common/hooks.md](../common/hooks.md) with TypeScript/JavaScript specific content. - -## PostToolUse Hooks - -Configure in `~/.claude/settings.json`: - -- **Prettier**: Auto-format JS/TS files after edit -- **TypeScript check**: Run `tsc` after editing `.ts`/`.tsx` files -- **console.log warning**: Warn about `console.log` in edited files - -## Stop Hooks - -- **console.log audit**: Check all modified files for `console.log` before session ends diff --git a/dot_claude/rules/typescript/patterns.md b/dot_claude/rules/typescript/patterns.md index d50729d..81147e9 100644 --- a/dot_claude/rules/typescript/patterns.md +++ b/dot_claude/rules/typescript/patterns.md @@ -7,7 +7,6 @@ paths: --- # TypeScript/JavaScript Patterns -> This file extends [common/patterns.md](../common/patterns.md) with TypeScript/JavaScript specific content. ## API Response Format diff --git a/dot_claude/rules/typescript/security.md b/dot_claude/rules/typescript/security.md deleted file mode 100644 index 98ba400..0000000 --- a/dot_claude/rules/typescript/security.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -paths: - - "**/*.ts" - - "**/*.tsx" - - "**/*.js" - - "**/*.jsx" ---- -# TypeScript/JavaScript Security - -> This file extends [common/security.md](../common/security.md) with TypeScript/JavaScript specific content. - -## Secret Management - -```typescript -// NEVER: Hardcoded secrets -const apiKey = "sk-proj-xxxxx" - -// ALWAYS: Environment variables -const apiKey = process.env.OPENAI_API_KEY - -if (!apiKey) { - throw new Error('OPENAI_API_KEY not configured') -} -``` - -## Agent Support - -- Use **security-reviewer** skill for comprehensive security audits diff --git a/dot_claude/rules/typescript/testing.md b/dot_claude/rules/typescript/testing.md deleted file mode 100644 index 6f2f402..0000000 --- a/dot_claude/rules/typescript/testing.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -paths: - - "**/*.ts" - - "**/*.tsx" - - "**/*.js" - - "**/*.jsx" ---- -# TypeScript/JavaScript Testing - -> This file extends [common/testing.md](../common/testing.md) with TypeScript/JavaScript specific content. - -## E2E Testing - -Use **Playwright** as the E2E testing framework for critical user flows. - -## Agent Support - -- **e2e-runner** - Playwright E2E testing specialist diff --git a/dot_claude/settings.json b/dot_claude/settings.json index ae05e9a..b173497 100644 --- a/dot_claude/settings.json +++ b/dot_claude/settings.json @@ -1,4 +1,8 @@ { + "attribution": { + "commit": "", + "pr": "" + }, "cleanupPeriodDays": 365, "env": { "DISABLE_ERROR_REPORTING": "1", @@ -6,7 +10,9 @@ "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" }, "permissions": { - "allow": [], + "allow": [ + "Bash(*)" + ], "deny": [ "Bash(rm -rf *)", "Bash(rm -fr *)", @@ -147,7 +153,17 @@ "alwaysThinkingEnabled": true, "skipDangerousModePermissionPrompt": true, "enabledPlugins": { - "worktrunk@worktrunk": true + "worktrunk@worktrunk": true, + "terraform-skill@antonbabenko": true, + "frontend-design@claude-plugins-official": true, + "code-review@claude-plugins-official": true, + "claude-md-management@claude-plugins-official": true, + "modern-go-guidelines@goland-claude-marketplace": true, + "mgrep@Mixedbread-Grep": true, + "hookify@claude-plugins-official": true, + "security-guidance@claude-plugins-official": true, + "context7@claude-plugins-official": false, + "deploy-on-aws@agent-plugins-for-aws": false }, "sandbox": { "filesystem": { diff --git a/dot_claude/skills/coding-standards/SKILL.md b/dot_claude/skills/coding-standards/SKILL.md deleted file mode 100644 index 992abee..0000000 --- a/dot_claude/skills/coding-standards/SKILL.md +++ /dev/null @@ -1,529 +0,0 @@ ---- -name: coding-standards -description: Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development. ---- - -# Coding Standards & Best Practices - -Universal coding standards applicable across all projects. - -## When to Activate - -- Starting a new project or module -- Reviewing code for quality and maintainability -- Refactoring existing code to follow conventions -- Enforcing naming, formatting, or structural consistency -- Setting up linting, formatting, or type-checking rules -- Onboarding new contributors to coding conventions - -## Code Quality Principles - -### 1. Readability First -- Code is read more than written -- Clear variable and function names -- Self-documenting code preferred over comments -- Consistent formatting - -### 2. KISS (Keep It Simple, Stupid) -- Simplest solution that works -- Avoid over-engineering -- No premature optimization -- Easy to understand > clever code - -### 3. DRY (Don't Repeat Yourself) -- Extract common logic into functions -- Create reusable components -- Share utilities across modules -- Avoid copy-paste programming - -### 4. YAGNI (You Aren't Gonna Need It) -- Don't build features before they're needed -- Avoid speculative generality -- Add complexity only when required -- Start simple, refactor when needed - -## TypeScript/JavaScript Standards - -### Variable Naming - -```typescript -// ✅ GOOD: Descriptive names -const marketSearchQuery = 'election' -const isUserAuthenticated = true -const totalRevenue = 1000 - -// ❌ BAD: Unclear names -const q = 'election' -const flag = true -const x = 1000 -``` - -### Function Naming - -```typescript -// ✅ GOOD: Verb-noun pattern -async function fetchMarketData(marketId: string) { } -function calculateSimilarity(a: number[], b: number[]) { } -function isValidEmail(email: string): boolean { } - -// ❌ BAD: Unclear or noun-only -async function market(id: string) { } -function similarity(a, b) { } -function email(e) { } -``` - -### Immutability Pattern (CRITICAL) - -```typescript -// ✅ ALWAYS use spread operator -const updatedUser = { - ...user, - name: 'New Name' -} - -const updatedArray = [...items, newItem] - -// ❌ NEVER mutate directly -user.name = 'New Name' // BAD -items.push(newItem) // BAD -``` - -### Error Handling - -```typescript -// ✅ GOOD: Comprehensive error handling -async function fetchData(url: string) { - try { - const response = await fetch(url) - - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${response.statusText}`) - } - - return await response.json() - } catch (error) { - console.error('Fetch failed:', error) - throw new Error('Failed to fetch data') - } -} - -// ❌ BAD: No error handling -async function fetchData(url) { - const response = await fetch(url) - return response.json() -} -``` - -### Async/Await Best Practices - -```typescript -// ✅ GOOD: Parallel execution when possible -const [users, markets, stats] = await Promise.all([ - fetchUsers(), - fetchMarkets(), - fetchStats() -]) - -// ❌ BAD: Sequential when unnecessary -const users = await fetchUsers() -const markets = await fetchMarkets() -const stats = await fetchStats() -``` - -### Type Safety - -```typescript -// ✅ GOOD: Proper types -interface Market { - id: string - name: string - status: 'active' | 'resolved' | 'closed' - created_at: Date -} - -function getMarket(id: string): Promise { - // Implementation -} - -// ❌ BAD: Using 'any' -function getMarket(id: any): Promise { - // Implementation -} -``` - -## React Best Practices - -### Component Structure - -```typescript -// ✅ GOOD: Functional component with types -interface ButtonProps { - children: React.ReactNode - onClick: () => void - disabled?: boolean - variant?: 'primary' | 'secondary' -} - -export function Button({ - children, - onClick, - disabled = false, - variant = 'primary' -}: ButtonProps) { - return ( - - ) -} - -// ❌ BAD: No types, unclear structure -export function Button(props) { - return -} -``` - -### Custom Hooks - -```typescript -// ✅ GOOD: Reusable custom hook -export function useDebounce(value: T, delay: number): T { - const [debouncedValue, setDebouncedValue] = useState(value) - - useEffect(() => { - const handler = setTimeout(() => { - setDebouncedValue(value) - }, delay) - - return () => clearTimeout(handler) - }, [value, delay]) - - return debouncedValue -} - -// Usage -const debouncedQuery = useDebounce(searchQuery, 500) -``` - -### State Management - -```typescript -// ✅ GOOD: Proper state updates -const [count, setCount] = useState(0) - -// Functional update for state based on previous state -setCount(prev => prev + 1) - -// ❌ BAD: Direct state reference -setCount(count + 1) // Can be stale in async scenarios -``` - -### Conditional Rendering - -```typescript -// ✅ GOOD: Clear conditional rendering -{isLoading && } -{error && } -{data && } - -// ❌ BAD: Ternary hell -{isLoading ? : error ? : data ? : null} -``` - -## API Design Standards - -### REST API Conventions - -``` -GET /api/markets # List all markets -GET /api/markets/:id # Get specific market -POST /api/markets # Create new market -PUT /api/markets/:id # Update market (full) -PATCH /api/markets/:id # Update market (partial) -DELETE /api/markets/:id # Delete market - -# Query parameters for filtering -GET /api/markets?status=active&limit=10&offset=0 -``` - -### Response Format - -```typescript -// ✅ GOOD: Consistent response structure -interface ApiResponse { - success: boolean - data?: T - error?: string - meta?: { - total: number - page: number - limit: number - } -} - -// Success response -return NextResponse.json({ - success: true, - data: markets, - meta: { total: 100, page: 1, limit: 10 } -}) - -// Error response -return NextResponse.json({ - success: false, - error: 'Invalid request' -}, { status: 400 }) -``` - -### Input Validation - -```typescript -import { z } from 'zod' - -// ✅ GOOD: Schema validation -const CreateMarketSchema = z.object({ - name: z.string().min(1).max(200), - description: z.string().min(1).max(2000), - endDate: z.string().datetime(), - categories: z.array(z.string()).min(1) -}) - -export async function POST(request: Request) { - const body = await request.json() - - try { - const validated = CreateMarketSchema.parse(body) - // Proceed with validated data - } catch (error) { - if (error instanceof z.ZodError) { - return NextResponse.json({ - success: false, - error: 'Validation failed', - details: error.errors - }, { status: 400 }) - } - } -} -``` - -## File Organization - -### Project Structure - -``` -src/ -├── app/ # Next.js App Router -│ ├── api/ # API routes -│ ├── markets/ # Market pages -│ └── (auth)/ # Auth pages (route groups) -├── components/ # React components -│ ├── ui/ # Generic UI components -│ ├── forms/ # Form components -│ └── layouts/ # Layout components -├── hooks/ # Custom React hooks -├── lib/ # Utilities and configs -│ ├── api/ # API clients -│ ├── utils/ # Helper functions -│ └── constants/ # Constants -├── types/ # TypeScript types -└── styles/ # Global styles -``` - -### File Naming - -``` -components/Button.tsx # PascalCase for components -hooks/useAuth.ts # camelCase with 'use' prefix -lib/formatDate.ts # camelCase for utilities -types/market.types.ts # camelCase with .types suffix -``` - -## Comments & Documentation - -### When to Comment - -```typescript -// ✅ GOOD: Explain WHY, not WHAT -// Use exponential backoff to avoid overwhelming the API during outages -const delay = Math.min(1000 * Math.pow(2, retryCount), 30000) - -// Deliberately using mutation here for performance with large arrays -items.push(newItem) - -// ❌ BAD: Stating the obvious -// Increment counter by 1 -count++ - -// Set name to user's name -name = user.name -``` - -### JSDoc for Public APIs - -```typescript -/** - * Searches markets using semantic similarity. - * - * @param query - Natural language search query - * @param limit - Maximum number of results (default: 10) - * @returns Array of markets sorted by similarity score - * @throws {Error} If OpenAI API fails or Redis unavailable - * - * @example - * ```typescript - * const results = await searchMarkets('election', 5) - * console.log(results[0].name) // "Trump vs Biden" - * ``` - */ -export async function searchMarkets( - query: string, - limit: number = 10 -): Promise { - // Implementation -} -``` - -## Performance Best Practices - -### Memoization - -```typescript -import { useMemo, useCallback } from 'react' - -// ✅ GOOD: Memoize expensive computations -const sortedMarkets = useMemo(() => { - return markets.sort((a, b) => b.volume - a.volume) -}, [markets]) - -// ✅ GOOD: Memoize callbacks -const handleSearch = useCallback((query: string) => { - setSearchQuery(query) -}, []) -``` - -### Lazy Loading - -```typescript -import { lazy, Suspense } from 'react' - -// ✅ GOOD: Lazy load heavy components -const HeavyChart = lazy(() => import('./HeavyChart')) - -export function Dashboard() { - return ( - }> - - - ) -} -``` - -### Database Queries - -```typescript -// ✅ GOOD: Select only needed columns -const { data } = await supabase - .from('markets') - .select('id, name, status') - .limit(10) - -// ❌ BAD: Select everything -const { data } = await supabase - .from('markets') - .select('*') -``` - -## Testing Standards - -### Test Structure (AAA Pattern) - -```typescript -test('calculates similarity correctly', () => { - // Arrange - const vector1 = [1, 0, 0] - const vector2 = [0, 1, 0] - - // Act - const similarity = calculateCosineSimilarity(vector1, vector2) - - // Assert - expect(similarity).toBe(0) -}) -``` - -### Test Naming - -```typescript -// ✅ GOOD: Descriptive test names -test('returns empty array when no markets match query', () => { }) -test('throws error when OpenAI API key is missing', () => { }) -test('falls back to substring search when Redis unavailable', () => { }) - -// ❌ BAD: Vague test names -test('works', () => { }) -test('test search', () => { }) -``` - -## Code Smell Detection - -Watch for these anti-patterns: - -### 1. Long Functions -```typescript -// ❌ BAD: Function > 50 lines -function processMarketData() { - // 100 lines of code -} - -// ✅ GOOD: Split into smaller functions -function processMarketData() { - const validated = validateData() - const transformed = transformData(validated) - return saveData(transformed) -} -``` - -### 2. Deep Nesting -```typescript -// ❌ BAD: 5+ levels of nesting -if (user) { - if (user.isAdmin) { - if (market) { - if (market.isActive) { - if (hasPermission) { - // Do something - } - } - } - } -} - -// ✅ GOOD: Early returns -if (!user) return -if (!user.isAdmin) return -if (!market) return -if (!market.isActive) return -if (!hasPermission) return - -// Do something -``` - -### 3. Magic Numbers -```typescript -// ❌ BAD: Unexplained numbers -if (retryCount > 3) { } -setTimeout(callback, 500) - -// ✅ GOOD: Named constants -const MAX_RETRIES = 3 -const DEBOUNCE_DELAY_MS = 500 - -if (retryCount > MAX_RETRIES) { } -setTimeout(callback, DEBOUNCE_DELAY_MS) -``` - -**Remember**: Code quality is not negotiable. Clear, maintainable code enables rapid development and confident refactoring. diff --git a/dot_claude/skills/continuous-learning/SKILL.md b/dot_claude/skills/continuous-learning/SKILL.md deleted file mode 100644 index af33eef..0000000 --- a/dot_claude/skills/continuous-learning/SKILL.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -name: continuous-learning -description: Automatically extract reusable patterns from Claude Code sessions and save them as learned skills for future use. ---- - -# Continuous Learning Skill - -Automatically evaluates Claude Code sessions on end to extract reusable patterns that can be saved as learned skills. - -## When to Activate - -- Setting up automatic pattern extraction from Claude Code sessions -- Configuring the Stop hook for session evaluation -- Reviewing or curating learned skills in `~/.claude/skills/learned/` -- Adjusting extraction thresholds or pattern categories -- Comparing v1 (this) vs v2 (instinct-based) approaches - -## How It Works - -This skill runs as a **Stop hook** at the end of each session: - -1. **Session Evaluation**: Checks if session has enough messages (default: 10+) -2. **Pattern Detection**: Identifies extractable patterns from the session -3. **Skill Extraction**: Saves useful patterns to `~/.claude/skills/learned/` - -## Configuration - -Edit `config.json` to customize: - -```json -{ - "min_session_length": 10, - "extraction_threshold": "medium", - "auto_approve": false, - "learned_skills_path": "~/.claude/skills/learned/", - "patterns_to_detect": [ - "error_resolution", - "user_corrections", - "workarounds", - "debugging_techniques", - "project_specific" - ], - "ignore_patterns": [ - "simple_typos", - "one_time_fixes", - "external_api_issues" - ] -} -``` - -## Pattern Types - -| Pattern | Description | -|---------|-------------| -| `error_resolution` | How specific errors were resolved | -| `user_corrections` | Patterns from user corrections | -| `workarounds` | Solutions to framework/library quirks | -| `debugging_techniques` | Effective debugging approaches | -| `project_specific` | Project-specific conventions | - -## Hook Setup - -Add to your `~/.claude/settings.json`: - -```json -{ - "hooks": { - "Stop": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "~/.claude/skills/continuous-learning/evaluate-session.sh" - }] - }] - } -} -``` - -## Why Stop Hook? - -- **Lightweight**: Runs once at session end -- **Non-blocking**: Doesn't add latency to every message -- **Complete context**: Has access to full session transcript - -## Related - -- [The Longform Guide](https://x.com/affaanmustafa/status/2014040193557471352) - Section on continuous learning -- `/learn` command - Manual pattern extraction mid-session - ---- - -## Comparison Notes (Research: Jan 2025) - -### vs Homunculus (github.com/humanplane/homunculus) - -Homunculus v2 takes a more sophisticated approach: - -| Feature | Our Approach | Homunculus v2 | -|---------|--------------|---------------| -| Observation | Stop hook (end of session) | PreToolUse/PostToolUse hooks (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 | - -**Key insight from homunculus:** -> "v1 relied on skills to observe. Skills are probabilistic—they fire ~50-80% of the time. v2 uses hooks for observation (100% reliable) and instincts as the atomic unit of learned behavior." - -### Potential v2 Enhancements - -1. **Instinct-based learning** - Smaller, atomic behaviors with confidence scoring -2. **Background observer** - Haiku agent analyzing in parallel -3. **Confidence decay** - Instincts lose confidence if contradicted -4. **Domain tagging** - code-style, testing, git, debugging, etc. -5. **Evolution path** - Cluster related instincts into skills/commands - -See: `/Users/affoon/Documents/tasks/12-continuous-learning-v2.md` for full spec. diff --git a/dot_claude/skills/continuous-learning/config.json b/dot_claude/skills/continuous-learning/config.json deleted file mode 100644 index 1094b7e..0000000 --- a/dot_claude/skills/continuous-learning/config.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "min_session_length": 10, - "extraction_threshold": "medium", - "auto_approve": false, - "learned_skills_path": "~/.claude/skills/learned/", - "patterns_to_detect": [ - "error_resolution", - "user_corrections", - "workarounds", - "debugging_techniques", - "project_specific" - ], - "ignore_patterns": [ - "simple_typos", - "one_time_fixes", - "external_api_issues" - ] -} diff --git a/dot_claude/skills/continuous-learning/evaluate-session.sh b/dot_claude/skills/continuous-learning/evaluate-session.sh deleted file mode 100755 index a5946fc..0000000 --- a/dot_claude/skills/continuous-learning/evaluate-session.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash -# Continuous Learning - Session Evaluator -# Runs on Stop hook to extract reusable patterns from Claude Code sessions -# -# Why Stop hook instead of UserPromptSubmit: -# - Stop runs once at session end (lightweight) -# - UserPromptSubmit runs every message (heavy, adds latency) -# -# Hook config (in ~/.claude/settings.json): -# { -# "hooks": { -# "Stop": [{ -# "matcher": "*", -# "hooks": [{ -# "type": "command", -# "command": "~/.claude/skills/continuous-learning/evaluate-session.sh" -# }] -# }] -# } -# } -# -# Patterns to detect: error_resolution, debugging_techniques, workarounds, project_specific -# Patterns to ignore: simple_typos, one_time_fixes, external_api_issues -# Extracted skills saved to: ~/.claude/skills/learned/ - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CONFIG_FILE="$SCRIPT_DIR/config.json" -LEARNED_SKILLS_PATH="${HOME}/.claude/skills/learned" -MIN_SESSION_LENGTH=10 - -# Load config if exists -if [ -f "$CONFIG_FILE" ]; then - if ! command -v jq &>/dev/null; then - echo "[ContinuousLearning] jq is required to parse config.json but not installed, using defaults" >&2 - else - MIN_SESSION_LENGTH=$(jq -r '.min_session_length // 10' "$CONFIG_FILE") - LEARNED_SKILLS_PATH=$(jq -r '.learned_skills_path // "~/.claude/skills/learned/"' "$CONFIG_FILE" | sed "s|~|$HOME|") - fi -fi - -# Ensure learned skills directory exists -mkdir -p "$LEARNED_SKILLS_PATH" - -# Get transcript path from stdin JSON (Claude Code hook input) -# Falls back to env var for backwards compatibility -stdin_data=$(cat) -transcript_path=$(echo "$stdin_data" | grep -o '"transcript_path":"[^"]*"' | head -1 | cut -d'"' -f4) -if [ -z "$transcript_path" ]; then - transcript_path="${CLAUDE_TRANSCRIPT_PATH:-}" -fi - -if [ -z "$transcript_path" ] || [ ! -f "$transcript_path" ]; then - exit 0 -fi - -# Count messages in session -message_count=$(grep -c '"type":"user"' "$transcript_path" 2>/dev/null || echo "0") - -# Skip short sessions -if [ "$message_count" -lt "$MIN_SESSION_LENGTH" ]; then - echo "[ContinuousLearning] Session too short ($message_count messages), skipping" >&2 - exit 0 -fi - -# Signal to Claude that session should be evaluated for extractable patterns -echo "[ContinuousLearning] Session has $message_count messages - evaluate for extractable patterns" >&2 -echo "[ContinuousLearning] Save learned skills to: $LEARNED_SKILLS_PATH" >&2 diff --git a/dot_claude/skills/security-review/SKILL.md b/dot_claude/skills/security-review/SKILL.md deleted file mode 100644 index 26cfaf6..0000000 --- a/dot_claude/skills/security-review/SKILL.md +++ /dev/null @@ -1,494 +0,0 @@ ---- -name: security-review -description: Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist and patterns. ---- - -# Security Review Skill - -This skill ensures all code follows security best practices and identifies potential vulnerabilities. - -## When to Activate - -- Implementing authentication or authorization -- Handling user input or file uploads -- Creating new API endpoints -- Working with secrets or credentials -- Implementing payment features -- Storing or transmitting sensitive data -- Integrating third-party APIs - -## Security Checklist - -### 1. Secrets Management - -#### ❌ NEVER Do This -```typescript -const apiKey = "sk-proj-xxxxx" // Hardcoded secret -const dbPassword = "password123" // In source code -``` - -#### ✅ ALWAYS Do This -```typescript -const apiKey = process.env.OPENAI_API_KEY -const dbUrl = process.env.DATABASE_URL - -// Verify secrets exist -if (!apiKey) { - throw new Error('OPENAI_API_KEY not configured') -} -``` - -#### Verification Steps -- [ ] No hardcoded API keys, tokens, or passwords -- [ ] All secrets in environment variables -- [ ] `.env.local` in .gitignore -- [ ] No secrets in git history -- [ ] Production secrets in hosting platform (Vercel, Railway) - -### 2. Input Validation - -#### Always Validate User Input -```typescript -import { z } from 'zod' - -// Define validation schema -const CreateUserSchema = z.object({ - email: z.string().email(), - name: z.string().min(1).max(100), - age: z.number().int().min(0).max(150) -}) - -// Validate before processing -export async function createUser(input: unknown) { - try { - const validated = CreateUserSchema.parse(input) - return await db.users.create(validated) - } catch (error) { - if (error instanceof z.ZodError) { - return { success: false, errors: error.errors } - } - throw error - } -} -``` - -#### File Upload Validation -```typescript -function validateFileUpload(file: File) { - // Size check (5MB max) - const maxSize = 5 * 1024 * 1024 - if (file.size > maxSize) { - throw new Error('File too large (max 5MB)') - } - - // Type check - const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'] - if (!allowedTypes.includes(file.type)) { - throw new Error('Invalid file type') - } - - // Extension check - const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif'] - const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0] - if (!extension || !allowedExtensions.includes(extension)) { - throw new Error('Invalid file extension') - } - - return true -} -``` - -#### Verification Steps -- [ ] All user inputs validated with schemas -- [ ] File uploads restricted (size, type, extension) -- [ ] No direct use of user input in queries -- [ ] Whitelist validation (not blacklist) -- [ ] Error messages don't leak sensitive info - -### 3. SQL Injection Prevention - -#### ❌ NEVER Concatenate SQL -```typescript -// DANGEROUS - SQL Injection vulnerability -const query = `SELECT * FROM users WHERE email = '${userEmail}'` -await db.query(query) -``` - -#### ✅ ALWAYS Use Parameterized Queries -```typescript -// Safe - parameterized query -const { data } = await supabase - .from('users') - .select('*') - .eq('email', userEmail) - -// Or with raw SQL -await db.query( - 'SELECT * FROM users WHERE email = $1', - [userEmail] -) -``` - -#### Verification Steps -- [ ] All database queries use parameterized queries -- [ ] No string concatenation in SQL -- [ ] ORM/query builder used correctly -- [ ] Supabase queries properly sanitized - -### 4. Authentication & Authorization - -#### JWT Token Handling -```typescript -// ❌ WRONG: localStorage (vulnerable to XSS) -localStorage.setItem('token', token) - -// ✅ CORRECT: httpOnly cookies -res.setHeader('Set-Cookie', - `token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`) -``` - -#### Authorization Checks -```typescript -export async function deleteUser(userId: string, requesterId: string) { - // ALWAYS verify authorization first - const requester = await db.users.findUnique({ - where: { id: requesterId } - }) - - if (requester.role !== 'admin') { - return NextResponse.json( - { error: 'Unauthorized' }, - { status: 403 } - ) - } - - // Proceed with deletion - await db.users.delete({ where: { id: userId } }) -} -``` - -#### Row Level Security (Supabase) -```sql --- Enable RLS on all tables -ALTER TABLE users ENABLE ROW LEVEL SECURITY; - --- Users can only view their own data -CREATE POLICY "Users view own data" - ON users FOR SELECT - USING (auth.uid() = id); - --- Users can only update their own data -CREATE POLICY "Users update own data" - ON users FOR UPDATE - USING (auth.uid() = id); -``` - -#### Verification Steps -- [ ] Tokens stored in httpOnly cookies (not localStorage) -- [ ] Authorization checks before sensitive operations -- [ ] Row Level Security enabled in Supabase -- [ ] Role-based access control implemented -- [ ] Session management secure - -### 5. XSS Prevention - -#### Sanitize HTML -```typescript -import DOMPurify from 'isomorphic-dompurify' - -// ALWAYS sanitize user-provided HTML -function renderUserContent(html: string) { - const clean = DOMPurify.sanitize(html, { - ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'], - ALLOWED_ATTR: [] - }) - return
-} -``` - -#### Content Security Policy -```typescript -// next.config.js -const securityHeaders = [ - { - key: 'Content-Security-Policy', - value: ` - default-src 'self'; - script-src 'self' 'unsafe-eval' 'unsafe-inline'; - style-src 'self' 'unsafe-inline'; - img-src 'self' data: https:; - font-src 'self'; - connect-src 'self' https://api.example.com; - `.replace(/\s{2,}/g, ' ').trim() - } -] -``` - -#### Verification Steps -- [ ] User-provided HTML sanitized -- [ ] CSP headers configured -- [ ] No unvalidated dynamic content rendering -- [ ] React's built-in XSS protection used - -### 6. CSRF Protection - -#### CSRF Tokens -```typescript -import { csrf } from '@/lib/csrf' - -export async function POST(request: Request) { - const token = request.headers.get('X-CSRF-Token') - - if (!csrf.verify(token)) { - return NextResponse.json( - { error: 'Invalid CSRF token' }, - { status: 403 } - ) - } - - // Process request -} -``` - -#### SameSite Cookies -```typescript -res.setHeader('Set-Cookie', - `session=${sessionId}; HttpOnly; Secure; SameSite=Strict`) -``` - -#### Verification Steps -- [ ] CSRF tokens on state-changing operations -- [ ] SameSite=Strict on all cookies -- [ ] Double-submit cookie pattern implemented - -### 7. Rate Limiting - -#### API Rate Limiting -```typescript -import rateLimit from 'express-rate-limit' - -const limiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100, // 100 requests per window - message: 'Too many requests' -}) - -// Apply to routes -app.use('/api/', limiter) -``` - -#### Expensive Operations -```typescript -// Aggressive rate limiting for searches -const searchLimiter = rateLimit({ - windowMs: 60 * 1000, // 1 minute - max: 10, // 10 requests per minute - message: 'Too many search requests' -}) - -app.use('/api/search', searchLimiter) -``` - -#### Verification Steps -- [ ] Rate limiting on all API endpoints -- [ ] Stricter limits on expensive operations -- [ ] IP-based rate limiting -- [ ] User-based rate limiting (authenticated) - -### 8. Sensitive Data Exposure - -#### Logging -```typescript -// ❌ WRONG: Logging sensitive data -console.log('User login:', { email, password }) -console.log('Payment:', { cardNumber, cvv }) - -// ✅ CORRECT: Redact sensitive data -console.log('User login:', { email, userId }) -console.log('Payment:', { last4: card.last4, userId }) -``` - -#### Error Messages -```typescript -// ❌ WRONG: Exposing internal details -catch (error) { - return NextResponse.json( - { error: error.message, stack: error.stack }, - { status: 500 } - ) -} - -// ✅ CORRECT: Generic error messages -catch (error) { - console.error('Internal error:', error) - return NextResponse.json( - { error: 'An error occurred. Please try again.' }, - { status: 500 } - ) -} -``` - -#### Verification Steps -- [ ] No passwords, tokens, or secrets in logs -- [ ] Error messages generic for users -- [ ] Detailed errors only in server logs -- [ ] No stack traces exposed to users - -### 9. Blockchain Security (Solana) - -#### Wallet Verification -```typescript -import { verify } from '@solana/web3.js' - -async function verifyWalletOwnership( - publicKey: string, - signature: string, - message: string -) { - try { - const isValid = verify( - Buffer.from(message), - Buffer.from(signature, 'base64'), - Buffer.from(publicKey, 'base64') - ) - return isValid - } catch (error) { - return false - } -} -``` - -#### Transaction Verification -```typescript -async function verifyTransaction(transaction: Transaction) { - // Verify recipient - if (transaction.to !== expectedRecipient) { - throw new Error('Invalid recipient') - } - - // Verify amount - if (transaction.amount > maxAmount) { - throw new Error('Amount exceeds limit') - } - - // Verify user has sufficient balance - const balance = await getBalance(transaction.from) - if (balance < transaction.amount) { - throw new Error('Insufficient balance') - } - - return true -} -``` - -#### Verification Steps -- [ ] Wallet signatures verified -- [ ] Transaction details validated -- [ ] Balance checks before transactions -- [ ] No blind transaction signing - -### 10. Dependency Security - -#### Regular Updates -```bash -# Check for vulnerabilities -npm audit - -# Fix automatically fixable issues -npm audit fix - -# Update dependencies -npm update - -# Check for outdated packages -npm outdated -``` - -#### Lock Files -```bash -# ALWAYS commit lock files -git add package-lock.json - -# Use in CI/CD for reproducible builds -npm ci # Instead of npm install -``` - -#### Verification Steps -- [ ] Dependencies up to date -- [ ] No known vulnerabilities (npm audit clean) -- [ ] Lock files committed -- [ ] Dependabot enabled on GitHub -- [ ] Regular security updates - -## Security Testing - -### Automated Security Tests -```typescript -// Test authentication -test('requires authentication', async () => { - const response = await fetch('/api/protected') - expect(response.status).toBe(401) -}) - -// Test authorization -test('requires admin role', async () => { - const response = await fetch('/api/admin', { - headers: { Authorization: `Bearer ${userToken}` } - }) - expect(response.status).toBe(403) -}) - -// Test input validation -test('rejects invalid input', async () => { - const response = await fetch('/api/users', { - method: 'POST', - body: JSON.stringify({ email: 'not-an-email' }) - }) - expect(response.status).toBe(400) -}) - -// Test rate limiting -test('enforces rate limits', async () => { - const requests = Array(101).fill(null).map(() => - fetch('/api/endpoint') - ) - - const responses = await Promise.all(requests) - const tooManyRequests = responses.filter(r => r.status === 429) - - expect(tooManyRequests.length).toBeGreaterThan(0) -}) -``` - -## Pre-Deployment Security Checklist - -Before ANY production deployment: - -- [ ] **Secrets**: No hardcoded secrets, all in env vars -- [ ] **Input Validation**: All user inputs validated -- [ ] **SQL Injection**: All queries parameterized -- [ ] **XSS**: User content sanitized -- [ ] **CSRF**: Protection enabled -- [ ] **Authentication**: Proper token handling -- [ ] **Authorization**: Role checks in place -- [ ] **Rate Limiting**: Enabled on all endpoints -- [ ] **HTTPS**: Enforced in production -- [ ] **Security Headers**: CSP, X-Frame-Options configured -- [ ] **Error Handling**: No sensitive data in errors -- [ ] **Logging**: No sensitive data logged -- [ ] **Dependencies**: Up to date, no vulnerabilities -- [ ] **Row Level Security**: Enabled in Supabase -- [ ] **CORS**: Properly configured -- [ ] **File Uploads**: Validated (size, type) -- [ ] **Wallet Signatures**: Verified (if blockchain) - -## Resources - -- [OWASP Top 10](https://owasp.org/www-project-top-ten/) -- [Next.js Security](https://nextjs.org/docs/security) -- [Supabase Security](https://supabase.com/docs/guides/auth) -- [Web Security Academy](https://portswigger.net/web-security) - ---- - -**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution. diff --git a/dot_claude/skills/security-review/cloud-infrastructure-security.md b/dot_claude/skills/security-review/cloud-infrastructure-security.md deleted file mode 100644 index 24e9ec2..0000000 --- a/dot_claude/skills/security-review/cloud-infrastructure-security.md +++ /dev/null @@ -1,361 +0,0 @@ -| name | description | -|------|-------------| -| cloud-infrastructure-security | Use this skill when deploying to cloud platforms, configuring infrastructure, managing IAM policies, setting up logging/monitoring, or implementing CI/CD pipelines. Provides cloud security checklist aligned with best practices. | - -# Cloud & Infrastructure Security Skill - -This skill ensures cloud infrastructure, CI/CD pipelines, and deployment configurations follow security best practices and comply with industry standards. - -## When to Activate - -- Deploying applications to cloud platforms (AWS, Vercel, Railway, Cloudflare) -- Configuring IAM roles and permissions -- Setting up CI/CD pipelines -- Implementing infrastructure as code (Terraform, CloudFormation) -- Configuring logging and monitoring -- Managing secrets in cloud environments -- Setting up CDN and edge security -- Implementing disaster recovery and backup strategies - -## Cloud Security Checklist - -### 1. IAM & Access Control - -#### Principle of Least Privilege - -```yaml -# ✅ CORRECT: Minimal permissions -iam_role: - permissions: - - s3:GetObject # Only read access - - s3:ListBucket - resources: - - arn:aws:s3:::my-bucket/* # Specific bucket only - -# ❌ WRONG: Overly broad permissions -iam_role: - permissions: - - s3:* # All S3 actions - resources: - - "*" # All resources -``` - -#### Multi-Factor Authentication (MFA) - -```bash -# ALWAYS enable MFA for root/admin accounts -aws iam enable-mfa-device \ - --user-name admin \ - --serial-number arn:aws:iam::123456789:mfa/admin \ - --authentication-code1 123456 \ - --authentication-code2 789012 -``` - -#### Verification Steps - -- [ ] No root account usage in production -- [ ] MFA enabled for all privileged accounts -- [ ] Service accounts use roles, not long-lived credentials -- [ ] IAM policies follow least privilege -- [ ] Regular access reviews conducted -- [ ] Unused credentials rotated or removed - -### 2. Secrets Management - -#### Cloud Secrets Managers - -```typescript -// ✅ CORRECT: Use cloud secrets manager -import { SecretsManager } from '@aws-sdk/client-secrets-manager'; - -const client = new SecretsManager({ region: 'us-east-1' }); -const secret = await client.getSecretValue({ SecretId: 'prod/api-key' }); -const apiKey = JSON.parse(secret.SecretString).key; - -// ❌ WRONG: Hardcoded or in environment variables only -const apiKey = process.env.API_KEY; // Not rotated, not audited -``` - -#### Secrets Rotation - -```bash -# Set up automatic rotation for database credentials -aws secretsmanager rotate-secret \ - --secret-id prod/db-password \ - --rotation-lambda-arn arn:aws:lambda:region:account:function:rotate \ - --rotation-rules AutomaticallyAfterDays=30 -``` - -#### Verification Steps - -- [ ] All secrets stored in cloud secrets manager (AWS Secrets Manager, Vercel Secrets) -- [ ] Automatic rotation enabled for database credentials -- [ ] API keys rotated at least quarterly -- [ ] No secrets in code, logs, or error messages -- [ ] Audit logging enabled for secret access - -### 3. Network Security - -#### VPC and Firewall Configuration - -```terraform -# ✅ CORRECT: Restricted security group -resource "aws_security_group" "app" { - name = "app-sg" - - ingress { - from_port = 443 - to_port = 443 - protocol = "tcp" - cidr_blocks = ["10.0.0.0/16"] # Internal VPC only - } - - egress { - from_port = 443 - to_port = 443 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] # Only HTTPS outbound - } -} - -# ❌ WRONG: Open to the internet -resource "aws_security_group" "bad" { - ingress { - from_port = 0 - to_port = 65535 - protocol = "tcp" - cidr_blocks = ["0.0.0.0/0"] # All ports, all IPs! - } -} -``` - -#### Verification Steps - -- [ ] Database not publicly accessible -- [ ] SSH/RDP ports restricted to VPN/bastion only -- [ ] Security groups follow least privilege -- [ ] Network ACLs configured -- [ ] VPC flow logs enabled - -### 4. Logging & Monitoring - -#### CloudWatch/Logging Configuration - -```typescript -// ✅ CORRECT: Comprehensive logging -import { CloudWatchLogsClient, CreateLogStreamCommand } from '@aws-sdk/client-cloudwatch-logs'; - -const logSecurityEvent = async (event: SecurityEvent) => { - await cloudwatch.putLogEvents({ - logGroupName: '/aws/security/events', - logStreamName: 'authentication', - logEvents: [{ - timestamp: Date.now(), - message: JSON.stringify({ - type: event.type, - userId: event.userId, - ip: event.ip, - result: event.result, - // Never log sensitive data - }) - }] - }); -}; -``` - -#### Verification Steps - -- [ ] CloudWatch/logging enabled for all services -- [ ] Failed authentication attempts logged -- [ ] Admin actions audited -- [ ] Log retention configured (90+ days for compliance) -- [ ] Alerts configured for suspicious activity -- [ ] Logs centralized and tamper-proof - -### 5. CI/CD Pipeline Security - -#### Secure Pipeline Configuration - -```yaml -# ✅ CORRECT: Secure GitHub Actions workflow -name: Deploy - -on: - push: - branches: [main] - -jobs: - deploy: - runs-on: ubuntu-latest - permissions: - contents: read # Minimal permissions - - steps: - - uses: actions/checkout@v4 - - # Scan for secrets - - name: Secret scanning - uses: trufflesecurity/trufflehog@main - - # Dependency audit - - name: Audit dependencies - run: npm audit --audit-level=high - - # Use OIDC, not long-lived tokens - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v4 - with: - role-to-assume: arn:aws:iam::123456789:role/GitHubActionsRole - aws-region: us-east-1 -``` - -#### Supply Chain Security - -```json -// package.json - Use lock files and integrity checks -{ - "scripts": { - "install": "npm ci", // Use ci for reproducible builds - "audit": "npm audit --audit-level=moderate", - "check": "npm outdated" - } -} -``` - -#### Verification Steps - -- [ ] OIDC used instead of long-lived credentials -- [ ] Secrets scanning in pipeline -- [ ] Dependency vulnerability scanning -- [ ] Container image scanning (if applicable) -- [ ] Branch protection rules enforced -- [ ] Code review required before merge -- [ ] Signed commits enforced - -### 6. Cloudflare & CDN Security - -#### Cloudflare Security Configuration - -```typescript -// ✅ CORRECT: Cloudflare Workers with security headers -export default { - async fetch(request: Request): Promise { - const response = await fetch(request); - - // Add security headers - const headers = new Headers(response.headers); - headers.set('X-Frame-Options', 'DENY'); - headers.set('X-Content-Type-Options', 'nosniff'); - headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); - headers.set('Permissions-Policy', 'geolocation=(), microphone=()'); - - return new Response(response.body, { - status: response.status, - headers - }); - } -}; -``` - -#### WAF Rules - -```bash -# Enable Cloudflare WAF managed rules -# - OWASP Core Ruleset -# - Cloudflare Managed Ruleset -# - Rate limiting rules -# - Bot protection -``` - -#### Verification Steps - -- [ ] WAF enabled with OWASP rules -- [ ] Rate limiting configured -- [ ] Bot protection active -- [ ] DDoS protection enabled -- [ ] Security headers configured -- [ ] SSL/TLS strict mode enabled - -### 7. Backup & Disaster Recovery - -#### Automated Backups - -```terraform -# ✅ CORRECT: Automated RDS backups -resource "aws_db_instance" "main" { - allocated_storage = 20 - engine = "postgres" - - backup_retention_period = 30 # 30 days retention - backup_window = "03:00-04:00" - maintenance_window = "mon:04:00-mon:05:00" - - enabled_cloudwatch_logs_exports = ["postgresql"] - - deletion_protection = true # Prevent accidental deletion -} -``` - -#### Verification Steps - -- [ ] Automated daily backups configured -- [ ] Backup retention meets compliance requirements -- [ ] Point-in-time recovery enabled -- [ ] Backup testing performed quarterly -- [ ] Disaster recovery plan documented -- [ ] RPO and RTO defined and tested - -## Pre-Deployment Cloud Security Checklist - -Before ANY production cloud deployment: - -- [ ] **IAM**: Root account not used, MFA enabled, least privilege policies -- [ ] **Secrets**: All secrets in cloud secrets manager with rotation -- [ ] **Network**: Security groups restricted, no public databases -- [ ] **Logging**: CloudWatch/logging enabled with retention -- [ ] **Monitoring**: Alerts configured for anomalies -- [ ] **CI/CD**: OIDC auth, secrets scanning, dependency audits -- [ ] **CDN/WAF**: Cloudflare WAF enabled with OWASP rules -- [ ] **Encryption**: Data encrypted at rest and in transit -- [ ] **Backups**: Automated backups with tested recovery -- [ ] **Compliance**: GDPR/HIPAA requirements met (if applicable) -- [ ] **Documentation**: Infrastructure documented, runbooks created -- [ ] **Incident Response**: Security incident plan in place - -## Common Cloud Security Misconfigurations - -### S3 Bucket Exposure - -```bash -# ❌ WRONG: Public bucket -aws s3api put-bucket-acl --bucket my-bucket --acl public-read - -# ✅ CORRECT: Private bucket with specific access -aws s3api put-bucket-acl --bucket my-bucket --acl private -aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json -``` - -### RDS Public Access - -```terraform -# ❌ WRONG -resource "aws_db_instance" "bad" { - publicly_accessible = true # NEVER do this! -} - -# ✅ CORRECT -resource "aws_db_instance" "good" { - publicly_accessible = false - vpc_security_group_ids = [aws_security_group.db.id] -} -``` - -## Resources - -- [AWS Security Best Practices](https://aws.amazon.com/security/best-practices/) -- [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services) -- [Cloudflare Security Documentation](https://developers.cloudflare.com/security/) -- [OWASP Cloud Security](https://owasp.org/www-project-cloud-security/) -- [Terraform Security Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/) - -**Remember**: Cloud misconfigurations are the leading cause of data breaches. A single exposed S3 bucket or overly permissive IAM policy can compromise your entire infrastructure. Always follow the principle of least privilege and defense in depth. diff --git a/dot_claude/skills/tdd-workflow/SKILL.md b/dot_claude/skills/tdd-workflow/SKILL.md deleted file mode 100644 index e7ae073..0000000 --- a/dot_claude/skills/tdd-workflow/SKILL.md +++ /dev/null @@ -1,409 +0,0 @@ ---- -name: tdd-workflow -description: Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests. ---- - -# Test-Driven Development Workflow - -This skill ensures all code development follows TDD principles with comprehensive test coverage. - -## When to Activate - -- Writing new features or functionality -- Fixing bugs or issues -- Refactoring existing code -- Adding API endpoints -- Creating new components - -## Core Principles - -### 1. Tests BEFORE Code -ALWAYS write tests first, then implement code to make tests pass. - -### 2. Coverage Requirements -- Minimum 80% coverage (unit + integration + E2E) -- All edge cases covered -- Error scenarios tested -- Boundary conditions verified - -### 3. Test Types - -#### Unit Tests -- Individual functions and utilities -- Component logic -- Pure functions -- Helpers and utilities - -#### Integration Tests -- API endpoints -- Database operations -- Service interactions -- External API calls - -#### E2E Tests (Playwright) -- Critical user flows -- Complete workflows -- Browser automation -- UI interactions - -## TDD Workflow Steps - -### Step 1: Write User Journeys -``` -As a [role], I want to [action], so that [benefit] - -Example: -As a user, I want to search for markets semantically, -so that I can find relevant markets even without exact keywords. -``` - -### Step 2: Generate Test Cases -For each user journey, create comprehensive test cases: - -```typescript -describe('Semantic Search', () => { - it('returns relevant markets for query', async () => { - // Test implementation - }) - - it('handles empty query gracefully', async () => { - // Test edge case - }) - - it('falls back to substring search when Redis unavailable', async () => { - // Test fallback behavior - }) - - it('sorts results by similarity score', async () => { - // Test sorting logic - }) -}) -``` - -### Step 3: Run Tests (They Should Fail) -```bash -npm test -# Tests should fail - we haven't implemented yet -``` - -### Step 4: Implement Code -Write minimal code to make tests pass: - -```typescript -// Implementation guided by tests -export async function searchMarkets(query: string) { - // Implementation here -} -``` - -### Step 5: Run Tests Again -```bash -npm test -# Tests should now pass -``` - -### Step 6: Refactor -Improve code quality while keeping tests green: -- Remove duplication -- Improve naming -- Optimize performance -- Enhance readability - -### Step 7: Verify Coverage -```bash -npm run test:coverage -# Verify 80%+ coverage achieved -``` - -## Testing Patterns - -### Unit Test Pattern (Jest/Vitest) -```typescript -import { render, screen, fireEvent } from '@testing-library/react' -import { Button } from './Button' - -describe('Button Component', () => { - it('renders with correct text', () => { - render() - expect(screen.getByText('Click me')).toBeInTheDocument() - }) - - it('calls onClick when clicked', () => { - const handleClick = jest.fn() - render() - - fireEvent.click(screen.getByRole('button')) - - expect(handleClick).toHaveBeenCalledTimes(1) - }) - - it('is disabled when disabled prop is true', () => { - render() - expect(screen.getByRole('button')).toBeDisabled() - }) -}) -``` - -### API Integration Test Pattern -```typescript -import { NextRequest } from 'next/server' -import { GET } from './route' - -describe('GET /api/markets', () => { - it('returns markets successfully', async () => { - const request = new NextRequest('http://localhost/api/markets') - const response = await GET(request) - const data = await response.json() - - expect(response.status).toBe(200) - expect(data.success).toBe(true) - expect(Array.isArray(data.data)).toBe(true) - }) - - it('validates query parameters', async () => { - const request = new NextRequest('http://localhost/api/markets?limit=invalid') - const response = await GET(request) - - expect(response.status).toBe(400) - }) - - it('handles database errors gracefully', async () => { - // Mock database failure - const request = new NextRequest('http://localhost/api/markets') - // Test error handling - }) -}) -``` - -### E2E Test Pattern (Playwright) -```typescript -import { test, expect } from '@playwright/test' - -test('user can search and filter markets', async ({ page }) => { - // Navigate to markets page - await page.goto('/') - await page.click('a[href="/markets"]') - - // Verify page loaded - await expect(page.locator('h1')).toContainText('Markets') - - // Search for markets - await page.fill('input[placeholder="Search markets"]', 'election') - - // Wait for debounce and results - await page.waitForTimeout(600) - - // Verify search results displayed - const results = page.locator('[data-testid="market-card"]') - await expect(results).toHaveCount(5, { timeout: 5000 }) - - // Verify results contain search term - const firstResult = results.first() - await expect(firstResult).toContainText('election', { ignoreCase: true }) - - // Filter by status - await page.click('button:has-text("Active")') - - // Verify filtered results - await expect(results).toHaveCount(3) -}) - -test('user can create a new market', async ({ page }) => { - // Login first - await page.goto('/creator-dashboard') - - // Fill market creation form - await page.fill('input[name="name"]', 'Test Market') - await page.fill('textarea[name="description"]', 'Test description') - await page.fill('input[name="endDate"]', '2025-12-31') - - // Submit form - await page.click('button[type="submit"]') - - // Verify success message - await expect(page.locator('text=Market created successfully')).toBeVisible() - - // Verify redirect to market page - await expect(page).toHaveURL(/\/markets\/test-market/) -}) -``` - -## Test File Organization - -``` -src/ -├── components/ -│ ├── Button/ -│ │ ├── Button.tsx -│ │ ├── Button.test.tsx # Unit tests -│ │ └── Button.stories.tsx # Storybook -│ └── MarketCard/ -│ ├── MarketCard.tsx -│ └── MarketCard.test.tsx -├── app/ -│ └── api/ -│ └── markets/ -│ ├── route.ts -│ └── route.test.ts # Integration tests -└── e2e/ - ├── markets.spec.ts # E2E tests - ├── trading.spec.ts - └── auth.spec.ts -``` - -## Mocking External Services - -### Supabase Mock -```typescript -jest.mock('@/lib/supabase', () => ({ - supabase: { - from: jest.fn(() => ({ - select: jest.fn(() => ({ - eq: jest.fn(() => Promise.resolve({ - data: [{ id: 1, name: 'Test Market' }], - error: null - })) - })) - })) - } -})) -``` - -### Redis Mock -```typescript -jest.mock('@/lib/redis', () => ({ - searchMarketsByVector: jest.fn(() => Promise.resolve([ - { slug: 'test-market', similarity_score: 0.95 } - ])), - checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true })) -})) -``` - -### OpenAI Mock -```typescript -jest.mock('@/lib/openai', () => ({ - generateEmbedding: jest.fn(() => Promise.resolve( - new Array(1536).fill(0.1) // Mock 1536-dim embedding - )) -})) -``` - -## Test Coverage Verification - -### Run Coverage Report -```bash -npm run test:coverage -``` - -### Coverage Thresholds -```json -{ - "jest": { - "coverageThresholds": { - "global": { - "branches": 80, - "functions": 80, - "lines": 80, - "statements": 80 - } - } - } -} -``` - -## Common Testing Mistakes to Avoid - -### ❌ WRONG: Testing Implementation Details -```typescript -// Don't test internal state -expect(component.state.count).toBe(5) -``` - -### ✅ CORRECT: Test User-Visible Behavior -```typescript -// Test what users see -expect(screen.getByText('Count: 5')).toBeInTheDocument() -``` - -### ❌ WRONG: Brittle Selectors -```typescript -// Breaks easily -await page.click('.css-class-xyz') -``` - -### ✅ CORRECT: Semantic Selectors -```typescript -// Resilient to changes -await page.click('button:has-text("Submit")') -await page.click('[data-testid="submit-button"]') -``` - -### ❌ WRONG: No Test Isolation -```typescript -// Tests depend on each other -test('creates user', () => { /* ... */ }) -test('updates same user', () => { /* depends on previous test */ }) -``` - -### ✅ CORRECT: Independent Tests -```typescript -// Each test sets up its own data -test('creates user', () => { - const user = createTestUser() - // Test logic -}) - -test('updates user', () => { - const user = createTestUser() - // Update logic -}) -``` - -## Continuous Testing - -### Watch Mode During Development -```bash -npm test -- --watch -# Tests run automatically on file changes -``` - -### Pre-Commit Hook -```bash -# Runs before every commit -npm test && npm run lint -``` - -### CI/CD Integration -```yaml -# GitHub Actions -- name: Run Tests - run: npm test -- --coverage -- name: Upload Coverage - uses: codecov/codecov-action@v3 -``` - -## Best Practices - -1. **Write Tests First** - Always TDD -2. **One Assert Per Test** - Focus on single behavior -3. **Descriptive Test Names** - Explain what's tested -4. **Arrange-Act-Assert** - Clear test structure -5. **Mock External Dependencies** - Isolate unit tests -6. **Test Edge Cases** - Null, undefined, empty, large -7. **Test Error Paths** - Not just happy paths -8. **Keep Tests Fast** - Unit tests < 50ms each -9. **Clean Up After Tests** - No side effects -10. **Review Coverage Reports** - Identify gaps - -## Success Metrics - -- 80%+ code coverage achieved -- All tests passing (green) -- No skipped or disabled tests -- Fast test execution (< 30s for unit tests) -- E2E tests cover critical user flows -- Tests catch bugs before production - ---- - -**Remember**: Tests are not optional. They are the safety net that enables confident refactoring, rapid development, and production reliability. diff --git a/dot_claude/skills/verification-loop/SKILL.md b/dot_claude/skills/verification-loop/SKILL.md deleted file mode 100644 index 1c09049..0000000 --- a/dot_claude/skills/verification-loop/SKILL.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -name: verification-loop -description: "A comprehensive verification system for Claude Code sessions." ---- - -# Verification Loop Skill - -A comprehensive verification system for Claude Code sessions. - -## When to Use - -Invoke this skill: -- After completing a feature or significant code change -- Before creating a PR -- 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 -``` - -### 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 -``` - -Review each changed file for: -- Unintended changes -- Missing error handling -- Potential edge cases - -## Output Format - -After running all phases, produce a verification report: - -``` -VERIFICATION REPORT -================== - -Build: [PASS/FAIL] -Types: [PASS/FAIL] (X errors) -Lint: [PASS/FAIL] (X warnings) -Tests: [PASS/FAIL] (X/Y passed, Z% coverage) -Security: [PASS/FAIL] (X issues) -Diff: [X files changed] - -Overall: [READY/NOT READY] for PR - -Issues to Fix: -1. ... -2. ... -``` - -## Continuous Mode - -For long sessions, run verification every 15 minutes or after major changes: - -```markdown -Set a mental checkpoint: -- After completing each function -- After finishing a component -- Before moving to next task - -Run: /verify -``` - -## Integration with Hooks - -This skill complements PostToolUse hooks but provides deeper verification. -Hooks catch issues immediately; this skill provides comprehensive review. diff --git a/private_dot_ssh/config.d/config_home b/private_dot_ssh/config.d/private_config_home similarity index 100% rename from private_dot_ssh/config.d/config_home rename to private_dot_ssh/config.d/private_config_home diff --git a/private_dot_ssh/config b/private_dot_ssh/private_config similarity index 100% rename from private_dot_ssh/config rename to private_dot_ssh/private_config diff --git a/source/intersolia/infrastructure/dot_claude/settings.local.json b/source/intersolia/infrastructure/dot_claude/settings.local.json new file mode 100644 index 0000000..5d686fa --- /dev/null +++ b/source/intersolia/infrastructure/dot_claude/settings.local.json @@ -0,0 +1,117 @@ +{ + "env": { + "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" + }, + "enabledPlugins": { + "deploy-on-aws@agent-plugins-for-aws": true + }, + "permissions": { + "allow": [ + "Bash(rm:*)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure log --oneline -20)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure show b62d856 --stat)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure show 28b4077 --stat)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure show b62d856 --no-stat)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure show b62d856)", + "Bash(terraform fmt:*)", + "WebFetch(domain:docs.digger.dev)", + "WebFetch(domain:docs.opentaco.dev)", + "WebFetch(domain:medium.com)", + "WebFetch(domain:news.ycombinator.com)", + "Bash(mkdir:*)", + "Bash(gh pr checks:*)", + "Bash(git log:*)", + "Bash(xargs cat:*)", + "Bash(git -C /Users/peter/source/intersolia/demo-tf log --oneline -10)", + "WebFetch(domain:docs.terrateam.io)", + "WebSearch", + "Bash(ls:*)", + "Bash(but status:*)", + "Bash(gh pr list:*)", + "Bash(gh pr view:*)", + "Bash(gh run list:*)", + "Bash(gh api:*)", + "Bash(gh pr diff:*)", + "WebFetch(domain:stategraph.com)", + "Bash(git -C /Users/peter/source/intersolia/argocd-applications log --all --oneline -- infra/platform/terrateam/)", + "Bash(git -C /Users/peter/source/intersolia/argocd-applications branch -r --contains cd43c86)", + "Bash(git -C /Users/peter/source/intersolia/argocd-applications branch:*)", + "Bash(git -C /Users/peter/source/intersolia/argocd-applications show origin/main:appsets/platform-infra.yaml)", + "Bash(grep:*)", + "WebFetch(domain:raw.githubusercontent.com)", + "WebFetch(domain:github.com)", + "Bash(gh search code:*)", + "WebFetch(domain:stategraph.github.io)", + "WebFetch(domain:stategraph.dev)", + "Bash(kustomize build:*)", + "WebFetch(domain:terrateam.io)", + "Bash(gh search:*)", + "Bash(find:*)", + "Bash(gh issue view:*)", + "Bash(but branch list:*)", + "Bash(but pull)", + "Bash(but branch:*)", + "Bash(but rub g0 feat/terrateam-plan-no-lock)", + "Bash(git add:*)", + "Bash(pre-commit run:*)", + "Bash(but commit --only -m \"$\\(cat <<''EOF''\nfeat: disable state lock for Terrateam plan operations\n\nAdd -lock=false to the plan step in Terrateam workflow config.\nSince plan operations are read-only, they don''t need the state lock,\nwhich allows concurrent plans for the same environment to run\nwithout lock contention errors.\n\nCo-Authored-By: Claude Opus 4.6 \nEOF\n\\)\" feat/terrateam-plan-no-lock)", + "Bash(but undo)", + "Bash(but discard g0)", + "Bash(but diff:*)", + "WebFetch(domain:registry.terraform.io)", + "Bash(terraform apply:*)", + "Bash(helm repo add:*)", + "Bash(helm repo update:*)", + "Bash(helm search repo:*)", + "Bash(kubectl:*)", + "Bash(skopeo inspect:*)", + "Bash(docker manifest inspect:*)", + "WebFetch(domain:docs.renovatebot.com)", + "Bash(gh pr comments:*)", + "WebFetch(domain:api.github.com)", + "Bash(go test:*)", + "Bash(make:*)", + "Bash(go build:*)", + "Bash(go vet:*)", + "Bash(terraform init:*)", + "Bash(terraform providers lock:*)", + "Bash(aws sts:*)", + "Bash(terraform providers:*)", + "Bash(git ls-remote:*)", + "WebFetch(domain:developer.hashicorp.com)", + "WebFetch(domain:masterpoint.io)", + "WebFetch(domain:dortort.com)", + "WebFetch(domain:grem1.in)", + "Bash(but rub mn renovate-terraform-lockfile)", + "Bash(but commit --only -m \"feat: add postUpgradeTasks for terraform lock file updates\n\nConfigure Renovate to automatically run terraform providers lock\nafter module and provider updates, ensuring .terraform.lock.hcl\nstays in sync with dependency changes.\" renovate-terraform-lockfile)", + "Bash(git checkout:*)", + "Bash(git commit:*)", + "Bash(chmod:*)", + "Bash(but rub qq renovate-terraform-lockfile)", + "Bash(but commit --only -m \"feat: add postUpgradeTasks for terraform lock file updates\n\nAdd a script that runs terraform init and providers lock in all\nenvironment directories, and configure Renovate postUpgradeTasks\nto run it after module and provider version bumps. This ensures\n.terraform.lock.hcl files stay in sync with dependency changes.\" renovate-terraform-lockfile)", + "Bash(but squash renovate-terraform-lockfile)", + "Bash(but discard renovate-terraform-lockfile)", + "Bash(python3:*)", + "Bash(but uncommit:*)", + "Bash(but commit:*)", + "Bash(gh pr review:*)", + "Bash(git -C /Users/peter/source/intersolia/infrastructure checkout -- terraform/environments/dev/.terraform.lock.hcl)", + "Bash(but rub:*)", + "Bash(git -C /Users/peter/source/intersolia/argocd-applications checkout -b fix/remove-renovate-allowed-commands)", + "Bash(git reset:*)", + "Bash(docker run:*)", + "Bash(docker pull:*)", + "Bash(gh pr comment:*)", + "WebFetch(domain:platformers.dev)", + "WebFetch(domain:kops.sigs.k8s.io)", + "Bash(true:*)" + ] + }, + "enabledMcpjsonServers": [ + "github", + "memory", + "sequential-thinking", + "context7", + "exa" + ] +}