chanda

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0

README

Chanda

Chanda: local memory for AI agents

release ci Go Reference license

Agent memory · MCP server · Hermes Agent plugin · RAG

Long-term memory for AI agents that never needs an LLM to build it.

Chanda is a memory server for agents, spoken over MCP. It stores what an agent learns and what a company documents (documents, session transcripts, facts with a validity period) in one SQLite file. It returns the right excerpt at the right moment: a short, delimited pre-context before the first turn, and ranked search during the task. It ships as a single Go binary that runs on CPU, with no cgo and no network access, and any MCP client can use it.

Most agent memories call an LLM on every write to extract and rewrite what they store. Chanda doesn't. Writing costs a hash, an embedding and a few rules, and reading uses full-text search, vectors, rules and a small ranking. An LLM is optional and only used offline. The result is memory that is fast, cheap and reproducible, and that can say exactly where every answer came from.

Why "Chanda"

The name comes from Chanda, a character in the series Pantheon: an Uploaded Intelligence that is restarted every day. His work moves forward because it is saved in files, but he starts from zero every morning, without remembering what he learned. Today's AI agents are in the same situation: every session starts blank, and what makes progress is the files, not the agent. This project is an attempt to change that. It gives an agent a memory reliable enough to work continuously for months and, over time, to grow in its role.

How it works

Chanda keeps every conversation and document exactly as it arrived, in a log that is never edited. It organises that material with rules instead of asking an LLM what to remember. When a piece of information changes, the old one is not deleted: it gets an end date and the new one takes effect. Contradictions in free text are detected by rules, and an LLM can be called during sleep to decide those pairs.

To answer, Chanda searches by keyword and by meaning, drops what has been superseded, and assembles a short context of many small excerpts instead of a few long ones. That assembly is what explains the results. On LongMemEval, Chanda's context held the complete evidence more often than a plain RAG's, and its accuracy came out higher on public benchmarks.

No LLM takes part in writing, so memory is built in seconds and at no cost, and the same input always produces the same result. Every record keeps its origin, its author and its trust level. That lets several agents share one memory, lets searches be filtered by source, and lets a piece of information be erased together with everything derived from it.

Highlights

0 LLM calls to build memory On the LongMemEval battery, Chanda ingested 60 conversations (about 500 turns each) with no LLM call and US$0. Mem0 needed 2,868 LLM calls and US$2.48 for the same 60.
About 50× faster ingestion 7.6 s per conversation (median, with e5 embeddings on CPU), against 402 s for Mem0.
Ahead of plain RAG on two benchmarks On LongMemEval, 300 questions never used for tuning: 82.7% against 77.7%. On LoCoMo, 584 questions from 7 conversations never seen before the freeze: 67.3% against 64.7%. Same embedder, reader, judge and 2,000-token budget in both.
A measured gain from the new context selection +4.7 points over the previous selection on the 300 held-out LongMemEval questions (78.0% → 82.7%; p = 0.024, pre-registered).
Search that finds the evidence 98.3% session recall@10 over all 500 LongMemEval S questions. Plain RAG gets 97.9% and BM25 95.6%. With the built-in hash embedder and no neural model at all, it still gets 93.4%, against 82.7% for plain RAG.
More of the evidence in the context On the 300 held-out LongMemEval questions, the context block held every evidence turn for 75.1% of questions, against 68.5% for plain RAG (paired p = 0.020, measured without an LLM).
Sleep that only adjudicates Sleep uses an LLM only to decide contradictions that rules detect automatically.
Compartmentalised, shareable memory Memory can be shared between agents, and every record carries its origin, access level, date and trust.
Forgetting you can verify forget deletes in cascade, then proves the content is gone from every read path, the full-text index, the vectors and the raw bytes of the database, WAL and SHM files (scenarios F1–F4).
Deterministic The same database and query give the same answer. The scenario suite is byte-identical across runs.
Near-duplicates caught 0 of 80 near-duplicates missed on the held-out deduplication suite with e5 embeddings, and no false merge (decision 0138).
Abstains when it doesn't know Correctly declines 87.5% of LongMemEval's unanswerable held-out questions (14 of 16), instead of guessing.
Published, pre-registered evaluation Every number above comes from a study in eval/, with its protocol, data, scripts and costs. Protocols were committed before the test runs.

