Skip to content

Memory service reference

The detail behind Use Marina as an agent memory service: the HTTP contract, retrieval, reliability, storage, portability, client interfaces, memory assistance and extensions. Start with that guide if you are new.

The standard install contains no ONNX runtime, tokenizer package or embedding model. To enable the local provider, install its isolated extension explicitly:

Terminal window
bun install --cwd extensions/local-embeddings --frozen-lockfile
bun run memory serve --db data/memory.db --embeddings local

--embeddings local loads that extension and downloads the pinned model on first use. Subsequent launches use data/memory-models; use --model-cache PATH to move the cache and --local-only to prohibit downloads. --embeddings none needs no model and provides exact symbolic queries, relation traversal and literal FTS5 search. The default is none; it does not provide paraphrase retrieval. See TypeScript, MCP and resident interfaces.

The standalone server uses SQLite WAL with synchronous=FULL. Do not treat this as proof of hardware power-loss behavior: the executable qualification tests process termination. For remote use, terminate TLS at your authenticated deployment boundary and set --host deliberately. No model-provider credentials are needed for the local embedding option.

All paths below start with /v1/memory. Use Authorization: Bearer TOKEN. Mutations also require Idempotency-Key: KEY. JSON bodies are limited to 2 MiB. Errors have {"error":{"code":"...","message":"..."}}. The only public read is GET /health.

Method and path Behavior
GET / and /me Actual configured capabilities and credential identity/scopes
GET /spaces, POST /spaces List authorized spaces; create with {name}
GET /spaces/:space Space state and current generation
POST /spaces/:space/records Verbatim {content, type?, tier?, importance?, subject?, metadata?, source_ids?, depends_on?, claim?, valid_time?, expected_vocabulary_version?}; returns stable record ID, version and optional index job ID
GET /spaces/:space/records/:id?version=N Current record by default; explicitly requested historical revision otherwise
PATCH /spaces/:space/records/:id Full replacement content plus expected_version; omitted attributes are retained
POST /spaces/:space/query Exact {subject?, predicate?, object?, type?, tier?, valid_at?, limit?, cursor?}; no embeddings; current records and generation-bound pagination
POST /spaces/:space/graph {subject, predicates?, direction?, max_depth?, valid_at?, limit?}; asserted relationships with record-cited paths; no inference
POST /spaces/:space/search {query, expansion?, mode?, limit?, subject?, type?, tier?, allow_degraded?, valid_at?, include_ended?}; current records still valid now (or at valid_at; include_ended = history read), source IDs, component ranks and generation
POST /spaces/:space/context Search plus budget_tokens; bounded evidence text, revision citations and truncation flags
POST /spaces/:space/sources Original JSON {content, session_id?}; returns durable source ID and cursor
GET /spaces/:space/sources?after=N&limit=100 Ordered source replay with next_cursor
POST /spaces/:space/source_search {query, expansion?, match?:"all"|"any"|"phrase", session_id?, limit?} searches original sources, including those with no derived record
GET /spaces/:space/sources/:id?start=N&end=N&text_hash=HASH Read an immutable UTF-8 byte range with representation/hash/continuation metadata
GET/POST /spaces/:space/vocabulary Read latest (or ?version=N); owner writes {expected_version, definition} with CAS
POST /spaces/:space/plan {task, use_model?, steps?, max_results?, max_bytes?} creates an inspectable read plan
POST /spaces/:space/execute_plan Executes a returned plan against its exact space generation and vocabulary version
POST /spaces/:space/retrieve Task-directed lexical/symbolic retrieval with original source windows, byte budgets and diagnostics; see retrieval contracts
GET/POST /spaces/:space/checkpoints/:name Get state; write {expected_version, data, source_cursor?, source_ids?} atomically. Use version 0 for first write.
POST /spaces/:space/checkpoints/:name/capture One transaction: capture up to 64 new items (1 MiB), a manifest listing order (existing source ids or item indexes), and the checkpoint with data[field] = entry + {source_ids, manifest_source_id}. The expected version is checked before anything is stored.
GET /spaces/:space/jobs/:id Durable embedding job state; worker lease secrets are excluded
POST /spaces/:space/reindex {expected_generation, limit?, cursor?}; page missing-vector jobs with job_ids, examined, next generation, and next_cursor
POST /spaces/:space/grants Owner grants {principal_id, role:"reader"|"writer"|null}; null revokes access
POST /spaces/:space/forget {record_ids} or {source_ids}; whole-space deletion requires {all:true, expected_generation} from its owner
POST /spaces/:space/sources/batch Atomically capture 1–64 sources (1 MiB total), retaining individual retry keys
GET /spaces/:space/export Authorized marina.memory.bundle.v1 snapshot of current records, raw sources and checkpoints
POST /spaces/:space/review {kind?:"all"|"stale"|"competing"|"pending", limit?, cursor?}; premise versions, temporally overlapping competing assertions, and live resolution membership
POST /spaces/:space/reaffirm {id, expected_version, dependency_versions, content?}; explicit reviewed replacement revision; confirms any await_confirmation set the record belongs to
POST /spaces/:space/resolve {id, policy, competing, rationale, valid_time?, deadline_ms?}; audited contradiction resolution — last_writer_wins, evidence_weighted, await_confirmation, keep_both
POST /spaces/:space/cache/delete Exact cache identity; delete only this principal’s reusable result, preserving authored memory
POST /spaces/:space/cache/get {inputs, model, policy}; live-authorized hit or an inspectable miss reason
POST /spaces/:space/cache/put Identity plus {value, records?, sources?, federated?, expires_at}; 1–32 explicit version/hash pins
POST /spaces/:space/acknowledge {keys}; acknowledge 1–100 consumed receipts belonging to the caller
GET/POST /spaces/:space/bundle Export/import the versioned marina.memory.bundle.v2 history envelope
GET /spaces/:space/federation_mounts List aliases configured for the caller’s principal
POST /spaces/:space/federated_search {mounts, query, kind?:"records"|"sources", mode?, limit?, max_bytes?, allow_partial?}
POST /spaces/:space/federated_read {mount, kind:"record"|"source", id, version?, start?, end?}; fresh peer authorization

Memory credentials have a separate audience from world and model credentials. Scopes are memory:read, memory:write, memory:share and memory:export; provisioning currently issues all four. Space grants restrict what those scopes can reach. Reader grants cannot mutate; only the owner can grant access or forget the whole space. API request headers cannot select another identity. Revoke a credential with:

Terminal window
bun run memory revoke --db data/memory.db --credential CREDENTIAL_ID

Credentials expire after 30 days. Sharing a space is an explicit same-instance grant, not a copy or federation. Service records use canonical Marina notes internally but remain isolated from legacy name-based /mem access. New memory api, symbolic human commands and MCP tools reach those service records through the same authorization layer. The full world server exposes the same /v1/memory routes over its database; provision against that DB for external HTTP access. See interface setup. Resident checkpoints and lossy context transforms use these durable APIs. Legacy notes and pools retain their existing interfaces.

Omitting mode always selects lexical retrieval, even when an embedding provider is installed. Only an explicit mode:"hybrid" requests embeddings. /search searches memory records; /source_search searches original sources. A default task plan searches both stores.

Hybrid search combines FTS5 and cosine similarity using reciprocal rank fusion (k=60). It returns current heads, applies scope and record filters, and identifies the embedding model. Lexical search selects at most 200 authorized current candidates through FTS5 before hydrating results, so it does not load every record head and has no record-count ceiling. Optional semantic search streams every eligible vector while retaining the top 200. coverage reports candidate counts and scored/missing/invalid vectors. Semantic work remains exact O(records × dimensions), with bounded JavaScript ranking memory; this is not an approximate-nearest-neighbor index.

Broad synchronous SQLite queries can delay other work; size the deployment from measured workloads and use exact filters where available. The default admission policy allows 100,000 retained revisions. Native history bundles and vocabulary changes have separate documented bounds.

Writes are durable before asynchronous semantic indexing finishes. Wait for the receipt’s job to become ready. Hybrid search fails with 503 retrieval_incomplete if the provider or eligible vectors are unavailable. An explicit allow_degraded:true returns available results with reasons; it does not disguise lexical results as semantic success. After enabling or changing a model, read the space generation, call reindex, and wait for the returned jobs. Reindex scans 1,000 records per page by default (limit 1–10,000). Continue with the returned generation and next_cursor, using a new request key for each page; a changed evidence generation invalidates the cursor. Stop when next_cursor is null. Model identities include preprocessing versions, preventing accidental mixing of incompatible embeddings.

Ranking is lexical-first and reputation-bounded. Within the actor’s own records nothing is weighted by the actor’s standing. For records written by ANOTHER principal (shared, granted or institutional spaces, or a co-writer in your own space) the page is re-sorted after rank fusion by a bounded writer-reputation term — 0.10 × clamp(author_standing / 100, 0, 1), expressed in units of a rank-1 RRF hit — so an established writer can win a near-tie but never outrank a stronger lexical match, and an unknown writer scores exactly as before. Authorship is the principal on the record’s first memory.created event; standing is the civic rollup keyed by the same durable users.id. The helper (applyReputationRerank in src/persistence/db-memory-ranking.ts) returns an inspectable ranking block (weight, standing_ceiling, applied, per-record authors). Legacy pool recall applies the identical term in SQL (REPUTATION_WEIGHT next to SCORE_EXPR). Corroboration is counted over writers, not rows: evidence_weighted resolution counts distinct (content hash, capturing principal) pairs, drops the record author’s own captures whenever another author supports the claim, and weights each independent writer by 0.05 + 0.95 × clamp(standing / 100) — so five fresh accounts (0.25) lose to one writer at standing 40 (0.43) with an independent source. The winner’s resolution.evidence_weights records the weights and the reliability floor.

budget_tokens conservatively limits the UTF-8 bytes of returned evidence text, including its framing and inline citations. This is an upper-bound estimate for byte-based tokenizers, not an exact provider tokenizer or a budget for the entire JSON response/system prompt. Truncated content is identified; the original remains available by record ID. Retrieved text is labeled as evidence and JSON-quoted, but prompt-injection resistance still requires agent-side policy.

Local embeddings use Apache-2.0 Tokenizers.js 0.2.0, MIT ONNX Runtime 1.31.1 (its telemetry switched off before it loads, see the extension’s README), and the Apache-2.0 all-MiniLM-L6-v2 model, pinned at 751bff37182d3f1213fa05d7196b954e230abad9. Tokenizer-checked chunks cover long input before normalized mean pooling; this avoids silently embedding only a prefix. It is a compact baseline, not a claim that MiniLM is the strongest multilingual or long-document model.

