TC Brain Kernel
jewbear66-cpu/tc-brain-kernel
Brain + knowledge-base self-hosted para frotas de agentes Claude Code
Ver no GitHubKernel de memória e base de conhecimento self-hosted para frota de agentes Claude Code, baseado em Postgres/pgvector e vault markdown. Expõe HTTP API e servidor MCP para recuperação de conhecimento estruturado fora do modelo, com clustering automático e síntese periódica de memória.
Instalação
npx convez-ai jewbear66-cpu/tc-brain-kernel1 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
Casos de uso
- Memória persistente para agentes de IA
- Base de conhecimento estruturada em markdown
- Busca semântica com pgvector em dados proprietários
Veredito

Infraestrutura técnica robusta para times que precisam de memória distribuída e base de conhecimento versionável fora do prompt. Exige expertise em Docker, Postgres e MCP — não é pick-and-play, mas é completo e open-source.
README
A tradução para o português deste README ainda está na fila.
tc-brain-kernel
The Team Console brain kernel — a self-hosted brain + knowledge-base substrate for Claude Code agent fleets. Bring your own vault, your own LLM keys, your own embeddings. Runs on a laptop, a server, or a Kubernetes cluster.
tc-brain-kernel is a local brain + knowledge-base kernel: Postgres + pgvector embeddings, an HTTP brain API, and an MCP server that exposes retrieval tools to Claude Code, all backed by an Obsidian-style markdown vault you can open and edit by hand. Memory lives outside the model, on the filesystem, in a structured vault — not in prompts. A scheduled tick (deterministic clustering plus optional LLM synthesis) writes hot arcs, signals, decay, and synthesis into the vault, and a single HTTP contract fans that vault out to every agent in your fleet.
It is self-contained — its own services, Helm charts, vault schema, and Claude Code MCP wiring — and ships as an optional component of Team Console. MIT licensed.
Team Console status
This repo is the optional FULL/kernel-mode stack used by Team Console. Team Console's working default is LIMITED mode, which does not require Docker or this kernel. FULL/kernel mode is currently contributor-facing and work-in-progress: the brain MCP is not yet wired into Team Console's orchestrator/workers, so the kernel should be treated as infrastructure to finish or experiment with rather than a completed Team Console feature.
The local Compose path builds images from this source tree. Published GHCR
images under ghcr.io/jewbear66-cpu/tc-* are optional for Helm or users who
choose to swap Compose build: blocks for image: references.
Architecture
The kernel runs as a small set of containers behind one HTTP contract and one MCP endpoint. Agents never touch the database or the vault directly — they call the brain over HTTP (Bearer auth) or through MCP, and the kernel owns storage, embeddings, and the scheduled memory loop.
- brain-api (
:8103) — the HTTP surface: vault read/write,/ingest,/feed,/signal,/marker,/tick. - embeddings (
:8102) — pgvector-backed embed + search, OpenAI-compatible. - mcp (
:8104) — the retrieval tools Claude Code calls:kb_search,kb_brief,brain_search_arcs,brain_get_arc. - brain-ops — the background loop: a periodic tick that clusters and (optionally) synthesizes memory into the vault, plus an on-demand drain and a signal consumer.
State lives in three places: Postgres + pgvector for embeddings, Redis streams for events, and a plain markdown vault on disk you can open and edit in any editor. Memory is on the filesystem, not in prompts. Agents reach all of it through just two integration points — the HTTP contract and the MCP server.
Quick Start (Docker Compose)
1. Clone and bootstrap
git clone https://github.com/jewbear66-cpu/tc-brain-kernel.git
cd tc-brain-kernel
./local/bootstrap.sh # generates ~/.tc-brain/.env, symlinks to repo, scaffolds ./vault
2. Configure your LLM provider (optional)
Edit ~/.tc-brain/.env — set at minimum one API key to enable semantic search:
# Required for embeddings (semantic search) — OpenAI or any compatible provider
LLM_API_KEY=<your-openai-key>
LLM_API_BASE=https://api.openai.com/v1 # or your LiteLLM proxy
# Required for AI tick + kb_brief synthesis — any OpenAI-compatible endpoint
INFERENCE_URL=https://api.openai.com/v1
INFERENCE_API_KEY=<your-openai-key>
No API key at all? The brain still works — brain_ingest, kb_search (vault text), brain_get_arc all function. Only semantic search and AI synthesis are disabled.
Free local alternative (Ollama):
docker compose -f compose.yml -f local/compose.ollama.yml up -d
docker compose exec ollama ollama pull llama3.2
3. Start
docker compose up -d # postgres, redis, brain-api, embeddings,
# mcp, tick-cron, tick-drain, amygdala
docker compose ps # all healthy
curl http://localhost:8104/ping # pong — MCP server is up
Note: the default Compose stack builds the service images locally from
services/*/Dockerfileon first run (~5 min). To pull pre-built images instead, see Images & forking.
4. Wire Claude Code
Register the kernel's MCP server with Claude Code so the agent can reach the brain. Add to your project-local or user MCP config (e.g. ~/.claude/.mcp.json):
{
"mcpServers": {
"tc_brain": {
"type": "sse",
"url": "http://localhost:8104/sse"
}
}
}
Restart Claude Code, run /mcp — you'll see tc_brain with 5 tools:
| Tool | Purpose |
|---|---|
kb_search | Federated search (embeddings + vault text) |
kb_brief | Search + LLM synthesis (3-5 line brief) |
brain_search_arcs | Semantic search over brain arcs |
brain_get_arc | Fetch full arc by cluster_id |
brain_ingest | Write text to the brain vault |
Note: the local compose stack runs the MCP proxy without auth (localhost-only). For remote/production deployments set
MCP_PROXY_API_KEYon the container and pass it via anx-api-keyheader.
5. Test it
TOK=$(grep ^KB_ROUTER_TOKEN .env | cut -d= -f2)
# Write something to the brain
curl -X POST http://localhost:8103/ingest \
-H "Authorization: Bearer $TOK" \
-F "message=The quick brown fox jumped over the lazy dog"
# Search for it
curl -X POST http://localhost:8103/search \
-H "Authorization: Bearer $TOK" \
-H "Content-Type: application/json" \
-d '{"query": "fox"}'
Content lands in ./vault/raw/inbox/. The tick drains it to a region dir, recomputes heat, and updates brain-feed.
Force a tick on demand (don't wait for the 2h scheduled cycle):
pip install -e . # one-time, installs the `brain` CLI
brain tick --no-ai --wait # deterministic-only, blocks until done
brain tick --wait # full AI tick
brain tick --dry-run --wait # read-only verify, no writes
The tick-drain service polls brain-feed/ticks/requested/ every 30s and runs brain_tick.py per request — same UX as the K8s tick-drain CronJob. Scheduled ticks still run every TICK_INTERVAL_SECONDS (default 2h) via tick-cron.
See local/README.md for full local docs, troubleshooting, port overrides, and inference modes.
HTTP contract
Bearer auth via KB_ROUTER_TOKEN on every endpoint. Base URL below is $BRAIN_URL.
GET /feed — hot arcs + inject blocks
curl -s "$BRAIN_URL/feed" -H "Authorization: Bearer $KB_ROUTER_TOKEN"
{
"hot_arcs": [ { "id", "title", "content", "priority", "ttl", "severity" }, ... ],
"inject_blocks": [ ... ],
"entries": [ ... ],
"generated_at": "2026-04-27T18:08:00+00:00",
"hash": "c4d87ac3f961be48",
"entry_count": 5
}
Cached server-side for FEED_CACHE_TTL_SECONDS (default 30s). Read on every agent's session start.
GET /health — liveness probe
Returns { "status": "ok" }.
GET /signal — current amygdala alert
Empty amygdala-active.md → { "active": false, ... }. Dedup via hash.
POST /marker — emit a brain marker
| Type | Routes to | Mode |
|---|---|---|
lesson | left/reference/lessons-YYYY-MM-DD.md | append |
milestone | left/projects/<source>/BLOCKS.md if dir exists, else daily/YYYY-MM-DD.md | append |
signal | amygdala/<timestamp>-<severity>-<slug>.md | new file |
decision | left/decisions/ADR-NNNN-<slug>.md (auto-numbered) | new file |
curl -s -X POST "$BRAIN_URL/marker" \
-H "Authorization: Bearer $KB_ROUTER_TOKEN" \
-H "Content-Type: application/json" \
-H "X-Idempotency-Key: session-abc-first-lesson" \
-d '{"type":"lesson","content":"NFS dirs need 777 for UID 1000 writers","attrs":{"source":"deploy"}}'
Idempotency-key window 1h (configurable via IDEMPOTENCY_TTL_SECONDS). Replay returns the original response with idempotent_replay: true.
POST /tick — request a manual brain tick
File-protocol: writes a request to brain-feed/ticks/requested/. The tick-drain worker picks it up and moves it to completed/ or failed/. Poll GET /tick/{job_id}.
CLI wrapper: brain tick [--dry-run] [--no-ai] [--wait]. With --wait, blocks until the job leaves requested/.
POST /ingest — universal ingest
Free-text in. The model named in BRAIN_CLASSIFY_MODEL classifies via your inference gateway (any OpenAI-compatible — see docs/GATEWAY-CONTRACT.md), fans URLs/repos/files to artifact storage, drops a markdown note in raw/inbox/. Spec: api/openapi.yaml.
POST /ingest_with_files — multipart ingest
Same as /ingest but accepts file attachments as multipart/form-data.
POST /index_artifact — sole brain-side embedding write
Per-artifact embedding write surface. Called by ingest pipelines after a blob is stored. Every embed flows through this endpoint. Spec: api/openapi.yaml.
Vault endpoints
All vault reads and writes flow through brain-api (which mounts /vault directly):
| Endpoint | Method | Purpose |
|---|---|---|
/vault/list | GET | List vault files under a path |
/vault/read | GET | Read a vault file by path |
/vault/search | GET | Full-text search across the vault |
/vault/write_inbox | POST | Write a file to raw/inbox/ |
Full HTTP reference: api/openapi.yaml.
Vault schema
Obsidian-compatible folder tree, writable by humans and by kernel services. brain scaffold is the authoritative writer of the schema marker; local/bootstrap.sh invokes it on first run.
<vault>/
.brain-schema # version marker (JSON)
README.md CLAUDE.md # vault rules for AI agents
# Cognitive regions (owned by brain-ops + daemons)
raw/{inbox,articles,media,transcripts}/
clusters/ # canonical arc storage
brain-feed/ # /feed reads here, /tick writes ticks/requested/
amygdala/ # /marker type=signal lands here
frontal-lobe/{conscious,unconscious}/
pineal/ # joy + breakthrough region
# Knowledge base (operator owns — agents curate)
identity/ # who you are — root node
left/ # technical hemisphere — projects, research, reference, decisions, incidents
right/ # creative hemisphere — ideas, strategy, life, creative, risk
bridge/ # cross-hemisphere synthesis
daily/ # append-only daily logs
templates/mubs/ # VISION SPECS BLOCKS TODO STATE BUGS KNOWN-ISSUES ENHANCEMENTS MVP PATCHES
Scaffold is idempotent. Schema-version mismatch is a hard error unless --force-upgrade is passed. Full reference: docs/VAULT-SCHEMA.md.
Configuration
| Env var | Default | Purpose |
|---|---|---|
VAULT_ROOT | /vault | Vault mount path inside containers (NFS in K8s, bind mount in Compose) |
KB_ROUTER_TOKEN / KB_ROUTER_TOKENS | — | Bearer auth (single token or comma-sep list) |
EMBEDDINGS_URL | http://embeddings:8080 | Embeddings service URL |
EMBEDDINGS_API_KEY | — | Bearer token for the embeddings service |
INFERENCE_URL | — | OpenAI-compatible LLM gateway. Empty = deterministic-only ticks. See docs/GATEWAY-CONTRACT.md |
INFERENCE_API_KEY | — | Bearer token for the inference gateway. Empty = no auth header (trusted-LAN ok) |
BRAIN_CLASSIFY_MODEL | brain-classify | Model name for brain-api classifier |
BRAIN_BRIEF_MODEL | brain-brief | Model name for kb_brief / tick synthesis |
MCP_PROXY_API_KEY | — | Bearer token mcp enforces on inbound calls |
FEED_CACHE_TTL_SECONDS | 30 | /feed cache window |
IDEMPOTENCY_TTL_SECONDS | 3600 | /marker replay window |
TICK_INTERVAL_SECONDS | 7200 | Tick cadence (compose mode) |
Local mode reads from .env (generated by bootstrap.sh). K8s mode reads from a Secret (Opaque or ESO-synced from your secret store — see docs/SECRETS.md).
Observability
The kernel ships a starter Grafana dashboard at observability/brain-health.json — drop it into Grafana to get an immediate picture of the brain's pulse: hot arcs, emergency signals, tick cadence, memory markers, and delivery health. The panels are grouped by the brain regions the kernel uses internally (frontal lobe · amygdala · broadcast cortex · pineal · hippocampus), so the layout maps onto the same terminology you see throughout the vault.
How to wire it. The JSON is a mock — every panel queries a grafana-clickhouse-datasource with uid: clickhouse, against the brain.* schema that services/brain-ops writes into ClickHouse on every tick (brain.tick_health, brain.signals, brain.arcs, brain.lessons, brain.embeddings, …). To go from mock to live:
- Import — in Grafana, Dashboards → New → Import → paste
observability/brain-health.json. - Datasource — install the ClickHouse datasource plugin, point it at the ClickHouse instance brain-ops writes to, and either name its uid
clickhouseor remap the dashboard's datasource at import time. - Schema — the queries assume brain-ops's default table layout. If you've renamed tables or split databases, edit the panel
rawSqlblocks — column names match theBrainTickHealthmodel inservices/brain-ops/brain_tick.py. - Refresh — default cadence is
30sover anow-6hwindow; override per your appetite.
If you don't run ClickHouse, the JSON is still useful as a panel-layout reference — swap each rawSql for the equivalent in your TSDB of choice and keep the structure.
Install on Kubernetes (Helm)
Helm charts ship in helm/ — brain-api, embeddings, mcp, and brain-ops. The service charts depend on tcc-k8s-service-template:0.3.8 (vendored as .tgz under each chart's charts/ for offline install). brain-ops is a custom 3-template chart for the CronJob + amygdala consumer.
Step 1 — Scaffold the vault on persistent storage
Copy the template tree straight onto the volume:
git clone https://github.com/jewbear66-cpu/tc-brain-kernel
cp -r tc-brain-kernel/tc_brain/templates/vault-layout/* /mnt/<your-export>/
The kernel images expect this layout under /vault (see docs/VAULT-SCHEMA.md). Idempotent — re-running just refreshes any missing files.
Step 2 — Provision Secrets
Path A — plain Opaque Secret (simplest, no External Secrets Operator):
./local/k8s-bootstrap.sh --apply -n <your-namespace>
Creates the Secrets (tc-brain-router-secrets, embeddings-secrets) with random tokens. Tokens persist in local/.k8s-tokens for re-use.
Path B — External Secrets Operator (GitOps-tracked):
Wire your secrets manager (OpenBao / AWS Secrets Manager / Vault) via an ESO ClusterSecretStore, then set externalSecret.enabled: true in your values overlay. Full walkthrough: docs/SECRETS.md.
Step 3 — helm install the charts
helm install tc-brain-brain-api ./helm/brain-api -f values-brain-api.yaml
helm install tc-brain-embeddings ./helm/embeddings -f values-embeddings.yaml
helm install tc-brain-mcp ./helm/mcp -f values-mcp.yaml
helm install tc-brain-brain-ops ./helm/brain-ops -f values-brain-ops.yaml # singleton, deploy ONCE per cluster
Each values-*.yaml overlay sets:
extraVolumes→ NFS server + path or PVC claim for the vault from step 1 (brain-api mounts vault at/vault)env.variables.INFERENCE_URL+BRAIN_CLASSIFY_MODEL+BRAIN_BRIEF_MODEL→ your LLM gateway + model namessecrets.external.secretRef→ the Secret from step 2
Sample overlays + ArgoCD Application CRs ship in examples/ — copy, replace every <your-*> placeholder, deploy.
Optional maintenance agent. A
brain-keeperchart (helm/brain-keeper) is provided for an optional autonomous vault-maintenance agent (triage, enrichment, replay). It is a bring-your-own external agent: it runs an agent-runtime container image that this kernel does not build or publish. The brain functions fully without it — skip the chart if you don't need it, or pointimage.repositoryat your own agent image.
Optional — ArgoCD instead of helm install
Same outcome, declarative. Copy examples/argocd/ into your platform repo, swap placeholders, kubectl apply -f the tc-brain-root.yaml. ArgoCD picks up the per-service Apps and the chart sources point back at this kernel repo via multi-source.
Once running, every agent in your fleet gets two env vars and consumes the brain over HTTP:
BRAIN_URL: http://tc-brain-brain-api.<your-namespace>.svc:8080
KB_ROUTER_TOKEN: <from-the-secret-in-step-2>
Connect Claude Code running in-cluster by pointing its MCP config at the in-cluster Service URL of the mcp chart:
{
"mcpServers": {
"tc_brain": {
"type": "sse",
"url": "http://tc-brain-mcp.<your-namespace>.svc:8080/sse",
"headers": {
"x-api-key": "${MCP_PROXY_API_KEY}"
}
}
}
}
Inject MCP_PROXY_API_KEY via envFrom: secretRef: from the K8s Secret backing the mcp chart (tc-brain-mcp-secrets by default).
Architecture reference: docs/architecture/ARCHITECTURE.md. Generic deployment guide: docs/DEPLOYMENT.md. MCP wiring reference: docs/MCP.md.
Server (Docker Compose, headless)
The same compose.yml works on any Linux box with Docker. Bind the vault to a real path, expose 8103 behind your reverse proxy of choice (Traefik, Caddy, nginx), and point your fleet at it via BRAIN_URL. No Kubernetes required.
Images & forking
The kernel publishes 4 service images via GitHub Actions. Standard consumers don't build anything — pull and go.
| Image | Source | Tag |
|---|---|---|
ghcr.io/jewbear66-cpu/tc-brain-api | services/brain-api/ | :dev |
ghcr.io/jewbear66-cpu/tc-embeddings | services/embeddings/ | :dev |
ghcr.io/jewbear66-cpu/tc-mcp | services/mcp/ | :dev |
ghcr.io/jewbear66-cpu/tc-brain-ops | services/brain-ops/ | :dev |
CI: .github/workflows/docker-build.yml runs on every push to dev (→ :dev). main is vestigial; :latest is not published.
| Path | Builds locally? | Pulls from GHCR? |
|---|---|---|
docker compose up -d (default) | ✅ first run, ~5 min | ❌ |
| Helm charts | ❌ | ✅ all 4 service images |
| Air-gapped install | ✅ via your registry mirror | n/a |
For forkers: push to your fork's dev or main, the same workflow runs under your namespace and publishes to ghcr.io/<your-org>/tc-brain-*. Edit each chart's image.repository (or your values overlay) to point at your namespace. The vendored tcc-k8s-service-template-0.3.8.tgz makes helm install work offline; refresh from upstream with helm dep update helm/<chart>.
Development
git clone https://github.com/jewbear66-cpu/tc-brain-kernel
cd tc-brain-kernel
python -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
pytest tests/unit # scaffold + compose tests
PYTHONPATH=services/brain-api:. pytest services/brain-api/tests -q # service tests
docker build -t tc-brain-brain-api:local services/brain-api
Workflow: dev is the working branch and the deploy branch. CI on dev ships :dev GHCR images automatically. main is vestigial.
The kernel is the canonical source of truth for everything brain-related — services, Helm charts, the vault layout schema, and the brain scaffold tool that writes it. All deployment-specific plumbing (cluster namespaces, model name aliases, secret-store paths, NFS hosts) lives in your own platform repo, not here.
Status
v0.1.x — stable. Four service images auto-published to GHCR (:dev from dev branch; :latest from main is not published). HTTP contract frozen at v1. Generic OpenAI gateway — the kernel speaks chat-completions to any compatible upstream (LiteLLM, OpenAI, Ollama, vLLM, …). Every embed flows through POST /index_artifact. Vault read/write is served by brain-api directly via the vault_reader module — no separate reader service.
Maturity tracking lives in operator/:
operator/VISION.md— what 100% meansoperator/STATE.md— current snapshotoperator/BLOCKS.md— in-flight workoperator/ENHANCEMENTS.md— backlogoperator/TODO.md— next actions
Further reading
docs/architecture/ARCHITECTURE.md— full kernel designdocs/architecture/CLUSTERS.md— arc lifecycledocs/architecture/MARKERS.md— marker grammardocs/architecture/TELEMETRY.md— OTel + Langfusedocs/MCP.md— MCP server + Claude Code wiringdocs/SECRETS.md— Opaque Secrets vs ESOdocs/DEPLOYMENT.md— multi-source ArgoCD patterndocs/VAULT-SCHEMA.md— vault layout v1api/openapi.yaml— HTTP contract
License
MIT.