A sleep cycle that rewrites memories in place

MemForge

A deprecated TypeScript memory server on PostgreSQL whose sleep cycle scores, evicts and LLM-rewrites consolidated memories, behind REST, an MCP server and SDKs.

LicenceMIT
Size18,508 lines of TypeScript in src, of which memory-manager.ts is 5,175 and sleep-cycle.ts 1,993; schema/schema.sql of 981 lines and 25 migrations; a 1,326-line Python SDK
Activity227 commits on main from 17 March to 16 November 2026 under five author names, 20 of them Dependabot; tags to v3.7.0; deprecated on 16 November 2026 with no further releases or security fixes
Tests507 node:test cases in 35 files and 34 Python SDK tests; CI runs the security, integration, LLM-path, HTTP, cache and load suites against pgvector; nine files are in no npm script; none run for this reading

Carries 5 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

MemForge is a self-hosted memory server for agents: TypeScript on Express over PostgreSQL with pgvector and pg_trgm, reached through a REST API, a stdio MCP server and TypeScript and Python SDKs. Memories move from a hot tier of raw events to a warm tier of consolidated rows, and a sleep cycle rescores the warm tier, evicts what scores low to a cold tier, and asks a model to rewrite rows it flags. The author deprecated it on 16 November 2026, with no further releases or security fixes, and the README's own notice states the two authorization gaps described below.

Notable: a rewrite keeps the old text twice. Before a revised row is updated in place, the prior and new text go into memory_revisions and into a per-target, HMAC-chained audit_chain whose content_before is readable by /audit history and a point-in-time route. Event time (occurred_at) is kept apart from ingestion time and filtered on all four retrieval arms.

Weak:

  • The model's rewrite replaces content and confidence and leaves the status. An established row stays established after a model rewrites it, and the new confidence is the model's own number (src/sleep-cycle.ts:923-933).
  • Conflict resolution has nothing to resolve. Phase 2.5 reads memory_conflicts, and no code in src/ inserts into it. The only insert is a test fixture.
  • Authorization stops at the token. The agent is a path segment, any valid token reaches any agent, and with no token configured every caller is anonymous with read and write scope (src/auth.ts:82-164, src/app.ts:1711-1717).
  • Summarize mode keeps no raw event. Consolidation deletes the hot rows in the same transaction that writes the summary (src/memory-manager.ts:1779-1784).

Five marks: trust_state, bitemporal, scope_enforced, audit_log, negative_eval. The sleep cycle's rewriting earns none of them by itself.

2. Mental Model

A memory starts as an event an agent posted and becomes a paragraph a consolidation pass wrote. The hot tier is not searchable; only the warm tier answers queries, so an event is retrievable after someone calls POST /consolidate.

The warm row is the unit everything else acts on. It carries:

  • importance, recomputed for every warm row of the agent on each sleep cycle from access, feedback, recency and graph signals;
  • confidence, which decays, drops on a supersession hint or a lost conflict, and is replaced by the model on a rewrite;
  • epistemic_status, provisional at birth, promoted to established by corroboration and positive retrievals, demoted when stale;
  • occurred_at, the earliest event time of the batch, when the caller gave one.

The sleep cycle is a maintenance pass the caller triggers. It does three things to stored knowledge, and they differ in what survives:

  • Rescoring changes numbers on every row and keeps no history of them beyond a batch count.
  • Eviction copies a row below importance 0.1 to cold_tier and deletes it from the warm tier; the row's revision history goes with it by cascade.
  • Revision replaces a flagged row's text with the model's, keeping the prior text in memory_revisions and audit_chain.
