TreeMem 🌲
Hierarchical, agent-writable memory for LLM agents exposed as a Model Context Protocol (MCP) server, stored as a plain folder of human-readable Markdown, with a live local web dashboard that visualizes every recall.
Table of Contents
- The Core Idea
- Why TreeMem? The Problem with Flat Memory & Naive RAG
- System Architecture
- The 8 System Invariants
- Quickstart in 3 Commands
- Live X-Ray Dashboard
- MCP Tool Reference & Harness Configuration
- Instruction-File Fallback (Zero-MCP Mode)
- Vault Specification & File Formats
- CLI Reference
- Benchmarks & Honest Evaluation
- Testing & Crash Recovery
- Limitations & Trade-offs
- Roadmap
1. The Core Idea
When an agent needs information, dumping every memory ever recorded into context wastes thousands of prompt tokens and drowns out the prompt's instructions.
TreeMem organizes memory as a hierarchical tree of topic nodes:
- Parent nodes contain concise summaries (40–120 tokens) and 1-line teasers for their children.
- Child nodes unpack greater topical detail.
- Leaf nodes store raw, granular facts referencing an append-only daily ledger.
When an agent queries TreeMem, it starts at the root summary (recall("/")). If the parent summary answers the query directly, the agent stops immediately ("parent-stop") having consumed fewer than 100 tokens. Only if the query demands specific detail does the agent step down one branch (recall("/topic") or expand).
The Library Analogy: A library catalog card is the root parent, the floor section is a child, and the shelf book is a leaf. You never pull all 50,000 books off the shelf just to look up a publishing date.
2. Why TreeMem? The Problem with Flat Memory & Naive RAG
| Approach | Token Scaling | Topical Drill-down | Developer Observability | Privacy Guarantees |
|---|---|---|---|---|
| Flat Scratchpad / Notes | $O(N)$ context explosion | ❌ All or nothing | ❌ None | ❌ Full context leak |
| Top-K Vector RAG | Unbounded chunk fragments | ❌ Loss of hierarchy | ❌ Black-box cosine distance | ⚠️ Chunk-level only |
| Chronological Trees (OptMem) | Balanced binary tree | ❌ No topical branches | ⚠️ Limited | ❌ No privacy masks |
| TreeMem 🌲 | $O(\log N)$ descent | ✅ Agent-guided descent | ✅ Live Cytoscape X-Ray | ✅ Descent masks & leak guards |
Key Differentiators:
- Agent-Guided Descent (Parent-Stop): Recalling the root gives a parent summary and child teasers. The agent decides if the parent summary is sufficient or if it needs to descend into child branches.
- Transparent, Zero-Lock-In Storage: The memory vault is a standard directory of human-readable Markdown files with YAML frontmatter, 100% compatible with Obsidian and standard CLI tools (
cat,grep). - Append-Only Ground Truth:
log/YYYY-MM-DD.mdstores every fact permanently. The hierarchical tree is a derived, rebuildable cache. - Agent-Written Summaries (No Server LLM Hosting): TreeMem never runs or hosts an LLM model, requiring no OpenAI or Anthropic API keys. The server hands out compression prompts; the agent writes the summary; the server rigorously validates token caps and child lists before committing atomically.
- Staleness Tracking: When a leaf is written, all ancestor directories are marked
dirty: true. Recalls flag stale summaries, prompting bottom-up compression. - Built-in Privacy Bounds: Sensitive subtopics (
sensitivity: private) are masked in ancestor teasers as"contains private details, expand to view"and are protected against leakages by automated substring and token-overlap validator checks.
3. System Architecture
Agent Harness (Antigravity / Devin / Claude Desktop / Cursor)
│ MCP (JSON-RPC stdio transport)
▼
┌────────────────── TreeMem Server (Single Process) ──────────────────┐
│ │
│ mcp_layer.py ────► remember, place, recall, expand, compress, │
│ commit_summary, search, split, rebuild, status │
│ │ │
│ tree_manager.py ─► Path resolution, dirty propagation, │
│ │ branching caps, privacy leakage validators │
│ │ │
│ ├── store.py (Atomic tmp-and-rename writes, locks) │
│ ├── log_writer.py (Append-only daily ledger YYYY-MM-DD) │
│ ├── index.py (BM25 lexical index over logs & leaves) │
│ ├── health.py (Validator asserting all 8 invariants) │
│ └── event_bus.py ──► SSE stream broadcast │
│ │ │
└───────────────────────────────────┼─────────────────────────────────┘
│ HTTP + SSE (127.0.0.1:8765)
▼
┌───────────────────── X-Ray Web Dashboard ───────────────────────────┐
│ Cytoscape.js Canvas | Live Recall Path | Inspector | Replay Engine │
└─────────────────────────────────────────────────────────────────────┘
│
▼
┌────────────────── Local Vault Filesystem (memory/) ─────────────────┐
│ summary.md (Root catalog summary & child teasers) │
│ ├── identity/summary.md (Subtopic summary & facts) │
│ ├── projects/summary.md (Subtopic summary & facts) │
│ └── log/YYYY-MM-DD.md (Append-only permanent ground truth) │
└─────────────────────────────────────────────────────────────────────┘
4. The 8 System Invariants
TreeMem is built around 8 strict structural invariants verified by treemem check and enforced continuously across all test suites:
- Node Completeness: Every directory under the vault root (except
log/and hidden folders) contains a validsummary.mdwith YAML frontmatter. - Log Ground Truth: Every fact in every node references an existing, valid log entry ID (
YYYY-MM-DD#line). - Child Directory Parity: The
## Childrenlist in a node'ssummary.mdstrictly matches the actual child subdirectories on disk (no missing, no invented children). - Rebuildability: Wiping the tree and running
treemem rebuildreconstructs all nodes and facts faithfully from the append-only log files. - No Private Leakage: An ancestor's summary text never leaks keywords, facts, or tokens from any descendant marked
sensitivity: private. - Dirty Propagation: Adding a fact to a node immediately marks that node and every ancestor path up to the root as
dirty: true. - Atomic Operations: No write leaves lingering
.tmpfiles on disk, even if aborted or interrupted. - Append-Only Ledger: Existing lines in
log/YYYY-MM-DD.mdare never edited or truncated.
5. Quickstart in 3 Commands
Step 1: Install TreeMem
Requires Python 3.10+. Install the published package:
pip install treemem-agent
# or with uv
uv pip install treemem-agent
Optional scoring/embedding upgrades are installed directly (there are no package extras):
pip install scikit-learn # hybrid TF-IDF + lexical scoring
pip install sentence-transformers # local dense embeddings
For development from source:
git clone https://github.com/Akshat-Rai0/treeMem.git
cd treeMem
uv venv && uv pip install -e .
Step 2: Initialize a Vault
Create a clean memory directory structure:
treemem init ./my_memory
This creates ./my_memory/summary.md and ./my_memory/log/.
Step 3: Launch the Live X-Ray Dashboard
Run the dashboard server locally on port 8765:
treemem serve ./my_memory --port 8765
Open the authenticated URL printed in your terminal (e.g. http://127.0.0.1:8765/?t=<token>).
Instant Demo: To test the dashboard immediately without an agent or memory files:
treemem serve --demoThis loads an interactive sandbox with 28 topic nodes and plays an animated live recall sequence.
6. Live X-Ray Dashboard
TreeMem includes a local web dashboard with two write actions (summary edit with conflict detection, per-node compress) served directly by the server:
- Graph Canvas: Interactive Cytoscape.js canvas supporting both top-down Hierarchical Tree and Radial layouts.
- Visual Encoding:
- Teal Glow: Traversed nodes and edges in the current recall path.
- Dashed Border: Dirty nodes whose child facts have updated.
- Lock Icon: Private nodes protected from ancestor leaks.
- Node Size: Dynamically scaled based on token count (clamped 40–150 tokens).
- Inspector Panel: Click any node to view its frontmatter metadata, summary, child teasers, and recent log events.
- Token Comparison Meter: Shows exact tokens consumed by the current descent vs. a flat dump baseline of all leaf facts.
- Time-Travel Replay Bar: Step through multi-hop recalls forward and backward, with adjustable playback speeds (0.5x, 1x, 2x).
- Health Indicator: Real-time badge asserting invariant compliance (Green = Clean, Amber = Dirty nodes pending compression, Red = Invariant violation).
7. MCP Tool Reference & Harness Configuration
Harness Setup (stdio Transport)
Add TreeMem to your agent harness configuration (e.g. Claude Desktop, Antigravity, Cursor, or Devin):
Claude Desktop (claude_desktop_config.json) / Antigravity (mcp_config.json):
{
"mcpServers": {
"treemem": {
"command": "treemem",
"args": ["serve", "/absolute/path/to/my_memory", "--mcp"]
}
}
}
Cursor (.cursor/mcp.json) / VS Code (.vscode/mcp.json or user settings):
{
"servers": {
"treemem": {
"command": "treemem",
"args": ["serve", "/absolute/path/to/my_memory", "--mcp"]
}
}
}
With
pipx/uvxinstalled,"command": "uvx"and"args": ["--from", "treemem-agent", "treemem", "serve", "/absolute/path/to/my_memory", "--mcp"]runs TreeMem without a local install.
The 12 MCP Tools
| Tool | Parameters | Description |
|---|---|---|
remember |
fact: str, hint?: str, sensitivity?: str, supersedes?: str, retracts?: str, valid_from?: str, valid_to?: str |
Appends fact to today's log, returns entry ID and candidate topic paths. sensitivity can be "normal" (default) or "private". supersedes/retracts link this fact to an older entry_id (mutually exclusive); valid_from/valid_to set an ISO-8601 validity interval for at= queries. |
retract |
entry_id: str |
Tombstones a memory (delete/invalidate). The fact stays in the log but is hidden from reads unless include_history=true. |
place |
entry_id: str, path: str, sensitivity?: str, volatile?: bool |
Places fact into a leaf node and marks all ancestors dirty. volatile marks facts that can be transcluded without dirtying embedding parents. |
recall |
path: str = "/", query?: str, follow?: bool, max_depth?: int, reveal?: bool, include_history?: bool, at?: str |
Reads node summary and 1-line child teasers (never child bodies). With query it adds the descent-gate verdict; with follow=true the server follows the gate read-only (never into private nodes) and returns where it stopped, in one call. reveal=true requests private details (honored only when server operator grants it). include_history=true shows superseded/retracted facts; at=<ISO-8601> returns facts valid at that time. |
expand |
path: str, reveal: bool = false, include_history?: bool, at?: str |
Drills down into child summaries or raw leaf facts. reveal=true is only honored when the server operator set TREEMEM_ALLOW_REVEAL=1; otherwise private content stays hidden and the result carries reveal_denied. include_history/at control superseded-fact and valid-time filtering as in recall. |
compress |
path: str, reveal: bool = false, include_history?: bool, at?: str |
Returns compression prompt and child text to clean a dirty node (Option A). reveal=true requests private details (honored only when server operator grants it). |
auto_compress |
path?: str |
(Optional) Compresses dirty nodes bottom-up using an external LLM (Groq); reads API keys from .env. |
commit_summary |
path: str, text: str |
Validates token cap, child list, and privacy before committing atomically. |
search |
query: str, limit: int = 10, reveal: bool = False, include_history?: bool, at?: str |
BM25 lexical search over log entries and leaves (fallback mechanism). Hits under private nodes are withheld unless reveal=true and the operator granted reveal (TREEMEM_ALLOW_REVEAL=1). Superseded/retracted hits are hidden unless include_history=true; at=<ISO-8601> filters by fact validity interval. |
split |
path: str, groups: dict |
Splits an overflowing node into subtopics to preserve branching caps. |
rebuild |
path?: str |
Reconstructs tree structure from append-only log files. Uses the placement journal as primary source, falling back to hints. |
status |
None | Session-start health report with total nodes, facts, and dirty count. |
Reveal policy. The model must not be able to grant itself access to private data, so reveal=true in a tool call is a request, not a switch. The MCP server honors it only when a human starts it with TREEMEM_ALLOW_REVEAL=1. Without that, expand, compress, and search return reveal_denied: true plus a note telling the agent to ask the user. Direct Python callers (tests, CLI, dashboard with its own token) use TreeManager directly and are not affected.
Privacy rules. A node marked sensitivity: private hides its content from all read operations unless reveal is granted. Privacy is inherited: a normal node under a private parent is treated as private. The index withholds unplaced private entries from search. The AutoCompressor never sends private content to external LLMs unless reveal is granted. The placement journal records sensitivity so rebuild preserves it. commit_summary never trusts agent-written teasers for private children: the server overwrites them with contains private details, expand to view (the result lists teasers_overwritten), and teasers of normal children are scanned for exact private facts and private numbers (3+ digits) before the write is accepted.
Note on Summarization Modes:
- Default Mode (Option A): TreeMem hosts zero models and requires zero external API keys. The client agent generates the summary text and commits it via
commit_summary.- Pluggable Auto-Compressor (
auto_compress/ Option B): An optional background engine that uses an external LLM (Groq) to clean dirty nodes bottom-up. RequiresGROQ_API_KEY_1orGROQ_API_KEYset in.env(which is git-ignored).
Path Names
TreeMem path segments (node names) follow these rules:
- Length: 1 to 100 characters after NFC Unicode normalization
- First character: Must be a Unicode letter or digit (
str.isalnum()) - Allowed characters: Letters, digits, combining marks (Unicode category starting with "M"), or: underscore (
_), hyphen (-), dot (.), plus (+), hash (#), space - No leading or trailing spaces: Spaces are allowed only in the middle of the name
- No two consecutive dots:
..is forbidden within a segment - Reserved names: The segment
logis reserved for the log directory - Hidden files: Segments starting with
.are rejected - Special characters:
/,\, NUL, and control characters are forbidden - Maximum depth: Paths can have at most 8 segments deep
Examples of valid names: node.js, C++, q3_résumé, मशीन लर्निंग, a.b+c#d
The entire path is normalized to NFC (Unicode composed form) so that résumé typed in different ways maps to the same directory.
Case collisions are rejected. A name that differs from an existing sibling only by letter case (docs vs Docs) is refused by place and split, because case-insensitive filesystems (macOS default, Windows) would map both to one directory while the tree treated them as two nodes. The error names the existing spelling to use.
8. Instruction-File Fallback (Zero-MCP Mode)
If your harness does not support MCP or you prefer standard file execution, provide your agent with the following system prompt block (found in examples/AGENTS_md_block.md):
# TreeMem Memory Protocol
You have access to a persistent hierarchical memory vault located at `memory/`.
## 1. Reading Memory (Parent-First Descent)
1. Read the root catalog first:
cat memory/summary.md
2. Check if the root summary or child teasers under `## Children` answer the question.
If yes, STOP immediately (Parent-Stop).
3. If more detail is required, inspect only the relevant child topic:
cat memory/<topic>/summary.md
4. Only read leaf notes if raw facts are required.
## 2. Storing New Facts
1. Append to today's daily log file (`memory/log/YYYY-MM-DD.md`):
echo "- <next_id> | $(date -u +%H:%M:%SZ) | session=agent | fact: <text> | hint: <topic>" >> memory/log/$(date -u +%Y-%m-%d).md
2. Place the fact in the appropriate leaf node:
echo "- <text> (log: $(date -u +%Y-%m-%d)#<next_id>)" >> memory/<topic>/summary.md
3. Set `dirty: true` in the YAML frontmatter of the leaf node and all ancestor directories up to the root.
9. Vault Specification & File Formats
1. Node Specification (<path>/summary.md)
---
name: projects
aliases: [software, coding, portfolio]
dirty: false
updated: 2026-10-23T12:00:00Z
tokens: 82
sensitivity: normal
children_cap: 10
---
Portfolio projects including TreeMem, an MCP hierarchical memory server.
## Children
- [[treemem]] - Hierarchical agent-writable memory system
- [[sidecar]] - Molecular structure viewer plugin
## Facts
- Completed Phase 1 core storage and invariant tests (log: 2026-10-23#001)
2. Daily Log Specification (log/YYYY-MM-DD.md)
- 001 | 10:12:03Z | session=default | fact: Building TreeMem MCP server | hint: projects/treemem
- 002 | 10:15:22Z | session=default | fact: Favorite language is Python | hint: skills/python
10. CLI Reference
# Initialize a new empty vault
treemem init [path]
# Assert all 8 system invariants (exits 0 if clean, 1 if violated)
treemem check [path]
# Reconstruct all nodes and facts from the append-only daily logs
# Uses the placement journal (.placements.jsonl) as primary source,
# falling back to hints when no journal record exists.
treemem rebuild [path]
# Automatically compress dirty nodes bottom-up using server-side LLM (Option B)
treemem compress [path] [--node path]
# Start the local web dashboard (live views plus two write actions: summary edit with
# conflict detection, and per-node compress). With --mcp it runs inside the MCP process.
treemem serve [path] --port 8765
# Start dashboard with background auto-compressor daemon active
treemem serve [path] --auto-compress
# Launch as a stdio MCP server for agent harnesses (dashboard runs in-process by default)
# The dashboard URL is written to <vault>/.dashboard_url with mode 0o600
treemem serve [path] --mcp
# Launch as MCP server without the dashboard
treemem serve [path] --mcp --no-dashboard
# Launch interactive demo sandbox with pre-built sample memory
treemem serve --demo
11. Benchmarks & Honest Evaluation
Real LLM Agent Benchmark (qwen/qwen3.8-27b via Groq)
Automated evaluation comparing single-prompt flat memory dump against autonomous TreeMem MCP tool descent ($n=12$ queries across identity, career, education, preferences, private finance, and out-of-domain negative controls):
| Metric | Flat Memory Dump | TreeMem Autonomous Descent | Impact |
|---|---|---|---|
| Answer Accuracy | 100.0% (11/11) | 100.0% (11/11) | Parity on the scored questions |
| Memory Payload Tokens | 7,812 tokens | 1,371 tokens | 82.45% payload token reduction |
| Total API Wire Tokens | 9,858 tokens | 66,758 tokens | Multi-turn tool calling re-sends schema/prompts per hop |
| Parent-Stop Rate | N/A | 8.3% (1/12) | Evaluated at root depth 0 when summary was sufficient |
| Mean / Max Latency | 0.81s / 2.79s | 19.36s / 30.99s | Multi-hop sequential tool execution latency |
| Private Data Leaked (1 private question) | 1 | 0 | Flat has no access control; TreeMem withholds private nodes unless the operator grants reveal |
Raw data committed in bench/results/llm_eval_results.json.
The Multi-Turn Overhead Trade-Off: On small vaults (<30 facts), flat context dumps are faster and cheaper in total API wire tokens (9,858 vs 66,758 tokens) because multi-turn tool calling retransmits the system prompt and tool definitions on every hop. However, TreeMem achieves an 82.45% reduction in memory payload, proving that hierarchical descent prevents memory context saturation as vaults scale to hundreds and thousands of entries.
Synthetic Vault Scaling Study
Measuring memory payload token cost between flat note dumps vs. TreeMem hierarchical descent:
| Memory Scale | Flat Dump Cost | TreeMem Average Cost | Token Savings |
|---|---|---|---|
| 100 memories | 2,041 tokens | 110 tokens | 94.61% |
| 1,000 memories | 20,941 tokens | 223 tokens | 98.94% |
| 10,000 memories | 227,941 tokens | 1,465 tokens | 99.36% |
Raw data committed in bench/results/flat_vs_tree_tokens.json.
Repeated runs: flat vs manual descent vs guided descent
3 runs x 12 questions, qwen/qwen3.8-27b, mean ± std. Accuracy is over the non-private questions; latency excludes pacing sleeps.
| Arm | Accuracy % | Private leaks | Wire tokens | Mean hops | Single-call % | Mean latency (s) | Failed (request too large) |
|---|---|---|---|---|---|---|---|
| Flat dump | 100.0 ± 0.0 | 1.0 ± 0.0 | 9,858 ± 0 | 0.00 ± 0.00 | 0.0 ± 0.0 | 0.76 ± 0.15 | n/a |
| TreeMem, manual descent | 100.0 ± 0.0 | 0.0 ± 0.0 | 66,758 ± 0 | 3.83 ± 0.00 | 8.3 ± 0.0 | 18.98 ± 0.87 | n/a |
TreeMem, guided descent (follow=true) |
100.0 ± 0.0 | 0.0 ± 0.0 | 48,356 ± 0 | 2.67 ± 0.00 | 33.3 ± 0.0 | 14.39 ± 1.12 | n/a |
Std is 0 for accuracy, tokens and hops: temperature is 0 and the vault and questions are fixed, so repeated runs reproduce the same output. This shows reproducibility, not robustness.
Other real-LLM runs
Each table below is one results folder (bench/results_*). The folder name, model, number of runs and question mix are shown in its sub-heading.
results_large_vault (model qwen/qwen3.8-27b, 1 run(s), 15 questions)
questions: 15 lookup
1 runs x 15 questions, qwen/qwen3.8-27b, mean ± std. Accuracy is over the non-private questions; latency excludes pacing sleeps.
| Arm | Accuracy % | Private leaks | Wire tokens | Mean hops | Single-call % | Mean latency (s) | Failed (request too large) |
|---|---|---|---|---|---|---|---|
TreeMem, guided descent (follow=true) |
100.0 ± 0.0 | 0.0 ± 0.0 | 34,807 ± 0 | 1.07 ± 0.00 | 93.3 ± 0.0 | 6.30 ± 0.00 | n/a |
Std is 0 for accuracy, tokens and hops: temperature is 0 and the vault and questions are fixed, so repeated runs reproduce the same output. This shows reproducibility, not robustness.
Descent gate, offline check (no API calls)
python bench/gate_offline_eval.py --set all --compare asks, for each question: does the text returned by ONE recall(follow=true) call contain the answer? A "stop" where it does not is a premature stop. The held-out questions were written before the gate was changed and use different wording from the dev questions.
| Question set | Gate | Answerable from first call | Premature stops | Mean steps | Private leaks |
|---|---|---|---|---|---|
| 12 dev questions | legacy | 5/10 | q02_profession, q05_career_overview, q06_college_name, q09_project (4) | 0.417 | 0 |
| 12 dev questions | current | 9/10 | none (0) | 0.833 | 0 |
| 26 held-out questions | legacy | 10/19 | h06_intern, h08_degree, h10_classes (3) | 0.346 | 0 |
| 26 held-out questions | current | 12/19 | h06_intern (1) | 0.462 | 0 |
Measured with scikit-learn installed (hybrid TF-IDF + lexical scoring). Numbers differ slightly between the two modes.
The current gate counts a stop as sufficient only when the node summary covers the question's own words (a literal match counts more than a synonym), prefers a child that contains words the parent lacks, and descends when a child scores close to the parent, because a wrong stop is costly while an extra server-side step is nearly free. One parameter (descend_ratio) was chosen after seeing both sets, so the held-out set is no longer clean; the choice sits on a plateau (0.2 to 0.4 give the same results). Remaining misses are mostly vocabulary mismatches (for example "employs" against "Work history") and one routing error (h06: "intern before his current job" went to current_job). Those need better synonyms or embeddings, which I did not add to avoid fitting the sample vault.
Large-vault offline benchmark (no API calls)
python bench/large_vault_offline.py builds a deterministic 309-fact vault (bench/make_midsize_vault.py, invented unique values, fixed seed) and compares what each strategy would put in front of the model for 31 lookup questions, 8 overview questions (answers spread over several facts), 2 private and 6 unanswerable questions.
| Vault | Facts | Flat log (tokens) | BM25 top-5: lookups / overviews complete | Tree, one guided call: lookups / overviews complete | Tree premature stops | Est. wire tokens: flat / BM25 / tree |
|---|---|---|---|---|---|---|
| sample vault | 20 | 651 | 20/29 / 0/0 | 21/29 / 0/0 | h06_intern | 814 / 296 / 2,531 |
| mid-size vault, minimal teasers | 309 | 11,624 | 31/31 / 3/8 | 28/31 / 8/8 | m14_book, m21_tool, m23_tool | 11,787 / 396 / 2,249 |
| mid-size vault, rich teasers | 309 | 11,624 | 31/31 / 3/8 | 31/31 / 8/8 | none | 11,787 / 396 / 2,058 |
Gate measured with scikit-learn installed, seed 7. Retrieval only: no language model answered anything. "Answerable" means the returned text contains the expected answer; "overview complete" means it contains every item of a multi-fact answer. Wire tokens are a model: a per-call overhead of 1,862 tokens for tool calls and 163 for a plain prompt, taken from the committed real-LLM runs, plus the returned tokens, plus one extra call whenever the first call lacks the answer. BM25 is modelled as one-shot retrieval before a single prompt (no tool schemas). Tokens counted with cl100k_base.
What this does and does not show:
- Against a flat dump the tree is far smaller, and the flat log at this size no longer fits free-tier per-minute limits.
- For single-entity lookups a plain BM25 top-5 is as good as the tree and returns about the same number of tokens, because the question names the entity (a city, a genre) that appears in the fact. The tree's value is not beating keyword search on these.
- For overview questions the tree completes what top-5 keyword retrieval cannot, because following one node returns all its facts.
- Summary quality decides routing. With minimal parent teasers the gate misroutes a few questions; when each teaser lists the key terms of its children (what a careful agent writes), premature stops disappear. Instruct your agent to do this.
- The questions are generated from templates by the same script that makes the facts, so they share more vocabulary with the facts than real questions would. This is retrieval, not answer quality, and not a real-LLM result.
Known limitations (read before quoting numbers)
- Real-LLM evidence is limited. The only real-LLM result on the 309-fact vault is a 15-question, single-arm (
tree_follow), single-run evaluation covering only single-entity lookups. A full three-arm run (flat, tree, tree_follow, plus BM25) on all 47 questions (including overview, private, and unanswerable) is still needed before drawing broader conclusions. - Repeated runs are not independent samples. The model runs at temperature 0 on a fixed vault with fixed questions, so the committed 3-run result reproduced the same tokens, hops and answers every time (std = 0). That shows the harness is reproducible, not that the numbers are robust. Real variance needs paraphrased questions, a larger question set, or sampling at temperature above 0.
- Small sample. 12 questions (11 scored) on an 8-fact vault. Treat 100% accuracy as "no failures observed on this set", not as a measured accuracy.
- A flat dump still wins on this vault. Every tool call re-sends the system prompt and tool schemas (about 1,100 prompt tokens per call), so even a single guided call costs more than the whole flat dump. Guided descent cut total tokens and hops compared with manual descent in the committed runs, but not below the flat baseline. The memory-payload reduction (the tree returns far less memory text) does not become a total-token win at this size.
- Guided descent does not always help. In the committed runs it answered some questions in one call, but on others (for example the negative control and the private question) it cost as much as or more than manual descent.
- Premature stops are the real accuracy risk. The gate used to decide the root summary was sufficient when it only shared words with the question; an earlier run then answered "personal memory vault" for a question whose answer was a named project. The gate has since been tightened and is covered by the offline evaluation table above. Continue measuring it on larger and independently generated question sets because a wrong stop looks like a confident answer.
- Results are model-dependent. Observed in a gpt-oss-120b run whose result files are not included in this repository, the same tree answered a question in one call with one model and needed several calls with another. Do not generalize from one model.
- The grader matters. An earlier grader marked correct flat answers wrong because of a no-break space and a curly apostrophe. Answers are now normalized before matching, and
python bench/eval/rebuild_aggregate.py --regradere-grades saved runs with the current grader without any API calls. - The descent gate is a lexical + TF-IDF heuristic over summaries. If the question's words are not in the summaries it falls back to search.
- Break-even against flat is not measured with a real model. In the offline large-vault benchmark the 309-fact flat log is 11,624 tokens (about 12k), which already exceeds free-tier request limits, while one guided call returns about 200 tokens; the real-LLM wire cost is dominated by a fixed per-call tool overhead of roughly 1,400 to 1,900 tokens (see the measured overheads in bench/results_offline/large_vault_offline.json). A real-model comparison on the large vault needs the retrieval-baseline arm and a full 47-question run.
Plumbing Smoke Test ($n=5$, Scripted Descent)
- Token Reduction: 9.2% on a small 8-fact vault.
- Parent-Stop Rate: 20.0% (depth 0).
- Descent Latency: p50 = 2.29 ms, p95 = 2.87 ms.
- Raw data committed in
bench/results/smoke_test_results.json.
12. Testing & Crash Recovery
The test suite covers unit behavior, concurrent writers, crash simulation, security, and randomized property sequences:
PYTHONPATH=src python3 -m pytest tests/ -q
........................................................................ [100%]
============================== 378 passed in 30.01s ==============================
- Crash Mid-Write Simulation: Tests deliberately simulate process crashes (
SIGKILL/ interrupted writes) during atomic file operations to confirm that corruptions and stray.tmpfiles never persist. - Property-Based Testing: Randomized multi-step operations (
remember$\to$place$\to$recall$\to$search) verify that all 8 invariants hold under arbitrary mutation sequences.
13. Limitations & Known Issues
- Small Vaults Favor Flat Dump: On vaults with fewer than ~30 facts, a single flat context dump is faster and consumes fewer total API wire tokens (9,858 vs 66,758 tokens) because multi-turn tool calling re-transmits tool definitions and system prompts on every hop.
- The Agent Over-Descends: Without single-call guided descent (
follow=True), autonomous agents frequently take 4–6 tool calls when a parent summary was already sufficient to answer the question. - Negative-Control Exhaustion: When queried about facts absent from the vault (e.g., favorite sports car brand), agents tend to exhaust their multi-hop turn budget searching alternative branches before concluding the information is unknown.
- Single-Agent Local Focus: Designed as a local daemon for single-agent sessions; multi-user distributed synchronization is out of scope.
- Dense Vector Embeddings are Optional and Opt-In: Embeddings are an optional library feature (
src/treemem/embeddings.py), off by default (embedding_provider=None). They are not wired into the descent gate or recall routing, and never process private text (nodes marked private, unplaced facts with unknown sensitivity, or facts whose hint points to a private node are never sent). Inherent limit: when a remote embedding provider is explicitly configured, the incoming search query text passed tosearch(query)is sent to the remote provider to compute query similarity. Stored private facts and unplaced facts are never sent, but the raw search query string itself is transmitted to the remote provider. The built-in deterministic provider uses token/bigram hashing for offline plumbing tests and does not demonstrate semantic benefit. No embedding quality was measured. - Leak validation is lexical.
commit_summaryblocks whole-word and number overlap with private descendants (and refuses summaries on private nodes that quote their private children). A careful paraphrase of a private fact can still pass; the privacy boundary that matters is the read-side gating (revealoperator grant), not the validator.
14. Roadmap
- Phase 0: Harness feasibility notes, prior art analysis, and sample vault.
- Phase 1: Atomic markdown store, daily log writer, branching enforcement, and 8 invariants.
- Phase 2: MCP server with 11 tools, BM25 indexing, and Option A agent summarization.
- Phase 3: Event bus, SSE streaming, and Cytoscape.js X-Ray dashboard.
- Phase 5: Concurrency locking, crash recovery tests, and security hardening.
- Phase 4: Automated LongMemEval benchmark harness with real LLM inference.
- v1.5: Transclusion for volatile scalar facts (
![[node#line]]markdown embeds). - v2: Dense vector embeddings, real LLM large vault evaluation, and dashboard conflict handling.
License
Distributed under the MIT License.
Metadata
Release files for treemem-agent 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| treemem_agent-0.1.2.tar.gz | 366.7 kB | With provenance | Details for treemem_agent-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| treemem_agent-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for treemem_agent-0.1.2-py3-none-any.whl |
Total release size: 667.8 kB
Release files / treemem_agent-0.1.2.tar.gz
| Download URL | treemem_agent-0.1.2.tar.gz |
|---|---|
| Size | 366.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b946afbeeea45460d3cfb904a2bfa2558c34801f621bc18a4b84a7c687c3db8d
|
|
BLAKE2b-256 checksum How to use checksums |
3e82caf433f08cb8db12ea493f2b183e0c39d14e0ccfddecafee196a327e1ae3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / treemem_agent-0.1.2-py3-none-any.whl
| Download URL | treemem_agent-0.1.2-py3-none-any.whl |
|---|---|
| Size | 301.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
81a90c70c888bb5c13663c5ebaf1953c22daacb07585b80ee162d8ffe2cd6fe4
|
|
BLAKE2b-256 checksum How to use checksums |
e114acfd292b7a9f49ac8e6a1f78cc254cea5c3dc1246ea469b647c0b5456891
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for treemem-agent 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for treemem_agent-0.1.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.