An optional Ollama embedding adapter is available via --embeddings ollama --embedding-model MODEL --embedding-revision REVISION --embedding-url URL. The operator must keep that revision identifier aligned with the deployed model. It has not been live-qualified here. No Hindsight, Graphiti or Mem0 backend is installed by this slice.

The world server (bun run start) constructs the same providers from the environment. MARINA_MEMORY_EMBEDDINGS=none|local|ollama|openai (default none) selects the provider; local reads MARINA_MEMORY_EMBEDDING_CACHE / MARINA_MEMORY_EMBEDDING_LOCAL_ONLY, ollama requires MARINA_MEMORY_EMBEDDING_MODEL, MARINA_MEMORY_EMBEDDING_REVISION and optionally MARINA_MEMORY_EMBEDDING_URL, and openai (any OpenAI-compatible /v1/embeddings: the operator’s existing provider or a local server) requires the URL, model and revision, with MARINA_MEMORY_EMBEDDING_API_KEY and an optional MARINA_MEMORY_EMBEDDING_DIMENSIONS. Asymmetric embedders take MARINA_MEMORY_EMBEDDING_QUERY_PREFIX / _DOCUMENT_PREFIX (ollama, openai) and, for openai, _INPUT_TYPE=<query>,<document> (e.g. query,passage); changing the document side re-embeds records. Unset or none keeps both memory silos lexical, and an explicit mode:"hybrid" then fails with 503 retrieval_incomplete (semantic_not_configured) rather than quietly returning lexical results. An invalid value fails on first memory use instead of degrading silently; a local configuration without the installed extension reports embedding_unavailable naming extensions/local-embeddings. Turning embeddings on is evidence-gated: bun run qualify:paraphrase reports paraphrase hit@3 for legacy FTS (pre- and post-porter), vocabulary expansion, durable lexical and durable hybrid on a frozen corpus (benchmarks/paraphrase/). Migration 112 rebuilt the shared notes_fts index with the Porter stemmer, and OR-mode recall queries drop English stop words when a content token remains — both silos benefit because durable records and legacy notes share that index.

Forgetting a source deletes its linked records, their complete revision history, dependent records and vector jobs/index entries in the same transaction. Lineage is cumulative across revisions. Any forgetting invalidates all checkpoints in that space because opaque checkpoint payloads may contain copies. Forgetting just a record leaves its original sources intact.

Clients must declare source_ids and depends_on; the service cannot discover undeclared copies, erase downloaded exports, remote model inputs or backups, or promise forensic erasure of SQLite free pages/WAL. Receipt hashes and identifier-only audit/tombstone rows remain for safe retries. These are logical API deletion guarantees within recorded lineage.

The export endpoint contains current revisions. For bounded history transfers, use portable bundles, which preserve revisions and support atomic import into an empty owned space. Federation supports explicit peer reads; reusable results use exact keys and local evidence pins. These contracts do not provide Mem0 API emulation, automatic extraction, inferred temporal facts, a distributed atomic store, or semantic response caching.

Terminal window
bun run qualify:memory --embeddings none
bun run qualify:memory --embeddings local --model-cache data/memory-models

The harness provisions temporary credentials, runs the Python agent using HTTP only, kills the server with SIGKILL, starts fresh processes, and checks original artifact integrity, checkpoint recovery, retrieval, revisions, bounded context, sharing, revocation and forgetting. It cleans up its temporary database and does not use your memories.

That qualification agent uses a deterministic policy. Use it to check service behavior across restarts. To compare task outcomes from LLM agents, run the utility harness described under sustained qualification with your approved model budget and retain its report privately.

capture preserves a JSON value. Range reads expose string values directly as UTF-8; other values use the exact stored JSON serialization. content_hash identifies the stored JSON; text_hash identifies the range-readable text. Offsets address bytes in utf8-source-text-v1, not characters or tokenizer positions. The default range is up to 16 KiB; explicit ranges may span up to 64 KiB. A split UTF-8 codepoint is rejected. Follow next_start until null and send text_hash to detect a changed representation. Sources are immutable until explicitly forgotten. Source search returns bounded excerpts and IDs; read ranges to inspect complete evidence.

const matches = await client.sourceSearch(spaceId, {query: "incident Kestrel", match: "all"});
const hit = matches.results[0];
if (hit) {
const page = await client.sourceRange(spaceId, hit.id, {start: 0});
console.log(page.text, page.next_start, page.text_hash);
}

A space starts at vocabulary version 0 with an open predicate set. Owners can publish a versioned contract; writers can pin expected_vocabulary_version to reject a stale vocabulary. Each predicate declares an object type (entity, string, number, boolean or null) and cardinality (one or many). A closed vocabulary rejects unknown predicates. Updating a vocabulary validates existing active assertions; online validation is capped at 10,000 assertions.

await client.saveVocabulary(spaceId, 0, {
closed: true,
predicates: {status: {object: "string", cardinality: "one"}},
});
await client.remember(spaceId, {
content: "River was active during the first phase.",
claim: {subject: "project:river", predicate: "status", object: {kind: "literal", value: "active"}},
valid_time: {from: 100, until: 200},
expected_vocabulary_version: 1,
});
const at150 = await client.query(spaceId, {subject: "project:river", predicate: "status", valid_at: 150});

Valid time uses half-open intervals [from, until) in nonnegative UTC milliseconds; null bounds are unbounded. query and graph accept valid_at. Record search (and context, which uses it) excludes records whose validity has ended — a tombstone revise (note delete, a retired lesson) or a resolve loser — before ranking, so a retired record never takes a result slot; valid_at: T serves the records valid at T instead (the same [from, until) test as query), and include_ended: true is the explicit history read that ranks every active record regardless of validity (it can’t be combined with valid_at). query/graph without valid_at stay unfiltered exact reads; task retrieval passes its valid_at to every step, search included. A cardinality-one predicate rejects different objects whose intervals overlap; adjacent intervals are allowed. It reports conflicts without choosing a winner. This describes assertions, not verified truth. Current queries use current revisions; explicit get(..., version) preserves historical attributes. There is no global transaction-time/as-of query, rule engine or inferred ontology. For temporal questions, use valid_at rather than expecting an LLM to choose an interval from text-search results.

“What was true at T?” is two different questions, and the service answers each with the existing contract rather than a second timeline:

  • Valid time — what the space currently asserts held at instant T: query/graph with valid_at: T. Superseded assertions whose interval was closed by a resolution still answer for the instants they covered; they are never deleted, only bounded.
  • Transaction time — what a record said as of an earlier write: get(id, version). Every revision, including the ones resolve writes, is a new version; the previous version keeps its own valid_time, claim and metadata. There is no space-wide as_of filter on query/ search: it would have to reconstruct every head at T, which the versioned store does not index, so the version-based path is the supported one and a filter is deliberately not faked. (search’s valid_at is valid time over current heads, not transaction time.)
const plan = await client.plan(spaceId, {task: "Aster migration approval"});
console.log(plan.steps, plan.assumptions, plan.budget);
const evidence = await client.executePlan(spaceId, plan);

Default planning is deterministic keyword retrieval, with no model call. Explicit caller steps can combine exact query, graph, record search and source_search. Unknown operations and unsupported fields are rejected. Plans contain up to eight read steps, with up to 20 results per step and a total limit of 100 evidence items. max_bytes bounds serialized evidence items (256–131,072 bytes), not the entire response envelope. Traces expose inputs, evidence and truncation. answer_sufficiency:"not_assessed" explicitly leaves answer evaluation to the agent. Evidence, vocabulary or access changes make the plan stale and require replanning. Checkpoint-only writes preserve new plans carrying retrieval_generation.

To ask Marina’s existing model router to generate the read plan, configure the memory server. Set MARINA_MEMORY_PLANNER_TOKEN to an authorized model-router credential when required.

Terminal window
export MARINA_MEMORY_PLANNER_URL=http://127.0.0.1:3300/v1
export MARINA_MEMORY_PLANNER_MODEL=marina
bun run memory serve --db data/memory.db --embeddings none

Then pass use_model:true to plan. Only the operator selects the router URL/model/credential. The planner sends the task and authorized vocabulary, not stored source bodies. It makes a bounded model request, validates the returned plan, and pairs text discovery across both records and sources. Model errors remain errors; there is no silent downgrade. Permissions and generation are checked again after model work and between execution steps. Model planning can incur the router’s normal inference cost. It does not perform writes or answer the task.

depends_on binds a conclusion to the current revision of each declared premise. Supply dependency_versions: {RECORD_ID: VERSION} to pin the revisions you actually read; a racing change rejects the write. Correcting a premise atomically marks its direct and transitive current dependents freshness: "stale". Their original contents, ownership and history remain available. Default query, graph, search and context retrieval exclude stale conclusions. Use include_stale: true for review, or get a known record directly. freshness: "current" means its declared premises have not changed; it is not a truth or trust certification.

A text-only revision does not clear stale status. After reviewing the evidence, explicitly supply all current dependency_versions when revising the conclusion. Revalidate upstream premises first. Removing depends_on explicitly asserts independent support; historical lineage still controls forgetting. Older dependencies with no recorded revision bindings require review after migration. No model automatically corrects or reaffirms conclusions. Competing assertions are settled the same way — through explicit, audited resolve revisions — never by a background merge.

const premise = await memory.get(space, premiseId);
const conclusion = await memory.get(space, conclusionId);
await memory.revise(space, conclusion.id, conclusion.version, {
content: "Updated conclusion based on the reviewed evidence.",
depends_on: [premise.id],
dependency_versions: { [premise.id]: premise.version },
});

New plans and query cursors carry retrieval_generation. Evidence, assertions, vocabulary, permissions and forgetting invalidate it; checkpoint saves and reindex requests do not. The existing generation still tracks all service mutations. Old plans/cursors without the new marker retain the stricter generation check. Every execution rechecks live authorization.

For bursts, use TypeScript captureBatch, Python capture_batch, or generic MCP operation capture_batch, with items: [{content, key, session_id?}]. The whole batch is atomic. Keep both batch and item keys stable when retrying; individual receipts survive regrouping.

The TypeScript SDK exports opt-in retryMemoryOperation. Build the exact request and mutation key outside its callback. It defaults to five attempts for timeouts, network failures, 408/429/502/503/504, with bounded backoff and service Retry-After support. It does not retry permission denials or version conflicts. Residents use this helper internally. Retry exhaustion surfaces the failure; it never counts as successful persistence.

