convez.ai
SkillDesenvolvimento WebAvançado
ketzal88

Claude Code Framework para SaaS em Produção

ketzal88/claude-code-framework

Configuração completa de Claude Code com automação, rules e AST para SaaS

Ver no GitHub
InicialPluginScore · de 0 a 100

Framework completo de configuração do Claude Code para SaaS em produção, incluindo regras, hooks, comandos slash, enforcement de AST, workflow de desenvolvimento e execução paralela. Engloba 12 comandos, 7 subagentes diagnósticos, 6 regras AST e 8 hooks automatizados para garantir zero erros de TypeScript e regressões.

Instalação

$npx convez-ai ketzal88/claude-code-framework

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 5 dias
Versão
—
Issues abertas
0
Contribuidores
1

Casos de uso

  • Estruturar workflow de desenvolvimento com Claude para projetos Next.js em produção
  • Automatizar verificações de código, testes e deploys via comandos slash
  • Enforçar padrões de arquitetura (funções puras, TDD, contratos de computação)
  • Prevenir regressões com hooks automáticos e checkpoints de commit
  • Escalar equipes implementando guardrails e workflows codificados em arquivos

Veredito

Framework robusto e bem documentado para times que rodam Claude em produção. Exige disciplina e adaptação, mas elimina classes inteiras de bugs e inconsistências através de automação e regras claras. Vale a pena para equipes sérias com TypeScript + Firebase + Vercel.

README

A tradução para o português deste README ainda está na fila.

Claude Code Setup Guide — Worker Brain

How we configured Claude Code for a production Next.js 14 + Firebase + Vercel SaaS. 12 slash commands, 7 diagnostic subagents, 6 AST rules, 8 automated hooks (incl. two blocking Stop-hook ratchets — dead-code + design-contract), and an auto-routing operating procedure so the methodology runs without the operator invoking anything. Zero TS errors policy, pure-computation engines, TDD discipline, and a commit-checkpoint workflow that blocks regressions.


Table of Contents

  1. Philosophy
  2. Directory Structure
  3. CLAUDE.md — The Brain
  4. Rules (.claude/rules/)
  5. Slash Commands (.claude/commands/)
  6. Hooks (.claude/settings.json)
  7. Subagents
  8. Skills
  9. AST Rules (Static Analysis)
  10. How It All Connects
  11. Plugins & Development Workflow Skills
  12. Adapting This for Your Project

Philosophy

Four principles drive this setup:

  1. Teach, don't repeat. Rules go in files, not in your head. Every time you correct Claude, turn the correction into a rule so it never happens again.
  2. Automate the guardrails. Hooks run automatically on every edit/commit/push — Claude can't forget to check.
  3. Pure functions are testable functions. Any business logic engine must be pure computation (no DB access, no new Date()) — receives all data via input, returns results.
  4. Commands encode workflows. Multi-step processes (safe commit, new alert scaffolding, index deploy) become one-line slash commands.

Directory Structure

.claude/
├── CLAUDE.md                          # Main brain — architecture, patterns, reference tables
├── settings.json                      # Hooks (auto-run on edit/commit/push)
├── rules/
│   ├── operating-procedure.md         # Auto-router: Claude picks the sequence by task size + type
│   ├── alert-engine-pattern.md        # Pure-computation contract for engines
│   ├── cron-security.md               # Auth + error handling for crons
│   └── firestore-conventions.md       # Doc IDs, batching, index rules
├── commands/
│   ├── ts-check.md                    # /ts-check — TypeScript verification
│   ├── test-alerts.md                 # /test-alerts — alert engine unit tests
│   ├── commit-checkpoint.md           # /commit-checkpoint — safe commit workflow
│   ├── new-alert.md                   # /new-alert — scaffold new alert type
│   ├── new-channel-sync.md            # /new-channel-sync — scaffold new integration
│   ├── env-check.md                   # /env-check — validate env vars
│   ├── deploy-indexes.md              # /deploy-indexes — safe Firestore index deploy
│   ├── audit-parity.md               # /audit-parity — data drift detection
│   ├── client-health.md              # /client-health — per-client health snapshot
│   ├── slack-preview.md              # /slack-preview — digest dry-run
│   ├── backfill-client.md            # /backfill-client — data backfill with safety
│   └── prompt-version.md            # /prompt-version — AI prompt versioning
└── skills/
    └── worker-ast-rules/              # AST-based static analysis rules
        ├── SKILL.md
        ├── sgconfig.yml
        ├── scan.sh
        └── rules/
            ├── no-firestore-in-evaluate.yml
            ├── cron-requires-auth.yml
            ├── cron-must-declare-maxDuration.yml
            ├── no-hardcoded-conversion-metric.yml
            ├── no-console-error-swallow.yml
            └── no-null-as-delete-sentinel.yml