Protocols, raw data and full statistics for every number are in eval/: selection, learn and the LongMemEval battery.

What it does

Memory built without an LLM

Every write path is deterministic. Documents are chunked and indexed, session turns are logged with their speaker and date, and facts come from explicit assertions and from rule-based extractors (Markdown headers, two-column tables, regular expressions). Near-duplicates are folded at write time. The default embedder is a built-in hash embedder, and an e5 model runs locally on CPU when you want semantic recall.

Agentic memory, with an LLM only if you want one

The read path is hybrid. BM25 and vector lists are fused, an optional reranker can reorder them, evidence floors are applied, then diversity and a token budget. The output is one context block that labels each excerpt with its source, date and trust zone. Agents call context before the first turn and search, get, timeline and explain during the task.

With an LLM configured, agentic search is on by default (decision 0151). Before context and search, the LLM turns the query into search terms (names, dates, the topic, synonyms), and the read runs on the query plus those terms. If the call fails, the read uses the query as given. Set read.agentic_search: false to keep reads deterministic. Without an LLM, reads never call one.

The LLM's other use is offline, in sleep. Its deterministic maintenance phase always runs: integrity checks, pending embeddings, utility updates and entity-merge proposals. With a provider configured, an LLM phase can also consolidate facts and pages. The phase is gated: it is measured and rolled back if the evaluation score drops. The usage-guided digest (decision 0142) is off by default and has two modes, procedural (extractive, no LLM) and LLM.

Provenance and trust, recorded at write time

Every derived record points to the raw events it came from. Its trust zone (user, internal or external) is fixed by the channel it arrived through, so content from tools or the web never becomes guidance or a trusted fact. Facts are superseded, never overwritten, and they carry a validity period. You can ask what was true at any date. Every mutation goes into an append-only, hash-chained audit log.

Forgetting, verified

forget takes a record, a document, a source, an entity, a date range or a search match. It removes the content and everything derived from it, then runs probes that check the text is gone everywhere, including the database's raw bytes. A tombstone records what was removed, without the content.

Learning from use, and abstention
  • Outcomes. Agents report outcomes (outcome): whether an answer worked and which items it used. Chanda keeps per-record utility from these, which can feed the ranking: a learned ranker promoted through an evaluation gate, or a fixed weight (decision 0146).
  • Learned query keys. Positive outcomes can create learned query keys (decision 0145). A question that led to a good answer becomes an extra way to find the same record, and nothing is added to the context block. Both are opt-in, and their evaluation is in eval/learn/.
  • Abstention. When nothing clears the evidence floors, context returns nothing and says why (no_relevant_memory), so the agent gets no filler to guess from. On LongMemEval's held-out unanswerable questions, Chanda's answers correctly declined 14 of 16 (87.5%).
Built to run anywhere
  • One static Go binary, with no cgo and no network access.
  • A ready Hermes Agent memory provider plugin (adapters/hermes) and a generic Python adapter (adapters/generic).
  • One SQLite file per memory, with FTS5 for full text.
  • MCP over stdio or Streamable HTTP.
  • An in-process Go API (pkg/chanda/local).
  • Tool profiles (read, standard, admin), so an agent that reads untrusted content cannot forget or promote anything.

Evaluation and research

Every feature that affects answers was measured before it was turned on by default. Each study publishes its protocol, data, scripts, costs and deviations.

Study Question Outcome
LongMemEval battery How does Chanda compare with no memory, plain RAG, Mem0 and its own sleep, on 60 questions and 500 for retrieval? Search at 98.3% recall@10, the best of the retrieval methods compared (BM25, plain RAG, Chanda). It also pointed to the context block as the next thing to improve.
Context selection (pre-registered) Does a per-item cap with best-window truncation improve the block? Yes: +4.7 points on 300 held-out questions (78.0% → 82.7%, p = 0.024), now the default.
Usage-guided sleep (pre-registered, LoCoMo) Do digests of frequently used memories help later answers? Ships as an opt-in sleep mode, with procedural or LLM digests.
Learning from use (pre-registered, LoCoMo) Do utility ranking and learned query keys help later answers? Ships opt-in. On 7 unseen conversations, Chanda without learning scored 67.3%, against 64.7% for plain RAG.