Diagram — an event is searchable only after consolidation; the sleep cycle rescores every row, evicts the lowest and rewrites the flagged ones in place, and the prior text survives in two tables until eviction or the audit retention window
Diagram source
%% caption: an event is searchable only after consolidation; the sleep cycle rescores every row, evicts the lowest and rewrites the flagged ones in place, and the prior text survives in two tables until eviction or the audit retention window
flowchart TD
  ADD["POST /memory<br/>secrets redacted"]
  ADD --> HOT["hot_tier row<br/>not searchable"]
  HOT -->|"POST /consolidate"| MODE{"concat or<br/>summarize"}
  MODE -->|"concat, default"| WARM["warm_tier row<br/>provisional"]
  MODE -->|"summarize"| WARM
  MODE -.->|"same transaction"| DEL["hot rows deleted"]
  WARM --> QRY["query: four arms<br/>agent and namespace"]
  WARM -->|"POST /sleep"| P1["phase 1: rescore<br/>every warm row"]
  P1 --> P2{"importance below<br/>0.1, or flagged?"}
  P2 -->|"low importance"| COLD["copy to cold_tier,<br/>warm row deleted,<br/>revisions cascade"]
  P2 -->|"flagged, at<br/>most 50"| REV["phase 3: model<br/>returns new text"]
  REV --> KEEP["prior text into<br/>memory_revisions<br/>and audit_chain"]
  KEEP -->|"UPDATE in place,<br/>status unchanged"| WARM
  KEEP -->|"90 days after a<br/>later record"| HASH["cold_audit:<br/>hashes only"]

3. Architecture

Component Role Files
HTTP server Express routes, auth, rate limits, OpenAPI src/app.ts, src/auth.ts, src/server.ts, src/openapi.ts
Memory manager add, consolidate, query, clear, resume, pools, bootstrap, Anthropic bridge src/memory-manager.ts
Sleep cycle phased scoring, eviction, revision, graph upkeep, reflection, promotion src/sleep-cycle.ts
Audit per-target HMAC chain, history, point-in-time, archive src/audit.ts
Classifier secret and PII detection, redaction src/classifier.ts, src/llm-safety.ts
MCP server 46 stdio tools that call the REST API src/mcp.ts, src/client.ts
Dream runs a polled queue for batch passes and Anthropic Dreams compatibility src/dream-runs.ts
Schema 25 migrations and a canonical schema.sql schema/
Python SDK HTTP client python/

AuditChain is constructed unconditionally and handed to the manager, the sleep cycle and the app (src/server.ts:42-45). Without AUDIT_HMAC_KEY it falls back to a default key outside production and refuses to start in production.

Deployment and ergonomics

The CI jobs install schema.sql into pgvector/pgvector:pg16. The docker-compose.yml mounts the same file into postgres:16-alpine, an image that ships no pgvector, so CREATE EXTENSION IF NOT EXISTS vector (schema/schema.sql:14) fails on a compose install, and the official image's init scripts stop on the first error. schema.sql:57 also creates warm_tier_occurred_idx on warm_tier sixteen lines before the table exists; psql -f without ON_ERROR_STOP continues, so a fresh install has no event-time index and CI does not notice. migration-v3.13.sql:30 creates it for upgrades.

pip install memforge installs an unrelated project; the README says so. Remote model calls are refused unless ALLOW_REMOTE_LLM is set.

4. Essential Implementation Paths

  • Add. POST /memory validates, classifies the content, replaces restricted values with [REDACTED:type] and stores the redacted text (src/app.ts:387-389). add skips an identical hash in the same namespace within an hour, strips reserved metadata keys, inserts into hot_tier, and, if hints.supersedes names a warm id, lowers that row's confidence to at most 0.3 and tags it _superseded without waiting (src/memory-manager.ts:534-626).
  • Consolidate. Under an advisory lock, inner batches of hot rows are taken FOR UPDATE SKIP LOCKED, joined or summarized, written as one warm row with the earliest occurred_at, audited as create, and deleted from hot_tier (src/memory-manager.ts:1367-1858).
  • Query. Arms by mode, each filtered by agent and namespace; RRF; scoring passes; optional epistemic filter; a floor at 10 percent of the top score; retrieval logging (src/memory-manager.ts:694-1006).
  • Sleep. sleep() refuses a second cycle for the same agent in the same process, requires a model, caps the token budget at 200,000 and runs the phases (src/memory-manager.ts:2477-2533, src/sleep-cycle.ts:132-446).
  • Revise one row. reviseMemory prompts with the row, its entities, recent retrievals and up to five related rows; none raises confidence by 0.1; any other action writes the revision row, re-embeds, updates the warm row and appends an audit record (src/sleep-cycle.ts:795-947).

