Two files, one repository
danielvm-git/bigpowers ships 4 formats across 40 indexed files. The question worth asking is whether the second one says anything the first does not.
| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 0 | 40 | 26 | 0% |
| Commands | 0 | 10 | 2 | 0% |
| Section tags | 5 | 6 | 3 | 36% |
What each file covers
Sections
0 shared · 40 only in A · 26 only in B- − story: e38s08
- − story: e51s05
- − story: e45s22
- − story: e45s23
- − story: e55s03
- − bigpowers — Claude Code
- − Context Routing
- − Learned User Preferences
- − Workspace Facts
- − Project
- − Commands
- − Pre-Merge Checklist
- − Architecture
- − Conventions
- − Never
- − Token Management
- − Session Start
- − Agent Rules
- − bts toolchain
- − sqz — Context Compression (READ FIRST)
- − Preferred tools (MCP)
- − Bash commands (hooked automatically)
- − Escape hatch — when you see a `§ref:HASH§` token
- − When NOT to use sqz tools
- − RTK (Rust Token Killer) - Token-Optimized Commands
- − Golden Rule
- − ❌ Wrong
- − ✅ Correct
- − RTK Commands by Workflow
- − Build & Compile (80-90% savings)
- − Test (60-99% savings)
- − Git (59-80% savings)
- − GitHub (26-87% savings)
- − JavaScript/TypeScript Tooling (70-90% savings)
- − Files & Search (60-75% savings)
- − Analysis & Debug (70-90% savings)
- − Infrastructure (85% savings)
- − Network (65-70% savings)
- − Meta Commands
- − Token Savings Overview
- + Audit Code
- + Look-here-first (churn heuristic)
- + Modes
- + Checklist
- + Supply Chain & Security
- + Provenance & Metadata
- + Law of Demeter
- + CONVENTIONS.md Compliance
- + Scope
- + Boy Scout Rule
- + Types and Safety
- + Test Coverage
- + SOLID and Heuristics
- + Refactoring Smells (Fowler)
- + Code Style (CONVENTIONS.md)
- + Red Flags
- + Output
- + Verify
- + Handoff
- + Clean Code Heuristics (Chapter 17)
- + Comments (C)
- + Environment (E)
- + Functions (F)
- + General (G)
- + Naming (N)
- + Tests (T)
Commands
0 shared · 10 only in A · 2 only in B- − npm run compliance && bash scripts/run-verification-gates.sh
- − git status
- − cargo test
- − docker ps
- − kubectl get pods
- − git add . && git commit -m "msg" && git push
- − npm install -g bigpowers && bigpowers setup
- − npm run compliance
- − gh pr checks
- − python
- + gh issue create
- + npm test
Section tags
5 shared · 6 only in A · 3 only in B- − build
- − architecture
- − git-pr
- − monorepo
- − do-not
- − agent-behaviour
- + testing-strategy
- + security
- + docs
- setup
- test
- lint-format
- code-style
- types
Line diff
danielvm-git/bigpowers · CLAUDE.md
@@ −1 @@
1# story: e38s08
2# story: e51s05
3# story: e45s22
4# story: e45s23
5# story: e55s03
6
7# bigpowers — Claude Code
8
9Read CONVENTIONS.md before any GitHub or git operation.
10
11[`constitution.md`](constitution.md) is a consolidated entry point synthesizing
12this project's doctrine (this file, CONVENTIONS.md, docs/PRINCIPLES.md,
13docs/references/*.md) into bigspec's B0-B10 + Capstone blocks, with citations
14back to the fuller text. It's a starting point for a reader, not a
15replacement — this file remains fully authoritative for its own content today.
16
17<!-- BEGIN bigpowers:context-routing -->
18## Context Routing
19
20Load subdirectory context **by file glob** — do not read the full doc tree up front.
21
22| Glob / trigger | Load first | Fallback |
23|----------------|------------|----------|
24| `skills/**` | Active skill's `SKILL.md` + sibling `REFERENCE.md` if linked | `SKILL-INDEX.md` |
25| `specs/epics/**` | Capsule `epic.yaml` + active story `-tasks.yaml` | `specs/release-plan.yaml` |
26| `specs/product/**` | `SCOPE_LATEST.yaml`, `VISION_LATEST.yaml` | `specs/README.md` |
27| `specs/tech-architecture/**` | `tech-stack.md` + epic `eNN-TEST_PLAN_LATEST.md` if present | `CONVENTIONS.md` |
28| `scripts/**` | `CONVENTIONS.md` § Generated artifact targets | This file § Commands |
29| `website/**` | `website/README.md` if present | Never edit `website/src/content/docs/` (generated) |
30| `docs/**` | Matching doc under `docs/` | `docs/references/` |
31| Default / session start | This file → `CONVENTIONS.md` → `specs/state.yaml` | `survey-context` |
32
33Sub-AGENTS.md files (when present in consumer projects) override this table for their directory only.
34<!-- END bigpowers:context-routing -->
35
36<!-- BEGIN bigpowers:learned-preferences -->
37## Learned User Preferences
38
39_Durable preferences discovered across sessions. Update via `session-state` — do not infer from chat alone._
40
41- Prefer `rtk`-prefixed shell commands for git, test, and build output (token savings).
42- Run Preflight before forward work; never dismiss red gates as pre-existing.
43- Edit `skills/*/SKILL.md` sources only — never `.cursor/rules/` or `.gemini/` artifacts.
44
45## Workspace Facts
46
47_Stable repo facts — prefer these over re-discovery._
48
49- Stack: Markdown / Bash documentation project; skills sync via `bash scripts/sync-skills.sh`.
50- Planning SoT: `specs/state.yaml`, `specs/release-plan.yaml`, `specs/execution-status.yaml`.
51- Story traceability: `# story: eNNsNN` tags in implementing files; `bash scripts/trace-stories.sh --strict` in CI.
52- Rule matrix: `bash scripts/compile-rule-matrix.sh` → `specs/rule-matrix.json` (P0–P3 tiers from CONVENTIONS.md).
53<!-- END bigpowers:learned-preferences -->
54
55## Project
56
57bigpowers — agent skills for spec-driven, test-first software development by solo developers (skill count and catalog are auto-generated in `SKILL-INDEX.md`; never hardcode the count in docs).
58Stack: Markdown / Bash (documentation-based; skills integrate with Claude Code, Cursor, Gemini CLI)
59
60## Commands
61
62| Action | Command |
63|---------|---------|
64| Install | `npm install -g bigpowers && bigpowers setup` |
65| Run | `bash scripts/sync-skills.sh` |
66| Test | N/A (documentation project) |
67| Build | `bash scripts/install.sh` (from source) |
68| Lint | `bash scripts/sync-skills.sh` (validates SKILL.md syntax) |
69| Validate specs YAML | `bash scripts/validate-specs-yaml.sh` |
70| Typecheck | N/A (Markdown / Bash project) |
71| CI platform | GitHub Actions (`.github/workflows/publish.yml`, `sync-skills.yml`, `golden-suite.yml`) |
72| Compliance | `npm run compliance` |
73| Verification Gates | `bash scripts/run-verification-gates.sh` |
74| Traceability | `bash scripts/trace-stories.sh --strict` | grep for story tags (traceability check) |
75| Preflight | `npm run compliance && bash scripts/run-verification-gates.sh && bash scripts/sync-skills.sh && bash scripts/trace-stories.sh --strict` | Full local green stack before forward work. Chain ends on `--strict` traceability — no trailing always-exit-0 step. |
76| Catalog drift (advisory) | `bash scripts/check-catalog-drift.sh` | e54s02 Confirm gate during catalog freeze — always exits 0; run manually when changing skills, not part of Preflight. |
77| CI | `gh pr checks` | Remote CI green when a PR is open |
78
79### Pre-Merge Checklist
80
81Before opening a PR or landing a branch, run:
82
83```bash
84npm run compliance && bash scripts/run-verification-gates.sh
85```
86
87If any gate fails, fix before merging. Run `--baseline` after any intentional increase in skill count or structure.
88
89**BCP Plus:** For stories sized with the 13-dimension BCP Plus methodology, confirm the `bcp_plus_breakdown` is present in the epic YAML and carried into `state.yaml` as `epic_cycle.bcp_plus`. See `docs/references/bcp-plus.md` for the NFR Gate pattern.
90
91## Architecture
92
93Collection of verb-noun skills under `skills/`, each with a SKILL.md source file and supporting documentation. Runtime specs live in `specs/state.yaml`, `specs/release-plan.yaml`, and `specs/execution-status.yaml`; intent in `specs/product/`; epic shards in `specs/epics/`. The sync-skills.sh script auto-generates artifacts for Cursor (.cursor/rules) and Gemini CLI (.gemini/extensions/bigpowers/) from SKILL.md sources. All planning output goes to specs/ at the project root.
94
95## Conventions
96
97- Skill directories under `skills/` use verb-noun naming (two words, kebab-case)
98- Every skill has a single SKILL.md file as its source of truth
99- All planning/spec output goes to specs/ at project root
100- Artifacts in .cursor/rules and .gemini/ are auto-generated; edit SKILL.md, not artifacts
101- Run sync-skills.sh after any SKILL.md changes to regenerate artifacts
102- Website content in website/src/content/docs/ is auto-generated by prebuild; edit repo sources, not site files
103
104## Never
105
106- Never edit .cursor/rules or .gemini/extensions/ directly — these are generated files
107- Never edit website/src/content/docs/ directly — these are generated files; website/ is the fourth generated artifact target (alongside .cursor/, .gemini/, .pi/)
108- Never create a skill without a SKILL.md file and proper verb-noun naming
109- Never push changes without running sync-skills.sh first
110
111## Token Management
112
113**Mechanical backstop (e45s03):** `scripts/hooks/token-mgmt-pre-tool-use.sh` blocks oversized tool calls when prose rules are ignored. Wire as a `PreToolUse` hook for `Read`, `Grep`, and `Bash` (alongside `hooks/pre-tool-use.sh` for git safety). Thresholds: Read >100KB, Grep >200 matches without `head_limit`, Bash commands likely to exceed 500 output lines without `rtk`/`sqz compress`. Install snippet:
114
115```json
116{
117 "hooks": {
118 "PreToolUse": [
119 { "matcher": "Read|Grep|Bash", "hooks": [{ "type": "command", "command": "bash scripts/hooks/token-mgmt-pre-tool-use.sh" }] }
120 ]
121 }
122}
123```
124
125Context engineering (write/select/compress/isolate — see `docs/references/context-engineering.md`):
126
127- **Write (token-efficient content):** Short functions (4-20 lines), unique symbol names, headless tests. Don't restate code in comments.
128- **Select (include only what's relevant):** Use `bts_map` for ranked file lists, `survey-context` for phase bootstrap. Don't read files you don't need.
129- **Compress (reduce without losing structure):** Use `bts_compress` or pipe through `sqz compress`. Use `rtk` for build/test/git output (60-99% savings). Prefer `terse-mode` when context is heavy.
130- **Isolate (partition work):** Use `kickoff-branch` for isolated worktrees, `dispatch-agents` for parallel tasks with disjoint scopes, `session-state` for cold-start handoff.
131
132**Effort classification:** Skills carry an `effort:` frontmatter field (`light` | `standard` | `heavy`). Prefer `light` skills for bootstrap/status checks; reserve `heavy` for epic builds and multi-phase planning.
133
134- **Auto-Terse**: When a session exceeds 20 turns or the context window feels "heavy" (latency increasing), you MUST switch to `terse-mode` to save tokens.
135- **Context Compaction**: Every 10 turns, summarize the current session state and implementation decisions into a short, high-density note.
136- **Minimal Output**: Prefer text-only output for simple status; use `web_fetch` or `run_shell_command` only for evidence.
137- **Stream Stability**: When writing large files or long documents, output continuously in chunks of ~200 lines. Do not pause. If you need time to process, emit a placeholder comment rather than going silent.
138
139## Session Start
140
141Before any task, run this sequence — not optional:
142
1431. Read `CLAUDE.md` (this file)
1442. Read `CONVENTIONS.md`
1453. Read `specs/state.yaml` if it exists — current session and active epic
1464. Read `specs/release-plan.yaml` if it exists — active release context
147
148## Agent Rules
149
150- **Workflow Mandate:** You MUST use the bigpowers skills (e.g., `plan-work`, `develop-tdd`, `craft-skill`) to perform tasks. DO NOT write code directly in response to a user prompt like "build this feature".
151- **Always Green / fix-or-log:** Preflight and CI must be green before forward work. Any reproducible gate failure during unrelated work requires **quick-fix** or **fix-bug** — see CONVENTIONS § Discovered Defects. Never dismiss failures as pre-existing or out of scope.
152- Read specs/ and CONVENTIONS.md before writing code.
153- Write the minimum code that solves the stated problem. Nothing extra.
154- Run tests after every change. Show evidence before declaring done.
155- One clarifying question beats a wrong assumption baked into 200 lines.
156- All written output (plans, specs, investigations) goes in specs/.
157
158## bts toolchain
159
160`bts` is installed. Prefer its verbs over ad-hoc shell commands.
161
162| Task | Command | Avoid |
163|------|---------|-------|
164| Search code | `bts find --print <pattern>` | grep / find / cat |
165| Interactive search | `bts find <pattern>` | manual grep pipes |
166| Compress for context | `bts compress <file>` or `cmd \| bts compress` | summarising by hand |
167| Repo map | `bts map` | listing files by hand |
168| Library docs | `bts docs <lib>` | guessing from training data |
169| Package source | `bts src <pkg>` | git clone |
170| Toolchain health | `bts doctor` | which / command -v |
171
172**Rules**
173- Search with `bts find` before opening files to locate a symbol or pattern.
174- Pipe anything > 200 lines through `bts compress` before adding to context.
175- Run `bts map` when asked for a repo overview.
176- Use `bts docs <lib>` before answering questions about library APIs. Doc fetches use `scripts/lib/doc-fetch-cache.sh` (ETag-revalidated, 300s TTL — see `context7-mcp` skill, e45s20).
177- If a tool is missing, say so and run `bts doctor` — do not silently substitute.
178
179<!-- BEGIN rtk-pretooluse-hook (e45s16 — mechanical PreToolUse backstop; remove block to disable) -->
180
181**RTK hook (installed):** `scripts/hooks/rtk-rewrite.sh` is symlinked into `~/.claude/hooks/` by `bash scripts/install.sh` and registered as a Bash `PreToolUse` hook. It delegates to `rtk hook claude` — prose rules below are a fallback only when the hook is absent.
182
183<!-- END rtk-pretooluse-hook -->
184
185<!-- BEGIN sqz-claude-guidance (auto-installed by sqz init; remove this block to disable) -->
186
187## sqz — Context Compression (READ FIRST)
188
189sqz is installed in this project. It compresses tool output so large
190files, long logs, and verbose command output cost far fewer tokens.
191There are **two ways** sqz is wired in, and you should prefer each
192one in the situations below.
193
194### Preferred tools (MCP)
195
196The `sqz-mcp` server is registered in this project's MCP config. It
197exposes three read-only tools that compress their output through the
198sqz pipeline:
199
200- **`sqz_read_file`** — read a file from disk and return a compressed
201 view. **PREFER this over the built-in `Read` tool** for any file
202 larger than ~2KB or any file you might read more than once in the
203 same session. Repeat reads return a 13-token `§ref:HASH§` reference
204 instead of the full content.
205
206- **`sqz_grep`** — search files for a literal string or regex.
207 **PREFER this over the built-in `Grep`** for anything that might
208 match more than a handful of lines. Caps at 200 matches by default;
209 raise with `max_matches` if needed.
210
211- **`sqz_list_dir`** — list a directory. Skips `.git`, `node_modules`,
212 `target`, `dist`, `build`, `vendor`, `__pycache__` so the output
213 stays focused. **PREFER this over `ls -la` via Bash** when you want
214 to see a project layout.
215
216The built-in `Read`, `Grep`, `Glob` tools remain available. Use them for:
217- Tiny config files (<1KB) where compression can't help.
218- Byte-exact reads you'll hash or diff (lockfiles, signatures).
219- Globbing (sqz has no glob tool; `Glob` is still the right choice).
220
221### Bash commands (hooked automatically)
222
223When you run a shell command through the `Bash` tool, a PreToolUse hook
224rewrites it to pipe output through `sqz compress`. This is transparent:
225you don't need to remember to add anything, but it's useful to know
226that these commands get compressed automatically:
227
228```bash
229git status # → git status 2>&1 | sqz compress --cmd git
230cargo test # → cargo test 2>&1 | sqz compress --cmd cargo
231docker ps # → docker ps 2>&1 | sqz compress --cmd docker
232kubectl get pods # → kubectl get pods 2>&1 | sqz compress --cmd kubectl
233```
234
235The rewrite is skipped for interactive commands (`vim`, `ssh`,
236`python`), compound commands (`a && b`, `a > file.txt`), and anything
237already going through sqz.
238
239### Escape hatch — when you see a `§ref:HASH§` token
240
241If tool output contains a `§ref:a1b2c3d4§` token and you need the full
242content it points at, resolve it. Three equivalent ways:
243
244- Shell: `/Users/danielvm/.local/bin/sqz expand a1b2c3d4` (or paste the whole token
245 `/Users/danielvm/.local/bin/sqz expand §ref:a1b2c3d4§`).
246- MCP tool: call `expand` with `{ "prefix": "a1b2c3d4" }`.
247- To get uncompressed output for one command: prefix it with
248 `SQZ_NO_DEDUP=1` (e.g. `SQZ_NO_DEDUP=1 git log | sqz compress`).
249
250If the compressed output is actively making the task harder (looping
251on refs, small retries replacing one big read), call the `passthrough`
252MCP tool to get raw text.
253
254### When NOT to use sqz tools
255
256- Writing or editing files — use the built-in `Write`/`Edit` tools.
257 sqz has no write tools (by design; see issue #5 follow-up).
258- Running commands interactively or in watch mode.
259- Reading very small files (<1KB) where compression can't help.
260
261<!-- END sqz-claude-guidance -->
262
263<!-- rtk-instructions v2 -->
264# RTK (Rust Token Killer) - Token-Optimized Commands
265
266## Golden Rule
267
268**Always prefix commands with `rtk`**. If RTK has a dedicated filter, it uses it. If not, it passes through unchanged. This means RTK is always safe to use.
269
270**Important**: Even in command chains with `&&`, use `rtk`:
271```bash
272# ❌ Wrong
273git add . && git commit -m "msg" && git push
274
275# ✅ Correct
276rtk git add . && rtk git commit -m "msg" && rtk git push
277```
278
279## RTK Commands by Workflow
280
281### Build & Compile (80-90% savings)
282```bash
283rtk cargo build # Cargo build output
284rtk cargo check # Cargo check output
285rtk cargo clippy # Clippy warnings grouped by file (80%)
286rtk tsc # TypeScript errors grouped by file/code (83%)
287rtk lint # ESLint/Biome violations grouped (84%)
288rtk prettier --check # Files needing format only (70%)
289rtk next build # Next.js build with route metrics (87%)
290```
291
292### Test (60-99% savings)
293```bash
294rtk cargo test # Cargo test failures only (90%)
295rtk go test # Go test failures only (90%)
296rtk jest # Jest failures only (99.5%)
297rtk vitest # Vitest failures only (99.5%)
298rtk playwright test # Playwright failures only (94%)
299rtk pytest # Python test failures only (90%)
300rtk rake test # Ruby test failures only (90%)
301rtk rspec # RSpec test failures only (60%)
302rtk test <cmd> # Generic test wrapper - failures only
303```
304
305### Git (59-80% savings)
306```bash
307rtk git status # Compact status
308rtk git log # Compact log (works with all git flags)
309rtk git diff # Compact diff (80%)
310rtk git show # Compact show (80%)
311rtk git add # Ultra-compact confirmations (59%)
312rtk git commit # Ultra-compact confirmations (59%)
313rtk git push # Ultra-compact confirmations
314rtk git pull # Ultra-compact confirmations
315rtk git branch # Compact branch list
316rtk git fetch # Compact fetch
317rtk git stash # Compact stash
318rtk git worktree # Compact worktree
319```
320
321Note: Git passthrough works for ALL subcommands, even those not explicitly listed.
322
323### GitHub (26-87% savings)
324```bash
325rtk gh pr view <num> # Compact PR view (87%)
326rtk gh pr checks # Compact PR checks (79%)
327rtk gh run list # Compact workflow runs (82%)
328rtk gh issue list # Compact issue list (80%)
329rtk gh api # Compact API responses (26%)
330```
331
332### JavaScript/TypeScript Tooling (70-90% savings)
333```bash
334rtk pnpm list # Compact dependency tree (70%)
335rtk pnpm outdated # Compact outdated packages (80%)
336rtk pnpm install # Compact install output (90%)
337rtk npm run <script> # Compact npm script output
338rtk npx <cmd> # Compact npx command output
339rtk prisma # Prisma without ASCII art (88%)
340```
341
342### Files & Search (60-75% savings)
343```bash
344rtk ls <path> # Tree format, compact (65%)
345rtk read <file> # Code reading with filtering (60%)
346rtk grep <pattern> # Search grouped by file (75%). Format flags (-c, -l, -L, -o, -Z) run raw.
347rtk find <pattern> # Find grouped by directory (70%)
348```
349
350### Analysis & Debug (70-90% savings)
351```bash
352rtk err <cmd> # Filter errors only from any command
353rtk log <file> # Deduplicated logs with counts
354rtk json <file> # JSON structure without values
355rtk deps # Dependency overview
356rtk env # Environment variables compact
357rtk summary <cmd> # Smart summary of command output
358rtk diff # Ultra-compact diffs
359```
360
361### Infrastructure (85% savings)
362```bash
363rtk docker ps # Compact container list
364rtk docker images # Compact image list
365rtk docker logs <c> # Deduplicated logs
366rtk kubectl get # Compact resource list
367rtk kubectl logs # Deduplicated pod logs
368```
369
370### Network (65-70% savings)
371```bash
372rtk curl <url> # Compact HTTP responses (70%)
373rtk wget <url> # Compact download output (65%)
374```
375
376### Meta Commands
377```bash
378rtk gain # View token savings statistics
379rtk gain --history # View command history with savings
380rtk discover # Analyze Claude Code sessions for missed RTK usage
381rtk proxy <cmd> # Run command without filtering (for debugging)
382rtk init # Add RTK instructions to CLAUDE.md
383rtk init --global # Add RTK to ~/.claude/CLAUDE.md
384```
385
386## Token Savings Overview
387
388| Category | Commands | Typical Savings |
389|----------|----------|-----------------|
390| Tests | vitest, playwright, cargo test | 90-99% |
391| Build | next, tsc, lint, prettier | 70-87% |
392| Git | status, log, diff, add, commit | 59-80% |
393| GitHub | gh pr, gh run, gh issue | 26-87% |
394| Package Managers | pnpm, npm, npx | 70-90% |
395| Files | ls, read, grep, find | 60-75% |
396| Infrastructure | docker, kubectl | 85% |
397| Network | curl, wget | 65-70% |
398
399Overall average: **60-90% token reduction** on common development operations.
400<!-- /rtk-instructions -->
danielvm-git/bigpowers · .cursor/rules/audit-code.mdc
@@ +1 @@
1---
2description: "Self-review checklist for the coding agent to run before dispatching a reviewer. Checks CONVENTIONS.md compliance, Boy Scout Rule, test coverage, types, and SOLID. Produces a pass/fail checklist. Use before request-review, before committing, or when user asks for a code quality check."
3alwaysApply: false
4---
5
6# Audit Code
7> **HARD GATE** — **HARD GATE** — Audit must check for: bugs (correctness), security, performance, and clarity. Do NOT skip security review if the code touches user data, auth, or external APIs.
8
9
10Run this self-review before asking anyone else to look at the code. The goal is to catch everything that is clearly wrong or missing — so the reviewer can focus on design and architecture, not hygiene.
11
12**Distinct from `request-review`:** This is the coding agent checking its own work. No second agent is involved. Run this first; run `request-review` after this passes.
13
14## Look-here-first (churn heuristic)
15
16Before the checklist, rank changed files by git churn and review **high-churn hotspots first** — they carry the most latent risk regardless of diff size.
17
18```bash
19bash scripts/bp-churn-rank.sh --since 90.days --limit 15
20```
21
22Apply the full checklist to churn-ranked files in descending order. Files with zero recent commits but large diffs still get reviewed; churn only sets priority, not scope.
23
24## Modes
25
26- Default: full checklist
27- --quick: Run only Supply Chain and Test Coverage. Use for changes under 50 LOC.
28- --gate: Non-interactive mode for automated CI gating (used by build-epic step 6). Exit with non-zero status code (`exit 1`) on ANY checklist failure; `exit 0` only if ALL items pass. Produces a compact pass/fail summary to stderr. On failure, list every ✗ item with reason.
29- --parallel: Run checklist sections in **isolated git worktrees** (e45s18) so concurrent checks cannot corrupt each other's working tree:
30
31```bash
32bash scripts/lib/parallel-review-worktrees.sh audit-code
33```
34
35
36## Checklist
37
38### Supply Chain & Security
39
40- [ ] slopcheck run for new dependencies; packages tagged in plan-work: `[OK]`, `[SUS]`, or `[SLOP]`
41- [ ] No `[SLOP]` packages without documented human approval
42- [ ] No secrets in diff (`sk-`, `ghp_`, `AKIA`, `.env` values) — see `guard-git` patterns
43- [ ] OWASP Top 10 spot-check: injection, broken auth, sensitive data exposure, misconfiguration (see `docs/references/security-threats.md`)
44- [ ] Security: diff scanned — no unaddressed HIGH findings (or deviations documented in `specs/security/EXCEPTIONS.md`)
45
46### Provenance & Metadata
47
48- [ ] New plan artefacts include `type:` and `context:` metadata
49- [ ] Implementation steps reference ADR or commit SHA where decisions were made
50
51### Law of Demeter
52
53- [ ] No method chains through unrelated objects (e.g. `a.getB().getC().doX()`)
54- [ ] Collaborators talk to immediate neighbors only; law violations need explicit justification
55
56### CONVENTIONS.md Compliance
57
58- [ ] All output files are in `specs/` (no docs written to project root)
59- [ ] No `gh issue create` calls anywhere in new/modified skills or scripts
60- [ ] `gh` used only for PRs and repo clone operations
61- [ ] No GitHub REST API called directly (no curl/fetch to api.github.com)
62
63### Scope
64
65- [ ] Changes are limited to what was asked — nothing extra refactored or reorganized
66- [ ] No speculative features added
67- [ ] No files touched outside the stated scope
68- [ ] **Discovered defects:** Reproducible gate failures (Preflight, CI, golden suite) require fix-or-log — `quick-fix` or `fix-bug` — even when "outside" the story scope. Scope-minimization does not waive Always Green.
69- [ ] Boy Scout Rule applies to files opened to fix a gate failure; it does not excuse skipping red Preflight
70
71### Boy Scout Rule
72
73- [ ] Every file I touched is cleaner than when I found it
74- [ ] No dead code left behind
75- [ ] No commented-out code blocks
76
77### Types and Safety
78
79- [ ] No `any` types introduced (TypeScript) or untyped public functions (Python/Go/etc.)
80- [ ] No `@ts-ignore` or `// eslint-disable` added
81- [ ] No `as unknown as X` casts that bypass type safety
82
83### Test Coverage
84
85- [ ] Every new function has at least one test
86- [ ] Every bug fix has a regression test
87- [ ] Tests verify behavior through public interfaces (not implementation details)
88- [ ] Tests are F.I.R.S.T compliant (per CONVENTIONS.md §Tests; use `enforce-first` if unsure)
89
90### SOLID and Heuristics
91
92- [ ] Single Responsibility: no function or module doing two unrelated things
93- [ ] Open/Closed: extended through interfaces, not by modifying stable code
94- [ ] Dependency Inversion: dependencies injected, not imported globally where avoidable
95- [ ] **Chapter 17 Heuristics**: Code is free of smells documented in `audit-code/HEURISTICS.md` (G, N, C, T)
96
97### Refactoring Smells (Fowler)
98
99Explicitly name any detected smells: Mysterious Name, Duplicated Code, Feature Envy, Data Clumps, Primitive Obsession, Message Chains, Middle Man.
100
101### Code Style (CONVENTIONS.md)
102
103- [ ] Functions: 4–20 lines; split if longer
104- [ ] Functions: descend exactly one level of abstraction (The Stepdown Rule / G34)
105- [ ] Files: under 300 lines (ideally 200–300)
106- [ ] Names: specific and unique (grep returns < 5 hits for each name)
107- [ ] No duplication — shared logic extracted (DRY / G5)
108- [ ] Early returns over nested ifs; max 2 levels of indentation
109- [ ] Conditionals: expressed as positives (G29)
110- [ ] Comments explain WHY, not WHAT
111
112### Red Flags
113
114Before reporting, name any rationalization you caught yourself making for skipping a checklist item. Silence is not acceptable — if you skipped an item, state the reason explicitly.
115
116## Output
117
118Report the checklist with ✓ / ✗ per item. For each ✗, describe what needs to be fixed.
119
120If all items pass: suggest running `request-review` for an independent second opinion.
121If any items fail: fix them before proceeding.
122
123In `--gate` mode, print one summary line per checklist section (`PASS Supply Chain` / `FAIL Provenance (2 items)`). Exit `0` only if all PASS. Write full report to `specs/verifications/AUDIT-<epic>-<story>.md`.
124
125## Verify
126
127→ verify: `test -f CONVENTIONS.md && test -d skills/enforce-first && test -d skills/request-review`
128
129## Handoff
130
131Gate: READY -> next: commit-message
132Writes: state.yaml handoff.next_skill = commit-message
133
134
135<!-- story: e01s02 -->
136<!-- story: e06s03 -->
137<!-- story: e07s01 -->
138
139---
140
141# Clean Code Heuristics (Chapter 17)
142
143A summary of Robert C. Martin's catalogue of code smells and heuristics, used as the technical benchmark for `audit-code`.
144
145## Comments (C)
146- **C1: Inappropriate Information**: Comments should only hold technical notes. Metadata (author, change history) belongs in Git.
147- **C2: Obsolete Comment**: Update or delete comments that are no longer accurate.
148- **C3: Redundant Comment**: Don't describe code that adequately describes itself (e.g., `i++; // increment i`).
149- **C4: Poorly Written Comment**: If you write a comment, spend time making it the best it can be.
150- **C5: Commented-Out Code**: Delete it. Git remembers it.
151
152## Environment (E)
153- **E1: Build Requires More Than One Step**: Building should be a single trivial operation (e.g., `bash install.sh`).
154- **E2: Tests Require More Than One Step**: Running all tests should be one simple command (e.g., `npm test`).
155
156## Functions (F)
157- **F1: Too Many Arguments**: 0 is ideal, 1-2 is fine, 3 requires special justification. Never > 3.
158- **F2: Output Arguments**: Avoid them. If a function changes state, it should change the state of its owning object.
159- **F3: Flag Arguments**: Boolean arguments are a smell that the function does > 1 thing.
160- **F4: Dead Function**: Discard methods that are never called.
161
162## General (G)
163- **G1: Multiple Languages in One Source File**: Try to minimize the mixing of languages (e.g., HTML inside Java).
164- **G5: Duplication (DRY)**: **The root of all evil.** Every time you see duplication, it's a missed opportunity for abstraction.
165- **G6: Code at Wrong Level of Abstraction**: High-level concepts in base classes; low-level details in derivatives.
166- **G25: Replace Magic Numbers with Named Constants**: No "naked" numbers or strings.
167- **G28: Encapsulate Conditionals**: Prefer `if (shouldBePublished())` over complex boolean logic.
168- **G29: Avoid Negative Conditionals**: Prefer `if (buffer.shouldCompact())` over `if (!buffer.shouldNotCompact())`.
169- **G30: Functions Should Do One Thing**: If a function can be split into sections, it's doing too much.
170- **G31: Hidden Temporal Couplings**: If execution order matters, make the dependency explicit via arguments.
171- **G34: Functions Should Descend Only One Level of Abstraction**: The Stepdown Rule.
172
173## Naming (N)
174- **N1: Choose Descriptive Names**: Names should reveal intent and be updated as code evolves.
175- **N4: Unambiguous Names**: Names should make the working of a function/variable clear.
176- **N7: Names Should Describe Side-Effects**: Describe everything the function is or does.
177
178## Tests (T)
179- **T1: Insufficient Tests**: A test suite should test everything that could possibly break.
180- **T4: An Ignored Test Is a Question about an Ambiguity**: Document the reason for `@Ignore`.
181- **T5: Test Boundary Conditions**: Most bugs happen at the boundaries; test them exhaustively.
182- **T8: Test Coverage Patterns Can Be Revealing**: Analyze what code is *not* executed to find gaps.
183- **T9: Tests Should Be Fast**: Slow tests don't get run.
184
@@ −1 +1 @@
1−# story: e38s08
2−# story: e51s05
3−# story: e45s22
4−# story: e45s23
5−# story: e55s03
1+---
2+description: "Self-review checklist for the coding agent to run before dispatching a reviewer. Checks CONVENTIONS.md compliance, Boy Scout Rule, test coverage, types, and SOLID. Produces a pass/fail checklist. Use before request-review, before committing, or when user asks for a code quality check."
3+alwaysApply: false
4+---
65
7−# bigpowers — Claude Code
6+# Audit Code
7+> **HARD GATE** — **HARD GATE** — Audit must check for: bugs (correctness), security, performance, and clarity. Do NOT skip security review if the code touches user data, auth, or external APIs.
88
9−Read CONVENTIONS.md before any GitHub or git operation.
109
11−[`constitution.md`](constitution.md) is a consolidated entry point synthesizing
12−this project's doctrine (this file, CONVENTIONS.md, docs/PRINCIPLES.md,
13−docs/references/*.md) into bigspec's B0-B10 + Capstone blocks, with citations
14−back to the fuller text. It's a starting point for a reader, not a
15−replacement — this file remains fully authoritative for its own content today.
10+Run this self-review before asking anyone else to look at the code. The goal is to catch everything that is clearly wrong or missing — so the reviewer can focus on design and architecture, not hygiene.
1611
17−<!-- BEGIN bigpowers:context-routing -->
18−## Context Routing
12+**Distinct from `request-review`:** This is the coding agent checking its own work. No second agent is involved. Run this first; run `request-review` after this passes.
1913
20−Load subdirectory context **by file glob** — do not read the full doc tree up front.
14+## Look-here-first (churn heuristic)
2115
22−| Glob / trigger | Load first | Fallback |
23−|----------------|------------|----------|
24−| `skills/**` | Active skill's `SKILL.md` + sibling `REFERENCE.md` if linked | `SKILL-INDEX.md` |
25−| `specs/epics/**` | Capsule `epic.yaml` + active story `-tasks.yaml` | `specs/release-plan.yaml` |
26−| `specs/product/**` | `SCOPE_LATEST.yaml`, `VISION_LATEST.yaml` | `specs/README.md` |
27−| `specs/tech-architecture/**` | `tech-stack.md` + epic `eNN-TEST_PLAN_LATEST.md` if present | `CONVENTIONS.md` |
28−| `scripts/**` | `CONVENTIONS.md` § Generated artifact targets | This file § Commands |
29−| `website/**` | `website/README.md` if present | Never edit `website/src/content/docs/` (generated) |
30−| `docs/**` | Matching doc under `docs/` | `docs/references/` |
31−| Default / session start | This file → `CONVENTIONS.md` → `specs/state.yaml` | `survey-context` |
16+Before the checklist, rank changed files by git churn and review **high-churn hotspots first** — they carry the most latent risk regardless of diff size.
3217
33−Sub-AGENTS.md files (when present in consumer projects) override this table for their directory only.
34−<!-- END bigpowers:context-routing -->
35−
36−<!-- BEGIN bigpowers:learned-preferences -->
37−## Learned User Preferences
38−
39−_Durable preferences discovered across sessions. Update via `session-state` — do not infer from chat alone._
40−
41−- Prefer `rtk`-prefixed shell commands for git, test, and build output (token savings).
42−- Run Preflight before forward work; never dismiss red gates as pre-existing.
43−- Edit `skills/*/SKILL.md` sources only — never `.cursor/rules/` or `.gemini/` artifacts.
44−
45−## Workspace Facts
46−
47−_Stable repo facts — prefer these over re-discovery._
48−
49−- Stack: Markdown / Bash documentation project; skills sync via `bash scripts/sync-skills.sh`.
50−- Planning SoT: `specs/state.yaml`, `specs/release-plan.yaml`, `specs/execution-status.yaml`.
51−- Story traceability: `# story: eNNsNN` tags in implementing files; `bash scripts/trace-stories.sh --strict` in CI.
52−- Rule matrix: `bash scripts/compile-rule-matrix.sh` → `specs/rule-matrix.json` (P0–P3 tiers from CONVENTIONS.md).
53−<!-- END bigpowers:learned-preferences -->
54−
55−## Project
56−
57−bigpowers — agent skills for spec-driven, test-first software development by solo developers (skill count and catalog are auto-generated in `SKILL-INDEX.md`; never hardcode the count in docs).
58−Stack: Markdown / Bash (documentation-based; skills integrate with Claude Code, Cursor, Gemini CLI)
59−
60−## Commands
61−
62−| Action | Command |
63−|---------|---------|
64−| Install | `npm install -g bigpowers && bigpowers setup` |
65−| Run | `bash scripts/sync-skills.sh` |
66−| Test | N/A (documentation project) |
67−| Build | `bash scripts/install.sh` (from source) |
68−| Lint | `bash scripts/sync-skills.sh` (validates SKILL.md syntax) |
69−| Validate specs YAML | `bash scripts/validate-specs-yaml.sh` |
70−| Typecheck | N/A (Markdown / Bash project) |
71−| CI platform | GitHub Actions (`.github/workflows/publish.yml`, `sync-skills.yml`, `golden-suite.yml`) |
72−| Compliance | `npm run compliance` |
73−| Verification Gates | `bash scripts/run-verification-gates.sh` |
74−| Traceability | `bash scripts/trace-stories.sh --strict` | grep for story tags (traceability check) |
75−| Preflight | `npm run compliance && bash scripts/run-verification-gates.sh && bash scripts/sync-skills.sh && bash scripts/trace-stories.sh --strict` | Full local green stack before forward work. Chain ends on `--strict` traceability — no trailing always-exit-0 step. |
76−| Catalog drift (advisory) | `bash scripts/check-catalog-drift.sh` | e54s02 Confirm gate during catalog freeze — always exits 0; run manually when changing skills, not part of Preflight. |
77−| CI | `gh pr checks` | Remote CI green when a PR is open |
78−
79−### Pre-Merge Checklist
80−
81−Before opening a PR or landing a branch, run:
82−
8318 ```bash
84−npm run compliance && bash scripts/run-verification-gates.sh
19+bash scripts/bp-churn-rank.sh --since 90.days --limit 15
8520 ```
8621
87−If any gate fails, fix before merging. Run `--baseline` after any intentional increase in skill count or structure.
22+Apply the full checklist to churn-ranked files in descending order. Files with zero recent commits but large diffs still get reviewed; churn only sets priority, not scope.
8823
89−**BCP Plus:** For stories sized with the 13-dimension BCP Plus methodology, confirm the `bcp_plus_breakdown` is present in the epic YAML and carried into `state.yaml` as `epic_cycle.bcp_plus`. See `docs/references/bcp-plus.md` for the NFR Gate pattern.
24+## Modes
9025
91−## Architecture
26+- Default: full checklist
27+- --quick: Run only Supply Chain and Test Coverage. Use for changes under 50 LOC.
28+- --gate: Non-interactive mode for automated CI gating (used by build-epic step 6). Exit with non-zero status code (`exit 1`) on ANY checklist failure; `exit 0` only if ALL items pass. Produces a compact pass/fail summary to stderr. On failure, list every ✗ item with reason.
29+- --parallel: Run checklist sections in **isolated git worktrees** (e45s18) so concurrent checks cannot corrupt each other's working tree:
9230
93−Collection of verb-noun skills under `skills/`, each with a SKILL.md source file and supporting documentation. Runtime specs live in `specs/state.yaml`, `specs/release-plan.yaml`, and `specs/execution-status.yaml`; intent in `specs/product/`; epic shards in `specs/epics/`. The sync-skills.sh script auto-generates artifacts for Cursor (.cursor/rules) and Gemini CLI (.gemini/extensions/bigpowers/) from SKILL.md sources. All planning output goes to specs/ at the project root.
94−
95−## Conventions
96−
97−- Skill directories under `skills/` use verb-noun naming (two words, kebab-case)
98−- Every skill has a single SKILL.md file as its source of truth
99−- All planning/spec output goes to specs/ at project root
100−- Artifacts in .cursor/rules and .gemini/ are auto-generated; edit SKILL.md, not artifacts
101−- Run sync-skills.sh after any SKILL.md changes to regenerate artifacts
102−- Website content in website/src/content/docs/ is auto-generated by prebuild; edit repo sources, not site files
103−
104−## Never
105−
106−- Never edit .cursor/rules or .gemini/extensions/ directly — these are generated files
107−- Never edit website/src/content/docs/ directly — these are generated files; website/ is the fourth generated artifact target (alongside .cursor/, .gemini/, .pi/)
108−- Never create a skill without a SKILL.md file and proper verb-noun naming
109−- Never push changes without running sync-skills.sh first
110−
111−## Token Management
112−
113−**Mechanical backstop (e45s03):** `scripts/hooks/token-mgmt-pre-tool-use.sh` blocks oversized tool calls when prose rules are ignored. Wire as a `PreToolUse` hook for `Read`, `Grep`, and `Bash` (alongside `hooks/pre-tool-use.sh` for git safety). Thresholds: Read >100KB, Grep >200 matches without `head_limit`, Bash commands likely to exceed 500 output lines without `rtk`/`sqz compress`. Install snippet:
114−
115−```json
116−{
117− "hooks": {
118− "PreToolUse": [
119− { "matcher": "Read|Grep|Bash", "hooks": [{ "type": "command", "command": "bash scripts/hooks/token-mgmt-pre-tool-use.sh" }] }
120− ]
121− }
122−}
31+```bash
32+bash scripts/lib/parallel-review-worktrees.sh audit-code
12333 ```
12434
125−Context engineering (write/select/compress/isolate — see `docs/references/context-engineering.md`):
12635
127−- **Write (token-efficient content):** Short functions (4-20 lines), unique symbol names, headless tests. Don't restate code in comments.
128−- **Select (include only what's relevant):** Use `bts_map` for ranked file lists, `survey-context` for phase bootstrap. Don't read files you don't need.
129−- **Compress (reduce without losing structure):** Use `bts_compress` or pipe through `sqz compress`. Use `rtk` for build/test/git output (60-99% savings). Prefer `terse-mode` when context is heavy.
130−- **Isolate (partition work):** Use `kickoff-branch` for isolated worktrees, `dispatch-agents` for parallel tasks with disjoint scopes, `session-state` for cold-start handoff.
36+## Checklist
13137
132−**Effort classification:** Skills carry an `effort:` frontmatter field (`light` | `standard` | `heavy`). Prefer `light` skills for bootstrap/status checks; reserve `heavy` for epic builds and multi-phase planning.
38+### Supply Chain & Security
13339
134−- **Auto-Terse**: When a session exceeds 20 turns or the context window feels "heavy" (latency increasing), you MUST switch to `terse-mode` to save tokens.
135−- **Context Compaction**: Every 10 turns, summarize the current session state and implementation decisions into a short, high-density note.
136−- **Minimal Output**: Prefer text-only output for simple status; use `web_fetch` or `run_shell_command` only for evidence.
137−- **Stream Stability**: When writing large files or long documents, output continuously in chunks of ~200 lines. Do not pause. If you need time to process, emit a placeholder comment rather than going silent.
40+- [ ] slopcheck run for new dependencies; packages tagged in plan-work: `[OK]`, `[SUS]`, or `[SLOP]`
41+- [ ] No `[SLOP]` packages without documented human approval
42+- [ ] No secrets in diff (`sk-`, `ghp_`, `AKIA`, `.env` values) — see `guard-git` patterns
43+- [ ] OWASP Top 10 spot-check: injection, broken auth, sensitive data exposure, misconfiguration (see `docs/references/security-threats.md`)
44+- [ ] Security: diff scanned — no unaddressed HIGH findings (or deviations documented in `specs/security/EXCEPTIONS.md`)
13845
139−## Session Start
46+### Provenance & Metadata
14047
141−Before any task, run this sequence — not optional:
48+- [ ] New plan artefacts include `type:` and `context:` metadata
49+- [ ] Implementation steps reference ADR or commit SHA where decisions were made
14250
143−1. Read `CLAUDE.md` (this file)
144−2. Read `CONVENTIONS.md`
145−3. Read `specs/state.yaml` if it exists — current session and active epic
146−4. Read `specs/release-plan.yaml` if it exists — active release context
51+### Law of Demeter
14752
148−## Agent Rules
53+- [ ] No method chains through unrelated objects (e.g. `a.getB().getC().doX()`)
54+- [ ] Collaborators talk to immediate neighbors only; law violations need explicit justification
14955
150−- **Workflow Mandate:** You MUST use the bigpowers skills (e.g., `plan-work`, `develop-tdd`, `craft-skill`) to perform tasks. DO NOT write code directly in response to a user prompt like "build this feature".
151−- **Always Green / fix-or-log:** Preflight and CI must be green before forward work. Any reproducible gate failure during unrelated work requires **quick-fix** or **fix-bug** — see CONVENTIONS § Discovered Defects. Never dismiss failures as pre-existing or out of scope.
152−- Read specs/ and CONVENTIONS.md before writing code.
153−- Write the minimum code that solves the stated problem. Nothing extra.
154−- Run tests after every change. Show evidence before declaring done.
155−- One clarifying question beats a wrong assumption baked into 200 lines.
156−- All written output (plans, specs, investigations) goes in specs/.
56+### CONVENTIONS.md Compliance
15757
158−## bts toolchain
58+- [ ] All output files are in `specs/` (no docs written to project root)
59+- [ ] No `gh issue create` calls anywhere in new/modified skills or scripts
60+- [ ] `gh` used only for PRs and repo clone operations
61+- [ ] No GitHub REST API called directly (no curl/fetch to api.github.com)
15962
160−`bts` is installed. Prefer its verbs over ad-hoc shell commands.
63+### Scope
16164
162−| Task | Command | Avoid |
163−|------|---------|-------|
164−| Search code | `bts find --print <pattern>` | grep / find / cat |
165−| Interactive search | `bts find <pattern>` | manual grep pipes |
166−| Compress for context | `bts compress <file>` or `cmd \| bts compress` | summarising by hand |
167−| Repo map | `bts map` | listing files by hand |
168−| Library docs | `bts docs <lib>` | guessing from training data |
169−| Package source | `bts src <pkg>` | git clone |
170−| Toolchain health | `bts doctor` | which / command -v |
65+- [ ] Changes are limited to what was asked — nothing extra refactored or reorganized
66+- [ ] No speculative features added
67+- [ ] No files touched outside the stated scope
68+- [ ] **Discovered defects:** Reproducible gate failures (Preflight, CI, golden suite) require fix-or-log — `quick-fix` or `fix-bug` — even when "outside" the story scope. Scope-minimization does not waive Always Green.
69+- [ ] Boy Scout Rule applies to files opened to fix a gate failure; it does not excuse skipping red Preflight
17170
172−**Rules**
173−- Search with `bts find` before opening files to locate a symbol or pattern.
174−- Pipe anything > 200 lines through `bts compress` before adding to context.
175−- Run `bts map` when asked for a repo overview.
176−- Use `bts docs <lib>` before answering questions about library APIs. Doc fetches use `scripts/lib/doc-fetch-cache.sh` (ETag-revalidated, 300s TTL — see `context7-mcp` skill, e45s20).
177−- If a tool is missing, say so and run `bts doctor` — do not silently substitute.
71+### Boy Scout Rule
17872
179−<!-- BEGIN rtk-pretooluse-hook (e45s16 — mechanical PreToolUse backstop; remove block to disable) -->
73+- [ ] Every file I touched is cleaner than when I found it
74+- [ ] No dead code left behind
75+- [ ] No commented-out code blocks
18076
181−**RTK hook (installed):** `scripts/hooks/rtk-rewrite.sh` is symlinked into `~/.claude/hooks/` by `bash scripts/install.sh` and registered as a Bash `PreToolUse` hook. It delegates to `rtk hook claude` — prose rules below are a fallback only when the hook is absent.
77+### Types and Safety
18278
183−<!-- END rtk-pretooluse-hook -->
79+- [ ] No `any` types introduced (TypeScript) or untyped public functions (Python/Go/etc.)
80+- [ ] No `@ts-ignore` or `// eslint-disable` added
81+- [ ] No `as unknown as X` casts that bypass type safety
18482
185−<!-- BEGIN sqz-claude-guidance (auto-installed by sqz init; remove this block to disable) -->
83+### Test Coverage
18684
187−## sqz — Context Compression (READ FIRST)
85+- [ ] Every new function has at least one test
86+- [ ] Every bug fix has a regression test
87+- [ ] Tests verify behavior through public interfaces (not implementation details)
88+- [ ] Tests are F.I.R.S.T compliant (per CONVENTIONS.md §Tests; use `enforce-first` if unsure)
18889
189−sqz is installed in this project. It compresses tool output so large
190−files, long logs, and verbose command output cost far fewer tokens.
191−There are **two ways** sqz is wired in, and you should prefer each
192−one in the situations below.
90+### SOLID and Heuristics
19391
194−### Preferred tools (MCP)
92+- [ ] Single Responsibility: no function or module doing two unrelated things
93+- [ ] Open/Closed: extended through interfaces, not by modifying stable code
94+- [ ] Dependency Inversion: dependencies injected, not imported globally where avoidable
95+- [ ] **Chapter 17 Heuristics**: Code is free of smells documented in `audit-code/HEURISTICS.md` (G, N, C, T)
19596
196−The `sqz-mcp` server is registered in this project's MCP config. It
197−exposes three read-only tools that compress their output through the
198−sqz pipeline:
97+### Refactoring Smells (Fowler)
19998
200−- **`sqz_read_file`** — read a file from disk and return a compressed
201− view. **PREFER this over the built-in `Read` tool** for any file
202− larger than ~2KB or any file you might read more than once in the
203− same session. Repeat reads return a 13-token `§ref:HASH§` reference
204− instead of the full content.
99+Explicitly name any detected smells: Mysterious Name, Duplicated Code, Feature Envy, Data Clumps, Primitive Obsession, Message Chains, Middle Man.
205100
206−- **`sqz_grep`** — search files for a literal string or regex.
207− **PREFER this over the built-in `Grep`** for anything that might
208− match more than a handful of lines. Caps at 200 matches by default;
209− raise with `max_matches` if needed.
101+### Code Style (CONVENTIONS.md)
210102
211−- **`sqz_list_dir`** — list a directory. Skips `.git`, `node_modules`,
212− `target`, `dist`, `build`, `vendor`, `__pycache__` so the output
213− stays focused. **PREFER this over `ls -la` via Bash** when you want
214− to see a project layout.
103+- [ ] Functions: 4–20 lines; split if longer
104+- [ ] Functions: descend exactly one level of abstraction (The Stepdown Rule / G34)
105+- [ ] Files: under 300 lines (ideally 200–300)
106+- [ ] Names: specific and unique (grep returns < 5 hits for each name)
107+- [ ] No duplication — shared logic extracted (DRY / G5)
108+- [ ] Early returns over nested ifs; max 2 levels of indentation
109+- [ ] Conditionals: expressed as positives (G29)
110+- [ ] Comments explain WHY, not WHAT
215111
216−The built-in `Read`, `Grep`, `Glob` tools remain available. Use them for:
217−- Tiny config files (<1KB) where compression can't help.
218−- Byte-exact reads you'll hash or diff (lockfiles, signatures).
219−- Globbing (sqz has no glob tool; `Glob` is still the right choice).
112+### Red Flags
220113
221−### Bash commands (hooked automatically)
114+Before reporting, name any rationalization you caught yourself making for skipping a checklist item. Silence is not acceptable — if you skipped an item, state the reason explicitly.
222115
223−When you run a shell command through the `Bash` tool, a PreToolUse hook
224−rewrites it to pipe output through `sqz compress`. This is transparent:
225−you don't need to remember to add anything, but it's useful to know
226−that these commands get compressed automatically:
116+## Output
227117
228−```bash
229−git status # → git status 2>&1 | sqz compress --cmd git
230−cargo test # → cargo test 2>&1 | sqz compress --cmd cargo
231−docker ps # → docker ps 2>&1 | sqz compress --cmd docker
232−kubectl get pods # → kubectl get pods 2>&1 | sqz compress --cmd kubectl
233−```
118+Report the checklist with ✓ / ✗ per item. For each ✗, describe what needs to be fixed.
234119
235−The rewrite is skipped for interactive commands (`vim`, `ssh`,
236−`python`), compound commands (`a && b`, `a > file.txt`), and anything
237−already going through sqz.
120+If all items pass: suggest running `request-review` for an independent second opinion.
121+If any items fail: fix them before proceeding.
238122
239−### Escape hatch — when you see a `§ref:HASH§` token
123+In `--gate` mode, print one summary line per checklist section (`PASS Supply Chain` / `FAIL Provenance (2 items)`). Exit `0` only if all PASS. Write full report to `specs/verifications/AUDIT-<epic>-<story>.md`.
240124
241−If tool output contains a `§ref:a1b2c3d4§` token and you need the full
242−content it points at, resolve it. Three equivalent ways:
125+## Verify
243126
244−- Shell: `/Users/danielvm/.local/bin/sqz expand a1b2c3d4` (or paste the whole token
245− `/Users/danielvm/.local/bin/sqz expand §ref:a1b2c3d4§`).
246−- MCP tool: call `expand` with `{ "prefix": "a1b2c3d4" }`.
247−- To get uncompressed output for one command: prefix it with
248− `SQZ_NO_DEDUP=1` (e.g. `SQZ_NO_DEDUP=1 git log | sqz compress`).
127+→ verify: `test -f CONVENTIONS.md && test -d skills/enforce-first && test -d skills/request-review`
249128
250−If the compressed output is actively making the task harder (looping
251−on refs, small retries replacing one big read), call the `passthrough`
252−MCP tool to get raw text.
129+## Handoff
253130
254−### When NOT to use sqz tools
131+Gate: READY -> next: commit-message
132+Writes: state.yaml handoff.next_skill = commit-message
255133
256−- Writing or editing files — use the built-in `Write`/`Edit` tools.
257− sqz has no write tools (by design; see issue #5 follow-up).
258−- Running commands interactively or in watch mode.
259−- Reading very small files (<1KB) where compression can't help.
260134
261−<!-- END sqz-claude-guidance -->
135+<!-- story: e01s02 -->
136+<!-- story: e06s03 -->
137+<!-- story: e07s01 -->
262138
263−<!-- rtk-instructions v2 -->
264−# RTK (Rust Token Killer) - Token-Optimized Commands
139+---
265140
266−## Golden Rule
141+# Clean Code Heuristics (Chapter 17)
267142
268−**Always prefix commands with `rtk`**. If RTK has a dedicated filter, it uses it. If not, it passes through unchanged. This means RTK is always safe to use.
143+A summary of Robert C. Martin's catalogue of code smells and heuristics, used as the technical benchmark for `audit-code`.
269144
270−**Important**: Even in command chains with `&&`, use `rtk`:
271−```bash
272−# ❌ Wrong
273−git add . && git commit -m "msg" && git push
145+## Comments (C)
146+- **C1: Inappropriate Information**: Comments should only hold technical notes. Metadata (author, change history) belongs in Git.
147+- **C2: Obsolete Comment**: Update or delete comments that are no longer accurate.
148+- **C3: Redundant Comment**: Don't describe code that adequately describes itself (e.g., `i++; // increment i`).
149+- **C4: Poorly Written Comment**: If you write a comment, spend time making it the best it can be.
150+- **C5: Commented-Out Code**: Delete it. Git remembers it.
274151
275−# ✅ Correct
276−rtk git add . && rtk git commit -m "msg" && rtk git push
277−```
152+## Environment (E)
153+- **E1: Build Requires More Than One Step**: Building should be a single trivial operation (e.g., `bash install.sh`).
154+- **E2: Tests Require More Than One Step**: Running all tests should be one simple command (e.g., `npm test`).
278155
279−## RTK Commands by Workflow
156+## Functions (F)
157+- **F1: Too Many Arguments**: 0 is ideal, 1-2 is fine, 3 requires special justification. Never > 3.
158+- **F2: Output Arguments**: Avoid them. If a function changes state, it should change the state of its owning object.
159+- **F3: Flag Arguments**: Boolean arguments are a smell that the function does > 1 thing.
160+- **F4: Dead Function**: Discard methods that are never called.
280161
281−### Build & Compile (80-90% savings)
282−```bash
283−rtk cargo build # Cargo build output
284−rtk cargo check # Cargo check output
285−rtk cargo clippy # Clippy warnings grouped by file (80%)
286−rtk tsc # TypeScript errors grouped by file/code (83%)
287−rtk lint # ESLint/Biome violations grouped (84%)
288−rtk prettier --check # Files needing format only (70%)
289−rtk next build # Next.js build with route metrics (87%)
290−```
162+## General (G)
163+- **G1: Multiple Languages in One Source File**: Try to minimize the mixing of languages (e.g., HTML inside Java).
164+- **G5: Duplication (DRY)**: **The root of all evil.** Every time you see duplication, it's a missed opportunity for abstraction.
165+- **G6: Code at Wrong Level of Abstraction**: High-level concepts in base classes; low-level details in derivatives.
166+- **G25: Replace Magic Numbers with Named Constants**: No "naked" numbers or strings.
167+- **G28: Encapsulate Conditionals**: Prefer `if (shouldBePublished())` over complex boolean logic.
168+- **G29: Avoid Negative Conditionals**: Prefer `if (buffer.shouldCompact())` over `if (!buffer.shouldNotCompact())`.
169+- **G30: Functions Should Do One Thing**: If a function can be split into sections, it's doing too much.
170+- **G31: Hidden Temporal Couplings**: If execution order matters, make the dependency explicit via arguments.
171+- **G34: Functions Should Descend Only One Level of Abstraction**: The Stepdown Rule.
291172
292−### Test (60-99% savings)
293−```bash
294−rtk cargo test # Cargo test failures only (90%)
295−rtk go test # Go test failures only (90%)
296−rtk jest # Jest failures only (99.5%)
297−rtk vitest # Vitest failures only (99.5%)
298−rtk playwright test # Playwright failures only (94%)
299−rtk pytest # Python test failures only (90%)
300−rtk rake test # Ruby test failures only (90%)
301−rtk rspec # RSpec test failures only (60%)
302−rtk test <cmd> # Generic test wrapper - failures only
303−```
173+## Naming (N)
174+- **N1: Choose Descriptive Names**: Names should reveal intent and be updated as code evolves.
175+- **N4: Unambiguous Names**: Names should make the working of a function/variable clear.
176+- **N7: Names Should Describe Side-Effects**: Describe everything the function is or does.
304177
305−### Git (59-80% savings)
306−```bash
307−rtk git status # Compact status
308−rtk git log # Compact log (works with all git flags)
309−rtk git diff # Compact diff (80%)
310−rtk git show # Compact show (80%)
311−rtk git add # Ultra-compact confirmations (59%)
312−rtk git commit # Ultra-compact confirmations (59%)
313−rtk git push # Ultra-compact confirmations
314−rtk git pull # Ultra-compact confirmations
315−rtk git branch # Compact branch list
316−rtk git fetch # Compact fetch
317−rtk git stash # Compact stash
318−rtk git worktree # Compact worktree
319−```
178+## Tests (T)
179+- **T1: Insufficient Tests**: A test suite should test everything that could possibly break.
180+- **T4: An Ignored Test Is a Question about an Ambiguity**: Document the reason for `@Ignore`.
181+- **T5: Test Boundary Conditions**: Most bugs happen at the boundaries; test them exhaustively.
182+- **T8: Test Coverage Patterns Can Be Revealing**: Analyze what code is *not* executed to find gaps.
183+- **T9: Tests Should Be Fast**: Slow tests don't get run.
320184
321−Note: Git passthrough works for ALL subcommands, even those not explicitly listed.
322−
323−### GitHub (26-87% savings)
324−```bash
325−rtk gh pr view <num> # Compact PR view (87%)
326−rtk gh pr checks # Compact PR checks (79%)
327−rtk gh run list # Compact workflow runs (82%)
328−rtk gh issue list # Compact issue list (80%)
329−rtk gh api # Compact API responses (26%)
330−```
331−
332−### JavaScript/TypeScript Tooling (70-90% savings)
333−```bash
334−rtk pnpm list # Compact dependency tree (70%)
335−rtk pnpm outdated # Compact outdated packages (80%)
336−rtk pnpm install # Compact install output (90%)
337−rtk npm run <script> # Compact npm script output
338−rtk npx <cmd> # Compact npx command output
339−rtk prisma # Prisma without ASCII art (88%)
340−```
341−
342−### Files & Search (60-75% savings)
343−```bash
344−rtk ls <path> # Tree format, compact (65%)
345−rtk read <file> # Code reading with filtering (60%)
346−rtk grep <pattern> # Search grouped by file (75%). Format flags (-c, -l, -L, -o, -Z) run raw.
347−rtk find <pattern> # Find grouped by directory (70%)
348−```
349−
350−### Analysis & Debug (70-90% savings)
351−```bash
352−rtk err <cmd> # Filter errors only from any command
353−rtk log <file> # Deduplicated logs with counts
354−rtk json <file> # JSON structure without values
355−rtk deps # Dependency overview
356−rtk env # Environment variables compact
357−rtk summary <cmd> # Smart summary of command output
358−rtk diff # Ultra-compact diffs
359−```
360−
361−### Infrastructure (85% savings)
362−```bash
363−rtk docker ps # Compact container list
364−rtk docker images # Compact image list
365−rtk docker logs <c> # Deduplicated logs
366−rtk kubectl get # Compact resource list
367−rtk kubectl logs # Deduplicated pod logs
368−```
369−
370−### Network (65-70% savings)
371−```bash
372−rtk curl <url> # Compact HTTP responses (70%)
373−rtk wget <url> # Compact download output (65%)
374−```
375−
376−### Meta Commands
377−```bash
378−rtk gain # View token savings statistics
379−rtk gain --history # View command history with savings
380−rtk discover # Analyze Claude Code sessions for missed RTK usage
381−rtk proxy <cmd> # Run command without filtering (for debugging)
382−rtk init # Add RTK instructions to CLAUDE.md
383−rtk init --global # Add RTK to ~/.claude/CLAUDE.md
384−```
385−
386−## Token Savings Overview
387−
388−| Category | Commands | Typical Savings |
389−|----------|----------|-----------------|
390−| Tests | vitest, playwright, cargo test | 90-99% |
391−| Build | next, tsc, lint, prettier | 70-87% |
392−| Git | status, log, diff, add, commit | 59-80% |
393−| GitHub | gh pr, gh run, gh issue | 26-87% |
394−| Package Managers | pnpm, npm, npx | 70-90% |
395−| Files | ls, read, grep, find | 60-75% |
396−| Infrastructure | docker, kubectl | 85% |
397−| Network | curl, wget | 65-70% |
398−
399−Overall average: **60-90% token reduction** on common development operations.
400−<!-- /rtk-instructions -->
