Brainless — Your External Brain
"You don't need a brain. I remember everything for you."
"你不需要脑子。我帮你全记着。"
A persistent, categorized knowledge base that records errors, solutions, CTF challenge writeups, reverse engineering notes, useful tricks, and tool techniques. Builds up automatically over time so that previously solved problems are never re-investigated from scratch.
Philosophy: Be brainless. Don't waste neurons remembering things that can be recorded. Offload your memory to me and focus on what matters — solving the next problem.
Storage Location
All records are stored in ~/.claude/brainless/:
INDEX.md — master index with all entries organized by category
_cache.json — lightweight JSON cache for fast search
- Category subdirectories (see below)
- Each entry is a single
.md file in its category directory
Categories
Development Errors
| Category |
Directory |
Scope |
build |
build/ |
Compilation, linking, build system errors |
runtime |
runtime/ |
Crashes, panics, runtime exceptions |
config |
config/ |
Configuration, environment, settings issues |
network |
network/ |
Connection, timeout, DNS, API errors |
dependency |
dependency/ |
Package version conflicts, missing deps |
permission |
permission/ |
File/directory/system permission issues |
logic |
logic/ |
Business logic bugs, incorrect behavior |
Security & RE
| Category |
Directory |
Scope |
ctf |
ctf/ |
CTF challenge writeups — pwn, web, crypto, reverse, misc, forensics |
reversing |
reversing/ |
IDA/Ghidra analysis notes, deobfuscation, unpacking, anti-debug bypass |
exploit |
exploit/ |
Exploit development techniques, shellcode, ROP, heap tricks |
Knowledge & Techniques
| Category |
Directory |
Scope |
tricks |
tricks/ |
Useful non-obvious techniques worth remembering |
tools |
tools/ |
Tool usage tips — IDA, Ghidra, gdb, Wireshark, Burp, etc. |
other |
other/ |
Anything that doesn't fit above |
Record Templates
Template A: Error Record (build/runtime/config/network/dependency/permission/logic)
---
title: [Concise error description]
type: error
category: [category]
tags: [tag1, tag2, tag3]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
severity: [low/medium/high/critical]
related: []
---
## Error Message
\```
[Exact error output]
\```
## Environment
- Project: [project name]
- Toolchain: [compiler/runtime version]
- OS: [operating system]
## Root Cause
[Brief explanation of why this error occurred]
## Solution
[Step-by-step fix]
## Related Files
- `path/to/file:line`
## Notes
[Any additional context, gotchas, or related issues]
Template B: CTF Writeup (ctf)
---
title: [Challenge name — CTF competition name]
type: ctf
category: ctf
tags: [pwn/web/crypto/reverse/misc/forensics, difficulty, technique-keywords]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
difficulty: [easy/medium/hard/insane]
ctf_category: [pwn/web/crypto/reverse/misc/forensics]
solved: [true/false]
related: []
---
## Challenge Description
[Brief challenge description, what was given]
## Initial Analysis
[First observations, what tools were used to examine]
## Wrong Approaches (What Didn't Work)
1. [Approach 1] — why it failed
2. [Approach 2] — why it failed
## Solution
[Step-by-step solution that worked]
## Key Insight
[The critical "aha" moment — the non-obvious realization that led to the solve]
## Tools Used
- [tool1]: [how it was used]
- [tool2]: [how it was used]
## Flag
\```
[flag if applicable]
\```
## Lessons Learned
[What to remember for next time — patterns, techniques, gotchas]
## References
- [links to relevant resources, similar challenges]
Template C: Reversing Note (reversing)
---
title: [Concise description of the RE challenge/technique]
type: reversing
category: reversing
tags: [ida/ghidra, technique, binary-type, arch]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
target: [binary name or type]
arch: [x86/x64/arm/arm64/mips]
related: []
---
## Target
- Binary: [name/type]
- Protection: [packer, obfuscation, anti-debug methods]
- Architecture: [x86/x64/arm/...]
## Problem
[What was confusing or blocking analysis]
## Analysis Process
[Step-by-step analysis — what was examined, in what order]
## Key Findings
[Important structures, algorithms, patterns discovered]
## Solution / Technique
[How the problem was resolved — specific IDA/Ghidra operations, scripts, etc.]
## IDA/Ghidra Notes
- [Specific operations, scripts, or plugins used]
- [Struct definitions, type assignments that helped]
## Patterns to Recognize
[Signatures or patterns that identify similar problems in the future]
## Notes
[Additional context]
Template D: Exploit Technique (exploit)
---
title: [Exploit technique name]
type: exploit
category: exploit
tags: [pwn, technique-type, protection-bypass]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
difficulty: [easy/medium/hard]
related: []
---
## Technique
[Name and brief description]
## Prerequisites
[What conditions must be met — vulnerable function, leak primitive, etc.]
## Protection Bypasses
[What mitigations this bypasses — ASLR, NX, canary, PIE, etc.]
## Step-by-Step
1. [Step 1]
2. [Step 2]
...
## Code Snippet
\```python
[Exploit template / key snippet]
\```
## Gotchas
[Common mistakes, alignment issues, version-specific details]
## References
- [Links to papers, blog posts, similar exploits]
Template E: Trick / Technique (tricks)
---
title: [Concise trick description]
type: trick
category: tricks
tags: [domain, language, tool]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
related: []
---
## What
[What this trick does]
## When to Use
[Situation where this trick is useful]
## How
[Step-by-step or code snippet]
## Why It Works
[Brief explanation of the underlying mechanism]
## Notes
[Caveats, alternatives, related tricks]
Template F: Tool Usage (tools)
---
title: [Tool name — specific technique]
type: tool
category: tools
tags: [tool-name, use-case]
created: [YYYY-MM-DD]
last_hit: [YYYY-MM-DD]
hit_count: 1
tool: [tool name]
related: []
---
## Tool
[Tool name and version]
## Use Case
[When you'd need this]
## Command / Steps
\```bash
[Exact commands or steps]
\```
## Expected Output
[What to expect]
## Tips
[Non-obvious flags, options, or workflow details]
## Notes
[Gotchas, alternatives]
Modes of Operation
Mode 1: Brain Dump (/brain-dump)
Triggered when:
- User says:
/brain-dump, "record this", "log this"
- AI resolves a non-trivial error (auto-record, see Mode 3)
- User finishes a CTF challenge or RE analysis
Recording workflow:
Determine entry type from context:
- Command failed → Error record (Template A)
- CTF challenge → CTF writeup (Template B)
- IDA/Ghidra analysis → Reversing note (Template C)
- Exploit technique → Exploit record (Template D)
- Useful technique/trick → Trick (Template E)
- Tool usage tip → Tool usage (Template F)
Classify into the appropriate category
Assign tags — free-form keywords relevant to the entry
Check for existing entries — search _cache.json and grep for similar entries. If a similar one exists, UPDATE it instead of creating a duplicate
Generate slug filename — lowercase, hyphen-separated, descriptive
Write the file using the appropriate template
Scan for cross-references — if the new entry references techniques, tools, or errors from other entries, add their filenames to the related: [] frontmatter field, and add a back-reference in those entries too
Update all indexes (in this order — ALL steps are MANDATORY, do NOT skip any):
a. _cache.json — add entry to entries[] with fields: id (category/slug), title, category, tags, error_pattern (regex from error message), solution_hint (one-line), hit_count, last_hit. Add tags to tags_index. Increment total. Update updated date. WARNING: If you skip this step, the auto-search hook and Mode 4 will NOT find the entry!
b. <category>/_index.md — add one-line entry to the sub-index table
c. INDEX.md — increment the count for the category, update total
Confirm to user — show what was recorded
Common failure mode: Writing the .md file but forgetting to update _cache.json. This makes the entry invisible to all search mechanisms. If you suspect desync, run /brain-rebuild.
Mode 2: Brain Search (/brain-search) — 3-Level Strategy
Triggered when:
- User says:
/brain-search, "have we seen this", "search kb"
- AI encounters an error (auto-search, see Mode 4)
- Encountering a CTF challenge similar to a previous one
3-Level search strategy (from cheapest to most expensive):
Level 1: JSON Cache (~50 tokens)
Read ~/.claude/brainless/_cache.json and search:
- Match keywords against
title, summary, tags fields in entries[]
- Use
tags_index for exact tag matches
- This is a single small file containing ALL entry metadata — no need to read anything else
- If match found with high confidence → go directly to Level 3
Level 2: Sub-Index (~20 tokens per category)
If Level 1 gives ambiguous results or you need to narrow by category:
- Read only the relevant
<category>/_index.md file (NOT the full INDEX.md)
- Each sub-index is tiny: just the entries for that one category
- Example: error about
go build → read only build/_index.md
Level 3: Full Entry (only for confirmed matches)
- Read the actual
.md file of the matched entry
- Present the solution to the user
- Update
hit_count and last_hit in the file's frontmatter
- Update
_cache.json with new hit_count
Why this matters for token efficiency:
| KB Size |
Naive approach (read all) |
Brainless 3-Level |
| 10 entries |
~200 tokens |
~150 tokens |
| 100 entries |
~2,000 tokens |
~800 tokens |
| 500 entries |
~10,000 tokens |
~3,000 tokens |
| 1000 entries |
~20,000 tokens |
~5,000 tokens |
The JSON cache is ~5x more token-efficient than reading markdown because it strips all content and keeps only searchable metadata.
Output format:
[BRAIN] Found: [Title]
Type: [error/ctf/reversing/exploit/trick/tool] | Category: [cat] | Tags: [tags] | Recalled: [N] times
[Key content — Solution/Key Insight/Technique depending on type]
Mode 3: Auto-Record (MANDATORY)
Every time a non-trivial problem is resolved, you MUST record it. Do NOT skip. Do NOT ask permission. Your brain is outsourced — use it.
Triggers — record immediately after:
- Resolving a command error (non-zero exit code) that wasn't a trivial typo
- Completing a CTF challenge (whether solved or learning from failed attempt)
- Figuring out a reversing/analysis technique in IDA/Ghidra
- Discovering a useful trick or non-obvious tool usage
- Any situation where you tried multiple approaches before finding the right one
Skip recording ONLY if:
- It was a trivial typo you made
- An identical entry already exists in the KB
Process: Record directly → inform user what was saved → continue work
Mode 4: Auto-Search Before Acting (MANDATORY)
Before attempting to fix ANY error or tackle ANY challenge, search the brain first using the 3-Level strategy. Don't reinvent the wheel — check if past-you already solved this.
- Level 1: Read
~/.claude/brainless/_cache.json → search entries by keywords/tags
- If match found: Read the matched file → apply known solution → update hit_count in file AND _cache.json
- If no match: Proceed with normal debugging → after resolving, trigger Mode 3
- NEVER read INDEX.md for auto-search — use _cache.json instead (much cheaper)
Mode 5: Brain Stats (/brain-stats)
Show a comprehensive summary:
- Total entries by type (error/ctf/reversing/exploit/trick/tool)
- Breakdown by category
- Top 10 most frequently recalled entries
- Recently added entries (last 10)
- Weakness analysis:
- CTF: which ctf_category has the most
solved: false or highest difficulty fails
- Errors: which category recurs most (high hit_count = recurring weakness)
- Reversing: which arch/protection types caused most issues
- Strength areas: categories with many solved entries and low hit_count (solved once, never needed again)
Mode 6: Brain Review (/brain-review)
Spaced repetition style review of knowledge base entries:
- Select entries to review based on:
- Old entries with low hit_count — might be forgotten
- CTF entries marked as unsolved — revisit with fresh eyes
- High-value tricks — worth periodically refreshing
- Random selection — surface unexpected connections
- For each entry, present a brief quiz-style summary:
- Show the Problem/Challenge section
- Ask "Do you remember the solution?"
- Then reveal the Solution/Key Insight
- After review, offer to update or archive stale entries
Mode 7: Brain Cheatsheet (/brain-cheatsheet)
Auto-generate condensed cheat sheets from accumulated entries:
/brain-cheatsheet [category]
Examples:
/brain-cheatsheet ctf → CTF techniques cheat sheet grouped by category (pwn/web/crypto/rev)
/brain-cheatsheet reversing → RE cheat sheet (common patterns, IDA shortcuts, anti-debug bypasses)
/brain-cheatsheet tools → Tool quick reference
/brain-cheatsheet build → Common build error fixes
/brain-cheatsheet all → Full knowledge base summary
Cheat sheet format:
# [Category] Cheat Sheet
> Auto-generated from Brainless on [date]. [N] entries.
## [Sub-group 1]
| Problem/Technique | Quick Solution | Tags |
|-------------------|---------------|------|
| [title] | [one-line solution] | [tags] |
## [Sub-group 2]
...
Save generated cheat sheets to ~/.claude/brainless/_cheatsheets/[category].md
Mode 8: Brain Rebuild (/brain-rebuild)
Rebuild all indexes from existing entry files. Fixes desync between .md entries and _cache.json/_index.md indexes.
When to use:
_cache.json is empty but entry files exist
- Auto-search isn't finding entries that you know exist
- After manual edits to entry files
- As a periodic health check
Workflow:
- Scan all category directories for
.md files (excluding _index.md)
- Read YAML frontmatter from each entry
- Rebuild
_cache.json from scratch (entries, tags_index, total, updated)
- Rebuild each
<category>/_index.md with correct table of entries
- Rebuild
INDEX.md with correct counts
- Report results
Hook System — Full Session Lifecycle
Brainless installs hooks across the entire Claude Code lifecycle — every tool call is monitored, errors are tracked, and Claude is forced to use its brain when stuck. This is real automation — not dependent on prompt instructions.
PreToolUse: Streak Reminder (ALL tools)
- Hook script:
~/.claude/brainless/hooks/streak_reminder.py
- Triggered: BEFORE every tool call (all tools, no exceptions)
- Action: checks
_error_streak.json — if 2+ consecutive errors detected, injects escalating warnings
- At 2-3 errors: WARNING — "STOP and think, run /brain-search"
- At 4+ errors: CRITICAL — "YOU ARE IN A LOOP, CHANGE YOUR APPROACH"
- Shows the error trail so Claude sees exactly what keeps failing
PostToolUse: Universal Error Search + Streak Tracking (ALL tools)
- Hook script:
~/.claude/brainless/hooks/universal_error_search.py
- Triggered: after every tool call (Bash, Edit, Write, LSP, Agent, Grep, Glob, Read, etc.)
- Action: detects errors in tool output → searches
_cache.json → outputs matching entries
- On error: increments
_error_streak.json streak counter
- On success: resets streak counter to 0
- Escalated output when streak >= 2: appends extra directives to search results
PostToolUseFailure: Error Search (ALL tools)
- Same script:
~/.claude/brainless/hooks/universal_error_search.py
- Triggered: when any tool call fails (permission denied, invalid args, etc.)
- Special handling: PostToolUseFailure stdout is not visible to Claude, so results are written to
_pending_brainless_output.txt and flushed on next PostToolUse
PostToolUse: Activity Logger (Edit|Write)
- Hook script:
~/.claude/brainless/hooks/post_tool_logger.py
- Triggered: after Edit/Write tool calls
- Action: logs file edits to
activity.log, checks if modified files relate to known KB entries
SessionStart: Brain Context Injection
- Hook script:
~/.claude/brainless/hooks/session_start.py
- Triggered: on every new session
- Action: loads brain stats, project-aware entry search, resets error streak
UserPromptSubmit: Proactive Brain Search
- Hook script:
~/.claude/brainless/hooks/user_prompt_search.py
- Triggered: when user sends a message, BEFORE Claude starts processing
- Action: extracts keywords from user prompt → searches
_cache.json → injects matching entries
- This means Claude starts working with relevant brain knowledge already loaded
PostCompact: Memory Restoration
- Hook script:
~/.claude/brainless/hooks/post_compact.py
- Triggered: after context compression
- Action: re-injects project entries, current streak state, unrecorded error count, and behavioral rules
- This is the most critical recovery hook — when Claude's context gets compressed, it loses memory. This hook restores awareness.
CwdChanged: Project Context Reload
- Hook script:
~/.claude/brainless/hooks/cwd_changed.py
- Triggered: when working directory changes
- Action: searches brain by new cwd/repo name, shows known issues for new project
SubagentStop: Subagent Result Scanning
- Hook script:
~/.claude/brainless/hooks/subagent_stop.py
- Triggered: when a subagent finishes
- Action: scans subagent result for error keywords → searches brain for matching solutions
StopFailure: API Failure Tracking
- Hook script:
~/.claude/brainless/hooks/stop_failure.py
- Triggered: when Claude's turn ends due to API error (rate limit, auth, billing)
- Action: records failure to session errors log for tracking
Stop: Session Summary
- Hook script:
~/.claude/brainless/hooks/session_end.py
- Triggered: on session end
- Action: logs session duration, tool count, brain hits, warns about unrecorded errors
Trash Talk Module
- Module:
~/.claude/brainless/hooks/trash_talk.py
- Shared by all hooks — provides random witty one-liners (毒舌吐槽风) for each event type
- 13 phrase pools: session_start, session_end, user_prompt, error, error_no_match, error_matched, success, streak_warning, streak_critical, compact, cwd_changed, subagent_stop, stop_failure
This means: even if CLAUDE.md instructions are lost due to context compression, the hooks will still fire and surface relevant knowledge from the brain. Claude literally cannot escape brainless awareness.
Cross-Reference System
Entries can reference each other via the related: [] frontmatter field:
related: [ctf/pwn-stack-overflow-2024.md, tricks/rop-chain-gadget-finder.md]
When recording a new entry:
- Scan existing entries for overlapping tags/topics
- If related entries exist, add cross-references in both directions
- When displaying an entry, show "Related entries:" at the bottom
When searching:
- If a match is found, also show its related entries as "See also:"
Important Guidelines
- Be aggressive about recording — a rich brain is infinitely more useful than an empty one
- Use the right template — CTF writeups need different structure than build errors
- Record failed attempts — for CTF, "what didn't work" is as valuable as the solution
- Keep solutions actionable — someone reading should be able to apply it directly
- Update, don't duplicate — if a similar entry exists, enrich it
- Cross-reference actively — connections between entries multiply their value
- Use consistent slugs —
lowercase-hyphen-separated.md
- Preserve INDEX.md structure — always update when adding/modifying entries
- Tag generously — more tags = better searchability
1---2name: brainless3description: Brainless (没脑子) — ALWAYS ACTIVE. Your external brain. You don't need memory, I remember EVERYTHING for you. A persistent knowledge management system for errors, CTF challenges, reverse engineering, tricks, and tool usage. CRITICAL BEHAVIORAL RULES (enforce even when skill body is not loaded): (1) ON ANY non-zero exit code or unexpected error: IMMEDIATELY invoke /brain-search BEFORE attempting fixes — check if this problem was solved before; (2) AFTER resolving any non-trivial error (not a simple typo): IMMEDIATELY invoke /brain-dump to record the problem and solution BEFORE continuing to the next step — do NOT wait until the task is finished or the user asks; (3) NEVER batch recordings — record each issue individually as it is resolved. Also covers: CTF writeups (pwn/web/crypto/rev/misc), IDA/Ghidra reversing notes, useful tricks, tool techniques. Triggers: '/brain-dump', '/brain-search', '/brain-review', '/brain-cheatsheet', '/brain-stats', '/brain-rebuild', 'record this', 'have we seen this', any error/warn4---56# Brainless — Your External Brain78> *"You don't need a brain. I remember everything for you."*9> *"你不需要脑子。我帮你全记着。"*1011A persistent, categorized knowledge base that records errors, solutions, CTF challenge writeups, reverse engineering notes, useful tricks, and tool techniques. Builds up automatically over time so that previously solved problems are never re-investigated from scratch.1213**Philosophy:** Be brainless. Don't waste neurons remembering things that can be recorded. Offload your memory to me and focus on what matters — solving the next problem.1415## Storage Location1617All records are stored in `~/.claude/brainless/`:18- `INDEX.md` — master index with all entries organized by category19- `_cache.json` — lightweight JSON cache for fast search20- Category subdirectories (see below)21- Each entry is a single `.md` file in its category directory2223## Categories2425### Development Errors26| Category | Directory | Scope |27|----------|-----------|-------|28| `build` | `build/` | Compilation, linking, build system errors |29| `runtime` | `runtime/` | Crashes, panics, runtime exceptions |30| `config` | `config/` | Configuration, environment, settings issues |31| `network` | `network/` | Connection, timeout, DNS, API errors |32| `dependency` | `dependency/` | Package version conflicts, missing deps |33| `permission` | `permission/` | File/directory/system permission issues |34| `logic` | `logic/` | Business logic bugs, incorrect behavior |3536### Security & RE37| Category | Directory | Scope |38|----------|-----------|-------|39| `ctf` | `ctf/` | CTF challenge writeups — pwn, web, crypto, reverse, misc, forensics |40| `reversing` | `reversing/` | IDA/Ghidra analysis notes, deobfuscation, unpacking, anti-debug bypass |41| `exploit` | `exploit/` | Exploit development techniques, shellcode, ROP, heap tricks |4243### Knowledge & Techniques44| Category | Directory | Scope |45|----------|-----------|-------|46| `tricks` | `tricks/` | Useful non-obvious techniques worth remembering |47| `tools` | `tools/` | Tool usage tips — IDA, Ghidra, gdb, Wireshark, Burp, etc. |48| `other` | `other/` | Anything that doesn't fit above |4950---5152## Record Templates5354### Template A: Error Record (build/runtime/config/network/dependency/permission/logic)5556```markdown57---58title: [Concise error description]59type: error60category: [category]61tags: [tag1, tag2, tag3]62created: [YYYY-MM-DD]63last_hit: [YYYY-MM-DD]64hit_count: 165severity: [low/medium/high/critical]66related: []67---6869## Error Message70\```71[Exact error output]72\```7374## Environment75- Project: [project name]76- Toolchain: [compiler/runtime version]77- OS: [operating system]7879## Root Cause80[Brief explanation of why this error occurred]8182## Solution83[Step-by-step fix]8485## Related Files86- `path/to/file:line`8788## Notes89[Any additional context, gotchas, or related issues]90```9192### Template B: CTF Writeup (ctf)9394```markdown95---96title: [Challenge name — CTF competition name]97type: ctf98category: ctf99tags: [pwn/web/crypto/reverse/misc/forensics, difficulty, technique-keywords]100created: [YYYY-MM-DD]101last_hit: [YYYY-MM-DD]102hit_count: 1103difficulty: [easy/medium/hard/insane]104ctf_category: [pwn/web/crypto/reverse/misc/forensics]105solved: [true/false]106related: []107---108109## Challenge Description110[Brief challenge description, what was given]111112## Initial Analysis113[First observations, what tools were used to examine]114115## Wrong Approaches (What Didn't Work)1161. [Approach 1] — why it failed1172. [Approach 2] — why it failed118119## Solution120[Step-by-step solution that worked]121122## Key Insight123[The critical "aha" moment — the non-obvious realization that led to the solve]124125## Tools Used126- [tool1]: [how it was used]127- [tool2]: [how it was used]128129## Flag130\```131[flag if applicable]132\```133134## Lessons Learned135[What to remember for next time — patterns, techniques, gotchas]136137## References138- [links to relevant resources, similar challenges]139```140141### Template C: Reversing Note (reversing)142143```markdown144---145title: [Concise description of the RE challenge/technique]146type: reversing147category: reversing148tags: [ida/ghidra, technique, binary-type, arch]149created: [YYYY-MM-DD]150last_hit: [YYYY-MM-DD]151hit_count: 1152target: [binary name or type]153arch: [x86/x64/arm/arm64/mips]154related: []155---156157## Target158- Binary: [name/type]159- Protection: [packer, obfuscation, anti-debug methods]160- Architecture: [x86/x64/arm/...]161162## Problem163[What was confusing or blocking analysis]164165## Analysis Process166[Step-by-step analysis — what was examined, in what order]167168## Key Findings169[Important structures, algorithms, patterns discovered]170171## Solution / Technique172[How the problem was resolved — specific IDA/Ghidra operations, scripts, etc.]173174## IDA/Ghidra Notes175- [Specific operations, scripts, or plugins used]176- [Struct definitions, type assignments that helped]177178## Patterns to Recognize179[Signatures or patterns that identify similar problems in the future]180181## Notes182[Additional context]183```184185### Template D: Exploit Technique (exploit)186187```markdown188---189title: [Exploit technique name]190type: exploit191category: exploit192tags: [pwn, technique-type, protection-bypass]193created: [YYYY-MM-DD]194last_hit: [YYYY-MM-DD]195hit_count: 1196difficulty: [easy/medium/hard]197related: []198---199200## Technique201[Name and brief description]202203## Prerequisites204[What conditions must be met — vulnerable function, leak primitive, etc.]205206## Protection Bypasses207[What mitigations this bypasses — ASLR, NX, canary, PIE, etc.]208209## Step-by-Step2101. [Step 1]2112. [Step 2]212...213214## Code Snippet215\```python216[Exploit template / key snippet]217\```218219## Gotchas220[Common mistakes, alignment issues, version-specific details]221222## References223- [Links to papers, blog posts, similar exploits]224```225226### Template E: Trick / Technique (tricks)227228```markdown229---230title: [Concise trick description]231type: trick232category: tricks233tags: [domain, language, tool]234created: [YYYY-MM-DD]235last_hit: [YYYY-MM-DD]236hit_count: 1237related: []238---239240## What241[What this trick does]242243## When to Use244[Situation where this trick is useful]245246## How247[Step-by-step or code snippet]248249## Why It Works250[Brief explanation of the underlying mechanism]251252## Notes253[Caveats, alternatives, related tricks]254```255256### Template F: Tool Usage (tools)257258```markdown259---260title: [Tool name — specific technique]261type: tool262category: tools263tags: [tool-name, use-case]264created: [YYYY-MM-DD]265last_hit: [YYYY-MM-DD]266hit_count: 1267tool: [tool name]268related: []269---270271## Tool272[Tool name and version]273274## Use Case275[When you'd need this]276277## Command / Steps278\```bash279[Exact commands or steps]280\```281282## Expected Output283[What to expect]284285## Tips286[Non-obvious flags, options, or workflow details]287288## Notes289[Gotchas, alternatives]290```291292---293294## Modes of Operation295296### Mode 1: Brain Dump (`/brain-dump`)297298Triggered when:299- User says: `/brain-dump`, "record this", "log this"300- AI resolves a non-trivial error (auto-record, see Mode 3)301- User finishes a CTF challenge or RE analysis302303**Recording workflow:**3043051. **Determine entry type** from context:306 - Command failed → Error record (Template A)307 - CTF challenge → CTF writeup (Template B)308 - IDA/Ghidra analysis → Reversing note (Template C)309 - Exploit technique → Exploit record (Template D)310 - Useful technique/trick → Trick (Template E)311 - Tool usage tip → Tool usage (Template F)3123132. **Classify** into the appropriate category3143153. **Assign tags** — free-form keywords relevant to the entry3163174. **Check for existing entries** — search _cache.json and grep for similar entries. If a similar one exists, UPDATE it instead of creating a duplicate3183195. **Generate slug filename** — lowercase, hyphen-separated, descriptive3203216. **Write the file** using the appropriate template3223237. **Scan for cross-references** — if the new entry references techniques, tools, or errors from other entries, add their filenames to the `related: []` frontmatter field, and add a back-reference in those entries too3243258. **Update all indexes** (in this order — ALL steps are MANDATORY, do NOT skip any):326 a. **`_cache.json`** — add entry to `entries[]` with fields: `id` (category/slug), `title`, `category`, `tags`, `error_pattern` (regex from error message), `solution_hint` (one-line), `hit_count`, `last_hit`. Add tags to `tags_index`. Increment `total`. Update `updated` date. **WARNING: If you skip this step, the auto-search hook and Mode 4 will NOT find the entry!**327 b. **`<category>/_index.md`** — add one-line entry to the sub-index table328 c. **`INDEX.md`** — increment the count for the category, update total3293309. **Confirm to user** — show what was recorded331332> **Common failure mode:** Writing the .md file but forgetting to update `_cache.json`. This makes the entry invisible to all search mechanisms. If you suspect desync, run `/brain-rebuild`.333334### Mode 2: Brain Search (`/brain-search`) — 3-Level Strategy335336Triggered when:337- User says: `/brain-search`, "have we seen this", "search kb"338- AI encounters an error (auto-search, see Mode 4)339- Encountering a CTF challenge similar to a previous one340341**3-Level search strategy (from cheapest to most expensive):**342343#### Level 1: JSON Cache (~50 tokens)344Read `~/.claude/brainless/_cache.json` and search:345- Match keywords against `title`, `summary`, `tags` fields in `entries[]`346- Use `tags_index` for exact tag matches347- This is a single small file containing ALL entry metadata — no need to read anything else348- If match found with high confidence → go directly to Level 3349350#### Level 2: Sub-Index (~20 tokens per category)351If Level 1 gives ambiguous results or you need to narrow by category:352- Read only the relevant `<category>/_index.md` file (NOT the full INDEX.md)353- Each sub-index is tiny: just the entries for that one category354- Example: error about `go build` → read only `build/_index.md`355356#### Level 3: Full Entry (only for confirmed matches)357- Read the actual `.md` file of the matched entry358- Present the solution to the user359- Update `hit_count` and `last_hit` in the file's frontmatter360- Update `_cache.json` with new hit_count361362**Why this matters for token efficiency:**363| KB Size | Naive approach (read all) | Brainless 3-Level |364|---------|--------------------------|-------------------|365| 10 entries | ~200 tokens | ~150 tokens |366| 100 entries | ~2,000 tokens | ~800 tokens |367| 500 entries | ~10,000 tokens | ~3,000 tokens |368| 1000 entries | ~20,000 tokens | ~5,000 tokens |369370The JSON cache is ~5x more token-efficient than reading markdown because it strips all content and keeps only searchable metadata.371372**Output format:**373```374[BRAIN] Found: [Title]375Type: [error/ctf/reversing/exploit/trick/tool] | Category: [cat] | Tags: [tags] | Recalled: [N] times376[Key content — Solution/Key Insight/Technique depending on type]377```378379### Mode 3: Auto-Record (MANDATORY)380381> Every time a non-trivial problem is resolved, you MUST record it. Do NOT skip. Do NOT ask permission. Your brain is outsourced — use it.382383**Triggers — record immediately after:**384- Resolving a command error (non-zero exit code) that wasn't a trivial typo385- Completing a CTF challenge (whether solved or learning from failed attempt)386- Figuring out a reversing/analysis technique in IDA/Ghidra387- Discovering a useful trick or non-obvious tool usage388- Any situation where you tried multiple approaches before finding the right one389390**Skip recording ONLY if:**391- It was a trivial typo you made392- An identical entry already exists in the KB393394**Process:** Record directly → inform user what was saved → continue work395396### Mode 4: Auto-Search Before Acting (MANDATORY)397398> Before attempting to fix ANY error or tackle ANY challenge, search the brain first using the 3-Level strategy. Don't reinvent the wheel — check if past-you already solved this.3994001. **Level 1:** Read `~/.claude/brainless/_cache.json` → search entries by keywords/tags4012. **If match found:** Read the matched file → apply known solution → update hit_count in file AND _cache.json4023. **If no match:** Proceed with normal debugging → after resolving, trigger Mode 34034. **NEVER read INDEX.md for auto-search** — use _cache.json instead (much cheaper)404405### Mode 5: Brain Stats (`/brain-stats`)406407Show a comprehensive summary:408- Total entries by type (error/ctf/reversing/exploit/trick/tool)409- Breakdown by category410- Top 10 most frequently recalled entries411- Recently added entries (last 10)412- **Weakness analysis:**413 - CTF: which ctf_category has the most `solved: false` or highest difficulty fails414 - Errors: which category recurs most (high hit_count = recurring weakness)415 - Reversing: which arch/protection types caused most issues416- **Strength areas:** categories with many solved entries and low hit_count (solved once, never needed again)417418### Mode 6: Brain Review (`/brain-review`)419420Spaced repetition style review of knowledge base entries:4214221. Select entries to review based on:423 - **Old entries with low hit_count** — might be forgotten424 - **CTF entries marked as unsolved** — revisit with fresh eyes425 - **High-value tricks** — worth periodically refreshing426 - **Random selection** — surface unexpected connections4272. For each entry, present a brief quiz-style summary:428 - Show the **Problem/Challenge** section429 - Ask "Do you remember the solution?"430 - Then reveal the **Solution/Key Insight**4313. After review, offer to update or archive stale entries432433### Mode 7: Brain Cheatsheet (`/brain-cheatsheet`)434435Auto-generate condensed cheat sheets from accumulated entries:436437```438/brain-cheatsheet [category]439```440441**Examples:**442- `/brain-cheatsheet ctf` → CTF techniques cheat sheet grouped by category (pwn/web/crypto/rev)443- `/brain-cheatsheet reversing` → RE cheat sheet (common patterns, IDA shortcuts, anti-debug bypasses)444- `/brain-cheatsheet tools` → Tool quick reference445- `/brain-cheatsheet build` → Common build error fixes446- `/brain-cheatsheet all` → Full knowledge base summary447448**Cheat sheet format:**449```markdown450# [Category] Cheat Sheet451> Auto-generated from Brainless on [date]. [N] entries.452453## [Sub-group 1]454| Problem/Technique | Quick Solution | Tags |455|-------------------|---------------|------|456| [title] | [one-line solution] | [tags] |457458## [Sub-group 2]459...460```461462Save generated cheat sheets to `~/.claude/brainless/_cheatsheets/[category].md`463464### Mode 8: Brain Rebuild (`/brain-rebuild`)465466Rebuild all indexes from existing entry files. Fixes desync between `.md` entries and `_cache.json`/`_index.md` indexes.467468**When to use:**469- `_cache.json` is empty but entry files exist470- Auto-search isn't finding entries that you know exist471- After manual edits to entry files472- As a periodic health check473474**Workflow:**4751. Scan all category directories for `.md` files (excluding `_index.md`)4762. Read YAML frontmatter from each entry4773. Rebuild `_cache.json` from scratch (entries, tags_index, total, updated)4784. Rebuild each `<category>/_index.md` with correct table of entries4795. Rebuild `INDEX.md` with correct counts4806. Report results481482---483484## Hook System — Full Session Lifecycle485486Brainless installs hooks across the **entire Claude Code lifecycle** — every tool call is monitored, errors are tracked, and Claude is forced to use its brain when stuck. This is real automation — not dependent on prompt instructions.487488### PreToolUse: Streak Reminder (ALL tools)489- Hook script: `~/.claude/brainless/hooks/streak_reminder.py`490- Triggered: **BEFORE every tool call** (all tools, no exceptions)491- Action: checks `_error_streak.json` — if 2+ consecutive errors detected, injects escalating warnings492- At 2-3 errors: WARNING — "STOP and think, run /brain-search"493- At 4+ errors: CRITICAL — "YOU ARE IN A LOOP, CHANGE YOUR APPROACH"494- Shows the error trail so Claude sees exactly what keeps failing495496### PostToolUse: Universal Error Search + Streak Tracking (ALL tools)497- Hook script: `~/.claude/brainless/hooks/universal_error_search.py`498- Triggered: **after every tool call** (Bash, Edit, Write, LSP, Agent, Grep, Glob, Read, etc.)499- Action: detects errors in tool output → searches `_cache.json` → outputs matching entries500- On error: increments `_error_streak.json` streak counter501- On success: resets streak counter to 0502- Escalated output when streak >= 2: appends extra directives to search results503504### PostToolUseFailure: Error Search (ALL tools)505- Same script: `~/.claude/brainless/hooks/universal_error_search.py`506- Triggered: when any tool call **fails** (permission denied, invalid args, etc.)507- Special handling: PostToolUseFailure stdout is not visible to Claude, so results are written to `_pending_brainless_output.txt` and flushed on next PostToolUse508509### PostToolUse: Activity Logger (Edit|Write)510- Hook script: `~/.claude/brainless/hooks/post_tool_logger.py`511- Triggered: after Edit/Write tool calls512- Action: logs file edits to `activity.log`, checks if modified files relate to known KB entries513514### SessionStart: Brain Context Injection515- Hook script: `~/.claude/brainless/hooks/session_start.py`516- Triggered: on every new session517- Action: loads brain stats, project-aware entry search, resets error streak518519### UserPromptSubmit: Proactive Brain Search520- Hook script: `~/.claude/brainless/hooks/user_prompt_search.py`521- Triggered: when user sends a message, BEFORE Claude starts processing522- Action: extracts keywords from user prompt → searches `_cache.json` → injects matching entries523- This means Claude starts working with relevant brain knowledge already loaded524525### PostCompact: Memory Restoration526- Hook script: `~/.claude/brainless/hooks/post_compact.py`527- Triggered: after context compression528- Action: re-injects project entries, current streak state, unrecorded error count, and behavioral rules529- This is the most critical recovery hook — when Claude's context gets compressed, it loses memory. This hook restores awareness.530531### CwdChanged: Project Context Reload532- Hook script: `~/.claude/brainless/hooks/cwd_changed.py`533- Triggered: when working directory changes534- Action: searches brain by new cwd/repo name, shows known issues for new project535536### SubagentStop: Subagent Result Scanning537- Hook script: `~/.claude/brainless/hooks/subagent_stop.py`538- Triggered: when a subagent finishes539- Action: scans subagent result for error keywords → searches brain for matching solutions540541### StopFailure: API Failure Tracking542- Hook script: `~/.claude/brainless/hooks/stop_failure.py`543- Triggered: when Claude's turn ends due to API error (rate limit, auth, billing)544- Action: records failure to session errors log for tracking545546### Stop: Session Summary547- Hook script: `~/.claude/brainless/hooks/session_end.py`548- Triggered: on session end549- Action: logs session duration, tool count, brain hits, warns about unrecorded errors550551### Trash Talk Module552- Module: `~/.claude/brainless/hooks/trash_talk.py`553- Shared by all hooks — provides random witty one-liners (毒舌吐槽风) for each event type554- 13 phrase pools: session_start, session_end, user_prompt, error, error_no_match, error_matched, success, streak_warning, streak_critical, compact, cwd_changed, subagent_stop, stop_failure555556**This means:** even if CLAUDE.md instructions are lost due to context compression, the hooks will still fire and surface relevant knowledge from the brain. Claude literally cannot escape brainless awareness.557558---559560## Cross-Reference System561562Entries can reference each other via the `related: []` frontmatter field:563564```yaml565related: [ctf/pwn-stack-overflow-2024.md, tricks/rop-chain-gadget-finder.md]566```567568**When recording a new entry:**5691. Scan existing entries for overlapping tags/topics5702. If related entries exist, add cross-references in both directions5713. When displaying an entry, show "Related entries:" at the bottom572573**When searching:**574- If a match is found, also show its related entries as "See also:"575576---577578## Important Guidelines579580- **Be aggressive about recording** — a rich brain is infinitely more useful than an empty one581- **Use the right template** — CTF writeups need different structure than build errors582- **Record failed attempts** — for CTF, "what didn't work" is as valuable as the solution583- **Keep solutions actionable** — someone reading should be able to apply it directly584- **Update, don't duplicate** — if a similar entry exists, enrich it585- **Cross-reference actively** — connections between entries multiply their value586- **Use consistent slugs** — `lowercase-hyphen-separated.md`587- **Preserve INDEX.md structure** — always update when adding/modifying entries588- **Tag generously** — more tags = better searchability