5. Memory Data Model

warm_tier (schema/schema.sql:73-130) holds the content, two generated tsvectors, a halfvec embedding, source_hot_ids, occurred_at, time_start and time_end, consolidated_at, importance, confidence, staleness_score, revision_count, graduated, namespace, valid_until, epistemic_status (default provisional) and evidence_count. The TypeScript type admits five statuses, established, provisional, contested, deprecated and inferred (src/types.ts:24).

memory_revisions (schema/schema.sql:307-322) keeps previous_content, new_content, the revision type (augment, correct, merge, compress), reason, delta summary, confidence and model. Its warm_tier_id is ON DELETE CASCADE.

cold_tier (:155-165) is a content snapshot keyed by source table and id.

audit_chain (:360-388) covers warm_tier, entities, relationships, reflections and procedures, not hot_tier. Each record holds the operation, valid_from and valid_until, content_before and content_after, a content HMAC, the previous record's chain hash for the same target, its own chain hash, the trigger and the model. cold_audit (:398-411) keeps hashes and metadata and no content.

memory_conflicts (:419-431) has a pair of warm ids and a resolution. Shared pools (:467-508) hold published copies with hop counts and base confidence. RLS policies exist for each agent-keyed table (:768-946) without FORCE, so the owning role the server connects as bypasses them; the changelog says so.

6. Retrieval Mechanics

Four arms, chosen by mode, all reading warm_tier with agent_id = $1 AND namespace = $n:

  • keyword: an OR-joined tsquery over the content tsvector (src/memory-manager.ts:1041-1061);
  • code: the code-token tsvector (:1091-1103);
  • trigram: pg_trgm similarity (:1129-1141);
  • semantic: halfvec cosine (:1170-1184).

Hybrid mode fuses them by reciprocal rank at k 60 (:1191-1265). Shared-pool hits from pools the agent belongs to are merged with a trust weight (:759-810). Then come time decay, temporal proximity (on consolidated_at), an entity boost, an optional model rerank, snippets, a token budget and dedup.

The time window reads event time. buildTimeFilter compares COALESCE(occurred_at, time_end, consolidated_at) with after and COALESCE(occurred_at, time_start, consolidated_at) with before (:1269-1286), on every arm. timeline orders by COALESCE(time_start, consolidated_at), which is ingestion time.

The status filter is opt-in and post-limit. opts.epistemic drops rows below the requested level after the arms have returned their limit (:928-946). include_provisional admits established and provisional and so excludes inferred. The HTTP query route passes the option only when given; memforge_certainty describes include_provisional as its default and sends nothing when the agent omits it (src/mcp.ts:555-568, :957-963). resume returns the top rows by importance with no status filter (src/memory-manager.ts:2648-2713).

After a query, the access-count update runs WHERE id = ANY($1) with no agent predicate, and the retrieval-log insert takes the same ids (:988-1002). When pool hits are merged, their ids are shared_memories ids.

7. Write Mechanics

Writes do not block on a model. add is one insert, and the supersession update is fire-and-forget. Consolidation calls a model only in summarize mode.

Lag. An event is not retrievable until consolidation runs, and nothing runs it on a timer: the advisory endpoint and the MCP description both state that MemForge has no built-in scheduler (src/app.ts:1147, src/mcp.ts:297). The lag is whatever the caller's cron or agent chooses.

Consolidation. Concat, the default (src/server.ts:55), keeps the raw text inside the warm row. Summarize replaces a batch with a model summary, and the hot rows are deleted in the same transaction (src/memory-manager.ts:1779-1784); the audit record's content_after is the summary, so the raw events survive nowhere.

