The surfacing gate in front of memtomem

memtomem-stm

An MCP proxy that compresses tool responses and injects memtomem memories into them, with its own ledger of what it showed and the agent rejected.

LicenceApache-2.0 in LICENSE and pyproject.toml; contributions require a CLA letting DAPADA Inc. relicense them on any terms
Size89,441 lines of Python in 131 files under src/memtomem_stm, 12,981 of them in the 18 files of the surfacing package; 222,366 lines in 313 Python test files
Activity1,263 commits dated 10 April to 4 December 2026, 1,018 under the memtomem account and the rest from thirteen other contributors and bots; the GitHub repository was created on 9 April; version 0.8.0, labelled beta
Tests9,520 pytest functions in 313 files; CI runs them on Ubuntu and Windows across Python 3.12 to 3.14 with a 90% branch-coverage floor on one lane; none run here

Carries 1 of 7 rubric mechanisms. Most systems here carry none or one (41%), and a dash means the mechanism was not found at this commit — not that the system needed it. Each mark is one LLM reviewer's reading of the code at this commit rather than a run of it — known limits.

  • Tombstone
  • Trust state
  • Bi-temporal
  • Scope enforced
  • Mutation audit
  • Human review
  • Negative evals

1. Executive Summary

memtomem-stm is an MCP proxy that sits between a coding agent and its upstream MCP servers. It compresses and caches their responses and, when a memtomem core is configured, searches it over MCP and appends relevant memories to the tool result. It has no Python dependency on memtomem, stores no memory content, and the bundled server writes nothing durable into core except an access-count boost and, if enabled, a pending candidate.

Notable: STM keeps its own durable ledger about core's memories. A memory it surfaced is held back from later surfacings for seven days, across restarts. A memory the agent rated not_relevant or already_known in three distinct surfacing events is filtered out of STM's surfacing while core's ranking is left untouched. An opt-in holdout withholds a random share of injections so an offline resolver can measure whether surfaced memories are used.

Weak: by default the demotion runs only on proxied calls and the project scope only on hook calls, so no surfacing path has both. The ratings come from the agent that received the memories. Scope enforcement belongs to core, and a repository STM cannot identify is searched unscoped.

One mark: negative_eval (section 9).

Licence. The contributor agreement lets the maintainer relicense every contribution on any terms: CLA.md §4 grants DAPADA the right to distribute the Work under source-available or proprietary licences or "any other license terms that DAPADA may elect", and .github/workflows/cla.yml gates pull requests on a signature. The code itself is Apache-2.0 in LICENSE ("Copyright 2025-2026 DAPADA Inc. and memtomem contributors", LICENSE:179) and in pyproject.toml. SECURITY.md asks for vulnerabilities to go through a private GitHub advisory and forbids public issues for them.

2. Mental Model

STM owns no belief. A memory is whatever memtomem core returns for a query: a chunk id, its content, a score and a namespace. STM decides whether to search, what to search for, which of the returned chunks to show, and how to frame them. Its own documentation draws the line: core owns storage, indexing, namespaces, retrieval and review; STM owns proxying, compression, caching, surfacing gates and injection (docs/surfacing.md:11-16).

What STM remembers is a surfacing ledger in stm_feedback.db. A surfacing event records which memory ids a call delivered and with what scores. A seen row records the last time a memory id was delivered. A rating is the agent's verdict on one event or one memory in it: helpful, partially_helpful, not_relevant or already_known (src/memtomem_stm/surfacing/feedback_store.py:157-280, :50-57).

Two derived states follow from the ledger. A memory is held back while its seen row is younger than dedup_ttl_seconds, seven days by default (src/memtomem_stm/surfacing/config.py:219). It is demoted while negative ratings reach it from at least three distinct surfacing events (config.py:184-190). Neither state is written anywhere; both are recomputed from rows, and both lapse when the rows age out.

