convez.ai
HookProdutividadeIntermediário
jim4226

Claude Workspace Brain

jim4226/claude-workspace-brain

Memória persistente para Claude Code que não desaparece na compactação

Ver no GitHub
BomPluginScore · de 0 a 100

Sistema de memória persistente para Claude Code que sobrevive à compactação de contexto. Usa um único arquivo markdown para armazenar decisões, threads e estado do projeto, injetado automaticamente em novas sessões via hooks. Sem dependências externas, sem vector DB, sem APIs.

Instalação

$npx convez-ai jim4226/claude-workspace-brain

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

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
85%
Último commit
há 3 meses
Versão
v0.2.1
Issues abertas
1
Contribuidores
2

Casos de uso

  • Manter continuidade em projetos longos que requerem múltiplas sessões Claude
  • Rastrear decisões arquiteturais e threads bloqueadas entre contextos
  • Usar um arquivo markdown como source-of-truth que aparece em PRs e reviews

Veredito

Solução minimalista e prática que resolve um problema real de continuidade em Claude Code. O design inteligente (markdown legível + hooks automáticos + viewer HTML) o diferencia de abordagens mais complexas com embeddings. Válido para quem trabalha em projetos extensos.

README

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

claude-workspace-brain

Stop re-explaining your project to Claude every session. Context compaction becomes a thing of the past.

CI License: MIT Latest release Stars Python 3.8+ Claude Code

One markdown file. Two hooks. Zero dependencies. A minimal persistent-memory layer for Claude Code that survives context compaction. Also works with claude.ai (via Projects or the brain copy CLI — see below).

What this does that other memory tools don't

  • A single markdown file you can read in a PR. No vector DB, no embedding model, no external service, no API key required for the core to work.
  • A built-in eval harness (python -m eval.abtest) that measures whether the brain helps your sessions. Other memory tools claim value; this one quantifies it.
  • An interactive HTML viewer bundled in the template. python -m http.server and your brain becomes a live dashboard with a force-directed synapse graph.

How it Works

sequenceDiagram
    autonumber
    participant You
    participant Session1 as Claude (session 1)
    participant Brain as WORKSPACE_BRAIN.md
    participant Session2 as Claude (session 2, hours later)

    You->>Session1: "Let's work on X"
    Session1->>Session1: makes decisions, juggles threads<br/>(context fills)
    Note over Session1: ~150k tokens — auto-compaction imminent
    Session1->>Session1: PreCompact blocks the compaction once
    Session1->>Brain: Edit: flush decisions, threads, key numbers
    Note over Session1: compaction proceeds (lossy)
    Session1->>You: "session over"

    You->>Session2: opens new session
    Brain->>Session2: SessionStart hook injects brain
    Session2->>You: "Right — we were shipping X.<br/>Decision Y stands.<br/>Thread Z is still blocked on legal."

Two hooks:

HookFires whenWhat it does
SessionStartEvery new, resumed, or post-compaction sessionInjects WORKSPACE_BRAIN.md as Claude's first context. After a compaction it also asks Claude to reconcile any state the summary dropped.
PreCompactJust before Claude Code auto-compresses the conversationPauses the compaction once and tells Claude to flush working state into the brain first; then compaction proceeds. Manual /compact is never blocked.