What a sleep cycle rewrites.

  • The whole store's scores. Phase 1 recomputes importance, staleness and confidence decay for every warm row of the agent in SQL (src/sleep-cycle.ts:533-632), with one batch audit record.
  • Low-importance rows, out. Phase 2 copies rows below 0.1 into cold_tier and deletes them from the warm tier (:659-674); capacity eviction does the same (:768-784). Each is a batch audit record with target 0. The cold copy holds the latest text, and memory_revisions rows are removed by cascade.
  • Up to 50 flagged rows, rewritten. A row is flagged below confidence 0.4, with at least two negative feedbacks forming a majority, or when cited by a reflection that found a contradiction (:636-737). The model gets REVISION_SYSTEM_PROMPT (:26-50) and returns none, augment, correct, merge or compress. Anything but none writes memory_revisions (:905-910), re-embeds, and runs UPDATE warm_tier SET content = $2, confidence = $3 with the model's confidence (:923-933), then appends an audit revise with the old and new text (:936-944). merge rewrites the one row and leaves the others. epistemic_status is not touched.
  • Related context crosses namespaces. The related-memories query that feeds the revision prompt filters on agent only (:821-832), so a row in one namespace can be rewritten with text from another.
  • Status. Phase 5.12 promotes and demotes, and adds evidence for positive feedback in the last day (:1766-1815). Phase 5.6 cuts confidence by 0.2 on a row whose valid_until has passed (:1314-1330). Phase 5.10 decays rows in deprecated namespaces (:1489-1516).

Other in-place overwrites. pullFromAnthropic with the default anthropic-wins replaces warm content from an external store with no revision row and no audit record (src/memory-manager.ts:4175-4184). setMemoryValidity sets valid_until with no audit (:3519-3526).

Deletion. No route deletes one memory; the app's delete routes are pool, role and namespace operations. clear archives the hot and warm tiers to cold and deletes them (:1862-1926). Cold rows are hard-deleted only when COLD_TIER_RETENTION_DAYS is set (:2545).

Operational cost

A sleep cycle is synchronous on the request and holds an in-process lock per agent, so two server processes can run two cycles on one agent. Revision is bounded by the 50-row limit and the token budget; scoring touches every warm row each time.

8. Agent Integration

The MCP server is a client of the REST API, configured by MEMFORGE_URL, MEMFORGE_TOKEN, MEMFORGE_NAMESPACE and MEMFORGE_SESSION_ID (src/client.ts:103-104). It exposes 46 tools, against the 17 the README lists. Three matter here:

  • memforge_add sends content, metadata and namespace and no occurred_at or hints (src/mcp.ts:768-769), so an MCP agent writes no event time and cannot supersede.
  • memforge_sleep lets the agent start the cycle that rewrites its memories.
  • memforge_certainty is the only MCP path to the status filter.

The bridge to Anthropic's managed-agent memory stores pushes and pulls warm rows; createDreamRun refuses a new_namespace output mode (src/memory-manager.ts:3706-3712). bootstrapAgent copies another agent's established rows into a new agent as inferred at half importance and confidence, with audit records (:5040-5104).

9. Reliability, Safety, and Trust

The status is a filter the caller has to ask for

trust_state is earned on the producer and the filter: Phase 5.12 writes established and provisional, bootstrap writes inferred, and the query drops rows below the requested level. What it promises is narrower than the name:

  • Corroboration is evidence_count from positive feedback and positive retrievals on two days, both reported by the agent that reads the memory.
  • contested is written only by conflict resolution, whose input table no code fills, and deprecated has no writer at all.
  • A rewritten row keeps its status. The model can change what an established row says, and the badge stays.

Two copies of the old text, each with an expiry

memory_revisions.previous_content is written on every revision and read by no route; it is deleted with its warm row on eviction or clear. audit_chain keeps content_before and is readable through history and point-in-time routes (src/app.ts:1540-1599). archiveExpired moves records older than the retention window, 90 days by default, and closed by a later record, to cold_audit with hashes only, and deletes them under a session flag the delete trigger honours (src/audit.ts:347-386). verify requires an empty previous_hash at the first record it reads (:189-264), so a target whose early records were archived reports a broken chain. SECURITY.md lists audit-chain verification among the known unfixed limitations: it can report tampering on healthy data, and concurrent writers can fork the chain.

What the chain does not see