Diagram — STM searches core, then filters what core returned through its own ledger; the agent's ratings feed the ledger back
Diagram source
%% caption: STM searches core, then filters what core returned through its own ledger; the agent's ratings feed the ledger back
flowchart TD
    subgraph CALLS ["Two entry paths"]
        direction TB
        PX["Proxied MCP call<br/>no cwd, unscoped"] ~~~ HK["Hook call<br/>cwd, no rating prompt"]
    end
    CALLS --> GATE{"size, rate, cooldown,<br/>write-tool gate"}
    GATE -- "pass" --> SC["hook only:<br/>repo namespaces<br/>from git worktrees"]
    SC --> CORE["memtomem core<br/>mem_search or<br/>context_compose"]
    CORE --> FLOOR{"score >= floor<br/>tuned per tool"}
    FLOOR --> EXCL{"namespace in<br/>deny-list?"}
    EXCL -- "no" --> DEM{"proxy only:<br/>3 negative events<br/>for this id?"}
    DEM -- "no" --> SEEN{"surfaced in the<br/>last 7 days?"}
    SEEN -- "no" --> ENV["untrusted envelope<br/>plus rating prompt"]
    ENV --> ARM{"holdout draw"}
    ARM -- "shown" --> AGENT["agent context"]
    ARM -- "withheld" --> LEDGER
    ENV --> LEDGER[("stm_feedback.db<br/>events, seen ids")]
    AGENT --> RATE["stm_surfacing_feedback"]
    RATE --> LEDGER
    RATE -- "helpful" --> BOOST["core increment_access"]
    LEDGER -.-> DEM
    LEDGER -.-> SEEN
    LEDGER -.-> FLOOR

3. Architecture

Area Role
src/memtomem_stm/server.py The MCP server: proxy tool registration, the STM tools, and lifespan wiring of every store
src/memtomem_stm/proxy/ Upstream management, the clean, compress and cache pipeline, the response cache, metrics, progressive reads, and the library-only indexing path
src/memtomem_stm/surfacing/engine.py SurfacingEngine: gating, the core call, filtering, rendering, recording, feedback handling
src/memtomem_stm/surfacing/feedback_store.py The SQLite ledger and its retention sweeps
src/memtomem_stm/surfacing/feedback.py FeedbackTracker and AutoTuner
src/memtomem_stm/surfacing/mcp_client.py The MCP client to core: mem_search, mem_do actions, capability negotiation
src/memtomem_stm/surfacing/project_scope.py Working directory to namespace include-list
src/memtomem_stm/surfacing/formatter.py The <surfaced-memories> envelope and the rating prompt
src/memtomem_stm/surfacing/trial.py Pure outcome resolution for the holdout trial
src/memtomem_stm/cli/hook_cmd.py, src/memtomem_stm/daemon/ The PostToolUse hook bridge and the shared loopback daemon

Deployment and ergonomics

mms is a Python 3.12+ package run as the MCP server a client registers; each upstream MCP server is added with mms add and advertised as <prefix>__<tool> (README.md). Surfacing needs a memtomem core reachable over stdio, SSE or HTTP, by default the memtomem-server command (src/memtomem_stm/surfacing/config.py:86). Without one, proxying, compression and caching keep working and surfacing is off. The hook path auto-spawns a daemon bound to loopback and authenticated by a per-start token, so one warm LTM connection serves every hook call (SECURITY.md, src/memtomem_stm/daemon/server.py:1-35).

The capability table in the README maps core's advertised schema versions to STM behaviour, from legacy mem_search to context_compose with pinned context, adjacent chunks and score-scale metadata. Behaviour follows what the connected core advertises, not its package version.