Total LLM spend for all of them: US$8.20, through a metered proxy with a record/replay call store (eval/cmd/lmeproxy).

Third-party data is not redistributed. LongMemEval is fetched by lme fetch. LoCoMo (snap-research/locomo, CC BY-NC 4.0) is downloaded by hand (eval/locomo/SOURCE.md) and used here for research only.

Install

How
Prebuilt binary Download chanda-<version>-<os>-<arch> from Releases (Linux, macOS, Windows; amd64 and arm64) and check it against SHA256SUMS.
Go CGO_ENABLED=0 go install github.com/felipemarts/chanda/cmd/chanda@latest
MCP bundle Open chanda-mcp-<os>-<arch>.mcpb from Releases in a client that installs MCP bundles (Claude Desktop, for one). It asks for the database file (default ~/.chanda/chanda.db) and, optionally, a chanda.yaml.
MCP Registry Listed as io.github.felipemarts/chanda.
Hermes Agent hermes plugins install felipemarts/chanda/adapters/hermes/chanda_hermes, then hermes config set memory.provider chanda. See adapters/hermes.

Without a configuration file, chanda serve --db ~/.chanda/chanda.db runs with the defaults and keeps the memory in that file.

Build

Go 1.26, no cgo:

CGO_ENABLED=0 go build -o chanda ./cmd/chanda
CGO_ENABLED=0 go test ./...

Run

chanda serve  --config chanda.yaml              # MCP over stdio
chanda serve  --config chanda.yaml --http 127.0.0.1:7777   # Streamable HTTP at /mcp
chanda ingest --config chanda.yaml ./handbook   # ingest a file or folder
chanda forget --config chanda.yaml --kind document --value ./handbook/old.md --dry-run
chanda version

The CLI acts for a person at the terminal: it may ingest any path and write in the user zone. Every command prints the result envelope ({ok, data, notices, audit_id, error}) as JSON. chanda sleep runs consolidation now; chanda eval (or make eval) regenerates the evaluation report in eval/reports/. See docs/usage.md for every command.

Claude Code
claude mcp add chanda -- chanda serve --db ~/.chanda/chanda.db
# with a configuration file:
claude mcp add chanda -- /usr/local/bin/chanda serve --config /home/me/.config/chanda/chanda.yaml
Any MCP client (JSON configuration)
{
  "mcpServers": {
    "chanda": {
      "command": "/usr/local/bin/chanda",
      "args": ["serve", "--config", "/home/me/.config/chanda/chanda.yaml"]
    }
  }
}

In stdio mode stdout carries only MCP frames; logs go to stderr.

Go
api, closeFn, err := local.Open(ctx, "chanda.yaml") // github.com/felipemarts/chanda/pkg/chanda/local
defer closeFn()
ctx = chanda.WithActor(ctx, chanda.Actor{Name: "my-agent"})
pre, err := api.Context(ctx, chanda.ContextInput{Query: userRequest})

chanda.yaml

Every key is optional; a missing file means the defaults. The main options:

db_path: /home/me/.local/share/chanda/chanda.db
namespace: default          # used when a call omits namespace

mcp:
  profiles: [read, standard] # add admin only for a human-operated client
  actor: agent               # name written to the audit log
  human_actor: false         # true only when a person drives the client (needed by promote)
  max_zone: internal         # highest trust zone this channel writes; user requires human_actor

write:
  ingest_roots: [/home/me/company-docs]  # folders the MCP ingest tool may read; empty = refused
  ingest_extensions: [.md, .markdown, .txt]
  near_dup_threshold: 0.95
  extractors:                # deterministic fact extractors (no LLM)
    - {name: headers, kind: header}       # "Key: value" lines under a heading
    - {name: tables, kind: kv_table}      # two-column Markdown tables
    - {name: price, kind: regex, subject: Plano Pro, predicate: current_price,
       pattern: 'preço atual: (?P<value>R\$ ?[\d.,]+)'}

facts:
  single_predicates: [job_title, address, current_price, owner, email, phone, status, manager, employer, location]