Hot-tier writes, supersession hints, setMemoryValidity and the Anthropic pull write no record. Evictions and rescoring are counts at target_id 0. The audit write in a revision is awaited; the content_hash update on the warm row after it is not. The previous-hash read and the insert are not in one transaction, which is how two concurrent writes to one target chain from the same parent.

Authorization

The README's deprecation notice and SECURITY.md state it: without MEMFORGE_TOKEN or OAuth2 the server accepts unauthenticated requests, the shipped compose file does not pass the token through, and any valid token reads and writes every agent's memory. OAuth2 introspection records a client_id for device identity and does not bind it to an agent.

Privacy

On the HTTP add path the classifier replaces credential patterns, SSNs and card numbers with [REDACTED:type] before storage and tags email, phone and IBAN matches in metadata (src/classifier.ts:80-223, src/app.ts:387-389); llm-safety.ts sanitizes text again before any model call. SECURITY.md's design section says no PII-specific handling is built in, and the code has this classifier.

Marks withheld

  • tombstone: _superseded and _conflict_loser are metadata flags on the old row. No read path consults them; they feed conflict scoring, and the lower confidence sends the row to revision. Nothing refuses the same content when it is posted again.
  • human_review: no state waits for a person. Conflicts are scored by a heuristic, revisions apply at once, and the agent can trigger both the sleep cycle and the feedback that promotes.

10. Tests, Evals, and Benchmarks

Tests run under node --test against a real PostgreSQL. CI runs test:security without a database and test:integration, test:llm and test:http against pgvector/pgvector:pg16, plus cache and load jobs and an RLS check. npm test lists 24 files, among them epistemic-confidence and contested-conflicts, which CI does not run. Nine files are in no script: bitemporal, cold-tier-retention, cold-tier-search, consolidation-metadata, memory-budgeting, memory-namespaces, sleep-advisory, snippet and streaming-consolidation.

Populated negatives:

  • tests/epistemic-confidence.test.ts:236-256 seeds an established and a provisional row and requires a non-empty result of only established rows. The contested-exclusion case at :267-276 passes on an empty result, and :285-290 pins that no filter is the default.
  • tests/bitemporal.test.ts:102-119 requires one row absent from the last hour and present in its 2023 window.
  • tests/memory-namespaces.test.ts:128-175 asserts length === 0 across namespaces with positive controls in sibling cases. The CI namespace case, tests/http-api.test.ts:496-507, is a .some check that passes on empty.

tests/contested-conflicts.test.ts:94 inserts into memory_conflicts itself. tests/llm-paths.test.ts:230-290 checks that a revision is recorded; no case checks that previous_content equals the text before the rewrite.

Benchmarks: benchmarks/OFFICIAL-RESULTS.md reports LongMemEval-S QA at 67.6 percent on 29 July 2026 with a gpt-4o judge, recall@5 95.4 and complete-evidence recall 91.8. No per-question results are committed. The README retracts an earlier 93.2 percent recall@5 because the scorer ignored k. The benchmark harness never runs a sleep cycle, so no number measures the rewriting.

11. For Your Own Build

Steal

  • Write the prior text before the rewrite, in the store you will query. A revision row and an audit record with before and after text, from the same code path that updates the row.
  • Chain per target. One chain per memory keeps verification local and lets a point-in-time read rebuild one row.
  • Filter event time on every arm. One helper applied to keyword, trigram and vector alike, with ingestion time as the fallback.
  • Redact at the API edge, before the store and before any model.
  • A model rewrite is one of five named actions, with a reason and a delta, which makes a review queue cheap to add later.

Avoid

  • Letting the model set the confidence of its own rewrite, and keeping a status earned by the old text.
  • A resolver whose detector was never written. Phase 2.5 and the contested status read a table nothing fills, and the test fills it by hand.
  • Cascading the revision history away with the row. Eviction to a cold copy of the latest text loses every earlier version.
  • Archiving an audit record's text while verification still expects the chain to start at it.
  • A scope that is a path parameter behind a token that is not bound to it.
  • An init script that continues past errors and installs without the index the feature needs.

Fit

Nobody should deploy MemForge new: its author deprecated it with no security fixes, and by its own account every token holder is one trust domain. Someone already running it for one agent on a private network has a sound base in the concat consolidation and the revision audit, and should leave summarize mode off, set the token and the HMAC key, and schedule consolidation themselves.

As a design to borrow from, it suits a team that wants a model to tidy memories in the background and needs to answer what a memory said before. It does not suit a product where established must mean someone checked it, a superseded memory must stay out of results, or several tenants share one server: each of those needs a mechanism this code lacks, not a setting.

12. Open Questions

  • Pool hits merged into a query pass shared_memories ids to the warm-tier access-count update and the retrieval-log insert. Whether that bumps another row or fails the insert on its foreign key depends on id overlap at run time.
  • Whether a deployment that follows the README rather than docker-compose ever had the event-time index depends on its migration history.
  • The README lists /conflicts and /hints routes that src/app.ts does not register.

Appendix: File Index

  • Server and auth: src/app.ts, src/auth.ts, src/server.ts, src/openapi.ts
  • Memory: src/memory-manager.ts, src/types.ts
  • Sleep cycle: src/sleep-cycle.ts
  • Audit: src/audit.ts
  • Safety: src/classifier.ts, src/llm-safety.ts
  • Agent surfaces: src/mcp.ts, src/client.ts, src/dream-runs.ts, python/
  • Schema: schema/schema.sql, schema/migration-v3.13.sql, docker-compose.yml
  • Tests: tests/epistemic-confidence.test.ts, tests/bitemporal.test.ts, tests/memory-namespaces.test.ts, tests/http-api.test.ts, tests/contested-conflicts.test.ts, tests/llm-paths.test.ts
  • CI and benchmarks: .github/workflows/ci.yml, benchmarks/OFFICIAL-RESULTS.md, benchmarks/RESULTS.md

Recorded searches

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

  • Nothing in src fills memory_conflicts. git grep -n 'INSERT INTO memory_conflicts' returns only tests/contested-conflicts.test.ts:94.
  • No writer of deprecated. git grep -n -E "epistemic_status *= *'deprecated'" -- src returns nothing; the same pattern for 'contested' returns src/sleep-cycle.ts:1066.
  • previous_content is never read. git grep -n previous_content -- src returns the insert and the type.
  • The supersession flags are not read filters. git grep -n -E '_superseded|_conflict_loser' -- src returns the writers and conflict scoring.
  • No single-memory delete route. grep -n "app\.delete(" src/app.ts returns four pool, role and namespace routes.
  • No scheduler. git grep -n -E 'setInterval|cron|schedule' -- src returns the OAuth token-cache sweep, the dashboard refresh, the database health check, the dream-runs poll, the reflection trigger enum, and four statements that MemForge has no built-in scheduler.
  • The benchmarks never sleep. git grep -n -i -E 'sleep|revise|reflect' -- benchmarks returns one README line.
  • No paper of its own. git grep -n -i -E 'arxiv|bibtex|CITATION' returns other projects' papers cited in planning documents.
  • The event-time index precedes its table. git grep -n warm_tier_occurred_idx returns schema/schema.sql:57 and schema/migration-v3.13.sql:30; CREATE TABLE IF NOT EXISTS warm_tier is at schema/schema.sql:73.
  • Test files outside every script. For each file in tests/, a search of package.json for its name; nine return nothing.
  • No submodules. .gitmodules is absent.

History

2026-12-02 — f07e1370…. First reading, read at the user's request from the 2026-12-02 triage shortlist, from a full clone at the head of main, read only. Screened before reading: one auto-run surface, .claude/settings.local.json, a local permissions file; no build-time execution; nothing inside the cooldown; two unpinned surfaces, package.json with 17 floating ranges beside a package-lock.json unchanged for 127 days, and python/pyproject.toml with no lockfile; CLAUDE.md read as data. The server, memory manager, sleep cycle, audit, auth, MCP server, schema and the tests behind each mark were read; the dashboard, the dream-runs worker beyond its entry points and the Python SDK's internals were not. Nothing was installed, built or run, and none of the 507 test cases was run. Five marks: trust_state, bitemporal, scope_enforced, audit_log, negative_eval.