convez.ai
AgenteDevOps & InfraestruturaAvançado
ngc-shj

Claude Code Config

ngc-shj/claude-code-config

Config segura para Claude Code com hooks, skills e model routing

Ver no GitHub
InicialPluginScore · de 0 a 100

Configuração segura de padrões para Claude Code com arquitetura multi-modelo agnóstica. Fornece hooks, skills e regras para controlar permissões, validar commits, fazer reviews automatizados e minerar lições de projetos. Suporta backends locais (Ollama, llama.cpp) e remotos (OpenAI-compatíveis).

Instalação

$npx convez-ai ngc-shj/claude-code-config

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
1
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 3 semanas
Versão
—
Issues abertas
0
Contribuidores
1

Casos de uso

  • Automatizar reviews de código com backends LLM locais ou remotos
  • Validar commits e pull requests antes do merge
  • Gerar testes automaticamente e simplificar código existente
  • Minerar lições de projetos para criar regras reutilizáveis
  • Bloquear edições acidentais de arquivos sensíveis (secrets, locks)

Veredito

Solução robusta e bem estruturada para quem quer governança de IA no fluxo de desenvolvimento com suporte a múltiplos backends LLM. Requer conhecimento sólido de shell scripting e CI/CD para aproveitar plenamente.

README

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

claude-code-config

Safe default settings for Claude Code with agentic multi-model architecture.

Repository structure

claude-code-config/
├── .editorconfig                  # Editor formatting rules
├── .gitignore                     # Ignore .DS_Store, *.bak, etc.
├── LICENSE                        # MIT License
├── README.md                      # This file
├── CLAUDE.md                      # Notes for working *in this repo* (not installed)
├── global/
│   ├── CLAUDE.md                  # Global behavior rules + model routing strategy
│   └── RTK.md                     # RTK command reference (@-imported by CLAUDE.md)
├── settings.json                  # Permissions + hooks configuration
├── install.sh                     # Installer script
├── retrospect.config.json.example # Retrospective-mining config template (opt-in)
├── hooks/
│   ├── block-sensitive-files.sh   # Block edits to secrets/lock files
│   ├── commit-msg-check.sh       # Commit message validation via local LLM
│   ├── pre-review.sh             # Code/plan pre-screening via local LLM
│   ├── llm-utils.sh             # Common local-LLM layer: backend select + dispatch
│   ├── llm-commands.sh          # Backend-agnostic LLM command library for skills
│   ├── ollama-backend.sh        # Ollama provider: discover/load-balance + generate
│   ├── openai-backend.sh      # OpenAI-compatible provider (llama.cpp/vLLM): /v1 discovery + request
│   ├── notify.sh                 # Desktop notifications (macOS + Linux)
│   ├── stop-notify.sh            # Task completion notifications
│   ├── session-retrospect-check.sh # SessionStart: prompt when retrospective mining is due
│   ├── retro-state.sh            # Retrospect state CLI (cursors, due, snooze, config gate)
│   ├── retro-prescreen.sh        # Zero-token candidate discovery per knowledge source
│   └── check-rule-sync.sh        # Rule-ID + phase-manifest/terminator linter for triangulate files
├── skills/
│   ├── triangulate/
│   │   └── SKILL.md              # Triangulate: 3-phase × 3-expert review workflow
│   ├── simplify/
│   │   └── SKILL.md              # Code simplification and cleanup
│   ├── test-gen/
│   │   └── SKILL.md              # Automatic test generation
│   ├── pr-create/
│   │   └── SKILL.md              # Pull request creation with auto-description
│   ├── agent-review/
│   │   ├── SKILL.md              # Backend-agnostic diff review (ollama/codex/claude, local-first)
│   │   ├── review-backend.sh     # Reviewer-backend contract: detect + run (+ --adversarial)
│   │   └── schemas/
│   │       └── review-output.schema.json  # Canonical structured findings shape
│   ├── explore/
│   │   └── SKILL.md              # Deep codebase exploration and Q&A
│   ├── context-budget/
│   │   └── SKILL.md              # Audit context window consumption and surface savings
│   ├── security-scan/
│   │   └── SKILL.md              # Audit Claude Code config for secrets, injection, MCP risks
│   └── retrospect/
│       ├── SKILL.md              # Retrospective mining: lessons → rules/hooks/PR (opt-in)
│       ├── pipeline.md           # Steps 0-9, dispositions, safety invariants
│       ├── folding.md            # Rule sync-point edit map + hook authoring
│       └── sources/              # Per-source mining procedures (artifacts/github/transcripts/scout)
└── rules/
    ├── common/                   # Language-agnostic baseline (always applied)
    │   ├── coding-style.md
    │   ├── testing.md
    │   └── security.md
    ├── typescript/               # Overlays common/ for *.ts, *.tsx, *.js, *.jsx
    ├── python/                   # Overlays common/ for *.py
    └── golang/                   # Overlays common/ for *.go