import { retryMemoryOperation } from "marina/memory";
const key = crypto.randomUUID();
const items = [{ content: originalToolOutput, key: `${key}:source` }];
await retryMemoryOperation(() => memory.captureBatch(space, items, key));

Residents journal completed user, assistant and tool-result messages privately through the same authenticated service, awaiting acknowledgement before the runtime advances. Journal manifests link to previous manifests; read checkpoint.data.journal.manifest_source_id to start navigating. Compaction also preserves the original transcript before shrinking context. The source cursor advances at archival, so later journal evidence remains replayable. Explicit compaction pool configuration still shares only its summary. Storage failures retain local context and fail the current run; discarded checkpoints require restart before local re-archival. This does not make external tool side effects transactional: a tool can act before its result is captured, and unfinished streaming output is not a completed-message receipt.

Both standalone memory and the normal world entry point use SQLite synchronous=FULL by default. MARINA_DB_DURABILITY=normal is an explicit world-server tradeoff for fewer syncs; it weakens the power-loss guarantee. Hardware and filesystem behavior still matter. See SQLite synchronous semantics.

Back up the whole database, including any world data and credentials, using operator CLI access. This is not a scoped memory API export. Snapshot files are private (0600), verified with integrity and foreign-key checks, hashed, synced, and atomically published at a new path. A live WAL database is supported through SQLite VACUUM INTO.

Terminal window
bun run memory backup --db data/memory.db --output /secure-backups/memory-001.db
bun run memory restore --backup /secure-backups/memory-001.db --db data/restored-memory.db
bun run memory serve --db data/restored-memory.db --embeddings none

Restore always creates a new database; it refuses to overwrite an existing destination. The JSON receipt includes SHA-256, byte size and schema version. Test the restored instance before changing the deployment’s database path. Restores recover the snapshot’s point-in-time credentials and content: later revocations and forgetting must be reapplied when appropriate. A process killed during backup can leave a private .marina-snapshot-* staging directory; an incomplete file is never published as the requested destination. Operators own retention, encryption, off-host copies and cleanup of abandoned staging directories. Health checks confirm a schema read succeeds; they do not certify writable capacity or power-loss protection.

Reproduce process recovery and lost-receipt tests with:

Terminal window
bun run qualify:memory:reliability --cycles 100 --output /tmp/marina-memory-recovery.json

GET /v1/memory/usage, TypeScript/Python usage(), generic MCP {operation:"usage"}, and in-world memory usage report the authenticated principal’s owned-space totals, configured limits and over_limit dimensions. A shared writer consumes the space owner’s budget; usage never reveals another owner’s private totals. Inspecting usage does not create a resident space.

Migration 105 adds rebuildable accounting projections and backfills existing memory. Limits apply to both world and standalone entry points. Configure positive safe integers in the environment and restart, or pass memoryLimits when constructing MarinaDB:

Setting Default Counted scope
MARINA_MEMORY_MAX_BYTES 1,073,741,824 Logical UTF-8 payload bytes plus row allowances
MARINA_MEMORY_MAX_SOURCES 100,000 Retained original source rows
MARINA_MEMORY_MAX_REVISIONS 100,000 All retained record revisions, including superseded revisions
MARINA_MEMORY_MAX_SPACES 256 Active owned spaces

Logical bytes include original source JSON, record revisions and attributes, current checkpoints, vocabulary versions, operation receipts/events, grants, optional index jobs and vectors. Row allowances cover bookkeeping approximately. Retry receipts are retained and charged, including receipts in forgotten spaces. Replacing a checkpoint can grow usage even when its current payload has the same size. There is no automatic TTL, history pruning, or model-selected eviction.

A growing write that exceeds a dimension fails with 507 quota_exceeded; its content, receipts, events and accounting roll back together. Atomic batches roll back in full. Same-key receipt replays consume no additional budget. Existing over-budget data stays readable after an operator lowers limits. Explicit forgetting, cache deletion and revocation remain admitted even when their audit receipts increase usage; these exceptions mean the budget is not an absolute ceiling. Existing SQLite pages, FTS indexes, WAL, other world tables and backups require separate deployment disk quotas, monitoring and retention. Forgetting does not necessarily shrink the physical database file.

Error HTTP Recovery
storage_busy 503, Retry-After: 1 Bounded same-key retry after contention clears
quota_exceeded 507 Inspect usage; explicitly forget appropriate data or raise the owner’s configured budget
storage_full 507 Operator restores capacity before retrying the same request
storage_read_only 500 Operator repairs write access
storage_io_error 500 Operator investigates storage; preserve the original key for receipt recovery
storage_corrupt 500 Operator verifies storage and performs a controlled restore

Fault classification uses real SQLite result codes, not error-message text. Generic failures never echo SQL or source content. The SDK does not automatically retry 500 or 507. A lost response or cancellation cannot prove that a write failed; after recovery, replay the exact payload and original idempotency key. Optional vector admission failures retain a pending job with error:"quota_exceeded"; the existing bounded retry policy eventually marks it failed. After raising capacity, a failed job needs an explicit reindex request. Original memories remain usable without vectors.

Use a per-operation TypeScript client view and pass the same signal to the retry helper:

const controller = new AbortController();
const operation = memory.withSignal(controller.signal);
const key = crypto.randomUUID();
const payload = { tool: "test", result: "original result" };
const pending = retryMemoryOperation(
() => operation.capture(space, payload, "task:123", key),
{ signal: controller.signal },
);
// Attach your caller's usual error handling before cancelling.
controller.abort();
await pending; // Rejects with the cancellation reason.

withSignal leaves concurrent users of the base client unaffected. Cancellation stops local fetch/body waits, index polling and retry backoff, including non-cooperative custom transports. The memory-only MCP bridge forwards protocol cancellation to HTTP. Incoming HTTP requests check cancellation while reading bodies and waiting on query-planning or optional semantic providers. A cancelled optional query does not silently return degraded evidence. Cooperative configured providers receive the signal; synchronous SQLite work and already-sent commands are not preempted or rolled back by an abort.

Residents pass the runtime signal through completed-message journals and the compaction archival barrier. Aborting a stalled capture prevents the next model call and keeps original local context; a cancelled queued journal will not start later. WebSocket memoryService(request, timeoutMs, signal) cancels its local response wait and removes listeners. World MCP commands already queued in the engine may still run. The synchronous Python SDK retains its existing timeout behavior; it does not expose AbortSignal cancellation.

Cancellation is not a rollback receipt. A request sent before cancellation can still commit. Keep mutation keys outside retry callbacks and preserve them until the remote outcome is known. Cancellation does not make external tools transactional or retract already exported evidence.

review returns the record, source IDs, declared premise IDs with pinned/current versions, and competing assertions with overlapping half-open validity intervals. It does not decide which assertion is true. A cursor is valid only while the evidence/access generation is stable. Resolve upstream premises first; reaffirm requires the revision you reviewed and every current premise version, including {} for a conclusion with no premises. Racing changes return 409.

const page = await memory.review(space, { kind: "stale" });
for (const item of page.items) {
console.log(item.record, item.premises, item.competing_records);
// Read the indicated sources and premises before explicitly submitting a revision.
}
await memory.reaffirm(space, conclusionId, reviewedVersion, reviewedPremiseVersions,
"The conclusion supported by the reviewed evidence.");

Humans can use memory review, memory show ID, memory source ID START END, and memory reaffirm ID VERSION JSON_PINS. Full JSON retains provenance and continuation cursors. Python exposes review and reaffirm; generic MCP uses the same operation names through Marina’s existing authenticated, rate-limited command path.

review reports competing assertions — same subject and predicate, different objects, overlapping half-open validity — and deliberately does not pick a winner. resolve is the explicit, audited decision. It targets one head record and names its rivals:

await memory.resolve(space, parisId, {
policy: "last_writer_wins", // or evidence_weighted | await_confirmation | keep_both
competing: [berlinId],
rationale: "Facilities confirmed the move on the 3rd.",
}, "office-move-1");
Policy Effect
last_writer_wins The most recently revised member becomes the winner. Every other member gets an ordinary revision closing valid_time.until at the winner’s valid_from (or now; valid_time.from in the input overrides the cutoff), never extending an interval or producing an empty one, and is marked superseded in the review index.
evidence_weighted The member with the most independent supporting sources wins — distinct content_hash values among its current source_ids, excluding legacy-note twins (session_id: "legacy-notes"), assistance request envelopes and anything citing a marina-memory:// identity; ties fall back to recency. Losers are handled as above; the result and the winner’s metadata.resolution carry evidence_counts.
await_confirmation Nothing changes. The set is listed under review kind pending (with the resolution membership and optional deadline, from deadline_ms) until a later resolve supersedes it or a reaffirm of any member confirms it. The pair stays under competing meanwhile, because it is still a contradiction.
keep_both The conflict is irreducible: every member stays current, each gets metadata.qualified_by naming the others and the rationale, and review stops flagging the pair. A new rival is still flagged against both.

Resolutions are revisions, not deletions: losers stay readable by id and by valid_at for the instants they still cover, get(id, version) shows the open interval they had before, and the winner’s metadata.resolution records {id, policy, status, competitors, evidence_counts?}. Because each touched record is revised, conclusions that pinned it are marked stale exactly as after any correction — a contested premise deserves a second look; reaffirm them with the new version. Every call appends one row to memory_resolutions (actor, time, policy, inputs, outputs, rationale, request key) and is idempotent per Idempotency-Key: the same key with the same input replays the receipt, a different input returns 409 idempotency_conflict. Records must be active members of one subject/predicate (409 not_competing otherwise).

Authorization is the ordinary space-writer check (owner or writer grant; readers and strangers get 404, read-only scopes 403). An assistance helper cannot resolve: the lease admits only the read operations, so a resolve under assistance read returns assistance_read_only — helpers propose, owners decide. Forgetting a member of a pending set retires that set; an applied resolution is never undone by forgetting, so a superseded loser is not resurrected when its winner is forgotten.

Humans use memory resolve ID POLICY {"competing":[IDs],"rationale":"..."} and memory review {"kind":"pending"}; Python exposes resolve(record_id, policy, competing, rationale, key=None, **options); generic MCP uses operation resolve through memory_service. GET /v1/memory reports the policies under contradiction_resolution.

