A browser + Express "cognitive brain" that scores any text for attention, trust, manipulation and affect — through a 103-layer deterministic engine (no backprop, no ML runtime), with a live WebGL 3D brain that reacts to every scan.
BrainSNN is a content-response analyzer dressed as a brain. Paste a headline, ad, email or script and it estimates hook strength, trust, urgency, emotional charge, manipulation risk and brand safety — then enriches that base scan through a stack of 103 deterministic "cognitive" layers: a Cognitive Firewall, an Affective Decoder, a TRIBE-style 7-region projection, business-metric mapping, audit receipts, and the newest addition, a 39 Hz soliton field (Layer 103).
The whole engine is deterministic — identical content yields an identical result — so every layer is regression-testable and every scan produces a reproducible audit receipt. Results are AI-estimated content-response signals, not literal brain, biometric or EEG measurements.
The result lands in a tabbed results view (Overview / Line-by-line / Audience / Advanced) next to a live WebGL 3D brain whose regions light up from the scan, and you can export or share a score card. The scoring itself stays CPU-only and deterministic; the 3D brain is a lazy-loaded visualization layer.
Optional integrations (Google Gemini for deep analysis, Stripe for billing, Supabase for auth, an external TRIBE service for fMRI-style projection) each sit behind a single environment variable. Leave them unset and the app runs fully offline on its deterministic local engine.
Everything lives in brainsnn-r3f-app/ (an Express server that also serves the React SPA):
cd brainsnn-r3f-app
npm install
npm run dev # Express + Vite middleware → http://localhost:3000No keys required — the deterministic engine drives every panel out of the box.
npm test # node test runner (tinyVitest), 27 tests
npm run lint # tsc --noEmit
npm run build # vite build + esbuild → dist/ (client) + dist/server.cjs
npm start # node dist/server.cjs (production)
npm run test:e2e # Playwright end-to-endflowchart LR
subgraph Browser["Browser SPA — React 19 + Vite"]
views["Analyze · Improve · Autopsy · Research views"]
panels["Results panels:<br/>firewall · affect · TRIBE · soliton"]
end
server["Express (server.ts)<br/>API + Vite middleware / static dist"]
router["103-layer deterministic engine<br/>src/lib/layerRouter.js"]
views -->|POST /api/analyze| server
server --> router
router --> panels
router -. GEMINI_API_KEY .-> gemini["Gemini — deep analysis"]
server -. STRIPE_* .-> stripe["Stripe — billing"]
server -. SUPABASE_* .-> supabase["Supabase — magic-link auth"]
router -. TRIBE_API_URL .-> tribe["TRIBE — external projection"]
Every external arrow is gated by an env var; unset, the layer falls back to the deterministic
local path (Gemini → local scoring, Stripe/Supabase → 501 not_configured, TRIBE → local
7-region projection).
A base scan (src/lib/analysisEngine.js) is enriched by runLayerRouter
(src/lib/layerRouter.js), which stacks the core layers onto every result:
| Layer | What it does |
|---|---|
| L4 — Cognitive Firewall | Pressure scoring across urgency / outrage / fear / certainty / trust, with a per-category breakdown, a per-sentence pressure heatmap, an A–F grade, and named tactics with confidence (src/lib/firewallLayer.js, POST /api/firewall). |
| L29 — Affective Decoder | Dominant affect + valence/arousal, a 9-affect taxonomy on Russell's valence×arousal circumplex, and a per-sentence emotion trajectory (src/lib/affectLayer.js, POST /api/affect). |
| L3 — TRIBE Projection | 7-region (CTX/HPC/THL/AMY/BG/PFC/CBL) activation projection; uses an external TRIBE service when configured, else a local mapping. |
| L48 — Business Metrics | Maps the scan into 8 decision KPIs (hook strength, trust, manipulation risk, shareability, …). |
| L46 — Firewall Receipt | Deterministic content/result/soliton hashes for a reproducible audit trail. |
| L103 — 39 Hz Soliton Field | Gamma-band synchrony + leapfrogging ionic-soliton model (below). |
The scores used to be asserted. They are now measured against a labelled
corpus of 18 content archetypes (src/lib/calibrationCorpus.js), reported as
rank agreement rather than invented precision, and guarded in CI so a
scoring change cannot silently regress:
| Dimension | Spearman ρ | Pairs ordered wrongly |
|---|---|---|
| trust | 0.700 | 16 / 107 |
| urgency | 0.641 | 14 / 111 |
| manipulation risk | 0.631 | 21 / 117 |
| viral pull | 0.366 | 32 / 107 |
81% of 442 labelled comparisons ranked correctly (mean ρ 0.585).
Calibration found a real defect: trust was originally anti-correlated (ρ −0.505), scoring outrage bait as more trustworthy than a sincere apology, because it counted trust vocabulary rather than evidence. Adding specificity and stated-limitation signals — and discounting specifics that sit inside urgency phrasing, so a fake deadline cannot buy credibility — turned it positive.
Two honesty notes, both enforced by tests rather than left to good intentions:
- The scores are 0–100 indices, not probabilities. Each one is shown with its percentile against the corpus, because "86th percentile of known archetypes" is a true statement where "86%" is not.
- Labels are ordinal. We can defend that phishing carries more pressure
than an understated luxury line; we cannot defend a claim that it scores
exactly 84. See
docs/ANNOTATION_RUBRIC.md, which also requires a Krippendorff's alpha (src/lib/agreement.js) before any corpus release claims reliability.
The 7-region model (src/features/brain3d/brainModel.js) is deterministic and
seeded, so the same content always produces the same run — which is what makes
brain readouts scoreable, shareable and verifiable. It exposes interventions
(lesion a region, cut a pathway, inject current) and derived measurements:
firing rates in Hz, PFC/AMY control ratio, hijack index, gain around the
THL→CTX→AMY→BG⊣THL control loop, E/I balance, spike correlation, settling
time, plasticity and net STDP flux.
That model is a rate model. src/lib/snn/ adds the real thing: a leaky
integrate-and-fire network in the Brunel (2000) formulation — Dale's law,
sparse random connectivity, transmission delays, Poisson drive — with the
standard measurements (CV of ISI, Fano factor, population spectrum). Its
regime behaviour is checked against the published analysis in
brunelValidation.test.js, so gamma-band power is measured rather than
asserted.
Claim boundary. Every neural readout ships with it: these are simulated dynamics of a model driven by lexical features of the text, not a measurement of any human brain, and not a clinical or predictive claim. The simulation is downstream of the same lexical scores, so it adds structure — not new information about the text.
The full catalog of 103 layers lives in src/lib/layerCatalog.js; the Research view has a
searchable Layer Explorer.
A biophysically-inspired signal layer that models the ~39 Hz gamma oscillation and the leapfrogging ionic solitons of neuronal microtubules:
- A Kuramoto ring of 13 protofilament oscillators near 39 Hz — coherence phase-locks for trustworthy content and fragments (desynchronizes) under manipulation pressure.
- A KdV soliton train — taller packets travel faster and overtake shorter ones; collisions carry the analytic two-soliton phase shift.
- Time-series traces (coherence/frequency waveform), a DFT of the binding envelope, delta→gamma oscillation bands with a theta–gamma phase-amplitude coupling metric, and a content-aware base frequency. Fully deterministic and seeded from the content hash.
It renders in the results view (SolitonFieldPanel) and has an interactive sensitivity lab in
the Research view (SolitonLabPanel), backed by POST /api/soliton, GET /api/soliton/presets
and POST /api/soliton/explore. It is a signal-processing analogy, not a microtubule/EEG
measurement.
| Method | Route | Purpose |
|---|---|---|
| GET | /healthz |
Container health check |
| GET | /api/layers |
The 103-layer catalog + core layers |
| GET | /api/engines/status |
Which optional engines are configured |
| POST | /api/analyze |
Full layer-router scan (Gemini if configured, else local) |
| POST | /api/firewall |
Cognitive Firewall profile for one input (offline) |
| POST | /api/affect |
Affective Decoder profile for one input (offline) |
| POST | /api/neural/analyze |
Analyze an authorized decoded-transcript envelope (L19 gateway) |
| POST | /api/neural/decode |
Proxy an external decoder via NEURAL_DECODER_URL, then analyze |
| GET | /api/neural/capabilities |
Neural gateway modes / modalities / remote status |
| POST | /api/rewrite |
Layer-stack rewrite toward a goal |
| POST | /api/autopsy |
A/B comparison of two variants |
| POST | /api/soliton |
Layer 103 field for one input (offline) |
| GET | /api/soliton/presets |
Field for the named archetypes |
| POST | /api/soliton/explore |
Ensemble-averaged driver sensitivity sweep |
| POST | /api/auth/magic-link · /api/billing/* |
Supabase / Stripe (when configured) |
brainsnn-r3f-app/mcp-server/ is a stdio MCP server that
exposes the deterministic engine to agents (Claude Code / Codex) — all tools run offline, no
keys. Tools: brain_analyze, brain_firewall, brain_affect, brain_soliton,
brain_soliton_explore, brain_layers, brain_decode.
cd brainsnn-r3f-app/mcp-server
npm install
npm run smoke # spawns the server, lists tools, calls a fewRegister it with an MCP client (e.g. Claude Code):
{
"mcpServers": {
"brainsnn": { "command": "node", "args": ["brainsnn-r3f-app/mcp-server/index.mjs"] }
}
}All optional — the app runs fully offline without any of them. Set them server-side (not VITE_):
| Variable | Unlocks |
|---|---|
GEMINI_API_KEY |
Gemini deep analysis on /api/analyze (else deterministic local engine) |
STRIPE_SECRET_KEY, STRIPE_PRICE_BASIC, STRIPE_PRICE_PRO, STRIPE_WEBHOOK_SECRET |
Stripe checkout, portal and webhook |
SUPABASE_URL, SUPABASE_ANON_KEY |
Magic-link auth |
TRIBE_API_URL |
External TRIBE projection health/scenarios (else local projection) |
NEURAL_DECODER_URL, NEURAL_DECODER_KEY |
Approved external communication-decoder endpoint for /api/neural/decode (analyzes decoded text only; else replay mode) |
PORT, APP_URL |
Server port (default 3000) / public URL |
the-brain/
├── brainsnn-r3f-app/ ← the deployable app (Express + React SPA)
│ ├── server.ts ← Express: API endpoints + Vite middleware / static dist
│ ├── src/
│ │ ├── app/ ← shell: AppShell, navigation, landing, Reconstruct page, command palette
│ │ ├── features/ ← scan · results (tabbed) · improve · autopsy · research · brain3d · social · export · …
│ │ ├── lib/ ← layerRouter · analysisEngine · solitonLayer · scoreMapping · storage · …
│ │ ├── components/ui/ ← Meter, Badge, Button, …
│ │ ├── styles/ ← tokens.css, utilities.css
│ │ └── test/ ← tinyVitest harness
│ ├── scripts/test-runner.mjs
│ └── tests/ ← Playwright e2e
├── ui/brainsnn-site/ ← marketing landing site
├── docs/screenshots/ ← UI screenshots
└── README.md
- Server: Express 4, TypeScript (run via
tsx, bundled withesbuild) - Frontend: React 19, Vite 6, Tailwind (
@tailwindcss/vite),motion,lucide-react - 3D brain: a live WebGL brain (
three,@react-three/fiber,@react-three/drei) that reacts to each scan. It is lazy-loaded —src/features/brain3d/Brain3D.jsxis the only module that importsthree/R3F, so it stays out of the main bundle and degrades to a 2D canvas fallback. - Engine: deterministic 103-layer router — regex/scoring firewall, affect decoder, Kuramoto + KdV soliton model, seeded PRNG; the scoring engine itself needs no ML runtime and no GPU.
- Results UI: tabbed — Overview / Line-by-line / Audience / Advanced — plus shareable score
cards (
src/features/social,src/features/export) and a classics gallery. - Optional:
@google/genai(Gemini), Stripe REST, Supabase Auth, external TRIBE service, and an external communication decoder viaNEURAL_DECODER_URL. - Tests:
tinyVitest(custom node runner) + Playwright; CI runs typecheck + tests + build + the MCP smoke on every PR (.github/workflows/ci.yml).
This repo is a joint AI workspace coordinated through .ai-memory/. See AGENTS.md and
GOOD_FIRST_ISSUES.md. Good first issues:
- A new manipulation template + firewall signal (
src/lib/layerRouter.js) - A new affect class in the decoder
- A new soliton preset / sweep axis in
src/lib/solitonLayer.js
MIT — see per-file headers.