4. Essential Implementation Paths

  • Wire. The lifespan builds a FeedbackTracker when feedback_enabled and passes it to SurfacingEngine; ProxyManager is constructed without an index engine (src/memtomem_stm/server.py:536-553, :653-662).
  • Seed the hold-back. At construction the engine loads every seen id younger than the dedup TTL into _surfaced_ids (src/memtomem_stm/surfacing/engine.py:513-527).
  • Gate. RelevanceGate.should_surface refuses excluded tools, tools matching write patterns such as *write* and *delete*, disabled tools, the per-minute rate limit and the cooldown (src/memtomem_stm/surfacing/relevance.py:78-154).
  • Scope. On a hook call with a cwd and no pinned namespace, the engine resolves the repository's namespaces (engine.py:1933-1945) and sends them as the namespace include-list (engine.py:2697-2699), which the client joins into one comma-separated argument (src/memtomem_stm/surfacing/mcp_client.py:1673-1676).
  • Search. context_compose when core advertises schema 2 or later, else mem_search, asking for twice the result cap (engine.py:2712-2798).
  • Filter. Score floor (engine.py:2890, :2955), namespace deny-list (:2960), demotion (:2963), then hold-back and within-batch dedup (:2996-3009).
  • Record. The event row and the seen rows are written in one worker hop, the seen rows even if the event row fails (engine.py:219-244).
  • Rate. stm_surfacing_feedback validates and records; a helpful rating calls core's mem_do(action="increment_access"), and a negative one filters warm cache entries (server.py:2005-2083, engine.py:1970-2067, mcp_client.py:2006-2030).

5. Memory Data Model

STM stores no memory content. Its ledger in stm_feedback.db (src/memtomem_stm/surfacing/feedback_store.py:157-280):

  • surfacing_events: id, server, tool, query (raw or an HMAC digest), the delivered memory_ids and scores as JSON, created_at, and core's score_scale. Holdout columns arm and holdout_rate are added for hook calls.
  • surfacing_feedback: surfacing id, an optional memory id, rating, created_at. The store refuses a rating for an unknown event, or for a memory id the event did not deliver (feedback_store.py:1944-1986).
  • seen_memories: memory id, first and last seen, a count.
  • auto_tune_adjustments: one min_score per tool.
  • surfacing_memory_paths: keyed hashes of each delivered memory's path and snippet 4-grams, for the holdout resolver; no path or text.
  • surfacing_opportunities: one row per call that entered surfacing, with the gate decision and a query digest.
  • surfacing_faults and stm_meta: day-aggregated fault counters and the per-install HMAC key.

The memory id is core's chunk id under the default structured format. Under compact it is a digest of namespace, source and content (src/memtomem_stm/surfacing/mcp_client.py:159), so two chunks with identical text in one namespace and source share one id and one rating history.

Three clocks age the ledger. Seen rows go after seven days; query text is nulled after 30; events go after 90 days, taking their ratings and path rows with them (feedback_store.py:2431-2443, :2466-2506, src/memtomem_stm/surfacing/config.py:219-252).

6. Retrieval Mechanics

Ranking is core's. STM asks for twice max_results candidates, three by default and two for a consumer model of 32K tokens or less, and keeps at most max_results after filtering (src/memtomem_stm/surfacing/config.py:130, :458-468). Pinned results from context_compose bypass the score floor, the deny-list, demotion and hold-back (src/memtomem_stm/surfacing/engine.py:2996-3009).

The score floor defaults to 0.017 and moves per tool. AutoTuner raises it when more than 60% of a tool's ratings are negative and lowers it when more than 80% are strictly helpful, after 20 samples, falling back to global ratios (src/memtomem_stm/surfacing/feedback.py:327-413). When core reports a score scale the default floor was not drawn on, the floor is suspended rather than applied (engine.py:1606-1623, :2925-2953).

The deny-list drops results from claude-plans and codex by default, and the context-window neighbours of a kept hit from those namespaces too (config.py:151-160, engine.py:1947-1968).

Demotion reads negative-rating counts per id, counting distinct surfacing events so repeated ratings of one event cannot demote by themselves (src/memtomem_stm/surfacing/feedback_store.py:2019-2082). It is applied on the miss path and again on cache hits, so a threshold crossed by another process sharing the file takes effect on a warm cache entry too (engine.py:2335-2350).