Agentic architecture

┌──────────────────────────────────────────────────┐
│  Claude Opus 5 (Main Orchestrator)               │
│  Complex design, planning, final decisions       │
└──┬────────────────┬─────────────────┬────────────┘
   │                │                 │
   ▼                ▼                 ▼
┌────────┐  ┌─────────────┐  ┌──────────────────┐
│Sonnet  │  │llm:think    │  │llm:nothink       │
│5       │  │(local)      │  │(local)           │
│        │  │             │  │                  │
│Explore │  │Code review  │  │Commit msg check  │
│Implement│ │pre-screening│  │Quick validation  │
│Test    │  │Security scan│  │Summarization     │
└────────┘  └─────────────┘  └──────────────────┘

Model routing

ModelRoleUse case
Claude Opus 5Main orchestratorArchitecture, planning, final decisions
Claude Sonnet 5Sub-agentExploration, implementation, testing
Claude Fable 5Hardest problemsDemanding reasoning, long-horizon agentic work (above Opus pricing)
llm:thinkLocal pre-screeningCode review, security analysis (before Claude)
llm:nothinkLocal quick checksCommit messages, lint, format, classification

The two local logical names (llm:think, llm:nothink) are what the hooks request; they name a reasoning mode, not a model size, and one local model can serve both. The active backend resolves them to a real model. Run via llama.cpp or Ollama (auto-selected by the llm-utils.sh dispatcher, llama.cpp preferred) — no API cost, no data leaves your machine. Called via hooks (shell + curl) for file-aware tasks, or MCP for ad-hoc text analysis.

Permission design

Commands are categorized into three levels:

  • deny — Blocked unconditionally (destructive, exfiltration, irreversible)
  • allow — Auto-approved (read-only, local-only, safe for development)
  • ask — Requires user confirmation each time (side effects but needed for development)

deny (examples)

  • rm -rf, sudo, chmod 777, dd
  • git push --force, git reset --hard, git clean -fd
  • curl -X POST/PUT/DELETE, curl --data
  • docker system prune, docker push, docker login
  • npm publish, eval, source, xargs

allow (examples)

  • Read-only: ls, cat, grep, find, head, tail, wc, diff
  • Git (safe): status, log, diff, add, commit, checkout, switch, fetch, pull
  • Docker (safe): ps, images, logs, inspect, build, compose up, exec, run
  • npm: list, run, test, install, ci

ask (examples)

  • git push, rm, mv, kill
  • docker stop, docker rm, docker rmi, docker compose down
  • gh pr merge, gh pr close

Hooks

block-sensitive-files.sh (PreToolUse)

Blocks Edit/Write/MultiEdit operations on:

  • Environment files: .env, .env.local, .env.production, etc.
  • Credential files: credentials.json, secrets.yaml, *.pem, *.key
  • Lock files: package-lock.json, yarn.lock, pnpm-lock.yaml, Cargo.lock, etc.
  • Git internals: .git/*
  • The installed harness under ~/.claude/, because install.sh overwrites it and an edit there is silently reverted on the next install: hooks/** (any file type — hooks/lib/ is re-copied wholesale), skills/**, rules/**, settings.json, CLAUDE.md, RTK.md, model-routing.md. Edit the repo and run ./install.sh. ~/.claude/settings.local.json stays editable — install.sh does not touch it — as does ~/.claude/projects/*/memory/. Note that Claude Code does not read a settings.local.json at the user level (only .claude/settings.local.json inside a project), so it is not where machine-wide env belongs; see "Configuration example" above.

commit-msg-check.sh (PreToolUse)

Validates commit messages using the local LLM (logical model llm:nothink, via the llm-utils.sh dispatcher — llama.cpp or Ollama):

  • Checks for conventional commit format (feat/fix/refactor/docs/test/chore)
  • Verifies the message is in English and concise
  • Provides improvement suggestions if needed
  • Gracefully skips if no local LLM backend is reachable

pre-review.sh (Utility — called by skills)

Pre-screening for code review and plan review using the local LLM (logical model llm:think, via the llm-utils.sh dispatcher — llama.cpp or Ollama):

# Review plan
PLAN_FILE=path/to/plan.md bash ~/.claude/hooks/pre-review.sh plan

# Review code changes
bash ~/.claude/hooks/pre-review.sh code
  • Reads files directly via shell (git diff, cat) — no Claude tokens consumed
  • Configurable via REVIEW_MODEL, LLM_BACKEND, and the host vars (LLM_TRUSTED_HOSTS, OPENAI_HOST / OLLAMA_HOST)
  • Gracefully skips if no local LLM backend is reachable