CLAUDE.md — The Brain

The main CLAUDE.md is the entry point Claude reads every conversation. It contains:

What goes here

  • Stack and env vars — so Claude knows the tech without asking
  • Database schema — collection names, doc ID patterns, relationships
  • Architectural patterns — the 5-6 core patterns everything follows
  • Reference tables — alert types, cron schedule, navigation routes
  • Testing commands — exact bash commands to run tests
  • Pointers to modular rules — @.claude/rules/alert-engine-pattern.md syntax

What does NOT go here

  • Implementation details (that's in the code)
  • Tutorials or explanations (Claude already knows TypeScript/Next.js)
  • Things that change weekly (use memory for that)

Key pattern: Modular Rules

Instead of a 500-line CLAUDE.md, we split domain rules into focused files:

## Modular Rules

@.claude/rules/firestore-conventions.md
@.claude/rules/alert-engine-pattern.md
@.claude/rules/cron-security.md

The @ syntax imports the file's content into CLAUDE.md context. Each rule file is self-contained and referenceable by hooks and commands.


Rules

Rules define invariants that must always hold. They're the laws of the codebase.

Rule 1: Alert Engine Pattern (alert-engine-pattern.md)

Core contract:

class SomeAlertEngine {
  static evaluate(input: AlertEvaluationInput): Alert[] {
    // zero DB access — all data is in `input`
    // zero network calls
    // zero time-dependence (referenceDate is injected)
  }
}

Why: Makes every engine unit-testable without mocks. Both the cron path and the snapshot path share the exact same logic.

Enforced by: AST rule no-firestore-in-evaluate, hook reminder on engine file edit, /test-alerts command.

Rule 2: Cron Security (cron-security.md)

Four non-negotiable requirements:

  1. validateCronSecret() as the FIRST call
  2. withErrorReporting() wrapper
  3. Idempotent operations (upserts, deterministic doc IDs)
  4. Explicit maxDuration export

Why: Every cron route is public-routable on Vercel — there's no "internal only."

Enforced by: AST rules cron-requires-auth + cron-must-declare-maxDuration, hook reminder on cron file edit.

Rule 3: Firestore Conventions (firestore-conventions.md)

  • Doc ID patterns: 4 standard formats, never invent new ones
  • Initialization: ignoreUndefinedProperties: true — undefined is stripped, null is stored
  • Sub-source detection: always via rawData.source, never infer from clientId
  • Batch limits: 500 per batch, BulkWriter for more
  • Indexes: add BEFORE shipping — queries silently fail without them

Enforced by: AST rule no-null-as-delete-sentinel, hook reminder on service file edit.


Slash Commands

Commands encode multi-step workflows into one-line invocations.

Development Workflow

CommandPurposeKey Behavior
/ts-checkRun tsc --noEmitReports errors grouped by file, doesn't fix
/test-alertsRun alert engine unit testsParses output, maps failures to engine files
/commit-checkpointSafe commitRuns ts-check + test-alerts before allowing commit

Scaffolding

CommandPurposeKey Behavior
/new-alertScaffold new alert typeCreates engine method, test, docs row, wiring — leaves predicate as TODO
/new-channel-syncScaffold channel integrationService, cron, OAuth, types, docs — full skeleton

Operations

CommandPurposeKey Behavior
/env-checkValidate env varsCross-references CLAUDE.md docs vs .env.local, never prints values
/deploy-indexesDeploy Firestore indexesDiffs local vs deployed, blocks on removed indexes
/audit-parityData drift detectionCompares stored snapshots vs live API — read-only
/client-healthClient health snapshotData freshness, alerts, cron failures — one screen
/slack-previewPreview digestRenders morning/weekly/monthly without posting
/backfill-clientData backfillSafety checks, dry-run support, budget tracking
/prompt-versionAI prompt versioningStaging → production workflow with diff and token estimates

Command Anatomy

Every command is a markdown file with YAML frontmatter:

---
description: One-line description shown in /help
argument-hint: [optional] [--flags] <required>
---

Context for Claude about what this command does.

Steps:
1. Specific step with exact bash command
2. Parse and report
3. Safety checks

Never <thing that would be dangerous>.

Design principles:

  • Commands are diagnostic by default — they report, they don't fix (unless explicitly asked)
  • Safety rails are built in — /commit-checkpoint blocks on test failures, /deploy-indexes blocks on index removal
  • Each command references the rules it enforces

Hooks

Hooks run automatically via .claude/settings.json. They fire on specific tool events.

Hook 1: File Change Reminders (PostToolUse on Edit/Write)

When Claude edits a file, context-aware reminders appear:

File PatternReminder
src/lib/alert-engines/*.ts"Run /test-alerts before committing"
/api/cron/**/route.ts"Verify validateCronSecret() + withErrorReporting()"
firestore.indexes.json"Use /deploy-indexes to diff before deploying"
*-service.ts in src/lib/"Consider running /audit-parity"

Hook 2: Error Reporting Check (PostToolUse on Edit/Write)

Runs scripts/check-error-reporting.js on any API route file edit. Advisory — warns if withErrorReporting / reportError / validateCronSecret is missing.

Hook 3: Secret Leak Prevention (PostToolUse on Bash git commit)

Runs scripts/check-no-secrets.sh before every commit. Blocking — exit code 1 stops the commit if secrets are detected.

Hook 4: Pre-Push Reminder (PostToolUse on Bash git push)

Advisory reminder to run npm run test:pre-push (TypeScript + alerts + pure function tests).

Hook 5: Critical Utility Change (PostToolUse on Edit/Write)

When objective-utils.ts, date-utils.ts, or cron-auth.ts is changed, reminds to run npm run test:unit.

Hook 6: Dead-Code Ratchet (Stop hook) — blocking

Before Claude ends a turn, runs knip and compares orphan count vs a committed baseline (.dead-code-baseline.json). If the count grew — new orphan exports, files, types, or unused deps — the Stop is blocked and Claude is forced to clean up before really finishing.

Why a Stop hook instead of a nightly cron? The original idea was a nightly "slop-cleaner" that batch-cleans dead code. But the real fix is at the source: don't let dead code reach the end of a turn. Stop hooks catch regressions at the exact moment Claude says "done" — before the operator ever sees the result.

Philosophy: same as the any-ratchet. The baseline is the floor. The count can only go down. When the total drops (intentional cleanup), regenerate the baseline.

What it catches:

  • Orphan exports / types with no consumer
  • Files never imported by anything
  • package.json dependencies not actually used
  • Duplicates, unlisted deps, unresolved imports

Skip conditions (safe no-ops):

  • No .ts/.tsx/.js changes in the working tree (nothing to check — saves ~5s per idle turn)
  • SKIP_DEADCODE=1 env var (explicit bypass)
  • knip or baseline missing (hasn't been adopted yet)
  • knip times out or crashes (never block on tooling bugs)

Adoption (one-time setup for a new project):

# 1. Install knip
npm install -D knip

# 2. Copy the two scripts from this repo into yours
cp examples/scripts/check-dead-code-baseline.js <your-repo>/scripts/
cp examples/scripts/stop-dead-code-guard.py    <your-repo>/scripts/

# 3. Copy the knip config template — edit entry points to match your project
cp examples/knip.example.json <your-repo>/knip.json

# 4. Add npm scripts to package.json:
#    "check:dead-code":    "node scripts/check-dead-code-baseline.js",
#    "dead-code-baseline": "node scripts/check-dead-code-baseline.js --write",

# 5. Freeze the initial baseline (commit .dead-code-baseline.json)
npm run dead-code-baseline

# 6. Add Stop hook to .claude/settings.json (see snippet below)

Stop hook snippet for .claude/settings.json:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python scripts/stop-dead-code-guard.py",
            "timeout": 90
          }
        ]
      }
    ]
  }
}