Project scope on hook calls maps a working directory to claude:<slug> for each git worktree of the repository, shared:<repo> and default, using git worktree list rather than slug prefixes so memtomem does not include memtomem-stm. Any failure, or a repository with no Claude Code project directory, yields an unscoped search (src/memtomem_stm/surfacing/project_scope.py:1-19, config.py:161-172).

7. Write Mechanics

The bundled server does not write tool responses into core. auto_index and extraction write markdown under ~/.memtomem and index it through a FileIndexer (src/memtomem_stm/proxy/memory_ops.py:142-268, :272-392), and the only ProxyManager construction in the tree passes no indexer (src/memtomem_stm/server.py:653-662). docs/configuration.md:528-530 calls the keys reserved for custom embedders.

Two writes reach core. A helpful rating boosts the chunk's access count, once per surfacing event (src/memtomem_stm/surfacing/engine.py:2032-2067). With MEMTOMEM_STM_FORMATION__ENABLED=true, stm_memory_propose submits a pending candidate through core's candidate_propose, with a default idempotency key hashed from the reference and text, and never falls back to a direct write (server.py:1938-1997, mcp_client.py:1981). Core's review decides the rest.

STM's own writes are off the request path. Event, seen and rating rows go through a bounded store-write queue; a rating that times out is reported busy, and its cache filter is applied anyway because the write is shielded and will land (engine.py:1990-2030). Within one process the in-memory seen set is claimed before the write, so a memory cannot be delivered twice while its seen row is queued (engine.py:2255-2280).

Operational cost

Each surfacing is one core call, plus a session-scratch listing when session context is on, bounded by timeout_seconds and a circuit breaker, and a few SQLite writes. No model runs in STM on the surfacing path. The retention sweeps run on the store worker at most once per cleanup interval (engine.py:3290-3351).

8. Agent Integration

The server advertises five STM tools by default: stm_proxy_describe_tool, stm_proxy_select_chunks, stm_proxy_read_more, stm_surfacing_feedback and stm_compression_feedback (src/memtomem_stm/server.py:1428, :1482, :1517, :2005, :2851). Eight observability actions sit behind stm_admin when an environment flag is set, and stm_memory_propose appears only with formation enabled (README.md).

The proxied path injects into the tool result and asks the agent to rate it: the block opens with the untrusted-data notice, then the surfacing id and a copyable stm_surfacing_feedback call (src/memtomem_stm/surfacing/formatter.py:195-230).

The hook path reaches built-in tools the proxy never sees. mms hook reads the PostToolUse payload, surfaces only for read-like tools, and returns memories as additionalContext; it always exits 0 and passes the result through untouched on any error (src/memtomem_stm/cli/hook_cmd.py:1-45). It emits no rating prompt: hook.record_feedback_events defaults to false, which also skips the demotion read and turns auto-tuning off in the daemon (src/memtomem_stm/config.py:421-432, src/memtomem_stm/daemon/server.py:332-358).

9. Reliability, Safety, and Trust

The reader rates what it read

stm_surfacing_feedback is a registered tool on the agent's surface, and the rating prompt is in the injected block. The agent that received a memory decides whether it was relevant, and three negative events demote it. The two negative ratings are not_relevant and already_known (src/memtomem_stm/surfacing/feedback_store.py:57), so a correct memory the agent reports knowing three times is filtered the same way as a wrong one. Demotion is a relevance mechanism; it records no judgement about truth.

Two paths, two halves

Project scoping needs the call's working directory, and only hook calls carry one (src/memtomem_stm/surfacing/engine.py:260-272, config.py:161-172). Demotion needs the feedback loop, and the hook path runs with it off by default (src/memtomem_stm/config.py:421-432). With defaults, a proxied call is demoted and unscoped, and a hook call is scoped and never demoted. Both paths write seen_memories when they share stm_feedback.db, and an engine reads it at construction, so the hold-back crosses paths at the next engine start (src/memtomem_stm/daemon/server.py:350-379).

Scope is core's