Reusable results are explicit and scoped to the calling principal in a space. They are stored separately from authored memories and checkpoints, charged to the space owner’s byte budget, and excluded from portable memory bundles. inputs, immutable model identity, and policy identity form an exact cache key. Pin 1–32 current record versions and/or source content hashes; expires_at is an absolute UTC millisecond expiration. Entries are bounded to 64 KiB, with 32 KiB inputs. Empty pin sets are refused.

const identity = { inputs: { task: "validate build", revision: "abc123" },
model: "router:model@revision", policy: "validation-v2" };
await memory.cachePut(space, { ...identity, value: { passed: true },
records: [{ id: evidence.id, version: evidence.version }],
expires_at: Date.now() + 3600000 });
const cached = await memory.cacheGet(space, identity);
if (cached.hit) console.log(cached.value);

Every read checks live authorization, expiration, evidence generation and declared pins. Corrections, vocabulary/access changes and forgetting invalidate reuse conservatively; forgetting also deletes stored cache values in that space. Checkpoint/cache-only writes do not invalidate evidence. Expired values remain charged until replaced, deleted with cacheDelete (Python cache_delete, MCP cache_delete), or removed by explicit forgetting; deletion preserves authored sources and other principals’ cached results. There is no automatic source eviction. Include time, locale and external-tool version assumptions in inputs/policy. The cache does not certify a result’s truth or memoize external side effects. Its pins are local; federated results require fresh remote reads.

note, recall, reflect, skill, pools and /mem are compatibility adapters into the same durable record history. Their numeric IDs remain supported; new integrations should use /v1/memory and versioned record IDs.

Numeric operation Canonical behavior
Create, claim, skill store/import/compose, pool add Commit a record and an empty numeric address in one transaction
Correct/evolve Revise with CAS; retain the predecessor address as a historical version
Source/derive Capture provenance and revise the record; self-derived references never become independent evidence
Verify/resolve Append verification audit and the canonical verdict atomically
Link/unlink Create or close a typed relation between records
Delete/consolidate Retire the record with closed validity; preserve history and mark dependents stale
Reflect adopt Give the adopted record a numeric address without creating a second record
Pool ratify Publish an independently authorized institutional assertion

Native edits are immediately visible through numeric references. Explicit durable forget erases record history and numeric addresses. Failed writes roll back; no background bridge, retry queue or backfill is required. Migration 138 converts old data and pending intents atomically while preserving existing IDs. Core key-value beliefs and process journals keep their separate semantics. Source URLs remain provenance and cannot establish a write binding. Creating a human account never claims an accountless namespace’s system-owned durable space.

Related commands address different memory semantics. memory kv … is the per-entity key-value belief store (memory kv set pace fast is the agent tick rate); the bare memory set/get/delete/list/history spellings still work and memory list prints a one-line hint pointing at the durable side.

You want to… Verb Store / cost
find your own notes by keyword recall <q> numeric record view, FTS-ranked, no model call
filter durable records exactly memory query <JSON> ({} lists) durable service, symbolic
pull everything on a topic, no synthesis recap <topic> notes + pools + chronicle, no model call
get a synthesised answer ask <question> model call over notes + guide + pools + world search
add web evidence to what you know dig <topic> notes + web, optional synthesis
deposit into a shared pool share <pool> <text> ≡ pool <pool> add <text> canonical record with pool-scoped numeric address
mark something checked note verify <id> … (legacy note) · memory reaffirm <ID> … (durable record, re-pins premises) · skill verify <name> (skill package) three different objects

Portable history and compatibility imports

Section titled “Portable history and compatibility imports”
const bundle = await memory.exportBundle(space);
await destination.importBundle(emptyOwnedSpace, bundle, "transfer-001");

Bundle v2 preserves portable record/source IDs, structured source bodies, Unicode source ranges, revision attributes, stale state, vocabulary versions and checkpoints. Destination import is atomic, owner-only, and requires an empty space. Existing IDs, including forgotten record tombstones, cause a collision error instead of silent merging or resurrection. Checkpoint source cursors are mapped to their destination sequence numbers; opaque data is preserved without rewriting embedded application-specific space IDs. Original timestamps describe the supplied history, not an authenticity guarantee. Imported assertions remain unverified.

The envelope and original bodies have SHA-256 checksums. Canonical envelope JSON recursively sorts object keys by JavaScript UTF-16 code-unit order, preserves array order, and uses JSON.stringify number/string encodings without Unicode normalization. memoryPortableDigest is the public implementation. A checksum detects corruption; authorization and explicit source provenance establish who may import. Invalid attributes, missing references, cyclic current dependencies and missing historical vocabulary versions roll back the whole import.

Online bundles are bounded to 1.5 MiB, 2,000 records/sources, and 2,000 versions per record. Oversize exports fail explicitly. Use scoped paginated reads for application-specific transfers, or operator snapshots for larger exact database transfers. Credentials, grants, receipts, indexes and cached outputs are not part of portable history; the importing owner establishes new access grants. Explicit exports are independent copies: revocation or forgetting at the origin cannot retract already exported data.

translateMemoryExport(format, raw, {origin, imported_at}) in the fetch-only TypeScript SDK converts two named formats to a native bundle and returns an explicit losses report:

  • mcp-knowledge-graph-v1: {entities, relations} from the MCP reference memory server. Entities, observations and directed relationships become explicit records/claims. The complete supplied export remains an original source. Reference format.
  • langgraph-items-v1: an array of {namespace: string[], key, value} items. Namespace/key identity and values are preserved. This is item import, not a BaseStore, checkpoint, batch, TTL, or vector API replacement. LangGraph store contract.

Import time is explicitly labeled when source history is unknown. No original revision history, authorization or dependency semantics are invented. These adapters are original Apache-2.0 Marina code and add no runtime package dependency.

Set MARINA_MEMORY_FEDERATION_CONFIG to an operator-owned JSON array of mounts and restart:

[{"owner_principal_id":"LOCAL_PRINCIPAL","alias":"research",
"url":"https://peer.example","space_id":"PEER_SPACE","token_env":"RESEARCH_MEMORY_TOKEN"}]

Supply the peer token through deployment secret configuration. Mounts bind to a local principal; callers cannot provide arbitrary URLs or choose another principal. The peer receives its configured credential. Local caller credentials are never forwarded. Up to eight mounts per principal may be selected explicitly per query:

const evidence = await memory.federatedSearch(space, {
mounts: ["research"], kind: "sources", query: "migration approval",
});
const original = await memory.federatedRead(space, {
mount: "research", kind: "source", id: evidence.results[0].origin.id,
});

Record ranking combines peer ranks, retaining mount, space, record ID and version. Source queries remain lexical and return source hashes/excerpts for follow-up range reads. Result counts/bytes are bounded, and truncation is explicit. A selected peer’s failure fails the query by default; allow_partial:true returns failures and incomplete:true. Local access and mount identity are checked again after network waits. Every new peer request uses live peer authorization, so future reads observe revocation and deletion. No source is automatically replicated, and no distributed atomic snapshot or retraction of already consumed evidence is promised.

Backup rotation, receipt retention and sustained qualification

Section titled “Backup rotation, receipt retention and sustained qualification”

Migration 106 adds acknowledged/retired request markers, a stale-review index, and separately accounted principal-scoped cached results. Existing migrations are unchanged. Backup and restore include this state; ordinary memory bundle imports do not import grants or cached outputs.

Terminal window
bun run memory rotate-backups --db data/memory.db --directory /secure-backups/memory --keep 7

Rotation first publishes and verifies a new snapshot and durable manifest, then prunes only verified managed snapshots for that same source path. Unrelated files, invalid manifests and corrupted snapshots are preserved and reported as skipped. Concurrent rotation is refused by an exclusive lock. After a crashed operator process, inspect the lock’s PID/run before removing a stale lock. Snapshots remain point-in-time copies; reapply later revocations/forgetting after a restore.

An agent may call acknowledge(space, keys) only after consuming those outcomes. The operator can preview and apply bounded compaction of acknowledged receipts:

Terminal window
bun run memory compact-receipts --db data/memory.db --before UTC_MILLISECONDS --limit 1000
bun run memory compact-receipts --db data/memory.db --before UTC_MILLISECONDS --limit 1000 --apply

Unacknowledged receipts are never selected. Compaction keeps key/fingerprint tombstones permanently: a late retry receives 410 receipt_retired and never executes the mutation again. A different payload still returns an idempotency conflict. This releases logical payload bytes, not necessarily filesystem space. Tombstones and audit history still consume space; there is no automatic TTL.

Reproduce qualification with disposable data:

Terminal window
bun run qualify:memory:storage /tmp/memory-storage.json
bun run qualify:memory:scale 1000000 /tmp/memory-scale.json
bun run qualify:memory:sustained --directory /tmp/memory-48h --duration-ms 172800000
bun run qualify:memory:utility --offline --repetitions 1 --output /tmp/memory-protocol.json

The Linux storage drill requires user/mount namespaces, mount tools and a C compiler. It exhausts only a private 32 MiB tmpfs, tests read-only startup refusal, and injects EIO at the libc write/sync boundary. It does not simulate damaged hardware or controller power loss. The sustained harness records actual elapsed runtime, completed cycles and errors in status.json; it never substitutes an accelerated clock for days of observation. It exercises real resident journals/compaction and clean server restarts with deterministic messages, without LLM calls. Resume requires the same harness/duration; inspect stale locks after a crash. Keep its disposable database/report for review.

The utility harness has twelve synthetic structured tasks, balanced condition order and repeated fresh HTTP-only agents. It records exact outcome/citation/abstention/correction scores, functional retry-configuration checks, latency, tokens and estimated cost. The harness seeds memories; the agents choose read operations and answers. It does not test agent-authored memory, actual repository edits, or multi-day LLM work. Live runs require an explicit --budget-usd and configured OpenAI credentials. The default is gpt-5.6-luna, using no reasoning effort for these short retrieval tasks. Historical GPT-4o-mini and GPT-4.1-mini snapshots remain selectable. All run through Marina’s router:

Terminal window
bun run qualify:memory:utility --repetitions 3 --budget-usd 1 --output /tmp/memory-utility.json

--model-cache EXISTING_CACHE adds the optional embedding condition without downloading a model. The gateway reserves a conservative cost bound before each actual upstream attempt, including retries and Luna’s cache-write input premium. Luna uses max_completion_tokens; historical models use max_tokens. Both are capped at 500. The Luna model catalog currently lists the model ID without a dated snapshot, so reports label that distinction and record returned model IDs. Reports include model/pricing identities, source hashes, task traces and expected evidence IDs, which are never sent to the agents. --offline proves protocol/grader execution only; it is not LLM task evidence. Keep internal qualification reports outside the public checkout.

Citation scoring accepts record/source IDs returned by tools, including a record’s explicit source_ids. It ignores IDs embedded in metadata or source bodies. Returned provenance establishes citation identity; it does not establish that the agent read the source body or that every sentence is entailed by it. Exact answer, current supporting citation and retry-functionality checks remain separate. To correct citation-availability grading in an older saved report without making model calls or modifying its original responses:

Terminal window
bun run scripts/research/memory-utility-regrade.ts --input /tmp/original.json --output /tmp/regraded.json

The output must be a new file. It retains prior citation grades and records the original report’s hash and the scorer’s hash. Task/prompt changes require a new experiment; do not silently regrade formatting failures as successes.

Use --agent-protocol v2 for the experimental structured-answer agent. It accepts the requested JSON value directly in the answer envelope and separates malformed model envelopes from memory service errors, with bounded repair turns. Reports preserve intermediate model replies and protocol errors for inspection. v1 remains the default for reproducing the original prompt and behavior. The graders and task fixtures are identical across protocols; report protocol comparisons as new experiments. Valid JSON alone does not prove that the agent retrieved evidence or answered correctly.

Validate answers against evidence you actually read

Section titled “Validate answers against evidence you actually read”

The TypeScript entry point marina/memory exports validateMemoryAnswer, collectMemoryEvidence, createMemoryCitation and the optional model-neutral runMemoryTask loop. These helpers run in the caller. They require no embedding provider or model package.

import {
collectMemoryEvidence, createMemoryCitation, validateMemoryAnswer,
type MemoryAnswerContract,
} from "marina/memory";
const contract: MemoryAnswerContract = {
schema: {
type: "object",
properties: { count: { type: "integer" } },
required: ["count"],
additionalProperties: false,
},
evidence: "required",
};
const range = await memory.sourceRange(spaceId, sourceId);
const evidence = collectMemoryEvidence(range, spaceId);
const citation = createMemoryCitation(evidence[0]!, "The corrected count is 17.");
const checked = validateMemoryAnswer(contract, {
status: "answered", answer: { count: 17 }, citations: [citation],
}, evidence);
if (!checked.ok) console.error(checked.errors);

Supply authenticated read results to collectMemoryEvidence, never model output or arbitrary documents. Source search excerpts, write receipts and a record’s source_ids do not count as source reads. Source citations pin the space, ID, text hash and exact returned UTF-8 range; record citations pin the space, ID and version. Quotations must occur in the witnessed text. createMemoryCitation copies those fields for a quotation the caller explicitly selects.

The schema subset supports string, boolean, null, finite number, safe integer, homogeneous arrays and objects with properties, required and additionalProperties:false. description is optional. Unsupported keywords are rejected; there is no coercion. Schema nesting is limited to 12 levels. Historical/stale record witnesses require explicit allow_historical:true. Validation checks shape and quotations; it does not establish entailment, resolve competing claims, reauthorize a previous read or detect concurrent changes after it. Reread evidence when current state matters.

runMemoryTask takes a task, space, contract, an operation allowlist, a next(messages, signal) model callback and a dispatch(request, signal) memory callback. It binds operations to the declared space, generates a mutation key, retains replies and traces, and permits bounded repair. Use runMemoryOperation for HTTP dispatch; retry the same request/key with retryMemoryOperation. The loop marks older witnesses historical after observing a newer revision. It distinguishes answered, explicit abstained, exhausted, error and cancelled; only the first two have a completion. Cancellation stops local waiting and does not undo a mutation already committed.

See the native-function caller for a complete OpenAI-compatible example and its resident WebSocket variant. Native functions expose actual operations to the model; the portable loop also works with callers that return JSON envelopes. For resumable work, explicitly ask the successor to read its named checkpoint, read original sources, preserve a correction, revise using the observed version and save the next checkpoint. Verify required mutations and executable outcomes separately from the answer contract.

These tools use disposable services and require an explicit output directory. Live tools require a spending ceiling and locally configured provider credentials; never put provider keys in prompts.

Terminal window
bun run qualify:memory:workflow --directory /tmp/memory-workflows --budget-usd 2
bun run qualify:memory:resident --directory /tmp/memory-resident --budget-usd 2
bun run qualify:memory:clients --directory /tmp/memory-claude --client claude --budget-usd 1
bun run qualify:memory:clients --directory /tmp/memory-codex --client codex --budget-usd 1
bun run qualify:memory:load --directory /tmp/memory-load --tenants 16 --operations 40

Workflow qualification compares fresh agents with memory, without memory and with direct source context, then checks long sources, graph/vocabulary/time queries, competing claims, multilingual queries and distractions. --suite lifecycle|retrieval selects a subset. Resident qualification runs the real LeanAgentAdapter in fresh processes and inspects durable checkpoints and journals. Client qualification runs installed Claude Code or Codex with temporary MCP settings and tests the resulting file independently. --task marina-sdk uses a copy of Marina’s citation module. The load test records latency including retries, tenant isolation, rate limiting and recovery of writes whose callers cancelled after commit. Reports state the tested scope and remaining limits.

For headless Codex, approval_policy="never" does not itself approve MCP operations. Configure the named server/tool approval mode intentionally for your credential’s authorized scope. The qualification harness approves its disposable Marina server only; it leaves global settings alone.

Marina’s durable memory is text, evidence, typed claims and versioned state. Embeddings are optional indexes. Exact symbolic queries and graph traversal work with --embeddings none, without model downloads or inference. The same operations are reachable from TypeScript, MCP, a portable skill and world commands.

Build the package with bun run build:memory. In this checkout or a package containing that build, marina/memory exports a fetch-only client and public TypeScript types. It runs under Node, Bun and browser bundlers with fetch and AbortSignal.any/timeout support. This source change has not been published to npm. Keep server credentials in server code; a browser client must receive its own appropriately scoped credential and have network/CORS access.

import { MarinaMemoryClient } from "marina/memory";
const memory = new MarinaMemoryClient(url, token);
const evidence = await memory.capture(spaceId, {tool: "test", result: "3 pass"}, "task:123", "evidence-1");
const saved = await memory.remember(spaceId, {
content: "The test suite passed for this revision.",
claim: {subject: "task:123", predicate: "test:status", object: {kind: "literal", value: "passed"}},
source_ids: [evidence.id],
}, "status-1");
const results = await memory.query(spaceId, {subject: "task:123", predicate: "test:status"});
await memory.remember(spaceId, {
content: "Task 123 belongs to Marina.",
claim: {subject: "task:123", predicate: "project", object: {kind: "entity", id: "project:marina"}},
}, "task-project-1");
const graph = await memory.graph(spaceId, {subject: "task:123", max_depth: 2});
await memory.saveCheckpoint(spaceId, "work", 0, {next: "review", record: saved.id}, evidence.seq, "checkpoint-1");

Query filters are conjunctive and exact. 1, "1", true, null, and an entity named "1" are distinct objects. Symbols are case-sensitive, without stemming, alias resolution or Unicode normalization. Use stable namespaced IDs shared by your applications. Numbers use JSON’s JavaScript numeric representation; use strings for identifiers and exact large integers.

A query page contains records, generation and next_cursor. Evidence or access changes invalidate existing cursors with 409 query_changed; restart to avoid silently mixing states. Checkpoint-only saves do not invalidate new cursors. Graph paths contain record IDs, and each edge contains the full current record. truncated means at least one reachable assertion was omitted by the edge or depth budget. The boundary is checked, so a terminal node or fully visited cycle does not produce a false flag.

For a question or task, use one bounded retrieval call:

const result = await memory.retrieve(spaceId, {
task: "deployment rollback procedure",
max_results: 6, max_bytes: 8192, source_bytes: 2048,
});
for (const item of result.evidence) {
if (item.kind === "source") {
console.log(item.id, item.text_hash, item.start, item.end, item.text);
} else {
console.log(item.id, item.version, item.content);
}
}
console.log(result.diagnostics);

retrieve combines inspectable planning, lexical/symbolic discovery and original source reads. It needs no embedding or model call by default. It searches captured originals even when no summary or authored record exists, then returns UTF-8 windows near the search matches. Source IDs, hashes and byte ranges can be verified with sourceRange and quoted by runMemoryTask. Pass steps for a custom read program; use_model:true instead requests the configured planner.

The default budgets are 6 evidence items, 8192 serialized evidence bytes and 2048 text bytes per source. Limits are 20 items, 65536 evidence bytes and 8192 bytes per source. Metadata, plans and diagnostics are outside max_bytes. status distinguishes evidence, empty and budget_exhausted; truncated and diagnostics.next_actions explain omissions. One sparse all-term source search may be supplemented by matching any term; set broaden:false to disable this and inspect diagnostics.broadened before using matches. This helps when a recent journaled question matches more query words than the older answer. Phrase and symbolic constraints are never broadened. This does not provide automatic semantic paraphrase recall.

Records must be current and valid at valid_at (UTC milliseconds, default request time). Pass time at the top level; it applies to every symbolic step. Original documents remain readable historical evidence and may contain conflicting or obsolete assertions. Retrieval does not certify relevance, truth, completeness or answer sufficiency. A 409 plan_changed requires a fresh call; evidence is not returned from a partially invalidated plan.

Provision and start the memory service; no world login is needed:

Terminal window
bun run memory init --db data/memory.db --name coding-agent --credentials data/coding-agent.json
bun run memory serve --db data/memory.db --embeddings none

The stdio bridge uses only the HTTP URL and a scoped memory credential:

Terminal window
bun run scripts/memory-mcp.ts --url http://127.0.0.1:3301 --credentials /absolute/path/to/data/coding-agent.json

It exposes memory_workflow, memory_retrieve, memory_service, memory_assist, memory_remember, memory_query and memory_graph. Start with memory_retrieve arguments {task:"deployment rollback procedure"} for citable evidence. The generic service tool accepts {operation, space_id?, id?, input?, key?}. Its operations are the MEMORY_OPERATIONS list in src/sdk/memory-operations.ts, the same set the HTTP client offers:

  • identity and spaces: me, spaces, create_space, space, capabilities, usage, grant
  • records: remember, get, revise, query, join, graph, knowledge_graph, search, context, forget, adopt
  • evidence: capture, capture_batch, sources, source_headers, source_search, source_range
  • retrieval and planning: retrieve, retrieve_cached, plan, execute_plan, workflow, vocabulary, save_vocabulary
  • rules and stores: json_store, save_rule, run_rule, materialize_rule
  • checkpoints and jobs: checkpoint, save_checkpoint, capture_checkpoint, job, reindex
  • review: review, reaffirm, resolve, acknowledge
  • cache: cache_get, cache_put, cache_delete
  • assistance: assist_create, assist_jobs, assist_get, assist_claim, assist_heartbeat, assist_read, assist_finish, assist_cancel, assist_delegate
  • export and transfer: export, export_page, export_bundle, import_bundle, transfer_begin, transfer_status, transfers, transfer_page, transfer_commit, transfer_abort
  • federation: federation_mounts, federated_search, federated_read, federated_retrieve

id is the record, checkpoint name or job ID as appropriate; input is the HTTP body, or GET options such as version, after, limit. Capture uses input: {content, session_id?}; checkpoint writes use input: {expected_version, source_cursor, source_ids?, data}. Space omission uses the configured default.

The bridge also publishes one MCP resource, memory://space (up to 20 current assertions in the configured space), and clients may subscribe to it: the bridge re-reads the space generation about once a second and sends notifications/resources/updated when it changes, including after writes made through HTTP or the world. A denied re-read ends the subscription without returning data. --profile knowledge-graph replaces the seven tools with the reference knowledge-graph tool names (create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations, read_graph, search_nodes, open_nodes) over the same scoped service, with a subscribable memory://knowledge-graph resource.

Tool replies include readable text plus structuredContent: {ok, space_id, result} or {ok:false,error:{code,message,status}}, and isError. Mutations accept an idempotency key; reuse it after an ambiguous failure. The bridge does not emit tokens to stdout. It fails startup if the credential cannot read the configured space.

Claude Code supports stdio MCP servers via its mcp add command:

Terminal window
claude mcp add --transport stdio marina-memory -- bun run /absolute/path/to/Marina/scripts/memory-mcp.ts --url http://127.0.0.1:3301 --credentials /absolute/path/to/data/coding-agent.json

This configuration follows Claude Code’s MCP documentation. For Codex, add a server entry to your Codex configuration:

[mcp_servers.marina_memory]
command = "bun"
args = ["run", "/absolute/path/to/Marina/scripts/memory-mcp.ts", "--url", "http://127.0.0.1:3301", "--credentials", "/absolute/path/to/data/coding-agent.json"]

The command/args configuration follows Codex MCP documentation. Use an absolute Bun executable path if the application cannot find it. Alternatively, set MARINA_MEMORY_TOKEN, MARINA_MEMORY_SPACE and MARINA_MEMORY_URL in the bridge’s environment; keep the token out of checked-in configuration. These recipes are documented configurations; protocol tests run an MCP SDK client, not the actual Claude or Codex applications.

The portable marina-memory skill teaches evidence capture, symbolic recall, checkpoint recovery and explicit correction. Copy its folder into the target project’s .agents/skills/marina-memory for Codex or .claude/skills/marina-memory for Claude. Those discovery locations follow the Codex skill documentation and Claude skill documentation. Configure MCP separately; a skill does not provide credentials or create storage by itself. No global configuration is changed by this implementation.

Residents and humans can run memory retrieve <task>. Resident agents also use marina_memory_service with {operation:"retrieve",input:{task:"..."}}; both return the same evidence and diagnostics as HTTP and MCP, subject to the caller’s space permissions.

The full world exposes /v1/memory on its HTTP/WebSocket port (normally 3300). World MCP is a different listener (normally 3301, /mcp), with login/auth and the same seven memory_* tools (the world listener publishes no memory resources). The standalone memory server also defaults to 3301; use different ports if running both. The stdio bridge connects to the memory HTTP listener, not the world MCP listener.

World commands bind to the logged-in durable world user principal and lazily create a private resident space. This applies to human and agent world accounts; existing agent-runtime principals are not silently merged into those accounts. Binding inherits the world’s login policy: passwordless world login is not a secure external identity provider. Standalone API credentials have their own audience and cannot authorize world operations.

memory service
memory claim project:marina status "active"
memory relate task:123 project project:marina
memory query {"subject":"project:marina"}
memory graph task:123
memory show RECORD_ID
memory sources incident Kestrel
memory source SOURCE_ID
memory plan Aster migration approval
memory vocabulary
memory review {"kind":"competing"}
memory resolve RECORD_ID evidence_weighted {"competing":["OTHER_ID"],"rationale":"two independent sources"}
memory api {"operation":"checkpoint","id":"work"}

Human verbs translate into the same service requests; responses retain full content, IDs and provenance. They do not run an LLM to guess the intended mutation. An assistant using the skill can translate natural language into explicit claims. There is no new dashboard editor.

Resident TypeScript clients can call MarinaClient.memoryService(request), which waits for a correlated reply rather than relying on the short command-output drain window. Full-profile residents receive marina_memory_service; compact profiles discover the commands in their command roster. MCP commands await completion and serialize per session to keep concurrent replies separate. All service reads/writes retain the shared service’s permission checks.

Use explicit grants to share a space between an external service principal and a world account. Read the principal IDs through each interface’s me operation. Existing memory set/get, note, recall and pools retain their numeric interfaces. Schema migration 138 converts their stored assertions to canonical records automatically.

reflect files a reflector job when a memory-reflector is running. Under the LOCAL ungated trust profile, when none runs and a runtime can serve one (provider keys present), reflect spawns Reflector (marina/default, role memory-reflector, budget 40) on the caller’s behalf, waits for its world account, and files the job; without a serving runtime it prints the deterministic template with the spawn hint. Shared and public profiles never auto-spawn.

Resident checkpoints and completed-message journals use the private durable service. The runtime awaits capture of each completed user, assistant and tool-result message before advancing. Read checkpoint.data.journal.manifest_source_id and follow previous-manifest links for recent messages. Every lossy context transform also awaits capture of the complete original message array before returning a compacted view. The archive uses ordered, UTF-8-safe source parts (json-utf8-parts-v1) plus a SHA-256 integrity hash in the resident checkpoint. Each archive also captures an immutable manifest with source_ids, sha256 and previous_manifest_source_id; the checkpoint exposes its manifest_source_id. Follow the manifest chain to reconstruct earlier conversations after successive compactions. Each message is its own part and the commas between messages are parts of their own, so an archive reuses the parts the journal already stored for the same messages, and growing histories reuse uploaded parts. A tool result is stored without its details (the harness’s live bookkeeping). The checkpoint validates that all referenced sources still exist. After restart, the resident sees its intent, archival summary and source IDs; it can read the originals through source_range.

A failed capture or checkpoint acknowledgment aborts compaction and retains local history. Forgetting invalidates checkpoints. A running resident that has observed a checkpoint will refuse to recreate it after invalidation; restart that resident before further checkpointing. This prevents automatic re-archival of its old local buffer. It does not erase context already held by an external client. Unfinished streaming output can still be lost on abrupt process death; external tool effects are not transactional with their result capture. Raw archives remain private. Existing compactionPool configuration still shares a bounded summary after durable capture; this explicit opt-in is best-effort and does not publish the raw archive.

For revision-aware dependency review, bounded batch/retry contracts and operational snapshots, see the reliability guide.

Storage usage is available through memory.usage() (TypeScript/Python), the MCP service operation usage, or the human command memory usage. Limits aggregate all spaces owned by the current principal and include history and retry receipts. See storage admission and recovery.

TypeScript callers can use memory.withSignal(signal) and retryMemoryOperation(..., {signal}) to stop local waits and retries. The memory-only MCP bridge forwards protocol cancellation; resident journaling uses the agent runtime signal. A sent write can still commit after abort: reuse its original request key to recover the receipt.

Marina participants can ask a librarian, reflector, or evaluator to investigate a memory task. Helpers use the same commands and durable memory API as humans and external agents. Results are attributed, cited proposals; they do not certify claims as true or change the requester’s existing records.

The memory-librarian, memory-reflector, and memory-evaluator roles are seeded when absent. You can inspect and edit them with the ordinary role commands. Spawning uses Marina’s existing agent.spawn permission and deployment profile.

agent spawn Librarian model marina/default role memory-librarian budget 40
agent spawn Reflector model marina/default role memory-reflector budget 40
agent spawn Evaluator model marina/default role memory-evaluator budget 40

Run each command after the preceding spawn completes. Helpers are resident agents; marina/default routes their model calls through Marina. One configured upstream model can serve all three. Helpers wait for direct work notifications, and model call budgets pause them when exhausted. Inspect them with agent status NAME. No embedding model or additional memory database is required.

memory remember Project Amber deploys on port 7419
memory assist librarian Librarian Find Amber's deployment port and cite the evidence
memory jobs
memory jobs {"open":true}
memory assistance REQUEST_ID

memory assist delegates reading of your private resident space. To choose another space you own, use memory api or the TypeScript/MCP interfaces. A shared-space writer cannot delegate the owner’s authority. Each request names one helper’s durable principal. It does not grant that helper general access to the space.

The librarian finds evidence and explains uncertainty. The reflector compares observed attempts and outcomes to propose a reusable lesson. The evaluator checks the support and limitations of a claim. You choose whether to adopt their proposals using ordinary versioned memory operations. Asking for help causes no automatic verification, ratification, or destructive pruning; a helper earns standing only when you adopt its proposal (see Adopt a proposal).

The three helpers also carry the curator duties — no fourth role:

  • Evaluator = Steward. When a job names competing, stale, or pending assertions (a [hygiene] or [shared-write-review] task), it adjudicates each with citations and proposes a resolve policy — last_writer_wins, evidence_weighted, await_confirmation, or keep_both — as part of its answer. It never applies one; the owner runs memory resolve, or does not.
  • Librarian = Auditor. Given a space to sweep, it finds unsupported claims, duplicates (repetition is not corroboration), and suspicious low-provenance clusters, proposes what to merge/retire/source, cites each finding, and never deletes.
  • Reflector = Janitor. Given an accumulation of related notes (an [accumulation] task lists ids and topic), it proposes ONE consolidated lesson that cites every source it merges. Append-and-link: the owner adopts it as a new record linked to its sources; the originals are never rewritten.

Re-seeding rule. Roles are installed when absent. A stored role is upgraded on boot only if its description tail carries an older [guidelines_version=N] marker (missing = 0) than MEMORY_HELPER_GUIDELINES_VERSION and nobody but system has ever saved it (created_by and every role history row). An operator-edited role is preserved at any version; copy new duty lines in with role edit if you want them.

Three triggers file assistance jobs without anyone typing memory assist. Every automatic job is an ordinary request: it appears in memory jobs, can be withdrawn with memory assist-cancel ID, and its result is a cited proposal, not a change.

Trigger When Files Guard
Hygiene ([hygiene]) hourly; stale + competing + pending ≥ 5 one evaluator job (local) / tells the owner the command (shared, public) one open hygiene job per account
Accumulation ([accumulation]) hourly; ≥ 8 fact-like personal notes in 24 h sharing a topic one reflector job “Consolidate these N notes about topic” with the note ids one open job per account; a process-tier [accumulation] … max_note=ID receipt prevents re-filing for the same notes; no reflector running → one hint per day with the spawn command
Shared-write review ([shared-write-review]) a pool_note deposit by a writer with standing < 5 (below rank 1) one evaluator job against the writer’s own space, deposit text included as untrusted data at most one per writer per hour; one open review per writer; silent (never notifies); skipped entirely under the local profile

Topic clustering is deterministic and lexical: distinct content terms (lower-cased, ≥ 4 chars, stop-words dropped); the term with the highest document frequency names the cluster, ties break alphabetically. The task carries legacy note ids; the reflector reads their canonical records through assist_read by searching the topic terms. The debounce maps are in-process and reset on restart; the durable guards (open-job marker, receipt note) do not.

import { MarinaMemoryAssistance, MarinaMemoryClient } from "marina/memory";
const memory = new MarinaMemoryClient(url, token);
const help = MarinaMemoryAssistance.http(memory);
const request = await help.create(spaceId, {
role: "librarian",
worker_id: helperPrincipalId,
task: "Find Amber's deployment port and cite the evidence",
max_operations: 32,
timeout_ms: 600_000,
}, "amber-port-request-1");
const status = await help.get(request.id);

The world and memory-only MCP servers expose memory_assist. The shared memory_service tool exposes assist_jobs, assist_get, assist_claim, assist_read, assist_heartbeat, assist_finish, assist_cancel, and assist_delegate. Human commands and the resident SDK use the same correlated operation replies.

assist_jobs accepts input: {open:true, limit:100, cursor:NEXT_CURSOR}. help.jobs({open:true}) uses the same filter. Follow next_cursor until null; authorization changes can produce an empty page with another cursor. Cursors are bound to the caller and the open filter. Selecting open work filters out completed history before limiting the page.

Resident agents also have a typed marina_memory_assistance tool in every tool profile. Its nested request.id identifies the record or source being read; the outer id identifies the assistance job. Use source_search to discover original documents and source_range to read them. search searches authored records, which can refer to sources but do not cover all captured documents.

External workers can use help.work(requestId, { next, maxTurns, signal }) with their own model callback. next receives model-neutral messages and may call Marina’s model endpoint. The loop claims the request, renews its lease, restricts reads, validates its cited answer, and submits the proposal. It reports errors, exhaustion, and abstention separately. A failed worker can reclaim after its lease expires; use a new claim key for a new attempt.

Helpers must read evidence through assist_read. Supported operations are search, query, graph, get, source_search, source_range, vocabulary, and review. The service binds identity and space; embedded write requests or requests to another space are rejected. Search is lexical; the helper can reason about aliases and alternative queries. Original source ranges remain readable.

Completion requires exact quotations from witnessed reads and current versions. This checks citation mechanics, not semantic entailment. An evaluator’s judgment is still attributed opinion. All observed records and sources are attached as dependencies of the result, including observations omitted from its citation list. Changed premises make results stale; unavailable evidence prevents their use. Editing a result record also invalidates its job result, so later edits cannot be presented as the helper’s original answer.

Helpers may call assist_delegate with their lease token, another worker’s principal ID, a role, and a subtask. Children retain the same space, owner authorization, deadline, and shared operation budget. A parent worker can inspect its child’s job, but must independently read evidence before citing it. Cycles are rejected. The limit is three delegation levels below the root and eight requests in the entire tree.

The TypeScript client exposes help.delegate(id, leaseToken, { worker_id, role, task }) and help.heartbeat(id, leaseToken) for these operations.

  • Requests and proposals survive process restarts. Requests use canonical sources; results use versioned records. Work leases and request IDs are durable coordination metadata. Portable memory exports preserve artifacts, not live work assignments. World JSON exports also omit leases; restoring a world closes existing assistance assignments. Create new requests after restore. SQLite snapshots retain the full durable job state, subject to the original credential and deadline checks.
  • A claim lasts up to two minutes and can be renewed before expiry. Lease tokens fence delayed workers after a new claim. Reuse a key and identical input to retry a mutation; a repeated read uses current authorization and current data.
  • state records the last work transition. work_open projects whether the request is unfinished, within its deadline, and has open ancestors. A deadline passing closes work without rewriting that history. An expired lease on an otherwise open request can be reclaimed; an expired request needs a new request.
  • A root request defaults to 32 delegated read/subtask operations and ten minutes. The owner can select 1–128 operations and 1 second–1 hour. These are protocol bounds; the resident’s model-call budget separately bounds model execution.
  • Responses are limited to 128 KiB, proposals to 32 KiB, and witnessed evidence to 256 entries. Coordination metadata counts toward the owner’s storage budget.
  • memory assist-cancel REQUEST_ID withdraws an unfinished request and closes its descendants’ delegated reads. Expiry, credential revocation, or principal suspension also closes delegated access. Already delivered content cannot be recalled from another participant’s process.
  • Forgetting within a space conservatively retires assistance request sources and their derived proposals, as well as opaque checkpoints. This prevents copied task text from retaining material the owner asked Marina to forget.
  • Helpers receive direct notifications containing request IDs, state, and budget. Durable assist_jobs discovery recovers missed notifications. Finished work does not depend on receiving a particular chat reply.

Direct memory reads remain usable when no helper or model is available.

memory adopt REQUEST_ID # into the job's own space
memory adopt REQUEST_ID space GUIDE_SPACE_ID {"rationale":"matches the docs"}
memory adopt REQUEST_ID confirm-abstention # credit an honest abstention
pool guide ratify 42 importance 8 verified against the registry

adopt (HTTP POST /v1/memory/assistance/:id/adopt or /spaces/:space/adopt, TS client.adopt(space, jobId, input, key), Python adopt, MCP memory_service op adopt) turns an answered job’s proposal into a versioned record. Record citations you can read become depends_on/dependency_versions, source citations source_ids, and the proposal record is metadata.derived_from. Adopting the same job into the same space twice returns the same record. The helper earns assistance_adopted standing (1.0; delegated trees split 0.6 root / 0.4 shared among answered contributors); a confirmed abstention earns 0.25; an adopted record later superseded by memory resolve debits 0.5. A person’s adoption credits any other helper, its own agents included; any other requester credits only a helper outside its own spawn lineage.

Institutional spaces (authorized publications from guide, orchestration:*, tradition:*; owned by the guide system principal, readable by everyone) accept only ratifications: standing ≥ 15, a sovereign, or the ungated local operator. Every ratified record carries metadata.ratified_by, so a shared record always answers “why is this shared?”. On a shared instance pool guide add files a proposal (importance capped at 4, unverified) until pool guide ratify <noteId> lifts it and mirrors it into the institutional space.

The real-resident qualification creates a disposable Marina instance and uses marina/default for all helpers and a fresh consuming agent:

Terminal window
bun run qualify:memory:assistance \
--directory /tmp/marina-assistance-qualification --budget-usd 2

It needs the configured upstream key. The harness checks a randomized answer used by the consumer, the reflector’s original incident citation, and the evaluator’s original methodology citation and stated limitations. It bounds upstream spending and writes reports and traces only to the chosen private directory. These are functional workflow checks; they do not establish general retrieval accuracy, statistical improvement, or long-horizon reliability across workloads.

These interfaces use the same durable memory service as residents, HTTP clients and native MCP tools. No embedding model is required. Sources remain authored evidence, relationships remain explicit assertions, and cached results do not become facts.

Use MarinaMemoryClient from marina/memory. Both clients need their own credentials. The exporter needs read/export access; the importer must own an empty destination space.

let page = await origin.exportTransferPage(originSpace);
const transfer = await destination.beginTransfer(destinationSpace, page.header, "begin-copy-1");
// Persist transfer.id and the source URL/space before sending pages.
while (true) {
const accepted = await destination.appendTransfer(
destinationSpace, transfer.id, page, `copy-1-page-${page.position}`,
);
if (page.done) {
await destination.commitTransfer(destinationSpace, transfer.id, accepted.sha256, "commit-copy-1");
break;
}
page = await origin.exportTransferPage(originSpace, accepted.next_cursor!);
}

After a restart, call transferStatus(destinationSpace, transferId). For receiving, resume export from next_cursor; a null cursor at position zero means no page has been accepted. For ready, commit using the returned sha256. committed is terminal. Use the original request key to recover an ambiguous page/commit acknowledgment. Retry transient errors with retryMemoryOperation, preserving the same payload and key. For example:

const accepted = await retryMemoryOperation(() => destination.appendTransfer(
destinationSpace, transferId, page, `copy-1-page-${page.position}`,
));

Each page has at most 256 KiB of decoded fragments (base64 makes the wire body larger), 128 fragments, and a chained SHA-256 digest. Each serialized row is limited to 4 MiB; the whole transfer to 64 MiB and 300,000 rows. Histories are streamed as individual revisions. IDs, exact original content, revision attributes, explicit relationships, vocabulary history and checkpoints are preserved or rejected. Credentials, grants, retry receipts, vectors and caches are excluded. Target ownership and grants are not copied from the source.

Any source-space generation change invalidates further export pages with transfer_changed. Pause writes while copying, or export from a stable restored backup. Checksums detect damaged content; they do not authenticate its author. Use trusted origins and authenticated transport.

Staging is durable and counts toward the owner’s storage quota. It is invisible to ordinary retrieval until one atomic publication succeeds. Publication can require substantial temporary disk space and synchronous SQLite work; measure larger imports on the deployment hardware. The final retained data must fit ordinary owner quotas. Existing ID conflicts and nonempty destinations are rejected. Nothing is silently merged or overwritten.

At most two active imports per owner are allowed. Writes expire 24 hours after beginning; expiry does not delete data. Inspect status and explicitly call abortTransfer to release unused staging, including expired transfers. Abort cannot delete a committed import; use ordinary explicit forgetting. Full instance snapshots preserve in-progress staging.

HTTP paths under /v1/memory/spaces/:space:

Method/path Operation
GET /transfer?cursor=... Export a bounded page
POST /transfers Begin with the export header
GET /transfers/:id Inspect/resume status
POST /transfers/:id/pages Append a complete page
POST /transfers/:id/commit Publish with {sha256}
POST /transfers/:id/abort Remove unpublished staging

The Python client provides export_page, export_pages, begin_transfer, transfer_status, append_transfer, commit_transfer, and abort_transfer. World and native MCP callers use memory_service operations export_page, transfer_begin, transfer_status, transfer_page, transfer_commit, and transfer_abort. Keep large page payloads out of a model’s context; an SDK worker can move them while the agent manages status.

Use the reference MCP knowledge-graph tools

Section titled “Use the reference MCP knowledge-graph tools”

Launch the memory stdio bridge with a named profile:

Terminal window
bun run memory:mcp --url http://127.0.0.1:3301 \
--credentials data/agent.json --profile knowledge-graph

Use that command/argument array in your coding client’s MCP configuration. The profile exposes create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations, read_graph, search_nodes, and open_nodes. The default --profile native retains Marina’s existing tools.

This profile follows the reference memory server’s nine tool contracts. Entities have {name, entityType, observations:string[]}; relations have {from, to, relationType}. Names are case-sensitive identities. Search performs case-insensitive substring matching across names, types and observations. Search/open results include relations incident to either selected endpoint; the other endpoint need not appear in the returned entities. Relations require both entities to exist. Each mutation batch is atomic.

The bounded profile differs from a full server replacement:

  • It supports the nine tools and one subscribable resource, memory://knowledge-graph (the bridge polls the space generation about once a second and sends a resource-updated notification when it changes), without reference JSONL persistence.
  • Each space has at most 2,000 profile records and a 1 MiB graph/result limit. Each entity, observation and relation uses a record. Names/types are nonempty and at most 256 characters; observations are nonempty and at most 8,192 characters. Owner quotas also apply.
  • Each observation has its own original source. Explicit deletion removes that source and its declared lineage. Native forgetting also invalidates checkpoints/caches and retires earlier profile receipts that might contain copied observations; replay then returns receipt_retired.
  • Native changes that leave malformed graph data require explicit repair. Stale profile records return compat_review_required; use native review/reaffirmation before reusing them.

Profile records remain searchable/readable through native APIs. Relations are native typed claims and work with exact queries and graph traversal. Native bundles and paged transfers preserve profile data and ordering. Keep application data in a dedicated space when possible. TypeScript also exposes client.knowledgeGraph(space, action, input, key?); Python exposes knowledge_graph. World agents use the knowledge_graph memory-service operation.

import { expandMemoryQuery } from "marina/memory";
const plan = expandMemoryQuery("shipping status", {
policy: "logistics-glossary:v1",
rules: [{ term: "shipping", alternatives: ["dispatch", "shipment"] }],
});
console.log(plan.applied, plan.truncated);
const result = await client.sourceSearch(space, {
query: plan.query, expansion: plan.expansion, match: "all",
});
console.log(result.expansion, result.results);

The helper makes literal, Unicode-aware substitutions against the original query. It does not recursively expand or combine every rule. Rule order selects up to four alternatives, and truncated reports omissions. Supply at most 128 rules and eight alternatives per rule. Persist/version this JSON vocabulary wherever your application stores authored configuration; it is separate from the service’s predicate/type vocabulary.

Both /search and /source_search accept expansion:{policy,queries} directly, including from Python or an explicit retrieval plan. A caller can also ask its chosen model to propose queries, inspect them, then submit them. No router call or inference is hidden in search. Queries are deduplicated against the original and each other. All queries apply the same authorization, filters and source-match mode in one read snapshot. Stale records stay excluded unless explicitly requested.

Fusion adds the original query’s reciprocal rank and the mean contribution of alternatives (k=60). Optional hybrid retrieval adds its existing semantic contribution. Responses report the policy, exact alternative queries, candidate counts and per-result ranks. Record queries have at most 200 candidates per ranker; source queries have at most 100. Original record search uses any-token FTS matching; source search defaults to all-token matching. Expansion can improve recall or add noise: measure the same tasks with and without it. Search excerpts remain discovery aids; read original stable ranges before quoting evidence.

An operator configures explicit principal mounts as described in the federation guide. Callers cannot supply arbitrary peer URLs. A cache write may combine local records/sources with explicit remote pins:

await client.cachePut(space, {
inputs: { task: "prepare release" }, model: "caller-model", policy: "release:v2",
value: { summary: "Caller-authored derived result" }, expires_at: Date.now() + 60_000,
federated: [{ kind: "record", mount: "team", space_id: peerSpace, id: recordId, version: 3 }],
}, "release-cache-1");

Remote source pins use {kind:"source",mount,space_id,id,content_hash}. There must be 1–32 pins total. Every write and lookup rechecks the configured endpoint, remote principal, retrieval generation, current record/version or source hashes, and live access. Local access and cache state are checked again after network waits. An unavailable, revoked, remounted or changed peer yields a miss; the old value is not returned as a fallback. Even unrelated peer evidence changes can invalidate a result conservatively.

These are per-peer checks, not an atomic distributed snapshot. A peer can change after its check completes. Mounts must be restored by operator configuration after service restart. An unchanged restored peer can validate existing entries again. Same-key acknowledgment recovery remains available during an outage, but it does not return cached content. Federated caching adds network validation work; it is useful when that costs less than recomputing the derived result. It does not automatically cache model tokens.

Owners can list imports without retaining their IDs:

const imports = await memory.transfers(space, { state: "receiving", limit: 20 });
const next = imports.next_cursor;
const status = await memory.transferStatus(space, imports.transfers[0]!.id);

state, expired, limit and cursor are optional filters. Listing is owner-only, uses an ID cursor, and reflects current status. Expired staging remains charged to its owner until explicitly aborted or forgotten.

Terminal window
bun run memory transfer-list --url http://localhost:3301 --credentials destination.json
bun run memory transfer-status --credentials destination.json --transfer TRANSFER_ID
bun run memory transfer-resume --credentials destination.json --transfer TRANSFER_ID \
--source-url http://source:3301 --source-credentials source.json
bun run memory transfer-abort --credentials destination.json --transfer TRANSFER_ID

Use --url for a destination outside the default local service. Resume supplies the original source connection again; Marina does not store its credentials. A ready transfer can be committed without reconnecting to the source. The TypeScript resumeMemoryTransfer(destination, space, id, { source, signal, progress }) helper follows the durable cursor and retries with stable request keys. Original source generations must remain unchanged.

Large publication runs in a trusted local subprocess, retaining one atomic SQLite transaction. Other tenants can continue reading. SQLite still permits only one writer: memory writes receive retryable 503 import_busy during publication, and other database writers fail promptly on lock contention. Publication has a 120-second limit. Use a client timeout above that limit for large commits; the CLI uses 130 seconds. Cancellation waits for the child to exit, but a write may already have committed. Inspect status and retry with the same key to recover its receipt. File-backed databases and the bundled dist/memory-import.js entry are required for background publication; normal source installs include its TypeScript entry.

Joins match explicit typed claims. Entity IDs and literal strings remain distinct:

const person = { variable: "person", type: "entity" } as const;
const project = { variable: "project", type: "entity" } as const;
const query = {
patterns: [
{ subject: person, predicate: "reviews", object: project },
{ subject: project, predicate: "status", object: { kind: "literal", value: "active" } },
],
select: ["person"],
valid_at: Date.now(),
} satisfies import("marina/memory").MemoryJoin;
const result = await memory.join(space, query);

Each match includes bindings, supporting record IDs and versions, and the intersection of their valid-time ranges. valid_at is optional; when supplied it uses UTC milliseconds and half-open ranges. Predicate variables use type symbol; literal variables use string, number, boolean or null. Repeated variables must agree in both type and value. Stale records are excluded.

Joins allow up to eight patterns, 256 distinct candidate queries, 8,000 candidates, 20,000 comparisons and 2,000 intermediate matches. Candidate and intermediate data each have a 4 MiB budget. Exceeding an intermediate budget returns symbolic_budget_exceeded. Final results are limited to 100 and report truncated; they never silently imply complete coverage. A caller-authored retrieval plan can include a join step.

Store a reusable rule as a native versioned memory:

const rule = await memory.saveRule(space, {
schema: "marina.memory.rule.v1",
name: "Reviewers of active projects",
query,
conclusion: { subject: person, predicate: "activeReviewer", object: project },
}, { source_ids: [policySourceId] });
const preview = await memory.runRule(space, rule.id, 1);
// An explicit authored write, after deciding to save the conclusions:
const saved = await memory.materializeRule(space, rule.id, 1);

A saved query retains its valid_at value. Pass a new valid_at to runRule or materializeRule when evaluating another time. Rules are nonrecursive pattern programs; they do not execute arbitrary code or infer verified truth. Their heads can use constants and variables bound by the body. Preview is read-only. Materialization refuses truncated results and saves inference records pinned to the rule and every supporting record version. Changing either can mark conclusions stale. Reaffirmation remains an explicit review action. To revise a rule, pass its id and expected_version to saveRule; native record history and portable transfers preserve its prior definitions.

World commands expose the same operations through memory join, memory rule-save, memory rule-run and memory rule-materialize, each accepting JSON. Native MCP callers can use memory_service with join, save_rule, run_rule or materialize_rule.

Open Memory in the dashboard header after signing into world chat. The workspace uses that resident’s authenticated connection and existing grants. It supports memory search, original source ranges, revision comparison, competing assertions, explicit reaffirmation, and transfer inspection or abort. Switching identity clears the displayed data. Service credentials are not stored in the browser.

sourceHeaders(space, after, limit) lists source metadata without loading original bodies; sourceRange reads the immutable text by byte range. These also appear as source_headers and source_range native operations.

The memory-only MCP bridge exposes memory://space in the native profile and memory://knowledge-graph in the reference graph profile. Resource reads recheck authorization. Subscriptions watch one configured resource per connection, poll at one-second intervals, and notify about HTTP and resident changes too. Notifications contain the resource URI; clients reread for content. Unsubscribe and disconnect stop polling. Access failure stops a subscription, which must be explicitly renewed after recovery. Resource bodies are limited to 1 MiB; use paged tools for larger data. These follow the MCP resource protocol.

For LangGraph namespace storage, see the optional JSON store adapter. Its langgraph-store-json-v1 profile supports authored JSON and exact filters without an embedding model.