Workflow when the ratchet blocks:

  1. Claude sees stderr with the list of new orphans + file paths
  2. Either (a) delete the orphan, (b) wire it to a consumer, or (c) run npm run dead-code-baseline if OTHER files were cleaned up and the total dropped
  3. Claude is free to stop the turn

Why this beats a nightly cleaner: it's the exact moment the code was introduced — no investigation needed, no "whose orphan is this", no batch noise a week later.

Hook 7: Design-Contract Ratchet (Stop hook) — blocking

The second Stop-hook ratchet (same philosophy as dead-code, different floor). Before Claude ends a turn that touched a .tsx, scripts/check-design-baseline.js scans the product-register UI for visual-contract violations and blocks if the count grew vs .design-baseline.json.

It enforces the three deterministic non-negotiables of a design system — for this project: no box-shadow, no arbitrary rounded-[…] radius, no gradient text. The key design choice is high precision over recall: a blocking gate must never false-positive, so it only flags unambiguous Tailwind utilities and leaves the judgment calls (e.g. "accent color ≤ 8% of the screen") to an on-demand visual audit. Brand/marketing surfaces are exempt by path.

cp examples/scripts/check-design-baseline.js <your-repo>/scripts/
cp examples/scripts/stop-design-guard.py     <your-repo>/scripts/
# package.json: "check:design": "node scripts/check-design-baseline.js",
#               "design-baseline": "node scripts/check-design-baseline.js --write"
npm run design-baseline   # freeze the floor (commit .design-baseline.json)