The brain file is hand-curated (with Claude's help). The hooks make sure it gets read at the start and updated before loss.

Why block instead of just printing a reminder? Claude only ingests hook stdout for SessionStart and UserPromptSubmit — a PreCompact hook's stdout goes to the debug log, never to the model. So the only way to reach Claude before compaction is to pause it once with a block decision whose reason is the flush instruction. The block is one-shot (a short-TTL marker lets the next compaction through) and fails open on any error, so it can never wedge a session.


Quick Start

Install (one line, in your project directory)

macOS / Linux:

curl -sSL https://raw.githubusercontent.com/jim4226/claude-workspace-brain/main/install.sh | bash

Windows (PowerShell):

irm https://raw.githubusercontent.com/jim4226/claude-workspace-brain/main/install.ps1 | iex

Both bootstrap by cloning the repo into a cache directory and copying the template (10 files, ~32 KB) into your current project. Idempotent: re-running merges with your existing .claude/settings.json rather than clobbering it.

Initialize (60 sec)

> /brain-init

Claude asks 6 questions (project type, current sprint, one in-flight thread, one recent decision + reason, one open question) and scaffolds a personalized brain. Most projects score 70+ on the linter immediately.

Done

Your next session starts with Loading workspace brain... in the status line, then Claude's first reply references your actual project state.


Real-world usage

Built for BoneVision (digital orthopedics research + product). Across 6 months and ~200 sessions:

  • Brain currently runs ~230 lines / 26 KB
  • 20 decisions logged with rationale (the why survives, not just the what)
  • Maintained 6 active in-flight threads across multiple compactions without re-explanation
  • Currently scores 83/100 on its own linter (honest — it's slightly over the soft size budget)

That's not a benchmark, it's a maintenance story. The repo's value is that it keeps quality up across the compaction boundary, not that it tops a leaderboard.


What You Get

your-project/
├── WORKSPACE_BRAIN.md          # the brain itself - edit this
└── .claude/
    ├── settings.json            # wires up the hooks (merged if you had one)
    ├── hooks/
    │   ├── brain_session_start.py    # injects brain at session start
    │   ├── brain_pre_compact.py      # nudges Claude to flush before compact
    │   └── brain_stop.py             # opt-in opportunistic flush
    ├── commands/
    │   ├── brain.md                  # /brain        - view + edit
    │   ├── brain-init.md             # /brain-init   - scaffold in 60 sec
    │   ├── brain-archive.md          # /brain-archive - auto-prune stale entries
    │   └── brain-grade.md            # /brain-grade  - AI quality review
    └── scripts/
        └── brain_lint.py             # static quality scorer

Plus, in the repo (not installed by default):

brain-viewer.html              # interactive HTML viewer — drop in project root
eval/
├── abtest.py                  # A/B harness: does the brain actually help?
├── questions.json             # 5 brain-dependent held-out questions
└── fixtures/sample_brain.md   # synthetic brain for demos

The Brain File: Section Guide

Each section has a specific job. Keep them in this order — hooks and linter assume it.

SectionPurposeGood entryBad entry
ACTIVE FOCUSOne paragraph: current goal + sprint"Shipping Stripe webhook signing by May 21 for compliance review""Working on auth"
ACTIVE THREADSIn-flight work, newest first"(in-progress) Schema migration for users.tier — blocked on Eng meeting""Various improvements"
DECISIONS LOGJudgment calls + the why"2026-05-12: switched from Memcached to Redis. Reason: Memcached lost data on staging restart""2026-05-12: switched to Redis"
SYNAPSESNon-obvious cross-references"Stripe webhook <-> orders.fulfillment_state enum — add value before deploying handler""Various coupling"
KEY NUMBERSStable facts asked about repeatedly"Prod URL: api.example.com (Azure SWA, eastus2, free tier 100k req/day)""We use Azure"
RECENT SESSIONSOne line per session, prepend; archive past ~10"2026-05-20: fixed CSP for blob: previews, deployed v3, demo'd to Stryker""Did stuff today"
OPEN QUESTIONSUnresolved. Flush when answered."Is legal review needed before staging or only before prod?""Several open items"

What NOT to put in the brain: anything in CLAUDE.md, git log, code patterns, or auto-memory. The brain is for non-derivable state.

If your brain grows past 16 KB, the linter warns. Past 32 KB, injection is truncated. Run /brain-archive to migrate stale entries to WORKSPACE_BRAIN_ARCHIVE.md.


Slash Commands

CommandPurpose
/brainSummarises the brain in ~10 lines + optionally edits a section.
/brain-initInteractive Q&A flow that scaffolds a personalised brain in 60 sec.
/brain-gradeAI-graded quality review on 5 axes + concrete edit suggestions. Waits for approval.
/brain-archiveMigrates completed threads + sessions >10 entries old to WORKSPACE_BRAIN_ARCHIVE.md.

The Linter

python .claude/scripts/brain_lint.py

Six axes, 100 points total:

AxisWeightChecks
Required sections20All 7 expected sections present
Size budget20Under 16 KB (soft) / 32 KB (hard injection cap)
Header freshness20Last sync: date within 14 days
Section balance15No section dominates >40% of file
Decision rationale15>=85% of decisions contain "Reason:" / "because"
Thread hygiene10Completed threads don't outnumber active >2:1; RECENT SESSIONS <=10

Always exits 0 — advisory, never a build blocker. No third-party deps; stdlib only.

brain_lint v1.0
File: WORKSPACE_BRAIN.md (230 lines, 26.1 KB, 10 sections)

Score: 83/100

Breakdown:
  [####################] Required sections       20.0 / 20
  [#######.............] Size budget              7.4 / 20
  [####################] Header freshness        20.0 / 20
  [####################] Section balance         15.0 / 15
  [##############......] Decision rationale      10.5 / 15
  [####################] Thread hygiene          10.0 / 10

The Eval Harness — does the brain actually help?

Most memory tools claim value. This one measures it. The harness asks Claude 5 brain-dependent questions (e.g., "what's currently blocked?", "what was the most recent decision and why?") with and without the brain in the system prompt, then a judge model scores both answers blind on accuracy / specificity / usefulness (0-10 each).

export ANTHROPIC_API_KEY=sk-...
pip install anthropic
python -m eval.abtest --runs 3

Real output against the bundled eval/fixtures/sample_brain.md (a synthetic web-app brain):

abtest v1.0
  brain:        sample_brain.md (2.6 KB)
  questions:    5 held-out, 3 run(s) each = 15 pairs
  answer model: claude-haiku-4-5-20251001
  judge model:  claude-sonnet-4-6

  [ 1/15] current_focus        + delta=+25.0  (with=30, without=5)
  [ 2/15] recent_decision      + delta=+29.0  (with=30, without=1)
  [ 3/15] blocked_work         + delta=+26.0  (with=27, without=1)
  [ 4/15] open_question        + delta=+28.0  (with=29, without=1)
  [ 5/15] non_obvious_dep      + delta=+26.0  (with=27, without=1)
  ...
============================================================
Results over 15 pairs
============================================================
  Mean delta (with - without):  +26.40 / 30 pts
  95% CI:                       [+24.98, +27.82]
  Wins / ties / losses:         15 / 0 / 0
  Mean score WITH brain:        28.5 / 30
  Mean score WITHOUT brain:     2.1 / 30
  Verdict:                      Brain helps (significant at 95% CI).

Without the brain, Claude (Haiku 4.5) can do little more than say "I don't know" to brain-dependent questions like "what's currently blocked?" — that's the 2.1/30. With the brain in context, the same model becomes nearly the upper bound on what the judge can score (28.5/30). The delta is the value the brain provides on a fixed model.

Cost: ~$0.05-0.15 per --runs 3 invocation. Prompt caching reduces brain-content cost by ~90% across runs. Use --dry-run to see the prompts without API calls.


Use with claude.ai (no Claude Code required)

The hooks only fire inside Claude Code, but the brain itself is just a markdown file — usable with any AI chat. Two patterns work today:

Pattern A: claude.ai Projects (recommended for long-running work)

claude.ai Projects let you attach files as Project knowledge that's available to every chat in the project.

  1. In claude.ai, create a Project for your codebase.
  2. Click Add content → upload WORKSPACE_BRAIN.md.
  3. Every chat in that project now sees your brain in its context — same effect as the SessionStart hook, but the trigger is "you start a chat in the Project," not "your session begins."
  4. When your brain changes meaningfully, re-upload to update Project knowledge.

This is the closest you can get to the Claude Code experience on claude.ai.

Pattern B: Manual paste with the brain CLI

For ad-hoc sessions or AI tools without project knowledge:

# Clone the repo once, then from any project root:
python /path/to/claude-workspace-brain/brain.py copy
# (Copies WORKSPACE_BRAIN.md in cwd to clipboard.)

Then paste into the chat as your first message — wrap it in a code fence or preface with "Here is the current state of my project — treat as ground truth:" so the AI knows what to do with it.

The brain CLI also has:

SubcommandWhat it does
brain copyCopy brain to clipboard (Windows clip / macOS pbcopy / Linux xclip+wl-copy+xsel)
brain showPrint brain to stdout — pipe into other tools
brain lintRun the 6-axis quality scorer
brain serveLaunch the HTML viewer in your browser (python -m http.server + open URL)
brain evalA/B harness against any model that speaks the Anthropic API

All subcommands accept --brain PATH to point at a brain outside the cwd.

What you lose without Claude Code

  • No automatic flush before compaction. claude.ai compacts long conversations too, but exposes no hook — so the brain doesn't auto-update at the boundary. You'll need to manually edit WORKSPACE_BRAIN.md between sessions, or ask the chat to summarise what to add and you paste it in.
  • No slash commands (/brain-init, /brain-grade, /brain-archive). The patterns are documented in template/.claude/commands/*.md if you want to copy-paste the prompts manually.

What you keep:

  • The brain file structure (sections, rules, archive pattern)
  • The linter (catches stale entries, oversize files, missing rationale)
  • The HTML viewer with synapse graph
  • The eval harness (proves the brain helps on YOUR project, against YOUR model)

How it Compares

ProjectStorageSetupExternal depsHas built-in eval?
claude-workspace-brain (this)One markdown fileOne curl|bashNoneYes
CipherVector DBRun the Cipher serverDatabase layerNo
coleam00/claude-memory-compilerKnowledge articles, multiple filesConfigure Agent SDKClaude Agent SDKNo
mem0.ai integrationMem0 vector DBAccount + API keyMem0 serviceNo
MemUMemU cloudAccount + API keyMemU serviceNo

The trade-off is the usual one: hand-curation gives you a precise, readable artifact at the cost of effort; auto-compilation scales further but you trust the compiler. This project is for people who'd rather have 200 lines of markdown they actually trust than a knowledge base they don't — and who want to measure whether either is helping.


Customising

The template's section list is opinionated but not sacred. Common variations (see examples/):

Project typeSections to addSections to drop
Research / paperEXPERIMENTAL RESULTS, OPEN REVIEWER QUESTIONS(keep all)
Web app / SaaSDEPLOY STATE, CUSTOMER ASKSSYNAPSES (optional)
ML trainingRUNNING EXPERIMENTS, HYPERPARAMETER NOTESRECENT SESSIONS (training logs replace)
Solo CLI tool(none)SYNAPSES, drop to 5 sections

If you rename a required section, the linter will mark it as missing — edit REQUIRED_SECTIONS in brain_lint.py to match.

Tuning the injection size

# Cap injection at 8 KB (smaller for token-conscious models)
BRAIN_MAX_KB=8 claude

Tuning the pre-compaction flush

The PreCompact hook blocks an auto-compaction once to force a flush, then a short-lived marker lets the next compaction through so it never loops. Widen or narrow that window (default 10 minutes):

# Only force a fresh flush if the last one was >20 min ago
BRAIN_PRECOMPACT_TTL_MIN=20 claude

Tuning the optional Stop hook

Off by default. Re-run the installer with --with-stop-hook. The hook only fires when the brain hasn't been touched in 30 minutes. Tune:

BRAIN_STOP_INTERVAL_MIN=60 claude

FAQ

Why a markdown file and not a JSON / SQLite store? Because Claude is excellent at reading markdown and the file doubles as documentation a human can skim. The brain is part of the project; it should be reviewable in a PR.

Won't this blow up my context window? The default soft cap is 16 KB; the injection cap is 32 KB. At 32 KB the brain is roughly 7-9k tokens — meaningful but not catastrophic on a 200k-token window. The linter warns you well before you get close.

What if I already have a .claude/settings.json? The installer parses both files and merges your existing SessionStart/PreCompact/Stop blocks alongside the brain hooks. Idempotent — re-running won't duplicate hooks.

Can I use this with a team? Yes. Commit .claude/settings.json, the hooks, and WORKSPACE_BRAIN.md to your repo. Each team member's Claude session picks up the brain. Treat brain edits like code edits — review them in PRs.

What if my project uses something other than Python? The hooks themselves are Python (it's the most-installed scripting language across dev environments). Rewriting them in Node / Go / Bash would be a 50-line port — PRs welcome.

Does the brain leak to Anthropic? The brain content goes into Claude's context the same way every file you read does. If your brain contains secrets, that's a problem with secrets in your brain, not with the hook itself. Standard advice: don't commit secrets, don't paste secrets into Claude.

What about the auto-memory at ~/.claude/projects/.../memory/? Claude Code's auto-memory is per-user-per-project (lives outside the repo). The brain is per-repo (committed). They complement each other: auto-memory holds your preferences and tooling notes, the brain holds the project's state.

How do I render the HTML viewer?

# from your project root
python -m http.server 8000
# then open
http://localhost:8000/template/brain-viewer.html?path=/WORKSPACE_BRAIN.md

Or pass ?theme=dark for the dark variant.


License

MIT. See LICENSE.

Contributing

Issues and PRs welcome. Particularly interested in:

  • Hook ports to other runtimes (Node, Bash, Go)
  • Project-type-specific brain templates (the examples/ directory)
  • Linter rule refinements
  • Additional held-out questions for the eval harness

See CONTRIBUTING.md for the workflow.

Credits

Built for BoneVision and battle-tested across a multi-month research + product cycle. The PreCompact hook idea was discussed in anthropics/claude-code#43733. The brain-viewer's force-directed synapse graph was inspired by Obsidian's graph view.

Ver o original no GitHub

Bom para

Relacionados