read:
  context_default_tokens: 800
  context_max_tokens: 1500
  min_term_coverage: 0.5     # abstention evidence (decision 0020)
  min_cosine: 0.5

embed:
  provider: hash             # built-in deterministic embedder (decision 0031)
  dim: 256

ranking:
  enabled: true
  lambda_max: 0.3

forget:
  tombstone_keeps_hash: false

See internal/config/config.go for every key and its default.

Tools

Every tool takes an optional namespace and answers in the same envelope. mcp.profiles decides which tools a server registers.

Profile Tools
read context, search, get, timeline, explain, stats
standard remember, assert_fact, ingest, log_session, outcome, flag, flush
admin forget, promote, sleep_run, verify, ranking_reset, learned_keys, conflicts

An agent that reads untrusted content should get read and standard only. promote also requires mcp.human_actor: true. Without an LLM provider, sleep_run runs phase 1 (deterministic maintenance) only.

A typical integration calls context with the user's request before the first turn and injects data.text (a block delimited by <chanda-context> that states it is retrieved information, not instructions), lets the agent use search, get and timeline during the task, and calls log_session and outcome at the end.

Repository

Path What
cmd/chanda CLI and MCP server entry point
internal/app the core: every area wired into chanda.API
internal/write, read, facts, dedup, embed, rank, prov, forget the areas of BASE.md
internal/mcp tool registration, profiles and the envelope
internal/store, audit, core, config, env foundation
internal/e2e end-to-end acceptance suites through MCP
pkg/chanda public Go API and wire types; pkg/chanda/local opens the core in process
docs/ decisions, error codes, research notes

Licence: Apache-2.0 (LICENSE).

Directories