STM's scope is an include-list it hands to core; it does not check the namespaces of what comes back against that list. A repository it cannot identify, a cancelled resolution or a missing git all fall back to an unscoped search by design (project_scope.py:15-19). The seen and feedback ledgers are keyed on memory id alone, so a demotion earned in one repository applies in every other for any memory core returns to both.

What the ledger keeps

Every surfacing writes the query by default; persist_query_text=False replaces it with an HMAC digest, the hook path forces that, and query text is nulled after 30 days (config.py:221-252, daemon/server.py:333-339). The injected block escapes every untrusted field and declares retrieved memories data, not instructions (formatter.py:18-20, :381). SECURITY.md states the residual risk that natural-language text may persuade a model anyway.

Marks

  • negative_eval — present. Three committed cases put a populated candidate list through STM's filter and assert one memory absent beside a control that is present: demotion (tests/test_surfacing_engine.py:2589-2621), cross-session hold-back (tests/test_cross_session_dedup.py:192-222) and the namespace deny-list (tests/test_surfacing_engine.py:6088-6101). The LTM is a stub in each.
  • scope_enforced — withheld. STM computes an include-list for hook calls and core applies it; proxied calls are unscoped, resolution failures widen, and STM's own ledgers carry no project key.
  • tombstone — withheld. Demotion is keyed on a memory id, a record and not a value, filters surfacing only, and lapses with the 90-day sweep. Under the compact format the id is a content digest, which is the nearest thing to value keying in the tree.
  • trust_state — withheld. Ratings are relevance votes, and demotion is a count derived on read.
  • audit_log — withheld. surfacing_events and surfacing_feedback record retrieval and feedback, and STM mutates no memory.
  • human_review — withheld. stm_memory_propose queues a candidate in core and holds no review state; approval is core's.
  • bitemporal — withheld. No validity time exists in STM.

10. Tests, Evals, and Benchmarks

The suite has 9,520 pytest functions in 313 files. CI runs it on Ubuntu with Python 3.12, 3.13 and 3.14 and on Windows with 3.12 and 3.13, the Ubuntu 3.14 and Windows 3.13 lanes advisory, with a 90% branch-coverage floor on Ubuntu 3.12; five bench_qa marker groups are excluded (.github/workflows/ci.yml:55-88). I ran none of them.

The surfacing tests run the real engine and a real SQLite ledger against a stub core. The demotion case seeds three negative events for one id, returns it beside a second memory, and asserts the first absent and the second present (tests/test_surfacing_engine.py:2589-2621). A sibling crosses the threshold out of band while a cache entry is warm and asserts the hit filters it (:2691-2737). Project-scope tests resolve real git repositories and assert a prefix-named sibling is not included (tests/test_project_scope.py:126-135), and that two repositories do not share a cached answer (tests/test_surfacing_engine.py:6020).

The bench_qa suite under tests/bench/ measures compression on eleven fixtures, not memory. The holdout trial is the instrument for surfacing: it assigns arms at random on hook calls, and scripts/stm_trial.py with src/memtomem_stm/surfacing/trial.py resolves whether the agent opened the memory's file or reused its text. No trial result is committed.

Cases to want first: a project-scoped hook call against a core holding two repositories, asserting the other repository's memory absent; and a demotion case on the hook path with the feedback loop on.

No paper describes memtomem-stm; CITATION.cff is absent and no arXiv, DOI or BibTeX reference is in the tree.

11. For Your Own Build

Steal

  • Persist the hold-back. A seen table with a TTL, loaded at startup and written in the same hop as the event, keeps a memory from reappearing every session (engine.py:219-244, :513-527).
  • Demote outside the store. Filtering on a counted, distinct-event signal leaves the store's ranking clean and lets the demotion lapse when the evidence ages out.
  • Refuse a rating the event did not deliver. Checking the memory id against the event's delivered list stops a stray id from suppressing an unrelated memory (feedback_store.py:1972-1978).
  • Measure surfacing with a holdout. Withholding a random share and resolving later use from hashed transcripts answers whether injection helps, which a rating cannot.