Local-LLM backend layer (llm-utils.sh)

Hooks and skills reach a local LLM through a single backend-agnostic layer, llm-utils.sh, which holds the common processing (shared discovery helpers, backend selection, logical→real model mapping, and the llm_request dispatcher) and sources two backend providers:

  • ollama-backend.sh — Ollama (native /api/generate, multi-server discovery)
  • openai-backend.sh — OpenAI-compatible servers (llama.cpp, vLLM, …) via /v1/chat/completions, /v1/models

Backend selection: LLM_BACKEND=openai|ollama pins the choice; otherwise the OpenAI-compatible backend is auto-preferred when a /v1/models endpoint is reachable, falling back to Ollama. That backend serves any OpenAI-surface server — llama.cpp, vLLM, etc. Bare LLM_TRUSTED_HOSTS entries are probed on every port in LLM_OPENAI_PORTS (default 8080 8000, i.e. llama.cpp's 8080 and vLLM's 8000), so one named host running both joins the pool once per reachable port. The implicit localhost default is probed on 8080 only — it is not multi-port-probed, so an unrelated local service on 8000 that happens to answer /v1/models is never silently trusted; to use a local vLLM on 8000, name it explicitly with LLM_TRUSTED_HOSTS="localhost" or OPENAI_HOST. OPENAI_HOST/OPENAI_HOSTS pin or replace the candidate list. Hooks always pass logical model names — llm:nothink / llm:think, which select a reasoning mode rather than a model. Both resolve to OPENAI_MODEL, and the mode travels with the request as two keys, because the engines disagree on which one is the switch: chat_template_kwargs.enable_thinking (llama.cpp, vLLM) and top-level reasoning_effort (mlx-serve's only switch, and it defaults to thinking off). The think slot sends both; the no-think slot sends only enable_thinking:false. OPENAI_MODEL_THINK/OPENAI_MODEL_NOTHINK override a single slot, for a pool that splits the modes across hosts. The command library (llm-commands.sh) and the direct-caller hooks (pre-review.sh, commit-msg-check.sh) source only llm-utils.sh.

Multi-server load balancing (ollama-backend.sh)

The Ollama provider probes the configured Ollama servers and load-balances across them:

  • Trust model (read this first) — prompts sent to a pool member include git diffs and full source-file contents, so every host in the pool is a potential exfiltration sink. The pool is therefore built from hosts you explicitly name (LLM_TRUSTED_HOSTS list, OLLAMA_HOST pin, or the backend-specific lists below). Requests travel over plain HTTP with no server authentication — use hosts on networks you control (or a Tailscale tailnet, which encrypts and authenticates the transport).

  • Opt-in auto-discovery (OLLAMA_DISCOVERY, default off) — setting OLLAMA_DISCOVERY=1 (both sources) or a list like OLLAMA_DISCOVERY="tailscale" / "mdns tailscale" enables automatic candidate enumeration: online Tailscale peers (MagicDNS FQDNs) and/or mDNS-advertised LAN hosts. Any candidate that answers /api/version joins the pool, regardless of hostname. mDNS candidates are unauthenticated: any device on the LAN that mimics the Ollama API will receive your code — enable mdns only on networks where every host is trusted. Tailscale peers are tailnet-authenticated, but shared or compromised nodes still receive code, hence opt-in as well.

  • Cross-platform discovery — mDNS auto-discovery uses avahi-browse (Linux only). macOS has no avahi and its dns-sd service-browse does not reliably surface plain Ollama hosts, so on macOS list your LAN host name(s) in LLM_TRUSTED_HOSTS — the OS resolver answers .local, so the probe reaches them anyway. Tailscale discovery works on both: the CLI is resolved from PATH, then the macOS app bundle (/Applications/Tailscale.app/Contents/MacOS/Tailscale), then $TAILSCALE_BIN.

  • Model-aware routing — servers do not have to host the same models. At probe time each server's /api/tags inventory is cached, and a request is routed (round-robin) only among servers that actually have the requested model. A model present nowhere makes the caller skip gracefully rather than hit a 404. Callers resolve their target with the exported ollama_host_for_model <model> function.

  • Load balancing — OLLAMA_HOST (one server, round-robin, model-agnostic default) and OLLAMA_HOSTS (full pool) are exported for back-compat. Existing callers that read only $OLLAMA_HOST keep working.

  • Overrides — LLM_TRUSTED_HOSTS is the primary multi-server configuration, shared with the llama.cpp backend (space-separated bare host, host:port, or URL; each backend probes bare names on its own default port and keeps only hosts that answer its own API — a host joins whichever backend's pool matches its actual behavior). OLLAMA_HOST pins to a single server (skips probing); OLLAMA_EXTRA_HOSTS adds Ollama-only hosts; OLLAMA_DISCOVERY_MAX caps probe fan-out per source (default 6). Probe results are cached for 5 minutes in a per-user private state dir ($XDG_RUNTIME_DIR/claude-llm-hooks, falling back to ~/.cache/claude-llm-hooks — never world-writable /tmp). The cache is bound to the trust configuration (OLLAMA_DISCOVERY + the trusted host lists) that produced it, so revoking or changing an opt-in takes effect on the next call — a host admitted under a since-revoked setting is never served from cache. localhost is used only when no remote server is reachable. A host that is down is not cached, so a permanently unreachable entry is re-probed (up to ~2 s) on every hook invocation — prune dead hosts from LLM_TRUSTED_HOSTS to avoid the per-call latency.

  • Configuration example — hooks inherit Claude Code's process environment, so these variables go in an env block that Claude Code actually reads. That is ~/.claude/settings.json, not ~/.claude/settings.local.json. Claude Code resolves three settings sources — user (~/.claude/settings.json), project (.claude/settings.json) and project-local (.claude/settings.local.json) — so a settings.local.json at the user level is never loaded. Despite the general rule that install.sh owns ~/.claude/settings.json, an env block there survives every install: the merge replaces only the template-owned permissions and hooks keys and keeps the rest. (A shell-profile export also works, for terminal launches only.) Copy the template's env block into your live file:

    # merge this file's "env" into ~/.claude/settings.json
    cat settings.local.json.example
    
    {
      "env": {
        "LLM_TRUSTED_HOSTS": "llm-server-1 llm-server-2.your-tailnet.ts.net",
        "OLLAMA_DISCOVERY": "off",
        "LLM_OPENAI_PORTS": "8080 8000",
        "OPENAI_MODEL": "unsloth/Qwen3.6-35B-A3B-MTP-GGUF:Q4_K_XL",
        "REVIEW_MODEL": "llm:think"
      }
    }
    

    Only LLM_TRUSTED_HOSTS and OPENAI_MODEL need editing — the other entries show the defaults and are safe to keep or drop. Merge the env block into the existing file rather than overwriting it.

    Adding or changing a key takes effect in a running session; removing one does not, because the deleted variable stays in the already-started process. Restart to clear it.

  • All environment variables — the example ships the common defaults; the rest are optional and belong in the same env block only when you need them (JSON has no comments, so opt-in / site-specific values are listed here rather than shipped as broken placeholders):

    VariableDefaultPurpose
    LLM_TRUSTED_HOSTS(empty)Space-separated trusted hosts, probed by both backends. Primary multi-server config.
    OLLAMA_DISCOVERYoffOpt in to unauthenticated auto-discovery: tailscale, mdns, "mdns tailscale", or 1/on/all. See the trust model above.
    OLLAMA_EXTRA_HOSTS(empty)Ollama-only additional hosts (probed on :11434), on top of LLM_TRUSTED_HOSTS.
    OLLAMA_HOST(unset)Pin Ollama to one server; skips all probing/discovery.
    OLLAMA_DISCOVERY_MAX6Cap on candidates probed per discovery source.
    TAILSCALE_BINtailscale on PATH, then the macOS app bundlePath/name of the tailscale CLI, used only when OLLAMA_DISCOVERY enables the tailscale source.
    LLM_OPENAI_PORTS8080 8000Ports probed for a bare OpenAI-backend host (llama.cpp 8080, vLLM 8000). A down bare host is probed on every port each hook call, so prune dead hosts — latency scales with the port count.
    OPENAI_HOST(unset)Pin the OpenAI backend to one server; skips probing and the cache.
    OPENAI_HOSTS(unset)Exclusive OpenAI-backend host list (replaces LLM_TRUSTED_HOSTS + localhost for this backend).
    OPENAI_MODEL(unset)Real model for both logical slots — the reasoning mode is a request flag, not a second model. Setting this alone is a complete model configuration.
    OPENAI_MODEL_NOTHINKunsloth/gpt-oss-20b-GGUF:F16Real model for llm:nothink. Overrides OPENAI_MODEL; set it only to split the slots across different servers.
    OPENAI_MODEL_THINKunsloth/Qwen3.6-35B-A3B-MTP-GGUF:Q4_K_XLReal model for llm:think. Overrides OPENAI_MODEL.
    OPENAI_MODEL_SMALL / OPENAI_MODEL_LARGE(unset)Deprecated spellings of the two above, still honored. They were named after the 20b/120b gpt-oss tags this harness first shipped with, so they describe parameter count rather than the role a caller selects.
    OPENAI_REASONING_EFFORTlowLevel sent as top-level reasoning_effort on the llm:think slot — mlx-serve's only thinking switch, and accepted by llama.cpp. low is bounded by the tightest caller (retro-prescreen.sh gives the slot 30s; on Qwen3.8-Flash-Next the levels measured 1.3s / 10.8s / 52s for low / medium / xhigh). Set to the empty string to omit the key for a server that rejects it.
    OLLAMA_MODEL_NOTHINK / OLLAMA_MODEL_THINKgpt-oss:20b / gpt-oss:120bOllama tags for the two slots. Ollama takes the reasoning mode as a think field rather than a chat-template kwarg, so on that backend the slot's model tag carries the mode.
    LLM_BACKEND(auto)Pin the backend to openai or ollama; otherwise the OpenAI backend is auto-preferred when reachable.
    REVIEW_MODELllm:thinkLogical model for pre-review.sh.
    REVIEW_TIMEOUT600Per-request timeout (seconds) for pre-review.sh.

    Tailscale example — trust specific peers and let discovery add any other online peer that answers, resolving the CLI from a non-standard path:

    {
      "env": {
        "LLM_TRUSTED_HOSTS": "llm-server-1.your-tailnet.ts.net",
        "OLLAMA_DISCOVERY": "tailscale",
        "TAILSCALE_BIN": "/Applications/Tailscale.app/Contents/MacOS/Tailscale"
      }
    }
    

llm-commands.sh (Utility — called by skills)

Backend-agnostic local-LLM command library for skills and hooks (routes through llm-utils.sh, so commands run on whichever backend is active):

# Generate a kebab-case slug from task description
echo "Add user authentication" | bash ~/.claude/hooks/llm-commands.sh generate-slug

# Summarize a git diff
git diff main...HEAD | bash ~/.claude/hooks/llm-commands.sh summarize-diff

# Merge and deduplicate review findings from multiple agents
cat findings1.txt findings2.txt | bash ~/.claude/hooks/llm-commands.sh merge-findings

# Classify changed files (feature/fix/refactor/docs/test/chore)
git diff --name-only | bash ~/.claude/hooks/llm-commands.sh classify-changes

# Classify a user question into an explore query type (explanation / usage-search / architecture / location / data-flow)
echo "How does the request router work?" | bash ~/.claude/hooks/llm-commands.sh classify-query

# Analyze a diff from an expert perspective (functionality / security / testing)
# Used by triangulate Phase 3 to seed Claude sub-agents with findings
# instead of each sub-agent reading the full diff — reduces Claude token usage.
git diff main...HEAD | bash ~/.claude/hooks/llm-commands.sh analyze-functionality
git diff main...HEAD | bash ~/.claude/hooks/llm-commands.sh analyze-security
git diff main...HEAD | bash ~/.claude/hooks/llm-commands.sh analyze-testing

# Pre-screen reuse candidates (shared-utils inventory + diff) for the simplify skill
{ bash ~/.claude/hooks/scan-shared-utils.sh; echo '=== OLLAMA-INPUT-SEPARATOR ==='; \
  git diff main...HEAD; } | bash ~/.claude/hooks/llm-commands.sh score-utility-match

# Audit mock return values in a test file against the real type definitions
{ cat tests/foo.test.ts; echo '=== OLLAMA-INPUT-SEPARATOR ==='; \
  cat src/types/foo.ts; } | bash ~/.claude/hooks/llm-commands.sh verify-mock-shapes

# Generate a PR title from classify-changes + summarize-diff output
{ echo "$CATEGORY"; echo '=== OLLAMA-INPUT-SEPARATOR ==='; echo "$SUMMARY"; } \
  | bash ~/.claude/hooks/llm-commands.sh generate-pr-title

# Generate a PR body from commits + diff stat + ALL review artifacts (mirrors the pr-create skill invocation)
{ echo '=== COMMIT LOG ==='; git log main...HEAD --oneline; \
  echo; echo '=== DIFF STAT ==='; git diff main...HEAD --stat; \
  for f in ./docs/archive/review/*-plan.md ./docs/archive/review/*-review.md \
           ./docs/archive/review/*-deviation.md ./docs/archive/review/*-code-review.md; do \
    [ -f "$f" ] || continue; echo; echo "=== $f ==="; cat "$f"; done; } \
  | bash ~/.claude/hooks/llm-commands.sh generate-pr-body

# Generate a deviation log delta from plan + existing log + diff (three sections)
{ cat plan.md; echo '=== OLLAMA-INPUT-SEPARATOR ==='; \
  cat existing-deviation.md 2>/dev/null || echo '# new'; \
  echo '=== OLLAMA-INPUT-SEPARATOR ==='; git diff main...HEAD; } \
  | bash ~/.claude/hooks/llm-commands.sh generate-deviation-log  # output = delta entries; APPEND to existing log

# Generate a commit body (subject line still hand-written)
git diff --cached | bash ~/.claude/hooks/llm-commands.sh generate-commit-body

# Generate a resolution-status entry from finding + fix commit
{ echo "$FINDING"; echo '=== OLLAMA-INPUT-SEPARATOR ==='; git show HEAD; } \
  | bash ~/.claude/hooks/llm-commands.sh generate-resolution-entry

# Summarize a round-to-round change for review artifacts
{ git log r1..HEAD --oneline; echo '=== OLLAMA-INPUT-SEPARATOR ==='; cat findings.txt; } \
  | bash ~/.claude/hooks/llm-commands.sh summarize-round-changes

# Propose plan edits for a finding (anchor + insertion pairs)
{ cat plan.md; echo '=== OLLAMA-INPUT-SEPARATOR ==='; echo "$FINDING"; } \
  | bash ~/.claude/hooks/llm-commands.sh propose-plan-edits
  • All commands read stdin, write stdout — composable with pipes
  • Backend-agnostic: routed through llm-utils.sh (llama.cpp auto-preferred, else Ollama)
  • Gracefully returns empty output if no local LLM backend is reachable
  • Supports reasoning/thinking models (Ollama .response→.thinking; llama.cpp content→reasoning_content)

notify.sh (Notification)

Cross-platform desktop notifications (macOS via afplay/osascript, Linux via paplay/aplay + notify-send) when:

  • permission_prompt: Claude needs permission approval — plays sound + notification
  • idle_prompt: Claude is waiting for input — plays sound + notification

Linux sounds resolve from the freedesktop theme; all calls are best-effort and skip silently if the tools or audio are unavailable.

stop-notify.sh (Stop)

Notifies when Claude finishes a response:

  • end_turn: Task complete — plays Glass sound + notification
  • max_tokens: Token limit reached — plays alert sound + warning notification

Skills

triangulate

A development workflow skill with three phases:

  1. Plan creation & review — Local LLM pre-screening + 3 Claude expert agents
  2. Coding — Sonnet sub-agent implementation with deviation tracking
  3. Code review — Local LLM pre-screening + 3 Claude expert agents

Each review phase uses local LLM (llm:think) to catch obvious issues before launching Claude sub-agents. Implementation is delegated to Sonnet sub-agents while Opus orchestrates, reducing API cost while maintaining quality.

simplify

Reviews changed code for reuse, quality, and efficiency improvements:

  • Local LLM pre-analysis for complexity hotspots and duplication (zero Claude tokens)
  • Sonnet sub-agent explores codebase for concrete before/after proposals
  • User selects which proposals to apply

test-gen

Generates tests for specified or changed code:

  • Auto-detects test framework and conventions
  • Local LLM generates test case outlines (zero Claude tokens)
  • Sonnet sub-agent implements and verifies tests with fix loop (max 3 iterations)

pr-create

Creates a pull request with auto-generated description:

  • Local LLM summarizes diff and classifies change type (zero Claude tokens)
  • Local LLM composes PR body with summary, motivation, and test plan (zero Claude tokens)
  • User reviews draft before gh pr create

agent-review

Backend-agnostic diff review: a reviewer is treated as any agent that takes a diff and returns findings headlessly, so the review path never depends on one CLI (this subsumes the former codex-review skill — Codex is now just one selectable backend):

  • Auto-detects available backends in preference order — ollama (free; sends the diff only to your explicitly configured local-LLM hosts via the llm-utils.sh dispatcher — llama.cpp when reachable, else Ollama; see the ollama-backend trust model above) → codex (external second opinion, codex review) → claude (fresh headless context, spends tokens)
  • Defaults to the free local backend, reusing llm-commands.sh (functionality / security / testing) — zero Claude tokens when a local backend (llama.cpp or Ollama) is reachable
  • Review scope: uncommitted changes, a base branch, or a specific commit; optionally cross-checks findings against triangulate review artifacts
  • --adversarial mode challenges the design/approach/failure-modes instead of a line-by-line pass (ollama gets a dedicated adversarial-review pass; codex/claude get an approach-challenging prompt)
  • Normalizes every backend's output into a canonical structured shape (schemas/review-output.schema.json: verdict / findings / next_steps), and backgrounds slow reviews via the harness's run_in_background
  • Data flow varies by backend — ollama stays on the local/LAN host, codex/claude send the diff to their servers; do not run an external backend on a diff that stages secrets
  • Add a backend by extending one branch in review-backend.sh; the skill steps stay identical
  • Borrows its structured-findings, background-job, and adversarial-review ideas from OpenAI's codex-plugin-cc, adapted to a single multi-backend skill

explore

Deep codebase exploration and Q&A:

  • Local LLM extracts search keywords and builds file relevance map (zero Claude tokens)
  • Sonnet sub-agent traces code paths and builds structured answers
  • Supports: explanation, usage search, architecture, location, data flow queries

context-budget

Audits token overhead across agents, skills, rules, CLAUDE.md, and MCP servers, then surfaces prioritized savings:

  • Inventory phase is pure shell (word count, line count) — zero Claude tokens
  • Claude classifies components as always/sometimes/rarely needed and ranks optimizations
  • Flags bloated descriptions, heavy files, MCP oversubscription, CLAUDE.md creep
  • Adapted from everything-claude-code (skills/context-budget/)

security-scan

Audits Claude Code configuration for common security misconfigurations — zero external dependencies:

  • Deterministic pattern checks (grep + jq) for secrets, Bash(*) wildcards, hook injection, MCP supply chain, prompt-injection surface in CLAUDE.md
  • Optional deep analysis via llm:think through llm-commands.sh analyze-security (zero Claude tokens)
  • Graded A/F report with severity-classified findings
  • Concept borrowed from everything-claude-code (skills/security-scan/, which wraps the AgentShield npm package); reimplemented here as a self-contained shell + local-LLM workflow

retrospect

Automates this repo's self-improvement loop (opt-in — see "Retrospective mining" below):

  • Mines configured knowledge sources for lessons: review artifacts in sibling repos, GitHub PR review comments, own session transcripts (privacy-protected), whitelisted external references
  • Skepticism-first dedupe against the existing rule set, then folds novel lessons into skills/triangulate/common-rules.md rows, detection hooks + bats tests, and cross-skill guards — gated by check-rule-sync.sh and the full test suite
  • Ends with a triangulate self-review and a PR; the human squash-merges

Retrospective mining (opt-in)

Disabled until you create a config. Everything is driven by three hooks (session-retrospect-check.sh, retro-state.sh, retro-prescreen.sh) plus the retrospect skill; state (per-source high-water cursors) lives in ~/.claude/state/retrospect.json, which the installer never touches.

Enable

cp retrospect.config.json.example ~/.claude/retrospect.config.json
# edit: list your sibling repos under sources.artifacts.repos, enable sources
bash ~/.claude/hooks/retro-state.sh seed --high-water artifacts=<last-manually-mined-date>

From then on, the first session of a day where a source's interval_days has elapsed opens with a prompt offering to run the retrospect skill. Decline to snooze (bash ~/.claude/hooks/retro-state.sh snooze <source> [days]); delete the config to disable entirely.

Notes

  • Transcripts source: raw transcript text never reaches Claude context, stdout, stderr, or a non-loopback LLM endpoint. Distillation requires a LOOPBACK local LLM; setting sources.transcripts.allow_remote_llm: true acknowledges that raw excerpts would then cross the network in plaintext HTTP to your configured LLM host.
  • State-loss recovery: re-run bash ~/.claude/hooks/retro-state.sh seed --high-water <source>=<scalar> with the scalar cursors recorded in the latest docs/archive/audit/*-lessons-*.md frontmatter (applies to artifacts/github/transcripts; scout recovers by re-fetching). Worst case, a lost cursor only causes re-mining, which the skill's dedupe pass absorbs.
  • Manual verification of the SessionStart hook: set a source's interval_days to 0, run seed, start a new Claude Code session — the mining prompt should appear once per day; bash tests/bench-hooks.sh reports the hook's latency.

Rules

Layered coding-style / testing / security guidance, consulted when editing matching files.

  • rules/common/ — language-agnostic baseline (KISS/DRY/YAGNI, test minimums, secrets handling). Always applied.
  • rules/{lang}/ — language overlays that extend the baseline and override where the language idiom differs (e.g. Go mutability). Each file declares paths: in YAML frontmatter.

Currently shipped: typescript/, python/, golang/. Extend by dropping a new rules/{lang}/ directory with at least coding-style.md and a paths: frontmatter.

Loading differs by layer, and the paths: frontmatter is what decides it:

  • rules/common/*.md declare no paths:, so nothing scopes them — they are auto-injected into every session and count against the context budget permanently (~1,200 tokens). Keep them short.
  • rules/{lang}/*.md declare paths:, so they stay out of context until Claude reads them for a matching file.

Adding a paths: frontmatter to a common/ file would move it out of the always-loaded set — which is why the baseline rules deliberately have none.

Installation

Prerequisites

  • Claude Code installed
  • Ollama and/or an OpenAI-compatible server (llama.cpp, vLLM, …) (optional, for local LLM features — when both are reachable, the OpenAI backend is auto-preferred)

Setup

git clone https://github.com/ngc-shj/claude-code-config.git
cd claude-code-config
bash install.sh

The installer overwrites ~/.claude/CLAUDE.md (from global/), hooks, skills, and rules — this repo is the source of truth and git history is the rollback mechanism, so no .bak files are kept for them. Any stale .bak under ~/.claude/{hooks,skills,rules}/ from earlier installs is removed on the next run (stale skill backups otherwise load as shadow skills).

settings.json is the exception: it is merged into any existing live file rather than overwritten, so user-managed top-level keys the template does not own (e.g. mcpServers) survive. permissions and hooks are template-owned and replaced wholesale, so a stale user sub-key or unmanaged hook event in the live file does not leak through. A non-object/garbage live file is backed up and replaced instead of merged. A timestamped settings.json.bak.<ts> (mode 600) is written first. Backups are not auto-pruned — purge old ones periodically.

Which file a local customization belongs in follows from that merge. permissions and hooks are template-owned, so put project-scoped overrides of those in a project's .claude/settings.local.json. Everything else — env above all — belongs in ~/.claude/settings.json, where the merge preserves it: Claude Code does not read a user-level settings.local.json at all, so a machine-wide setting placed there is silently ignored rather than applied.

Status line and usage history (optional)

The status line is bash ~/.claude/usage/statusline-usage.sh, from claude-usage — a separate repo that renders the plan's rate-limit percentages and keeps a timestamped history of them in ~/.claude/usage-log.jsonl, sampled by its own systemd/launchd poller. Install it there; nothing else in this repo depends on it, and the status line simply renders nothing if it is absent.

Install local models (optional)

Ollama backend — the slots map to these tags by default (OLLAMA_MODEL_NOTHINK / OLLAMA_MODEL_THINK override them):

ollama pull gpt-oss:20b
ollama pull gpt-oss:120b

OpenAI-compatible backend — any server exposing /v1/models + /v1/chat/completions. Bare hosts are probed on LLM_OPENAI_PORTS (default 8080 8000): run llama-server on 8080 and/or vLLM on 8000. One model covers both slots — set OPENAI_MODEL and the mode rides on the request:

LogicalReal model id (default)Request carriesServer
llm:nothinkunsloth/gpt-oss-20b-GGUF:F16enable_thinking: falsellama.cpp
llm:thinkunsloth/Qwen3.6-35B-A3B-MTP-GGUF:Q4_K_XL (llama-server strips the unsloth UD- prefix, so the UD-Q4_K_XL build is requested as Q4_K_XL)enable_thinking: true + reasoning_effortllama.cpp, mlx-serve

The engines disagree on which key is the thinking switch, so the think slot sends both — measured against a live server of each:

Enginechat_template_kwargs.enable_thinkingreasoning_effort
llama.cpphonoredaccepted, keeps thinking on
mlx-servesilently ignoredthe only switch; defaults to OFF

Sending only the llama.cpp key is the dangerous half-measure: an mlx-serve host answers without thinking and without an error, so a review pass degrades to a one-shot answer that reads fine. Still verify a model before assigning it to llm:think — if reasoning_content comes back empty on a question that needs working out, that model is not reasoning no matter which key you sent.

When both backends are reachable, the OpenAI backend is auto-preferred; pin with LLM_BACKEND=ollama or LLM_BACKEND=openai.

What gets installed

SourceDestination
settings.json~/.claude/settings.json
global/CLAUDE.md~/.claude/CLAUDE.md
global/RTK.md~/.claude/RTK.md
hooks/*.sh~/.claude/hooks/
skills/*/SKILL.md~/.claude/skills/*/SKILL.md
rules/*/*.md~/.claude/rules/*/*.md

Additionally, ~/.claude/state/ is created (0700) for retrospect cursors; the installer never writes into it and never installs retrospect.config.json (user-created, see "Retrospective mining").

Customization

  • Edit settings.json to adjust permission rules and hooks
  • Edit global/CLAUDE.md to change global behavior rules and model routing. The root CLAUDE.md is not installed — it holds notes for working in this repo, and duplicating global content there would load it twice in sessions opened here
  • Add/remove hook scripts in hooks/
  • Add/remove skills in skills/
  • Add language-specific rules in rules/{lang}/ — each file carries a paths: frontmatter indicating which file globs it applies to
  • For project-specific rules, create a CLAUDE.md in the project root

License

MIT

Ver o original no GitHub

Bom para

Relacionados