[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-111263":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":15,"forks30d":15,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":24,"hasPages":22,"topics":25,"createdAt":10,"pushedAt":42,"updatedAt":43,"readmeContent":44,"aiSummary":45,"trendingCount":15,"starSnapshotCount":15,"syncStatus":46,"lastSyncTime":47,"discoverSource":48},111263,"Brain4Agent","SparkofSpike\u002FBrain4Agent","SparkofSpike","Committed to building the world’s most cutting-edge, CJK-first memory module for all mainstream agents. Any issues and PRs are welcome.","",null,"Python",183,26,1,0,4,23,125,16,73.79,"Apache License 2.0",false,"main",true,[26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41],"agent-memory","agent-skills","agent-tools","bm25","chinese","cjk","japanese","korean","local-first","long-term-memory","mcp","memory","no-llm","python","retrieval","sqlite","2026-11-22 17:47:19","2026-11-23 10:47:01","# Brain4Agent\n\n**English** | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md)\n\n> **Agents: start here.** [FOR_AGENTS.md](FOR_AGENTS.md) is this page written\n> for you — what the store does for an agent, how to install it, how to call\n> it, and where it stops being useful.\n\nLong-term memory for agents. CJK-first retrieval, no model in the core path,\nand evidence instead of confidence scores.\n\n`pip install \"Brain4Agent[precise]\"` needs Python 3.11+, plus a 20 MB optional\ndictionary. Everything works without it.\n\n---\n\n## Contents\n\n- [What it is](#what-it-is)\n- [Install](#install)\n- [Quick start](#quick-start)\n- [How it works](#how-it-works)\n- [Benchmarks](#benchmarks)\n- [Running alongside another memory server](#running-alongside-another-memory-server)\n- [Against the frontier](#against-the-frontier)\n- [Status](#status)\n- [Contributing](#contributing)\n- [Special thanks](#special-thanks)\n- [License](#license)\n\n## What it is\n\nAn agent working on a codebase accumulates context: why a decision was made,\nwhich approach failed, where a deployment lives. Brain4Agent stores those turns\nin one SQLite file and retrieves them by session.\n\n- **CJK works out of the box.** Character bigrams need no dictionary and no\n  segmentation model. The benchmarked numbers are Chinese; Japanese, Korean and\n  Vietnamese are supported and tested.\n- **The core makes no model calls.** Retrieval is BM25: no API key, no\n  accelerator, no cold start, single-digit milliseconds per query.\n- **It reports evidence, not verdicts.** A search returns which question words\n  the corpus never contained (`corpus_missing`) and which ones a given session\n  lacked (`missing_terms`). The caller decides what that means.\n- **What is stored is not what is indexed.** A memory keeps its full text; the\n  index can hold a narrower, more distinctive version.\n\nMemories also carry `tags` (scope), `superseded_by` (replacement) and `refs`\n(one-hop links), supplied by the writer.\n\n## Install\n\n```bash\npip install \"Brain4Agent[precise]\"   # recommended: adds jieba, hit@1 0.950\npip install Brain4Agent              # zero dependencies: bigrams only, hit@1 0.875\n```\n\nWindows and macOS both work; Python 3.11 or newer is required. The package is on\nPyPI as \u003Chttps:\u002F\u002Fpypi.org\u002Fproject\u002FBrain4Agent\u002F>. To work on the code itself,\n`git clone` and `pip install -e \".[precise,dev]\"`.\n\n`jieba` is a 20 MB static dictionary. Without it the code falls back to bigrams.\n\n**Windows, non-ASCII input.** The MCP server and the CLI pin their stdin\u002Fstdout\nto UTF-8, so CJK content works regardless of the console code page. Command\nline *arguments* are decoded by Python before any of that runs, though — if you\npass non-ASCII text as an argument, set `PYTHONUTF8=1`.\n\n## Quick start\n\n### CLI\n\n```bash\n$ brain4agent exchange \\\n    \"中文查询搜不到记忆，recall 返回空\" \\\n    \"根因在 keywords.py 第 443 行，正则不含汉字范围\"\nstored exchange in session 913bcac81341\n\n$ brain4agent exchange \\\n    \"杭州那台测试机的地址是 203.0.113.42\" \\\n    \"部署目录 \u002Fopt\u002Fdemo-app，跑的是 PostgreSQL 14\"\nstored exchange in session c060a5294037\n\n$ brain4agent search \"中文查询为什么搜不到\" -k 1\n1 sessions for '中文查询为什么搜不到'\n  [ 6.73 cov=1.00] 913bcac81341\n\n--- 913bcac81341  score=6.73  coverage=1.00 ---\nuser: 中文查询搜不到记忆，recall 返回空\nassistant: 根因在 keywords.py 第 443 行，正则不含汉字范围\n```\n\nA question the store cannot answer:\n\n```bash\n$ brain4agent search \"杭州测试机上装的是什么数据库\" -k 1\n1 sessions for '杭州测试机上装的是什么数据库'\n  corpus has no: 数据库, 机上\n  [ 4.81 cov=0.28] c060a5294037  session lacks: 数据库, 机上\n```\n\nBulk-load an existing history from JSONL (one object per line, `content`\nrequired):\n\n```bash\n$ brain4agent import conversations.jsonl\nimported 4 turns across 2 sessions\n```\n\n```jsonl\n{\"session_id\": \"s1\", \"role\": \"user\", \"content\": \"中文查询搜不到记忆\"}\n{\"session_id\": \"s1\", \"role\": \"assistant\", \"content\": \"根因在 keywords.py 第 443 行\"}\n```\n\n### MCP server\n\n```json\n{\"mcpServers\": {\"brain4agent\": {\n    \"command\": \"python\",\n    \"args\": [\"-m\", \"brain4agent.mcp_server\"],\n    \"env\": {\"BRAIN4AGENT_DB\": \"\u002Fpath\u002Fto\u002Fbrain.db\"}\n}}}\n```\n\nFive tools:\n\n| Tool | Purpose |\n|---|---|\n| `b4a_remember` | Store one turn; returns a session id |\n| `b4a_recall` | Search; returns sessions with `corpus_missing` and per-session `missing_terms` |\n| `b4a_ask` | Retrieve and answer in one step; needs a model, and says so when none is configured |\n| `b4a_session` | Read a whole session in order |\n| `b4a_stats` | Counts |\n\nThe same library is also packaged as an agent [skill](integrations\u002F).\n\n### Library\n\n```python\nfrom brain4agent import MemoryStore\n\nwith MemoryStore(\"brain.db\") as store:\n    sid = store.new_session()\n    store.add(\"杭州那台测试机的地址是 203.0.113.42\", session_id=sid, role=\"user\")\n    store.add(\"部署目录 \u002Fopt\u002Fdemo-app\", session_id=sid, role=\"assistant\")\n\n    result = store.search(\"杭州测试机上装的是什么数据库\")\n    print(result.corpus_missing)        # ['数据库', '机上']\n    print(result.best().coverage)       # 0.28\n```\n\n`add_exchange(user=..., assistant=...)` stores a pair as one session. Retrieval\nis session-level, not turn-level.\n\nBulk imports go through `batch()`, which defers the commit to one per group:\n\n```python\nwith store.batch():\n    for turn in turns:\n        store.add(turn.text, session_id=turn.sid, role=turn.role)\n```\n\n### Optional hosted judge\n\nOff by default. Enabled only when a key is present.\n\n```python\nfrom brain4agent import Judge, MemoryStore\n\njudge = Judge.from_env()          # reads BRAIN4AGENT_JUDGE_KEY; None if unset\nif judge:\n    r = store.search_judged(\"question\", judge)\n    print(r.verdict)              # found \u002F not_found \u002F uncertain\n```\n\n`uncertain` is a third state, distinct from `not_found`: a judge that times out\nis not evidence that the memory does not exist.\n\n## How it works\n\n```\n                write                          read\n                  │                              │\n        bigrams + dictionary words          dictionary words\n                  │                              │\n                  ▼                              ▼\n          ┌──────────────────────────────────────────┐\n          │  SQLite: id, session, role, content,     │\n          │          created_at, tokens              │\n          └──────────────────────────────────────────┘\n                  │                              │\n                  ▼                              ▼\n           BM25 index (in memory)  →  session-level evidence\n                                        + corpus_missing\n                                        + per-session coverage\n```\n\n### Storage\n\nOne SQLite file. Rows are turns; the unit of retrieval is the session. Index\ntokens are computed at write time and cached in a column, so rebuilding the\nin-memory index is a counting exercise.\n\n```\n                       import    rebuild   query\n127 turns   44 sessions          3.9 ms   1.8 ms\n1016 turns  352 sessions  0.25 s  29 ms   3.7 ms\n```\n\nWrites commit in batches. A 1,016-turn import takes 3.8 s one commit at a time\nand 0.25 s inside `batch()`.\n\nRebuild also builds the phrase pair index when English summaries are in play\n(D-041), which roughly doubles that column: 8.9 ms for the 127-turn corpus and\n60 ms for 1,016 turns on the machine this was last measured on.\n\n### Read\u002Fwrite tokenizer split\n\nIndexing and querying use different tokenizers. Measured over a 3×3 grid of\nindex strategy against query strategy (D-019), then two changes on top of the\nbest cell (D-037):\n\n| index | query | hit@1 | MRR |\n|---|---|---|---|\n| bigram | bigram | 0.825 | 0.891 |\n| jieba | jieba | 0.875 | 0.911 |\n| bigrams + words | words | 0.925 | 0.940 |\n| **bigrams + words** | **words − question words** | **0.950** | **0.961** |\n\nThe last row adds two things the 3×3 grid did not test: interrogatives are\nremoved from the query side, and a session's best three turns are folded into\none score. Both are measured in\n[D-037](docs\u002Fdecisions.md#d-037-query-side-question-words-and-session-folding);\nthe first 3×3 grid is [D-019](docs\u002Fdecisions.md#d-019-index-wide-query-narrow).\n\nEnglish gets the same treatment one language over (D-041): query-side stopwords\n(`when`, `the`, `for`), inflection folding on both sides (`camped` matches\n`camping`), and a small bonus when two adjacent query words appear adjacent in a\nmemory (`pottery class` outranks the same two words scattered). The stemmer\nruns at index time, not in the stored token column, so an existing database\nneeds no migration. Chinese is untouched by all three — its bigrams already\nindex adjacency, and the rules refuse non-ASCII terms.\n\n### Where the words sit\n\nBM25 counts occurrences. It cannot tell a session that is *about* an event from\none that mentions the same words in passing. On LoCoMo's 486 misses, 417 had the\nright session inside the top ten and **188 had it at rank 2**, usually within a\nfew percent of the winner (D-042).\n\nSo a document also earns a bonus for keeping the question's words together: the\nfraction of distinct query terms that share a window of 40 index tokens,\nmultiplied into the score. It is not coverage reweighted — coverage asks\n*whether* a session has the words, and four separate attempts to use it as a\npost-hoc term were flat or worse (D-020, D-024, D-039, D-041). This asks\n*where* they are, which is a fact the index throws away.\n\nThree guards, each from a measurement that regressed without it: only ASCII\nwords take part (Chinese bigrams already index adjacency), documents under\nthree windows are skipped (a one-sentence belief has no passage), and queries\nunder five terms are skipped (two to four words is a lookup — on a real store\nthe bonus cost 0.043 hit@1 there and nothing anywhere else, D-042).\n\n### Evidence, not verdicts\n\n- **`corpus_missing`** — a content word from the question appears nowhere in the\n  stored corpus.\n- **`missing_terms`** (per session) — which question words that session lacked.\n- **`term_frequencies`** — how many sessions each question word appears in. A\n  word present in 453 of 2898 memories is neither missing nor misspelt; it is\n  too common to separate anything, and the query needs another word (D-039).\n- **`related_terms`** — up to five words the top sessions use that the query did\n  not. The third word a two-word query needs, taken from the corpus (D-040).\n\nWhether to refuse is the caller's decision; the store reports the fact.\n\n## Benchmarks\n\nAll numbers are reproducible from the `bench\u002F` scripts, which import the\nshipping code rather than a copy of it.\n\n### LongMemEval (English) — retrieval\n\n470 answerable questions over the `s` variant (average haystack 493 turns):\n\n```\nhit@1    0.8660\nhit@5    0.9511\nhit@10   0.9660\nMRR      0.8990\n```\n\n`python -m bench.run_longmemeval --dataset s`. `bench\u002Fdata\u002F` is fetched by\n`bench\u002Ffetch_data.py` (264 MB, not committed).\n\nThese use the harness's bigram\u002Fbigram configuration. The store's own\nconfiguration (wide index, words minus question words, fuzzy) scored 0.8596 on\nthe same 500 tasks and took 8× longer, so LongMemEval keeps bigrams — measured,\nnot assumed.\n\nAcross three benchmarks:\n\n| benchmark | metric | this store | best third-party |\n|---|---|---|---|\n| LongMemEval `s` | hit@10 | 0.9660 | — |\n| PrecisionMemBench | active | **42\u002F43** | 18\u002F43 (open-knowledge-format) |\n| PrecisionMemBench | total | **74\u002F77** | 36\u002F77 (open-knowledge-format) |\n| LoCoMo | hit@1 | **0.7054** | not comparable |\n\n### PrecisionMemBench — retrieval precision\n\n77 single-turn cases over 35 beliefs. No generation model and no judge: the\nanswer is the set of belief IDs the store returns. `active` is the honest\ncolumn, because 33 of the 77 cases pass with an empty store.\n\n```\nactive  42\u002F43 = 0.9767     cases that need query-dependent retrieval\n total  74\u002F77 = 0.9610     including cases any store passes\n```\n\nThree changes lifted this from 34\u002F43 and 64\u002F77. The result set is now sized from\nthe names a query contains at every length, and only from beliefs the case's\nscope can see — the old rule forced `top_k=1` below eight words and counted\nout-of-scope beliefs. Whole-word name matching replaced substring matching, so\n`pipe` no longer matches inside `pipeline`. A fuzzy query path then matches a\nmisspelt English word against a corpus word one edit away (`typscript` →\n`typescript`, `mongod` → `mongodb`). See\n[D-038](docs\u002Fdecisions.md#d-038-sizing-the-result-set-and-matching-one-edit-away).\nTwo more cases came with the English query folding in\n[D-041](docs\u002Fdecisions.md#d-041-english-query-folding-stopwords-stems-and-adjacency):\na query's grammar is not a memory, so dropping `what` and `the` from the query\nside keeps a scope-bleed belief out of the result set.\n\nOfficial table, from the benchmark's own site (`tenureai.dev\u002Fbenchmark`):\n\n```\nSystem                  Active    Total\n----------------------  ------    -----\ntenure (the authors)    43\u002F43     77\u002F77\nthis store              42\u002F43     74\u002F77\nopen-knowledge-format   18\u002F43     36\u002F77\natomicmemory             5\u002F43     16\u002F77\nsupermemory              2\u002F43     15\u002F77\nyourmemory               0\u002F43     21\u002F77\ngbrain                   0\u002F43     11\u002F77\nhindsight                0\u002F43     11\u002F77\nzep                      0\u002F43      9\u002F77\nagentmemory              0\u002F43      9\u002F77\ncognee                   0\u002F43      9\u002F77\nmem0                     0\u002F43      9\u002F77\na-mem                    0\u002F43      7\u002F77\n```\n\nBest third-party result on both columns. The benchmark's own reference\nimplementation scores 43\u002F43 and 77\u002F77.\n\n### LoCoMo — retrieval\n\n1540 questions over 272 sessions, 5882 turns.\n\n```\nhit@1   0.7054\nhit@5   0.9086\nhit@10  0.9549\nMRR     0.7921\n```\n\n`python -m bench.locomo.run` — no model, data committed. These are session\nretrieval rates, not answer accuracy under an LLM judge, so they are not\ncomparable to published LoCoMo numbers.\n\nIndexing turns instead of sessions costs 2.5 points of hit@1 (0.6022 → 0.6310),\nsame tokenisers and scoring — measured before D-041 and D-042 raised both.\n\nBy category (hit@1): open-domain 0.7919, temporal 0.6906, single-hop 0.5445,\nmulti-hop 0.4494. The last two are lookups of a single fact inside a session,\nwhich is why the proximity bonus in [D-042](docs\u002Fdecisions.md#d-042-proximity-where-the-query-words-sit-not-just-whether-they-appear)\nturns itself off for short queries: it helps a question that names an event and\nhurts one that names a fact.\n\n### Chinese benchmark\n\n59 questions (40 answerable, 19 unanswerable), 44 sessions.\n\n| metric | bigram\u002Fbigram | current |\n|---|---|---|\n| hit@1 | 0.825 | **0.950** |\n| hit@5 | 0.950 | **1.000** |\n| hit@10 | 1.000 | 1.000 |\n| MRR | 0.891 | **0.961** |\n\n`current` is index `bigrams + words`, query `words minus interrogatives`, and\nsessions folded from their best three turns (D-037). hit@10 is saturated; only\nhit@1 and MRR discriminate.\n\n### Where the Chinese number stops holding\n\n**0.950 describes 44 sessions. Dense near-duplicates collapse it.**\n\n| corpus | hit@1 | hit@5 |\n|---|---|---|\n| 44 sessions | 0.950 | 1.000 |\n| +300 same-topic sessions | 0.000 | 0.000 |\n\nAsked which file and line caused a bug, a vague session saying \"some file, some\nline\" outranks the one saying `keywords.py line 443`. Supplying the gold\nsession's own file names, line numbers and commit hashes recovers 15%:\n\n| query | hit@1 |\n|---|---|\n| question only | 0.000 |\n| + 3 oracle entities | 0.150 |\n\nRead the top five, weight `corpus_missing` over raw score, and tag your\nmemories — scope, kind, what supersedes what. The fix is at write time; four\nquery-side attempts are in [D-020](docs\u002Fdecisions.md#d-020-bag-of-words-retrieval-degrades-on-dense-same-topic-corpora)\nand [D-021](docs\u002Fdecisions.md#d-021-oracle-entities-recover-15-the-failure-is-not-missing-literals).\n\n### Abstention\n\nAt the natural operating point of `corpus_missing`:\n\n| approach | keep | refuse | latency | resident |\n|---|---|---|---|---|\n| BM25 only | 1.000 | 0.000 | 0.22 ms | 0 |\n| **corpus_missing** | **0.875** | **0.632** | ~0 | 0 |\n| local 2B | 0.750 | 1.000 | 0.77 s | ~1 GB |\n| local 9B | 0.950 | 0.895 | 1.5–2 s | 15.2 GB |\n| hosted `deepseek-flash` | 0.925 | 1.000 | 0.81 s | 0 |\n\nA 0.875 keep rate means 12.5% of answerable questions would be refused\nautomatically, so the signal is reported rather than acted on. A hosted judge\nadds 0.81 s per lookup — 24 seconds across 30 lookups in one task.\n\n## Running alongside another memory server\n\n**Do not enable two memory MCP servers in the same agent.** With\n`neural-memory` and `b4a` both loaded, an agent queried the other server and\nreported \"memory has no record of this\" while five relevant memories sat in\n`b4a`. Use one memory server per agent, or names that make the choice\nunambiguous.\n\n## Against the frontier\n\n| Capability | Status here |\n|---|---|\n| Structured memory (typed facts, preferences, entities) | **Partial.** `kind` is a free-form label, `tags` are scopes, `refs` are links. No schema, no validation. |\n| Temporal \u002F graph memory (validity windows, relation evolution) | **Not built.** `created_at` and `superseded_by` only; no validity interval, no query-time traversal. One-hop `refs` scores 4\u002F4 on PrecisionMemBench. |\n| Conflict resolution | **Built.** `supersede(old, new)`; the replaced memory stops surfacing. PrecisionMemBench supersession category: 3\u002F3. |\n| Write-path deduplication \u002F pattern extraction | **Not built.** Extraction exists (`remember()`) and is **off by default** (D-023). |\n| Multi-retriever fusion | **Not built.** One retriever: BM25. |\n| Forgetting \u002F consolidation | **Crude.** `prune(keep_sessions=N)` is recency-based size control; `decay` and `prune_by_weight` add a weight signal. Recovering a noisy corpus needs deleting 95% of it (D-022). |\n| Cross-session aggregation | **Not built.** |\n| Proactive recall | **Partial.** `recall-context` for client-side hooks; no scheduler. |\n| Multimodal | **Not built.** |\n| Hallucination defence | **Partial.** Evidence\u002Fverdict separation, `corpus_missing`, three-state judge. Nothing detects a wrong answer produced from a correct retrieval. |\n| Reproducibility of published numbers | **Strong.** Three benchmarks, two with no model in the loop. |\n\n## Status\n\nLibrary, CLI and MCP server are complete.\n\n**New:** near-duplicate detection (`duplicates_of`, SimHash; reports, does not\nmerge, and is not on the search path) and weight (`reinforce`, `decay`,\n`prune_by_weight`). Retrieval drops question words from the query side, folds a\nsession's best three turns into one score, and matches an unknown English word\none edit away from a corpus word (D-037, D-038). English queries also drop\nstopwords, fold inflections, and reward word adjacency (D-041) — LoCoMo hit@1\n0.6310 → 0.6826 and PrecisionMemBench total 72\u002F77 → 74\u002F77, with the Chinese\nnumber unchanged. A session is also rewarded for keeping the question's words\nin one passage (D-042) — LoCoMo hit@1 0.6826 → 0.7054 and MRR 0.7784 → 0.7921,\nwith the Chinese benchmark, PrecisionMemBench, LongMemEval and keyword queries\nagainst the real store all measured unchanged.\n\n**Not built:** cross-session synthesis, multimodal, schema on `kind`,\nmulti-retriever fusion, a recall scheduler, time-decayed forgetting.\n\n**Measured and rejected:** query-time graph traversal (D-024), write-time\nextraction (D-023), chunking LoCoMo sessions for retrieval, running LongMemEval\non the store's own tokenisers (D-037), chunking LoCoMo sessions (D-037),\nminimum-span and early-position re-ranks (D-042).\n\nRelease history is in [CHANGELOG.md](CHANGELOG.md). The\n[decision log](docs\u002Fdecisions.md) records 42 entries; the\n[research notes](docs\u002Fresearch.md) and [landscape analysis](docs\u002Flandscape.md)\ncover the field.\n\n## Contributing\n\n```bash\npython -m pytest tests\u002F -q\npython -m ruff check src bench tests\npython -m ruff format --check src bench tests\npython -m bench.zh.e2e\npython -m bench.pmb.run\npython -m bench.locomo.run\n```\n\n`bench\u002Fzh\u002Fe2e.py` should report `hit@1 0.9500`; `bench.pmb.run` `pass 74\u002F77`;\n`bench.locomo.run` `hit@1 0.7054`. Lower is a regression. The last two need no\nAPI key and no network. Changes to a design decision belong in\n`docs\u002Fdecisions.md` as a new entry, with the measurement that justifies it.\n\n## Special thanks\n\nTo [nhadaututtheky](https:\u002F\u002Fgithub.com\u002Fnhadaututtheky) for\n[neural-memory](https:\u002F\u002Fgithub.com\u002Fnhadaututtheky\u002Fneural-memory). This project\nbegan as a bug fix there: a Chinese query returned nothing because the keyword\nregex had no Han range. Its brain is also the corpus for `bench\u002Fnmem\u002F`.\n\n## License\n\nApache-2.0. See [LICENSE](LICENSE).\n","Brain4Agent 是一个面向智能体（Agent）的轻量级、长期记忆存储模块，专为中日韩（CJK）文本优化设计。核心采用无模型的 BM25 检索算法，基于 SQLite 单文件持久化，支持会话级上下文存储、带标签（tags）、引用（refs）和替代关系（superseded_by）的结构化记忆管理；检索过程不依赖 LLM 或外部 API，毫秒级响应，并返回可解释的证据（如缺失词项），而非黑盒置信度。适用于本地优先、隐私敏感、需稳定低延迟记忆召回的 Agent 场景，如代码辅助 Agent、运维排障 Agent 或多轮 CJK 任务型 Agent。",2,"2026-11-24 04:40:36","CREATED_QUERY"]