Avoid

  • Do not let the reader's rating be the only signal. The agent that saw a memory is the cheapest rater and the least independent.
  • Do not fold "known" into "irrelevant". A demotion that counts both hides the memories the agent relies on most.
  • Do not split scope and demotion across entry paths. Each defends a different failure, and a reader of either path gets one.
  • Do not key cross-project state on an id alone when the same id can be returned to several projects.

Fit

Fits someone who runs memtomem as long-term memory and wants it to arrive in tool results unasked, with a cap on repetition and a way to measure whether it helps. The proxy half — compression, caching, progressive reads — earns its place without memory at all.

Walk away if the memory layer must enforce project isolation itself, if suppression must follow a person's decision rather than the agent's, or if the core is something other than memtomem.

12. Open Questions

  • Which project memtomem core resolves for its always-on scope fragment when one daemon's LTM child serves hook calls from several repositories.
  • Whether the hook path is meant to gain demotion once it has a feedback channel, as the hook command's docstring anticipates.
  • Whether already_known is meant to count toward demotion as well as toward raising a tool's score floor.
  • Whether a trial result will be committed beside the resolver.

Appendix: File Index

  • Server and wiring: src/memtomem_stm/server.py, src/memtomem_stm/config.py
  • Surfacing: src/memtomem_stm/surfacing/engine.py, src/memtomem_stm/surfacing/relevance.py, src/memtomem_stm/surfacing/config.py, src/memtomem_stm/surfacing/project_scope.py, src/memtomem_stm/surfacing/formatter.py, src/memtomem_stm/surfacing/mcp_client.py
  • Ledger: src/memtomem_stm/surfacing/feedback_store.py, src/memtomem_stm/surfacing/feedback.py
  • Trial: src/memtomem_stm/surfacing/trial.py, scripts/stm_trial.py
  • Hook and daemon: src/memtomem_stm/cli/hook_cmd.py, src/memtomem_stm/daemon/server.py
  • Library-only indexing: src/memtomem_stm/proxy/memory_ops.py, src/memtomem_stm/proxy/extraction.py
  • Docs: docs/surfacing.md, docs/configuration.md, SECURITY.md, CLA.md
  • Tests: tests/test_surfacing_engine.py, tests/test_cross_session_dedup.py, tests/test_project_scope.py

Recorded searches

Run from the repository root at the pinned commit with /usr/bin/git grep.

  • No import of memtomem core. git grep -n -E '^[[:space:]]*(from|import) memtomem([.[:space:]]|$)' -- . returns one prose line in CHANGELOG.md:10044; the control git grep -n -E '^[[:space:]]*(from|import) memtomem' -- src matches the package's own memtomem_stm imports.
  • The bundled server wires no index engine. git grep -n 'ProxyManager(' -- src returns src/memtomem_stm/server.py:653 only; git grep -n 'index_engine' -- src/memtomem_stm/server.py src/memtomem_stm/cli src/memtomem_stm/daemon returns nothing.
  • No approve verb in STM. git grep -n -w 'approve' -- src returns a Codex hook hint, a CLI comment and the review hint string at src/memtomem_stm/server.py:1996.
  • No value-keyed suppression. git grep -n -i 'tombstone' -- src returns nothing.
  • No paper. CITATION.cff is absent; git grep -n -i -E 'arxiv|doi\.org|bibtex' -- . returns nothing.

History

2026-12-04 — 1d5c6fa9…. First reading, from the 2026-12-04 triage shortlist, at the head of main reached on 2026-12-04; the shortlist assessed 6cff9ec1705f, which the depth-1 clone does not hold. Screened: no auto-run surface; three build-time execution points (tests/bench/conftest.py, tests/conftest.py, tests/daemon/conftest.py); two dependency surfaces inside the cooldown (pyproject.toml, uv.lock), a count the depth-1 clone inflates; no unpinned surface; CLAUDE.md read as data. Nothing was installed, built or run. One mark (section 9).