Adopting it: edit the regex rules in check-design-baseline.js to your own design contract, and the brand-exempt path list. Everything else (baseline diff, Stop hook, bypass via SKIP_DESIGN=1) is identical to the dead-code ratchet.

Hook 8: Cron Doc-Sync (PostToolUse) — advisory

Documentation drifts silently. This gate keeps a reference table in CLAUDE.md honest against its source of truth. When the cron schedule file changes, scripts/check-cron-doc-sync.js diffs the /api/cron/<name> endpoints between the workflow file and the CLAUDE.md cron table, and surfaces a reminder only on drift (silent when in sync). It runs both as a PostToolUse hook (in Claude's sessions) and in CI — so it covers manual edits too, not just Claude-driven turns. Name-level only; schedules and descriptions stay human-reviewed.

Settings File Structure

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "python -c \"...\"" }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "python -c \"...\"" }
        ]
      }
    ]
  }
}

Design principles:

  • Advisory hooks use stderr output (visible to Claude but don't block)
  • Blocking hooks use non-zero exit codes
  • All hooks are Python one-liners that parse JSON stdin (the tool use event)
  • Never use hooks for complex logic — keep them under 5 lines

Operating Procedure (Auto-Routing)

The hardest problem with a setup this size isn't building the commands — it's that a non-technical operator will never invoke them. Twelve slash commands that nobody types are dead weight. The fix is to stop treating the methodology as buttons and encode it as a router that Claude reads every session and applies on its own.

@.claude/rules/operating-procedure.md is that conductor. It does two things:

1. Triage by size first (the safety valve). Without this, a "think → plan → build → review → ship" methodology turns every "what does this function do?" into a five-step ritual. The router opens with: is this trivial? → answer directly, no ceremony. The heavy sequence is reserved for substantial work. This single rule is the difference between a methodology that helps and one that gets in the way.

2. Route by work type. For substantial work, a table maps work type → ordered gates: a UI change implies "implement → smoke-test → design ratchet"; a new engine implies "pure evaluate() + test in the same change"; a cron implies "auth + idempotency + keep the doc table in sync". Claude announces the chosen sequence in one line ("this is UI → I'll implement and smoke-test before closing") and follows it.

The operator never picks a command. They watch the methodology happen and interrupt when they want. The slash commands still exist — they're just the implementation of each routed step, not something a human has to remember to press.

This is the layer that makes everything above it actually run. Rules document invariants, hooks enforce them automatically, commands encode workflows — and the operating procedure decides which of them to apply, scaled to the task, without waiting to be asked.


Subagents

Diagnostic agents that spawn with specialized context. All are read-only — they investigate, never modify.

AgentPurposeWhen to Use
channel-sync-debuggerData parity between API fetches and Firestore"Google Ads dashboard shows $500 but snapshot has $470"
alert-engine-testerAlert logic tracing"Why isn't CPA_SPIKE firing for client X?"
meta-creative-debuggerCreative decision explanation"Why did ad 123 get killed?"
ecommerce-platform-specialistShopify/TN/WooCommerce issues"Tiendanube orders aren't syncing"
ai-analyst-prompt-engineerSystem prompt debugging"The meta_ads analyst is giving generic answers"
firestore-query-builderQuery design + index planning"Build me a query for channel_snapshots from last 30 days"
cron-health-doctorCron failure correlation"Morning briefing has been failing for 3 days"

When to create a subagent:

  • The diagnosis requires reading 5+ files and cross-referencing data
  • You find yourself repeating the same investigation pattern
  • The task is read-only (never create subagents that modify code)

Skills

Skills are larger knowledge bundles that auto-activate based on task context.

SkillPurpose
worker-brain-guideOverall architecture — auto-activates on codebase questions
worker-firestoreDoc ID patterns, indexes, batch write limits
worker-cronCron skeleton, auth, idempotency, timeout patterns
worker-slack-formattingDigest formatting, threads, anti-noise budget
worker-ast-rulesStatic analysis — ast-grep rules for architectural invariants

Skill vs Rule vs Command:

  • Rule: an invariant that must always hold (law)
  • Command: a workflow you invoke explicitly (tool)
  • Skill: domain knowledge that activates contextually (expertise)

AST Rules

Static analysis via ast-grep that enforces architectural invariants structurally (not textually — it parses the AST).

Rules Shipped

RuleSeverityWhat It Catches
no-firestore-in-evaluateerrordb.collection() inside any evaluate() method
cron-requires-autherrorCron route missing validateCronSecret reference
cron-must-declare-maxDurationwarningCron route without export const maxDuration
no-hardcoded-conversion-metricwarningDirect metrics.purchases / metrics.leads instead of getPrimaryMetric()
no-console-error-swallowwarningcatch block with only console.error (should use reportError)
no-null-as-delete-sentinelwarning.update({ field: null }) should use FieldValue.delete()

Running

bash .claude/skills/worker-ast-rules/scan.sh        # Full scan
ast-grep scan --rule rules/no-firestore-in-evaluate.yml  # Single rule

When to Add a Rule

All three must be true:

  1. The invariant is already documented in .claude/rules/*.md
  2. You've seen it violated at least once
  3. The violation is structural (code shape), not semantic (logic)

How It All Connects

User types: /commit-checkpoint
    │
    ├─ Command reads its .md definition
    ├─ Step 1: git diff --stat (what changed?)
    ├─ Step 2: if alert-engine files → /test-alerts
    ├─ Step 3: /ts-check
    ├─ Step 4: propose commit message
    ├─ Step 5: git commit
    │     │
    │     └─ Hook fires: check-no-secrets.sh (blocking)
    │
    └─ Done. User reviews.

User edits: src/lib/alert-engines/google-alert-engine.ts
    │
    ├─ Hook fires: "Run /test-alerts before committing"
    ├─ Hook fires: check-error-reporting.js (advisory)
    │
    └─ On next commit, /commit-checkpoint will catch regressions

User asks: "Why isn't CPA_SPIKE firing for client X?"
    │
    ├─ Subagent: alert-engine-tester spawns
    ├─ Reads engine code + test fixtures
    ├─ Traces the evaluate() logic
    │
    └─ Reports: threshold is 30% but client's delta is 28%

The Enforcement Pyramid

         ┌─────────┐
         │  Hooks   │  ← Automatic, every action
         │ (block)  │
         ├──────────┤
         │ AST Rules│  ← On-demand or CI, structural
         │ (scan)   │
         ├──────────┤
         │ Commands │  ← User-invoked workflows
         │ (/slash) │
         ├──────────┤
         │  Rules   │  ← Always-loaded context
         │ (.md)    │
         ├──────────┤
         │ CLAUDE.md│  ← Architecture + reference
         └──────────┘

Each layer reinforces the ones below it:

  • CLAUDE.md teaches Claude the patterns
  • Rules encode the invariants
  • Commands execute the verification workflows
  • AST rules catch structural violations
  • Hooks make enforcement automatic

Plugins & Development Workflow Skills

Beyond the project-specific setup, we use several Claude Code plugins that add development workflow discipline. These are installable plugins — they work across any project.

Superpowers Plugin

The superpowers plugin adds 14 skills that enforce disciplined software development. They auto-activate based on context — you don't invoke them manually.

The Development Lifecycle

  Idea → Brainstorming → Writing Plans → Executing Plans → Verification → Finishing Branch
           ↓                                    ↓
     systematic-debugging              requesting-code-review
     (if bugs found)                   receiving-code-review

Core Skills

SkillWhen It ActivatesWhat It Enforces
brainstormingBefore any creative work — features, components, modificationsExplores intent, proposes 2-3 approaches with trade-offs, gets design approval BEFORE any code is written. Hard gate: no implementation until design is approved.
writing-plansAfter brainstorming produces a specCreates bite-sized implementation plans (2-5 min per step). Each step is one action: write test → verify it fails → implement → verify it passes → commit. Plans are saved to docs/superpowers/plans/.
executing-plansWhen a written plan existsLoads plan, executes task-by-task with checkpoints. Stops on any blocker instead of guessing. Marks progress via TodoWrite.
test-driven-developmentBefore writing any implementation codeRed-Green-Refactor cycle. Iron law: no production code without a failing test first. If you wrote code before the test? Delete it. Start over.
systematic-debuggingOn any bug, test failure, or unexpected behaviorFour phases: (1) Root cause investigation, (2) Hypothesis formation, (3) Targeted fix, (4) Verification. Iron law: no fixes without root cause investigation first.
verification-before-completionBefore claiming work is doneIron law: no completion claims without fresh verification evidence. "Should pass" is not evidence — run the command and show the output.
dispatching-parallel-agentsWhen facing 2+ independent tasksOne agent per independent problem domain. Prevents sequential investigation of unrelated failures.
requesting-code-reviewAfter completing a featureTriggers a code review subagent to validate work meets requirements.
receiving-code-reviewWhen getting review feedbackRequires technical verification of suggestions before implementing — no blind agreement.
finishing-a-development-branchWhen implementation is completeGuides merge/PR/cleanup decision with structured options.
using-git-worktreesBefore feature work needing isolationCreates isolated git worktrees for parallel development.
subagent-driven-developmentFor plans with independent tasksDispatches parallel agents for non-blocking tasks in the plan.
writing-skillsWhen creating new skillsMeta-skill for authoring well-structured skills.

Key Design Principles

  1. Hard gates over soft suggestions. "No code before design approval" is enforced, not suggested.
  2. Iron laws are non-negotiable. Each skill has one — the thing that, if violated, invalidates the entire workflow.
  3. Auto-activation over manual invocation. Skills fire based on context, not user memory.
  4. Chained skills. Brainstorming → writing-plans → executing-plans → finishing-branch is a pipeline where each step invokes the next.

Hookify Plugin

Hookify creates behavioral rules that trigger on specific events. Unlike settings.json hooks (which run shell commands), hookify rules are markdown files that inject context or warnings into the conversation.

Rule Format

---
name: warn-dangerous-rm
enabled: true
event: bash
pattern: rm\s+-rf
---

STOP. You are about to run a recursive force-delete.
Verify the path is correct and not a parent directory.

Event Types

EventTriggers On
bashBash tool commands
fileEdit, Write, MultiEdit tools
stopWhen agent wants to stop working
promptWhen user submits a prompt
allAll events

Actions

  • warn (default) — Shows the message but allows the operation
  • block — Prevents the operation entirely

Rules are stored as .claude/hookify.{rule-name}.local.md files (gitignored by default — personal preferences).

Learning & Explanatory Mode

We run Claude Code in learning mode — a combination of interactive learning with educational explanations. This is configured via session settings (not a plugin).

What It Does

Before and after writing code, Claude provides educational insights:

★ Insight ─────────────────────────────────────
The functional core / imperative shell pattern keeps all side effects
at the boundary. evaluate() is pure computation — run() is the shell
that fetches data and injects dependencies like referenceDate.
─────────────────────────────────────────────────

When It Requests User Code Contributions

Instead of implementing everything, Claude identifies spots where the user's input matters:

  • Business logic with multiple valid approaches
  • Error handling strategies
  • Algorithm choices
  • UX decisions

It creates the file with context, adds function signatures, and asks the user to write 5-10 lines of meaningful code. Not busy work — decisions that shape the feature.

Other Useful Plugins

PluginPurpose
frontend-designProduction-grade UI with high design quality, avoids generic AI aesthetics
claude-code-setupAnalyzes codebase and recommends automations (hooks, skills, subagents)
claude-md-managementAudits and improves CLAUDE.md files
plugin-devTools for creating your own plugins (agents, commands, skills, hooks)
skill-creatorMeta-skill for creating and testing new skills
playgroundCreates interactive HTML playgrounds for visual configuration

GSD (Get Shit Done) — Project-Scale Orchestration

GSD is a full project management framework for Claude Code. While superpowers handles individual feature development (brainstorm → plan → execute), GSD handles multi-phase project delivery with roadmaps, milestones, and parallel agent execution.

When to Use GSD vs Superpowers

ScenarioUse
Single feature or bug fixSuperpowers (brainstorm → plan → execute)
Multi-phase project (5+ phases, dependencies)GSD (roadmap → phases → wave execution)
Greenfield project setupGSD /gsd:new-project
Quick task, no planning neededGSD /gsd:fast or just do it

The GSD Lifecycle

/gsd:new-project → /gsd:discuss-phase → /gsd:plan-phase → /gsd:execute-phase → /gsd:verify-work
      │                    │                    │                    │
      ▼                    ▼                    ▼                    ▼
  PROJECT.md          Discussion           Research             Wave-based
  ROADMAP.md          + assumptions         → Plan              parallel
  STATE.md            gathering             → Verify            execution

Research-First Planning (/gsd:plan-phase)

GSD doesn't jump to planning — it researches first:

  1. Research phase — A gsd-phase-researcher agent investigates the technical approach, reads docs, checks APIs, and writes RESEARCH.md
  2. Planning phase — A gsd-planner agent reads the research and creates detailed PLAN.md files with task breakdown
  3. Plan verification — A gsd-plan-checker agent reviews the plan against the phase goal (goal-backward analysis)
  4. Revision loop — If the checker finds issues, the planner revises (max 3 iterations)

Each step is a separate subagent with fresh context — the orchestrator stays lean and coordinates.

Wave-Based Parallel Execution (/gsd:execute-phase)

This is where GSD shines. Instead of executing tasks sequentially, it groups plans into waves based on dependencies:

Phase 5: Authentication System
├── Wave 1 (parallel — no dependencies)
│   ├── Plan 01: Database schema + migrations      → Agent A (worktree)
│   └── Plan 02: Auth provider integration          → Agent B (worktree)
├── Wave 2 (parallel — depends on Wave 1)
│   ├── Plan 03: API middleware                     → Agent C (worktree)
│   └── Plan 04: Session management                 → Agent D (worktree)
└── Wave 3 (sequential — depends on Wave 2)
    └── Plan 05: E2E auth flow tests                → Agent E (worktree)

How it works:

  1. Discover plans — Reads all PLAN-*.md files in the phase directory
  2. Analyze dependencies — Groups plans into waves by dependency order
  3. Spawn parallel agents — Each plan gets a gsd-executor subagent in an isolated git worktree (no merge conflicts)
  4. Wait for wave completion — Spot-check via SUMMARY.md + git log (handles signal failures)
  5. Post-wave hooks — Run pre-commit hooks once after all agents finish (they commit with --no-verify to avoid contention)
  6. Next wave — Only starts after all plans in the current wave complete

Key design decisions:

  • Worktree isolation — Each agent gets its own copy of the repo. No merge conflicts between parallel agents.
  • Orchestrator stays lean — Passes file paths, not content. Agents read files with their fresh context window.
  • Spot-check fallback — If an agent's completion signal is lost, the orchestrator checks for SUMMARY.md and recent commits to verify success.
  • Interactive mode — --interactive flag runs plans sequentially inline (no subagents) with user checkpoints between tasks. Lower token usage, good for small phases.

Other GSD Commands Worth Knowing

CommandPurpose
/gsd:fastInline execution for trivial tasks — no subagents, no planning overhead
/gsd:autonomousRun all remaining phases automatically (discuss → plan → execute per phase)
/gsd:debugSystematic debugging with persistent state across context resets
/gsd:map-codebaseParallel codebase analysis — spawns mapper agents by focus area
/gsd:verify-workConversational UAT — validates features through goal-backward analysis
/gsd:resume-workRestores context from previous session via STATE.md
/gsd:managerInteractive command center for managing multiple phases

What GSD Teaches About Scaling Claude Code

Even if you don't use GSD directly, its patterns are worth adopting:

  1. State files beat conversation memory. STATE.md persists across sessions. Claude can resume from where it left off without re-reading the entire conversation.
  2. Orchestrator ≠ executor. The agent that coordinates should NOT be the one writing code. Keep orchestration lean (file paths, not content).
  3. Worktrees solve parallel conflicts. isolation: "worktree" gives each agent its own branch and working directory — zero merge conflicts.
  4. Goal-backward verification. Don't check "did the tasks complete?" — check "does the codebase achieve the phase goal?" These are different questions.
  5. Research before planning, planning before execution. Three separate agents, three separate context windows. Each one is focused.

Installing Plugins

# Install from the official registry
claude plugins install superpowers
claude plugins install hookify
claude plugins install frontend-design

# GSD uses a different install method
# See: https://github.com/coleam00/gsd

Plugins are global (not per-project). Their skills auto-activate across all your projects based on task context.


Adapting This for Your Project

  1. Install superpowers first. claude plugins install superpowers — gives you brainstorming, TDD, verification, and debugging discipline for free across all projects.
  2. Start with CLAUDE.md. Document your stack, patterns, and the 3-5 rules that matter most.
  3. Extract rules. When you correct Claude twice for the same thing, create a .claude/rules/ file.
  4. Add commands. When you run the same 3 commands in sequence repeatedly, make a slash command.
  5. Wire hooks. When a rule gets violated despite documentation, add a hook that reminds or blocks.
  6. AST rules last. Only when you have documented rules that keep getting violated structurally.
  7. Build skills for your domain. When Claude needs specialized knowledge (your API, your database patterns, your team's conventions), create a skill.

The goal is not maximum configuration — it's zero repeated corrections.


Swarm / Multi-Agent Patterns

Beyond using plugins for parallel execution, we built a reactive event layer in our production app that lays the foundation for autonomous agent chains. These patterns apply to any system where multiple AI agents need to coordinate.

The Problem

Before scaling agent chains (critic loops, fan-out digests, autonomous diagnostics), you need two things:

  1. Cost visibility — without per-feature cost tracking, "the swarm will pay for itself via cache hits" is a guess, not a number.
  2. A shared signal bus — agents need to react to "what happened" without re-reading entire databases.

Pattern 1: Brain Events (Signal Blackboard)

A shared brain_events collection where any service can fire-and-forget a business-level signal:

// Alert engine emits after evaluation
await BrainEventsService.record({
  clientId: "abc123",
  kind: "alert",
  channel: "META",
  severity: "critical",
  code: "CPA_SPIKE",
  message: "CPA jumped 45% vs 7d average",
  source: "meta-alert-engine",
  dedupeKey: "abc123:CPA_SPIKE:2026-04-16",  // idempotent
});

Key design decisions:

DecisionWhy
Fire-and-forget (never throws)Producers don't know or care who consumes the event
dedupeKey as doc IDRetried crons don't double-write — same key = upsert
Post-filter in memoryAvoids one composite index per filter dimension
consumed + consumedBy fieldsDigests mark events as seen so the next run skips them
cleanupOldRecords(45)Weekly cron garbage-collects — the collection doesn't grow forever
BulkWriter for recordMany()Alert engines produce 10-30 events per run — batch writes

Consumers:

  • Morning briefing queries since(lastRunTimestamp) instead of re-scanning all snapshots
  • AI Analyst includes recent events in context XML for zero-shot awareness
  • Future: Cron Doctor reads kind: "cron" events to detect failure patterns

Pattern 2: LLM Cost Tracking

Every Claude/Gemini call gets a row in llm_usage_events with tokens, cost, and feature attribution:

await LlmUsageTracker.track({
  feature: "ai-analyst",
  step: "diagnose",
  clientId: "abc123",
  provider: "anthropic",
  model: "claude-sonnet-4-6",
  inputTokens: 12500,
  outputTokens: 890,
  cachedInputTokens: 10200,   // prompt cache hit
  durationMs: 3400,
  stopReason: "end_turn",
});
// costUsd computed automatically from built-in price table

Why this matters for agent chains:

  • Before adding a critic loop (Haiku reviews Sonnet's output), you need to prove the base cost
  • "Feature X costs $0.03/call with 80% cache hits" → adding a $0.008 Haiku critic is justified
  • Without this data, every agent chain proposal is vibes

Price table is in-code, not a config file — one source of truth, includes cache read/write multipliers.

Pattern 3: Context Cache (Two-Tier)

For the AI Analyst, each question rebuilds context from Firestore (10-50 reads). A two-tier cache eliminates redundant reads within a session:

Tier 1: In-process LRU Map (sub-ms, zero Firestore cost, dies with Lambda)
Tier 2: Firestore doc with TTL (shared across instances, survives recycles)

TTL is 5 minutes — short because ad metrics move fast. Better to re-read than serve stale data during diagnosis.

Invalidation API exists but isn't wired yet — the plan is sync crons call invalidateClientContext() after writing new snapshots. This is the natural bridge to event-driven invalidation via brain_events.

How These Three Connect

Sync crons → brain_event(kind:"sync") → invalidateClientContext()
                                              ↓
Alert engines → brain_event(kind:"alert") → morning briefing reads since(lastRun)
                                              ↓
AI Analyst ← context cache (warm) ← brain_events in context XML
    ↓
LLM usage tracker → /admin dashboard → proves cost before adding agents

The key insight: build the observability layer before building the agents. You can't optimize what you can't measure, and you can't coordinate agents without a shared signal bus.

Adopting This Pattern

  1. Start with cost tracking. Wire LlmUsageTracker.track() into every LLM call. This is 3 lines of code per call site.
  2. Add brain events to your alert/sync services. One record() call at the end of each engine run.
  3. Build the context cache only when you have a hot path (like a chat interface) that makes repeated DB reads.
  4. Only then build agent chains — now you have the data to justify the cost and the signals to coordinate them.
Ver o original no GitHub

Bom para

Relacionados