Path Synopsis
adapters
generic/go command
Command chanda-agent-example shows, in Go, the three moments an agent runtime owes Chanda (BASE.md "Why MCP alone is not enough"):
Command chanda-agent-example shows, in Go, the three moments an agent runtime owes Chanda (BASE.md "Why MCP alone is not enough"):
cmd
chanda command
Command chanda is the CLI and MCP server entry point.
Command chanda is the CLI and MCP server entry point.
eval
cmd/gensynth command
Command gensynth writes the deterministic synthetic Portuguese dataset.
Command gensynth writes the deterministic synthetic Portuguese dataset.
cmd/lmeproxy command
Command lmeproxy is the OpenAI-compatible reverse proxy that every LLM call of the LongMemEval battery goes through (reader, judge, Mem0 extraction, Chanda sleep phase 2).
Command lmeproxy is the OpenAI-compatible reverse proxy that every LLM call of the LongMemEval battery goes through (reader, judge, Mem0 extraction, Chanda sleep phase 2).
scenarios
Package scenarios is phase 5 of the evaluation battery: scripted, deterministic scenarios that drive a real `chanda serve` process over MCP stdio (and the chanda CLI where a person would act), without any LLM.
Package scenarios is phase 5 of the evaluation battery: scripted, deterministic scenarios that drive a real `chanda serve` process over MCP stdio (and the chanda CLI where a person would act), without any LLM.
internal
app
Package app wires every area of Chanda into one chanda.API over one env.Env: the write path with its in-transaction hook chain (facts, embedding queue, near-duplicates, integrity check), the read path with vectors and the ranking adapters, the embedding indexer, provenance, forgetting and ranking.
Package app wires every area of Chanda into one chanda.API over one env.Env: the write path with its in-transaction hook chain (facts, embedding queue, near-duplicates, integrity check), the read path with vectors and the ranking adapters, the embedding indexer, provenance, forgetting and ranking.
audit
Package audit writes the hash-chained audit log (principle 10).
Package audit writes the hash-chained audit log (principle 10).
cli
Package cli is the chanda command line: every command of the chanda binary lives here so that other binaries (chanda-hugot, which registers the hugot embed provider) run the same CLI through cli.Run.
Package cli is the chanda command line: every command of the chanda binary lives here so that other binaries (chanda-hugot, which registers the hugot embed provider) run the same CLI through cli.Run.
clock
Package clock provides the real and the test Clock implementations.
Package clock provides the real and the test Clock implementations.
config
Package config loads chanda.yaml.
Package config loads chanda.yaml.
conflicts
Package conflicts is conflict resolution between raw records (docs/decisions/0148-conflict-resolution-in-sleep.md), off by default.
Package conflicts is conflict resolution between raw records (docs/decisions/0148-conflict-resolution-in-sleep.md), off by default.
core
Package core holds the domain vocabulary shared by every Chanda package: trust zones, record types and id prefixes, statuses, time formatting, stable error codes and the interfaces behind external dependencies.
Package core holds the domain vocabulary shared by every Chanda package: trust zones, record types and id prefixes, statuses, time formatting, stable error codes and the interfaces behind external dependencies.
dedup
Package dedup is the near-duplicate guard (BASE.md write step 10, "Near-duplicate guard").
Package dedup is the near-duplicate guard (BASE.md write step 10, "Near-duplicate guard").
embed
Package embed holds the embedding side of Chanda (BASE.md "Go stack": Embeddings, Vector search; write step 7; the flush tool): the built-in deterministic HashEmbedder, the vector BLOB encoding, the exact in-memory vector index over the embeddings table, and the Indexer that drains embed_queue.
Package embed holds the embedding side of Chanda (BASE.md "Go stack": Embeddings, Vector search; write step 7; the flush tool): the built-in deterministic HashEmbedder, the vector BLOB encoding, the exact in-memory vector index over the embeddings table, and the Indexer that drains embed_queue.
env
Package env bundles the shared dependencies every component receives.
Package env bundles the shared dependencies every component receives.
eval
Package eval is Chanda's evaluation environment (BASE.md "Evaluation"): dataset format, baselines B0-B3, LLM-free retrieval metrics, the own-suite registry, the gate-set score and the reproducible report.
Package eval is Chanda's evaluation environment (BASE.md "Evaluation"): dataset format, baselines B0-B3, LLM-free retrieval metrics, the own-suite registry, the gate-set score and the reproducible report.
eval/coresys
Package coresys runs the real Chanda core (internal/app) as evaluation systems C1..C5 and implements the own suites that need a live core (deletion, injection, document update, deduplication, determinism, learning).
Package coresys runs the real Chanda core (internal/app) as evaluation systems C1..C5 and implements the own suites that need a live core (deletion, injection, document update, deduplication, determinism, learning).
facts
Package facts implements entities, the predicate catalog and temporal fact reconciliation (BASE.md write path steps 8 and 9, "Decision table for facts", "The two time axes", "Time queries"), plus the deterministic fact extractors that run on the synchronous write path.
Package facts implements entities, the predicate catalog and temporal fact reconciliation (BASE.md write path steps 8 and 9, "Decision table for facts", "The two time axes", "Time queries"), plus the deterministic fact extractors that run on the synchronous write path.
facts/norm
Package norm holds the deterministic text normalizations shared by fact reconciliation and the near-duplicate guard: entity aliases, predicate names, fact values, numbers and dates.
Package norm holds the deterministic text normalizations shared by fact reconciliation and the near-duplicate guard: entity aliases, predicate names, fact values, numbers and dates.
forget
Package forget implements cascade deletion with verification (BASE.md "Forgetting", differentiator "Verifiable forgetting").
Package forget implements cascade deletion with verification (BASE.md "Forgetting", differentiator "Verifiable forgetting").
ids
Package ids generates record ids "<prefix>_<ULID>" deterministically.
Package ids generates record ids "<prefix>_<ULID>" deterministically.
keys
Package keys owns the learned query keys (decision 0145): the learned_keys table, its FTS index (trigger-maintained), the key vectors (embeddings rows of record type "key", queued like every other record) and the per-namespace runtime switch.
Package keys owns the learned query keys (decision 0145): the learned_keys table, its FTS index (trigger-maintained), the key vectors (embeddings rows of record type "key", queued like every other record) and the per-namespace runtime switch.
llm
Package llm implements core.LLMProvider, the only door through which an LLM touches Chanda (BASE.md "Sleep", principles 2 and 3: never on the read or synchronous write path).
Package llm implements core.LLMProvider, the only door through which an LLM touches Chanda (BASE.md "Sleep", principles 2 and 3: never on the read or synchronous write path).
mcp
Package mcp exposes a chanda.API as an MCP server (go-sdk v1.8.0) over stdio and Streamable HTTP.
Package mcp exposes a chanda.API as an MCP server (go-sdk v1.8.0) over stdio and Streamable HTTP.
prov
Package prov owns the provenance graph (BASE.md "Provenance, forgetting and security"): writing edges, walking a derived record back to the events that produced it, deriving zones from those events, walking forward from events to everything derived from them, the integrity checker and promote.
Package prov owns the provenance graph (BASE.md "Provenance, forgetting and security"): writing edges, walking a derived record back to the events that produced it, deriving zones from those events, walking forward from events to everything derived from them, the integrity checker and promote.
prov/provtest
Package provtest seeds the tables prov and forget read, with direct SQL, for tests.
Package provtest seeds the tables prov and forget read, with direct SQL, for tests.
rank
Package rank implements "Ranking that learns from use" (BASE.md, principle 9, build phase 8): outcome and flag signals, per-record utility (stage 1), a small learned ranker (stage 2) in shadow mode, promotion by evaluation and reversibility.
Package rank implements "Ranking that learns from use" (BASE.md, principle 9, build phase 8): outcome and flag signals, per-record utility (stage 1), a small learned ranker (stage 2) in shadow mode, promotion by evaluation and reversibility.
read
Package read is the read path (BASE.md "Read path and pre-context"): keyword and vector search, rule filter, near-duplicate collapse, RRF fusion, optional rerank, utility adjustment, relevance cut, diversity and budget, assembly, the two modes (search and context) and retrieval logging.
Package read is the read path (BASE.md "Read path and pre-context"): keyword and vector search, rule filter, near-duplicate collapse, RRF fusion, optional rerank, utility adjustment, relevance cut, diversity and budget, assembly, the two modes (search and context) and retrieval logging.
sleep
Package sleep is offline consolidation (BASE.md "Sleep"): the only place an LLM touches memory.
Package sleep is offline consolidation (BASE.md "Sleep"): the only place an LLM touches memory.
store
Package store owns the SQLite file: opening, pragmas, migrations and transactions.
Package store owns the SQLite file: opening, pragmas, migrations and transactions.
window
Package window keeps the contiguous window of a text that best matches a set of terms within a cost (decision 0137, "best_window").
Package window keeps the contiguous window of a text that best matches a set of terms within a cost (decision 0137, "best_window").
write
Package write implements the synchronous write path (BASE.md "Write path"), steps 1 to 7 and 11: normalize, bind the origin, admit, check exact duplicates, write the raw event, compare document versions, enqueue for indexing, audit and respond.
Package write implements the synchronous write path (BASE.md "Write path"), steps 1 to 7 and 11: normalize, bind the origin, admit, check exact duplicates, write the raw event, compare document versions, enqueue for indexing, audit and respond.
write/normalize
Package normalize implements write step 1 (BASE.md "Write path"): Unicode NFC, standardized line breaks and collapsed whitespace, followed by a SHA-256 over the normalized text.
Package normalize implements write step 1 (BASE.md "Write path"): Unicode NFC, standardized line breaks and collapsed whitespace, followed by a SHA-256 over the normalized text.
pkg
chanda
Package chanda is the public Go API of Chanda and, at the same time, the wire contract of its MCP tools: every tool has an Input and an Output type here, and their JSON form (snake_case tags) is exactly what MCP clients send and receive inside the Envelope.
Package chanda is the public Go API of Chanda and, at the same time, the wire contract of its MCP tools: every tool has an Input and an Output type here, and their JSON form (snake_case tags) is exactly what MCP clients send and receive inside the Envelope.
chanda/embedreg
Package embedreg lets a separately built binary add an embed provider (for example the optional hugot module) without the main module importing it.
Package embedreg lets a separately built binary add an embed provider (for example the optional hugot module) without the main module importing it.
chanda/local
Package local is the importable Go entry point of Chanda: it opens the core in this process from a chanda.yaml and returns it as a chanda.API.
Package local is the importable Go entry point of Chanda: it opens the core in this process from a chanda.yaml and returns it as a chanda.API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL