Skip to content

Instantly share code, notes, and snippets.

@bradfeld
Last active March 11, 2026 15:27
Show Gist options
  • Select an option

  • Save bradfeld/1deb0c385d12289947ff83f145b7e4d2 to your computer and use it in GitHub Desktop.

Select an option

Save bradfeld/1deb0c385d12289947ff83f145b7e4d2 to your computer and use it in GitHub Desktop.
Advanced Claude Code Configuration Guide - patterns for professional solo development

Feld Claude Code Configuration Guide

A comprehensive guide documenting professional solo development patterns using Claude Code. Covers workflow discipline, session persistence, automated quality gates, business operations, and EOS management across twelve repositories and eight worktrees.

Last updated: 2026-03-08


Table of Contents

  1. Core Philosophy
  2. Directory Structure
  3. Session State Architecture
  4. Master Workflow
  5. Review Triage System
  6. Workflow Profiles
  7. Rules System
  8. On-Demand Reference Docs
  9. Hooks System
  10. Conditional Rule Loading
  11. Model Strategy
  12. Skills Inventory
  13. Superpowers Plugin
  14. Commands Inventory
  15. MCP Server Integration
  16. Repository Registry
  17. CompanyOS: Multi-Repo Architecture
  18. CEOS: EOS Framework
  19. Automated Jobs
  20. Multi-Instance Safety (Worktrees)
  21. Blog and Learning Capture
  22. Git Workflow Rules
  23. Coding Standards
  24. Database Migration Discipline
  25. Secrets Management
  26. Testing Patterns
  27. Critical Gotchas
  28. Quick Start for New Setup
  29. Key Insights

Core Philosophy

Global-first configuration. Configuration should be consistent everywhere. Project-level configuration creates maintenance burden and inconsistency.

Key principles:

  • Never create project-level .claude/settings.json — it breaks permission inheritance from global settings, causing unexpected prompts
  • No quick-fix mode — every ticket gets the full workflow (/start → implement → /commit)
  • Session state files survive context compaction — workflow continuity across long sessions
  • Evidence before assertions — never claim something about code without reading it first
  • Protected workflows — certain operations (/commit, /staging, /start) must never be done manually

Directory Structure

~/.claude/                          # Global configuration
├── settings.json                   # Permissions, hooks, plugins, env, attribution
├── rules/                          # 10 always-loaded rules (cross-project standards)
├── docs/                           # 13 on-demand reference docs (loaded when needed)
├── skills/                         # 52 skill directories (symlinked from 3 repos)
├── commands/                       # 42 user-level commands
├── hooks/                          # 10 hook scripts (event-driven automation)
├── agents/                         # Custom agent definitions
├── blog/notes/                     # Daily learning capture
├── command-tracker.jsonl           # Slash command success streaks
├── statusline.sh                   # Status bar script
└── plugins/                        # Marketplace plugins (superpowers, LSPs)

~/.claude-personal/                 # Personal context
├── CLAUDE.md                       # Global developer context (loaded every session)
├── voice/voice-profile.md          # Writing style calibration
├── plans/                          # Implementation plans
└── projects/                       # Per-project auto-memory

~/Code/companyos/                   # CompanyOS core repo (shared skills)
~/Code/companyos-config-*/          # Per-company config repos (2 companies)
~/Code/ceos/                        # CEOS repo (EOS framework skills)

project/.claude/                    # Project-specific
├── rules/                          # Project rules (with frontmatter globs)
├── commands/                       # Project commands
├── agents/                         # Project agents
└── docs/                           # Project reference docs

Session State Architecture

Session files stored in project/.claude-session/ persist workflow state including:

  • Current step and status (implementing, awaiting_user_test, committing)
  • Blocked actions to prevent accidental commits before testing
  • Implementation plans that survive context compaction
  • Progress tracking across worktrees

Circuit breaker protection: Commits are blocked when session status shows awaiting_user_test. The /commit command checks this state before proceeding.


Master Workflow

All tickets follow an identical loop:

  1. /start TICKET-XXX — Fetch ticket from Linear, analyze, create branch, post implementation plan
  2. Implement locally with manual testing
  3. /commit — Auto-triage review level, run /simplify, run review agents, push, update Linear
  4. /staging (magic-platform only) — Batch merge to preview, deploy, reset worktrees
  5. /production (magic-platform only) — Health audit, merge to main, verify

For direct-to-main repositories (CEOS, WordPress), /commit IS the deployment.

/start auto-detects the target repository from the ticket's Linear team prefix — the same command works across all twelve repositories.


Review Triage System

Automatic review depth selection based on change characteristics:

Level When What Runs
NONE Only non-source changes (docs, tests, config, styling) No review agents — just commit
LIGHT Any source code change (.ts/.tsx) that doesn't trigger FULL code-reviewer on Sonnet + selective agents in parallel
FULL 10+ files, shared packages, or sensitive paths Full parallel multi-agent review battery on Sonnet

Key rule: NONE never applies to source code changes. Even a 1-file .tsx change gets at least LIGHT review. This eliminates the "small change, big bug" escape path.

Triage Signals

Evaluated in priority order: path-based overrides first, then content-type exemption, then file-count baseline.

Path overrides (force FULL): middleware.ts, auth.ts, /auth/, supabase/migrations/, packages/*, payment, billing, webhook

Content-type exemption (downgrade to NONE): Only when ALL changed files are non-source — docs, tests, config, styling, lockfile (without package.json). package.json is NOT exempt.

Content-based agent selection: .tsx files add ui-consistency-reviewer. API routes/services/actions/hooks add silent-failure-hunter. Auth/migrations at FULL level add security-auditor.

Full decision algorithm and dispatch examples are in on-demand reference doc review-triage-reference.md.


Workflow Profiles

Each repository declares its workflow characteristics in CLAUDE.md as YAML:

workflow:
  base_branch: preview           # or main
  direct_to_main: false          # true for CEOS, WP
  quality_gates:
    - pnpm run type-check        # commands to run before commit
    - pnpm run lint
  review:
    max_level: FULL              # NONE, LIGHT, or FULL
  ship:
    method: pr                   # pr or direct_push
    linear_status: "In Progress" # status after commit
    deploy_hint: "/staging"      # what to do next

This declarative approach allows /start and /commit to work identically across twelve repositories without hardcoded logic. The unified /commit command reads the profile and adapts its behavior.


Rules System

10 always-loaded rules in ~/.claude/rules/ establish cross-project standards:

Rule Purpose
code-quality.md TypeScript strict mode, error handling, security, type duplication
commit-recipe.md Universal commit structure, pre-commit hooks, worktree staging
evidence-first.md Never assert without reading/verifying first
learning-capture.md Auto-capture insight blocks + suggested discovery capture
on-demand-references.md Index of 13 detailed reference docs
output-formatting.md Structured output completeness on first attempt
protected-workflows.md Workflows that must use their dedicated commands
reasoning-calibration.md Effort scaling: quick execution → standard → deep analysis
review-triage.md NONE/LIGHT/FULL triage framework
scope-intent.md Match response scope to what was actually requested

Project-level rules use frontmatter globs for conditional loading (see Conditional Rule Loading).

Key architectural decision (PLA-688, 2026-03-08): Rules were trimmed by extracting detailed reference material into on-demand docs. Always-loaded rules contain decision logic; reference tables and examples live in docs loaded only when needed.


On-Demand Reference Docs

13 docs in ~/.claude/docs/ loaded only when a task matches. The on-demand-references.md rule serves as the index:

Task Reference Doc
Writing Vitest tests testing-vitest.md
Configuring MCP servers mcp-server-config.md
Creating skills or commands skill-authoring.md
Committing changes commit-reference.md
Review triage dispatch review-triage-reference.md
Linear MCP operations mcp-linear.md
Multi-chain epic planning multi-chain-epics.md
Parallel subagent dispatch parallel-patterns.md
Shell scripting bash-patterns.md
Production database operations production-safety.md (project-level)
CI pipeline, staging, production ci-pipeline.md (project-level)

Why this pattern exists: Always-loaded rules consume context tokens every session. A 200-line reference table for commit workflows wastes tokens when you're doing codebase exploration. On-demand docs are loaded only when Claude encounters the matching task — zero cost otherwise.


Hooks System

10 hook scripts in ~/.claude/hooks/ respond to Claude Code lifecycle events. Configured in ~/.claude/settings.json under the hooks key.

Event Hook Purpose
SessionStart system-health-check.sh Verify system state on startup
SessionStart session-sync.sh CompanyOS auto-sync
PreToolUse (Edit/Write) file-protection.sh Prevent edits to protected files
UserPromptSubmit checkpoint-reminder.sh Remind about session checkpoints
UserPromptSubmit co-skill-track.sh Log skill invocations to Supabase
UserPromptSubmit command-tracker.sh Track slash command success streaks
PostToolUse (ExitPlanMode) macOS notification "Plan Ready" alert
PostToolUse (Skill) co-skill-track.sh Skill telemetry
PostToolUse (Edit/Write) changelog-tracker.sh Track file changes
PostToolUse (Google Workspace) google-workspace-retry.sh Detect OAuth port conflicts, instruct retry
PreCompact preserve-session-state.sh Save state before context compaction
PermissionRequest permission-auto-approve.sh Auto-approve known-safe operations

Plus notification hooks (ccnotify), terminal color hooks (iterm window_color.py, typing_monitor.py), and Stop hooks for command tracking.

Key architectural pattern: Hooks replaced several always-loaded rules. A rule that says "if Google Workspace fails with port 8766, retry" wastes tokens in every session. A PostToolUse hook fires only when the specific tool runs AND only outputs text when the error pattern matches — zero token cost in the common case.


Conditional Rule Loading

Project-level rules use YAML frontmatter to control when they load:

---
globs:
  - "apps/authormagic/web/src/lib/book-search/**"
  - "apps/authormagic/web/src/lib/services/book-*.ts"
alwaysApply: false
---

When alwaysApply: false with globs, the rule loads only when Claude touches files matching those patterns. When alwaysApply: true, the rule loads every session (same as the old behavior).

Project Rule Loading Glob Patterns
book-algorithm-regression.md Conditional AuthorMagic book search/services
database-migrations.md Conditional supabase/migrations/**, supabase/config.toml
nextjs-monorepo.md Conditional **/.next/**, **/next.config.*, **/validator.ts
ui-patterns.md Conditional **/*.tsx, **/*.css, **/globals.css
monorepo-type-errors.md Always General policy for pre-existing type errors

Token savings: In a 7-app monorepo, this prevents loading AuthorMagic book algorithm rules when editing MedicareMagic components.


Model Strategy

Established in PLA-584 (2026-02-20). Right model for right task:

Role Model Why
Primary agent (user sessions) Opus 4.6 Best reasoning, 1M context on Max plan
Plan subagent (/start) Sonnet 4.6 Nearly identical SWE-bench (79.6% vs 80.8%), 5x cheaper
Review agents (/commit) Sonnet 4.6 All review dispatch via model: "sonnet"
Explore agents Haiku 4.5 Quick codebase lookups
Platform AI (@platform/infra/ai) Tiered fast=Haiku, standard=Sonnet, premium=Opus

/deep-explore command: Sonnet 4.6 subagent for whole-codebase analysis leveraging its large context window.


Skills Inventory

52 skill directories in ~/.claude/skills/, sourced from four locations:

Domain Skills (11)

Skill Purpose
testing Test writing, debugging failures, choosing approaches
supabase Database queries, migrations, RLS debugging
vercel Deploy, build failures, environment management
linear Ticket management, issue creation, work tracking
context7 Library docs, API research, developer tools
notion Notion pages, databases, documentation
sentry Error investigation, issue viewing, trends
oauth Social provider OAuth setup
performance Core Web Vitals, bundle size, render optimization
mobile Mobile-responsive UI, layout fixes
form-patterns Form dirty state, "unsaved changes" bugs

CompanyOS Skills (20) — symlinked from ~/Code/companyos/skills/

Skill Purpose
co-ops Company operations, conventions, decisions, contacts
co-comms External communications — email, drafting, voice-matched
co-content Marketing, blog posts, announcements, social media
co-feedback User feedback review, triage, pattern analysis
co-calendar Scheduling, meeting prep, time awareness
co-search Cross-tool information search
co-secrets API keys, secrets, credential management
co-launch Launch cohorts, participants, messaging
co-support Customer support conversations, ticket triage
co-meetings Meeting notes, transcripts, action items
co-l10-prep Scorecard metric collection before L10 meetings
co-audit CompanyOS setup health, permissions, security
co-music Music playback, search, playlists
co-wisdom Inspirational/motivational moments
co-recurring Scheduled background job management
co-pipeline Multi-stage pipeline execution
co-pricing Pricing decisions, tier structures, value metrics
co-five-whys Root cause analysis before jumping to solutions
co-board-update Board meeting/deck summary for stakeholders
co-foundry-board-update Foundry-specific board update (from config repo)

CEOS Skills (21) — symlinked from ~/Code/ceos/skills/

Full Entrepreneurial Operating System implementation:

Skill EOS Component
ceos-vto Vision/Traction Organizer
ceos-rocks Quarterly Rocks (setting, tracking, scoring)
ceos-scorecard Weekly metrics, logging, trend analysis
ceos-l10 Level 10 weekly leadership meeting
ceos-ids Identify, Discuss, Solve issues
ceos-accountability Accountability Chart — seats, owners, roles
ceos-people Core Values alignment, GWC (right people, right seats)
ceos-process Core process documentation, followability review
ceos-todos To-Do tracking, creation, completion
ceos-trust Vulnerability-based trust exercises
ceos-lma Leadership and management assessment
ceos-delegate Delegate and Elevate 4-quadrant framework
ceos-cashflow 8 financial levers for cash flow optimization
ceos-clarity Clarity Break — strategic thinking time
ceos-annual Annual planning session
ceos-quarterly-planning Quarterly planning for leadership team
ceos-quarterly Quarterly conversations, 5-5-5 check-ins
ceos-checkup Organizational health assessment (Six Key Components)
ceos-kickoff Focus Day, Vision Building Day 1 & 2
ceos-assistance Daily operational delegation (The Stack)
ceos-dashboard Quick snapshot of overall business health

Superpowers Skills (13) — from marketplace plugin

See Superpowers Plugin.


Superpowers Plugin

A marketplace-distributed plugin (superpowers@superpowers-marketplace) that auto-updates core development methodology:

Skill Purpose
systematic-debugging Evidence-based bug investigation
verification-before-completion Run verification before claiming done
writing-plans Structured implementation planning
executing-plans Plan execution with review checkpoints
test-driven-development TDD workflow
subagent-driven-development Parallel task execution
dispatching-parallel-agents Independent task parallelization
using-git-worktrees Isolated worktree creation
finishing-a-development-branch Merge/PR/cleanup decisions
brainstorming Intent and requirements exploration
requesting-code-review Pre-merge verification
receiving-code-review Technical rigor for review feedback
writing-skills Skill creation and verification

Auto-updates ensure all sessions inherit new patterns without manual commits.


Commands Inventory

42 user-level commands in ~/.claude/commands/:

Universal (all repos)

/start, /commit, /checkpoint, /validate, /note, /view, /test, /verify-branch, /rules, /learn, /til, /global-status, /diagnose, /screenshot, /deep-explore, /start-chain, /secrets-scan, /dead-code, /weekly-cleanup, /done-color, /ground-truth, /auto-report

Magic Platform

/staging, /production, /localhost, /dashboard, /linear-image, /new-project

MagicEA

/deploy-ea

Freshell

/freshell

Blog

/blogaic-draft, /blogaic-post, /blog-feld

CompanyOS

/co-commit, /co-create-skill, /co-help, /co-plan, /co-recap, /co-recap-weekly, /co-skill-report, /co-switch, /co-test-gaps

Utility

/asana, /asana-companyos, /git-clean, /pr

Bundled (CC v2.1.63+)

/simplify — 3 parallel agents (reuse, quality, efficiency) that fix code directly. Wired into /commit as Step 2.5, runs before review agents. Complements review agents: /simplify FIXES code, reviewers REPORT on standards compliance.


MCP Server Integration

Architecture prefers PAT/API key auth over OAuth because API keys survive Claude Code updates, while OAuth tokens in Keychain become orphaned.

Configured Servers

Server Auth Method Purpose
Linear HTTP + Bearer token Issue tracking, project management
Supabase HTTP + Bearer token Database operations, Edge Functions
Stripe HTTP + Bearer token Billing, subscriptions, payments
Context7 HTTP + Bearer token Library documentation lookup
Better Stack HTTP + Bearer token Uptime monitoring, telemetry
Sentry Stdio + env vars Error monitoring, issue investigation
Notion Stdio + env vars Documentation, wikis
Firecrawl Stdio + env vars Web scraping, content extraction
HelpScout Stdio + env vars Customer support conversations
Google Workspace Stdio + per-user OAuth Gmail, Calendar, Drive, Docs
Vercel OAuth (only option) Deployments, environments
Claude in Chrome Browser extension Browser automation, page interaction

Tool Search (ENABLE_TOOL_SEARCH=true in settings.json env) defers tool loading on-demand, saving ~5k tokens per server by avoiding upfront schema loading. With 12+ servers, this saves ~60k tokens per session.


Repository Registry

/start TICKET-XXX auto-detects the target repository based on the ticket's Linear team prefix:

Repository Location Prefix(es) Base Branch Ship Method Commit Command
Magic Platform ~/Code/magic0-7 AUTM, MED, MYH, NEW, PLA, INT, CURE preview PR (/staging) /commit
MagicEA ~/Code/magicea TARS main PR (/deploy-ea) /commit
Freshell ~/Code/freshell FRE main PR (upstream maintainer) /commit
WordPress Sites ~/Code/wp WP main deploy.sh /commit
CompanyOS ~/Code/companyos-* COS main PR (review + merge) /co-commit
CEOS ~/Code/ceos CEO main Direct push /commit
Adventures in Claude ~/Code/adventuresinclaude AIC main Vercel auto-deploy /commit
Overwatch ~/Code/overwatch OVR main Direct push /commit
awsaudit ~/Code/awsaudit AWS main Direct push /commit
txvotes ~/Code/txvotes USV main Auto-deploy on merge /commit
Techstars OS ~/Code/techstarsos TOS main Contributor PR /commit
FeldSite ~/Code/feld.com FELD main Vercel auto-deploy /commit

BAF (Brad's Todos): Heterogeneous team — tickets can route to feld.com blog, AIC blog, CompanyOS, or other destinations. /start asks the user where to route each BAF ticket.

Deployment Models

Model Repos Post-Commit Status
Pipeline (3-tier) Magic Platform In Progress → /staging/production
Feature branch + deploy MagicEA In Progress → /deploy-ea
PR-based CompanyOS, Freshell, Techstars OS, txvotes In Progress → PR reviewed + merged
Direct-to-main CEOS, WP, awsaudit Done (commit IS the deploy)
Auto-deploy on push AIC, FeldSite Done (Vercel deploys on push)

CompanyOS: Multi-Repo Architecture

CompanyOS is an AI-first business operations system — Claude Code as the universal interface to all business systems. It spans three repositories in a tiered architecture:

Repository Structure

Repo Location Purpose
Core ~/Code/companyos Shared skills, rules, agents, scripts — the product
Config (Intensity Magic) ~/Code/companyos-config-intensitymagic Company-specific context, MCP registry, custom skills
Config (Foundry) ~/Code/companyos-config-foundry Foundry-specific context, custom skills (e.g., co-foundry-board-update)

Three-Level PR Hierarchy

Level 1: Local (uncommitted)
  User works in any clone — config or core repo

Level 2: Company config repo (companyos-config-*)
  /co-commit → direct push to main
  Skills available at company level immediately

Level 3: Core CompanyOS (companyos)
  GitHub Actions auto-creates a PR when skills/** change in config repo
  If accepted → skill available to all companies
  If rejected → stays company-specific only

propose-skills.yml GitHub Actions workflow detects skill changes in config repos and automatically creates cross-repo PRs using COMPANYOS_PAT.

Skill Activation Flow

  1. setup.sh symlinks skills/co-* from core repo into ~/.claude/skills/
  2. Config repo provides per-company co-company-context.md with contacts, conventions, systems
  3. Claude reads skill descriptions on session start, auto-invokes based on context
  4. Skill telemetry hook (co-skill-track.sh) logs invocations to Supabase

Skill Telemetry

Fully automatic. Two hooks track every skill invocation:

  • UserPromptSubmit hook: catches context-activated skills
  • PostToolUse (Skill) hook: catches explicitly invoked skills
  • Data stored in Supabase skill_invocations table
  • /co-skill-report generates weekly analytics
  • /auto-report uses streak data to identify automation candidates

Safety

  • Draft-first: External emails always start as drafts for human review
  • Audit logging: All external actions logged (emails, Stripe ops, support actions)
  • Voice profile: ~/.claude-personal/voice/voice-profile.md calibrates writing style (no hedging, no corporate language, uses hyphens)

Key Commands

Command Purpose
/co-commit Partitioned: PRs for core repo, direct push for config repos
/co-create-skill Generate new skill from description
/co-help List all CompanyOS capabilities
/co-plan Build prioritized daily plan
/co-recap Log session accomplishments
/co-recap-weekly Weekly rollup summary
/co-skill-report Skill usage analytics
/co-switch Switch company context
/co-test-gaps Detect untested setup.sh sections

CEOS: EOS Framework

Separate repository (~/Code/ceos) implementing the Entrepreneurial Operating System through Claude Code skills. Direct-to-main workflow (no feature branches).

21 skills covering all six EOS Key Components:

Component Skills
Vision ceos-vto (Vision/Traction Organizer), ceos-annual, ceos-quarterly-planning
People ceos-people (Core Values + GWC), ceos-accountability (Accountability Chart), ceos-trust, ceos-lma
Data ceos-scorecard, ceos-dashboard
Issues ceos-ids (Identify, Discuss, Solve), ceos-five-whys (via CompanyOS)
Process ceos-process, ceos-delegate
Traction ceos-rocks, ceos-todos, ceos-l10, ceos-quarterly, ceos-checkup

Plus: ceos-cashflow (8 financial levers), ceos-clarity (strategic thinking break), ceos-kickoff (EOS implementation sequence), ceos-assistance (daily delegation via The Stack).

All 21 skills symlinked from ~/Code/ceos/skills/ceos-*/ into ~/.claude/skills/.


Automated Jobs

CompanyOS includes autonomous Edge Functions running on pg_cron — these are NOT skills (Claude-interactive) or agents (Task-dispatch):

Job Schedule Purpose
email-agent Every 5 min (24/7) Gmail polling, Claude reply or task routing
daily-tasks-email Daily Team task digest email
support-agent Every 30 min HelpScout auto-triage
weekly-skill-report Fridays 4PM MT Skill usage analytics email
new-user-welcome On user INSERT Welcome email for new signups

Three execution models:

Model Trigger Human in Loop Location
Skills User invokes via Claude Code Yes skills/co-*/SKILL.md
Agents Claude dispatches via Task tool No (Claude orchestrates) .claude/agents/co-*.md
Automated Jobs pg_cron, webhooks, database triggers No supabase/functions/*/

Multi-Instance Safety (Worktrees)

8 worktrees (magic0-7) enable true parallel development. All are equal — when looping, always use 0 1 2 3 4 5 6 7.

Port Allocation

Formula: PORT = 3000 + (worktree × 10) + app_slot

App Slot magic0 magic1 magic4 magic7
AuthorMagic 0 3000 3010 3040 3070
MedicareMagic 1 3001 3011 3041 3071
IntensityMagic 2 3002 3012 3042 3072
MyHealthMagic 3 3003 3013 3043 3073
Book Sites 4 3004 3014 3044 3074
NewsletterMagic 5 3005 3015 3045 3075
CureCancerMagic 6 3006 3016 3046 3076

Configuration Sharing

Config Type Sharing Method
.env.local files Symlinked to magic0
Auto-memory Native CC v2.1.63 symlinks (memory/ dirs)
Rules, commands, docs Symlinked to magic0's .claude/
Agents Symlinked (restored for native discovery)
.claude/ file staging hash-object + update-index (never git add — resolves symlinks wrong)

Worktree commits always use --no-verify because pre-commit hooks re-stage files through symlinks, which auto-stages .claude/ file deletions. Verify afterward with git diff --name-status HEAD~1..HEAD | grep .claude/.


Blog and Learning Capture

Two capture modes write to the same daily notes file (~/.claude/blog/notes/YYYY-MM-DD.md):

Mode 1: Automatic (Insight Blocks)

Every ★ Insight block generated during work is silently appended to the daily notes file. No user notification. The user curates later.

Mode 2: Suggested (Discoveries)

When Claude discovers something interesting while working (not an insight block), it suggests capturing. Throttled to max 3 suggestions per hour, max 1 per category per hour.

Categories: gotcha, deep-dive, magic-trick, day-in-life, insight

Downstream Consumers

  1. /blogaic-draft — aggregates daily notes into blog post drafts
  2. /learn review — graduates patterns to permanent rules/skills

Git Workflow Rules

  • Never commit directly to main or preview (pre-commit hooks block). Exception: repos with direct_to_main: true
  • Branch naming: feature/TICKET-XXX-description, fix/, refactor/
  • Never bypass pre-commit with --no-verify except three documented exceptions:
    1. Merge commits during /staging or /production operations
    2. Pre-existing type errors in unrelated packages (document in commit message)
    3. Worktree symlink commits (magic1-7) — verify afterward
  • Force push: Always --force-with-lease, never --force
  • Attribution: Automatic via settings.json attribution setting — no manual Co-Authored-By needed
  • CI monitoring: Self-contained polling, never gh run watch (13K+ line output)
  • Production release: Sync preview with main using git merge -s ours

Coding Standards

TypeScript Strict Mode

  • Explicit types for function signatures, type guards for unknown
  • ?.trim() || "fallback" for database text (empty strings pass through ??)
  • prop?: T | undefined for exactOptionalPropertyTypes
  • Never define local interfaces when canonical types exist

Security

  • Parameterized queries only: db.query('...WHERE id = $1', [id])
  • Input validation with Zod at boundaries
  • Always .trim() env vars used as IDs or in equality comparisons

UI

  • Semantic color tokens always (text-foreground, bg-card) — never hardcoded Tailwind colors
  • Visual differences come from CSS variable values in each app's globals.css
  • <DateInput> from @platform/ui/date-input — never raw type="date" inputs

Database Migration Discipline

Golden rule: Git is the source of truth. Every migration must be:

  1. A file in supabase/migrations/
  2. Committed to git BEFORE any remote database has it
  3. Applied to environments via CI/CD (not manual SQL or MCP)

Idempotent Patterns

  • Tables/indexes: IF NOT EXISTS
  • RLS policies: DROP + CREATE (no native IF NOT EXISTS)
  • Every CREATE POLICY must include explicit TO clause (defaults to PUBLIC otherwise)
  • Every migration modifying existing tables: SET LOCAL statement_timeout = '30s'

Critical

  • ALTER ROLE SET REPLACES the entire value — always read current state via pg_options_to_table() before modifying. This caused a production outage when pgrst.db_schemas was overwritten.
  • RLS without policies = silent deny-all — always create policies in the same migration that enables RLS
  • USING(true) without TO clause grants access to ALL roles, defeating user-scoped policies

Secrets Management

Secrets stored in GCP Secret Manager. No persistent plaintext vault — sync scripts auto-regenerate from GCP SM on demand.

GCP SM naming: {section}_{service}_{key} (e.g., platform_supabase_preview)

Domain-scoped email keys: Each sending domain has its own Resend API key. Wrong key = silent send failure.

No trailing newlines: Use printf '%s' not echo for env values. Code must also .trim() env vars defensively.


Testing Patterns

Vitest 4 Signature (CRITICAL)

Options come BEFORE the test function:

it("slow test", { timeout: 15000 }, () => { ... });

Key Rules

  • Mock at abstraction level — mock the factory your code calls, not low-level SDKs
  • Never put async operations inside waitFor — they fire on every retry
  • vi.mock() path must match import path exactly
  • vi.clearAllMocks() doesn't drain once-value queues — use mockReset()
  • Class constructor mocks need actual classes, not arrow functions
  • jsdom v27: class-based ResizeObserver mock required

Critical Gotchas

  1. Stale .next cache (Next.js monorepos): Type-check fails on unmodified apps. Fix: find apps -name "validator.ts" -path "*/.next/*" -delete

  2. APFS directory hardlinks: Never use rm -rf on hardlinked directories — destroys data at both paths (PLA-448)

  3. Vercel CLI overwrites .env.local: Both vercel link and vercel env pull completely overwrite. Protection: store local-only vars in .env.development.local

  4. cn() silent failures: Tailwind's cn() silently drops invalid class names (hex codes, rgb values). Database color config must store Tailwind class names, not raw values.

  5. Nested Supabase joins with RLS: Fail silently. Use step-by-step queries instead of nested .select() with !inner

  6. ALTER ROLE SET replaces: See database migration section

  7. Reserved Bash variables: Avoid status, pipestatus, path — use alternatives

  8. OAuth tokens lost on updates: Only affects Vercel. All other MCP servers now use PAT/API key auth

  9. Worktree symlink staging: Never git add for .claude/ files in worktrees — resolves symlinks and stages wrong blob. Use hash-object + update-index.

  10. Linear MCP unified tools: save_issue replaces old create_issue/update_issue. save_comment replaces old create_comment. Parameter state not status. Labels replace, not append.


Quick Start for New Setup

  1. Create structure:

    mkdir -p ~/.claude/{rules,skills,commands,docs,hooks,blog/notes}
    mkdir -p ~/.claude-personal/{voice,plans}
  2. Configure settings.json with:

    • Permissions (allow/deny/ask patterns)
    • "ENABLE_TOOL_SEARCH": "true" in env
    • "attribution": {"commit": "Co-Authored-By: Claude <noreply@anthropic.com>"}
    • Hook definitions for lifecycle events
    • "enableAllProjectMcpServers": true
  3. Add MCP servers — prefer PAT/API key over OAuth. HTTP with Bearer tokens preferred.

  4. Install Superpowers plugin in enabledPlugins section

  5. Create core rules in ~/.claude/rules/: evidence-first, code-quality, commit-recipe, review-triage, scope-intent, protected-workflows, output-formatting, reasoning-calibration

  6. Extract reference material into ~/.claude/docs/ with an on-demand-references.md index rule

  7. Write global CLAUDE.md in ~/.claude-personal/ documenting developer context, workflow discipline, repository registry

  8. Add project-level rules with frontmatter globs for conditional loading

  9. Verify: claude mcp list, inspect rules/skills/hooks, run /global-status


Key Insights

Architecture

  1. Session state solves context amnesia.claude-session/ creates "process memory" surviving compaction
  2. Three-layer token budget: Always-loaded rules (minimal) → on-demand docs (loaded when needed) → hooks (zero tokens unless triggered). Each layer reduces baseline context cost.
  3. Conditional rule loading via frontmatter globs prevents loading irrelevant project rules in a multi-app monorepo
  4. Hooks replace rules for error handling — a PostToolUse hook fires only when needed vs. a rule consuming tokens every session
  5. Tool Search transforms MCP economics — lazy loading saves ~5k tokens per server, ~60k total

Workflow

  1. Review triage saves tokens without sacrificing quality — NONE/LIGHT/FULL based on change characteristics
  2. /simplify as pre-review step — fix code quality issues before reviewers report on them
  3. Workflow Profiles make commands project-agnostic across twelve repositories
  4. Chain mode enables batch ticket processing via /start-chain
  5. Model tiering — Opus for primary work, Sonnet for plans/reviews, Haiku for exploration

Configuration

  1. Global-first reduces cognitive load and drift across worktrees
  2. PAT/API key auth over OAuth eliminates reauth-on-update problems
  3. Attribution setting eliminates manual co-author lines in commits
  4. Evidence-first prevents confident wrong answers — tools before conclusions

CompanyOS & CEOS

  1. CompanyOS evolved from shared config to operating system — three-repo architecture with automated cross-repo PR proposals
  2. Config repos implement multi-tenancy — per-company context on top of shared core skills
  3. Three execution models: Skills (human-interactive), Agents (Claude-orchestrated), Automated Jobs (autonomous)
  4. CEOS as separate concern — business operations (co-) vs management framework (ceos-)
  5. Skill telemetry creates data-driven automation decisions — streak tracking → /auto-report

Hard-Won Lessons

  1. ALTER ROLE SET is a replace operation — a production outage teaching moment
  2. APFS hardlinks share datarm -rf destroys both paths
  3. Worktree symlinks need special staginggit add resolves symlinks, hash-object doesn't
  4. Self-describing data prevents drift — adding items never requires script changes
  5. Voice profile calibration produces natural-sounding communications matching individual style
@philsimon
Copy link

This list is very impressive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment