Skip to content

API Reference

1. Purpose

This document records the stable HotMem HTTP API. All endpoints are under /v1. Default: http://127.0.0.1:8711.

Interactive Swagger UI is available at http://127.0.0.1:8711/docs when the server is running.

2. Compatibility Rules

  • Existing request fields remain valid.
  • Default response shapes remain stable.
  • New file-native fields are optional.
  • Unsupported future formats should fail with explicit errors.

2.1 Policy-enforced daemon mode (#109, #110, #111)

When the daemon is started with a policy (--policy / mount/policy.json), these additional rules apply. They are breaking relative to an unauthenticated embedded server and are intentional for multi-caller use:

  • Every request requires a bearer token (or X-HotMem-Token).
  • POST /v1/add requires X-HotMem-Session-Id (or body session_id); missing attribution returns 400 session_required.
  • Optional X-HotMem-Harness-Id (or body harness_id) records the originating harness (for example codex or claude-code) in the hotmem-session-v1 provenance envelope ({envelope_version, caller_id, harness_id, session_id, source, namespace, store_id}).
  • Optional X-HotMem-Envelope-Version (or body envelope_version) defaults to hotmem-session-v1; unknown versions fail closed with 400 unsupported_envelope_version.
  • Conflicting context values between headers and JSON body fail with 400 context_conflict; control characters, overlong strings (>256 chars), or whitespace-only explicit overrides fail with 400 invalid_session_context.
  • Supplied harness_id, session_id, and source values are attribution, not authentication: they never grant namespace access or override the authenticated caller_id. A request may not claim another caller's bound session, source, harness, or caller_id (403 session_impersonation_denied).
  • Canonical generic tags (tags: list[str], e.g. ["model:gpt-5", "project:hotmem", "org:knowguard"]) are stored in memories.tags without dedicated model/project/org columns or parallel copies in metadata/provenance. Missing labels are omitted, [] is valid, and model:* tags may change per write within the same session. Invalid tag payloads fail with 400 invalid_tags; non-object metadata fails with 400 invalid_metadata.
  • Tags survive permitted /v1/search, /v1/memories, /v1/memory/{id}, /v1/events, and portable exports/handoffs, do not act as implicit retrieval filters, and obey secret_action and private_classification_action (including classification:private / visibility:confidential tags).
  • Repeated writes with the same X-HotMem-Idempotency-Key replay the original response without mutating original writer attribution; changing tags, harness_id, source, namespace, metadata, or payload under the same key returns 409 idempotency_key_conflict.
  • X-HotMem-Store-Id is a typo-safety assertion only; authorization comes from the token. A mismatch returns 409 store_mismatch after authentication.
  • Reading or hydrating a memory outside the caller's scope returns 404 (identical to a missing id); list/search/event results are filtered before ranking/output.
  • GET /v1/health requires the read operation, omits db_path, and reports store_state as verified_empty, ready, or empty_scope. Authenticated responses include policy_enforced: true and policy_revision; total_memory_count is non-zero only for management callers.
  • GET /v1/bundles and POST /v1/discover require management authority.
  • GET /v1/hygiene reports only the caller's visible rows and does not write audit events for read-only callers.
  • POST /v1/snapshot records scope (exported_count, scope_omitted_count, disclosure_omitted_count, omitted_count, redacted_count) in the manifest/metadata and redacts host/database paths. File-backed records with no portable reference are omitted.
  • Retrieval and export routes apply secret_action (allow/redact/omit/fail_closed) and private_classification_action (allow/omit/fail_closed) over text, summaries, metadata, provenance, tags, identifiers, and hydrated content. Responses include a disclosure object: {redacted_count, redacted_records, omitted_count, reasons, patterns}. fail_closed raises 403 policy_disclosure_blocked with a reason (secret_detected, private_classification, or non_text_payload) and matched pattern names — never the matched values.
  • copy_attachments=true requires allow_attachments (management callers are allowed) and returns 403 attachments_not_permitted otherwise.
  • /v1/vector-index/rebuild and DELETE /v1/vector-index require manage under policy; /v1/vector-index/status scopes counts and omits the index path for non-management callers.
  • Operation responses (snapshot, hydrate, handoff prepare/inspect) return paths relative to the daemon base directory when redact_host_paths is on.
  • Filesystem paths supplied to snapshot, hydrate, handoff *, and discover must resolve inside the daemon base directory (403 path_not_permitted).
  • Management callers can revoke immediately via POST /v1/policy/revoke and reload the policy file via POST /v1/policy/reload.

3. Health

GET /v1/health

Returns server status, memory count, DB path, and uptime (embedded mode), or scoped counts, store_state, policy_enforced, policy_revision, and no DB path (policy mode). Requires authentication in policy mode.

4. Add Memory

POST /v1/add
Content-Type: application/json
X-HotMem-Harness-Id: codex
X-HotMem-Session-Id: sess-alpha-101

{
  "identifier": "user",
  "fact": "prefers dark mode",
  "source": "chat",
  "importance": 0.5,
  "metadata": {},
  "tags": ["model:gpt-5", "project:hotmem", "org:knowguard"],
  "ttl_seconds": null
}

Returns memory_id, content_hash, and trace_ms (plus "deduplicated": true when logical identity (namespace, content_hash) matched an existing record in the target namespace without overwriting the original writer's id, attribution, tags, or metadata). Identical content in a different namespace is a distinct memory. File-backed identity covers identifier, the normalized source reference, and the byte range; source_checksum only verifies bytes. See docs/okf/interchange-v1.md section 3.1. In supported legacy/non-policy mode (require_auth=false), session_id, harness_id, and tags are optional and preserved when supplied.

POST /v1/search
Content-Type: application/json

{
  "query": "what theme does the user like",
  "top_k": 5,
  "max_chars": null
}

Returns ranked memories (LLM-ready message objects) with count and trace_ms.

Exact-identifier recall: GET /v1/memories

GET /v1/memories?identifier=tasks%2Fcurrent&order=desc&limit=1

Returns memories, count, and trace_ms without semantic ranking. When a policy is active it also returns the disclosure envelope, including omitted_count, redacted_count, reasons, and patterns. Results are ordered by created_at, then by local insertion order for records with the same timestamp. That insertion tie-breaker is not a portable sequence. order is asc or desc (default asc); limit must be 1..1000 (default 100) and invalid values return 400, not a clamped success. A caller must not treat visible rows as complete when disclosure.omitted_count > 0 or when the limit is reached.

MCP hosts can use list_memories in embedded and daemon-relay modes. MCP preserves the relay disclosure envelope and applies the configured embedded namespace. All normal caller namespace/share and disclosure checks apply.

Temporal retrieval (#142)

On POST /v1/add, inline and file-backed records accept three optional fields. Use valid_from for the first instant the fact applies to the subject and valid_until for the first instant it no longer applies. A start without an end gives an open-ended interval. An explicit end requires an earlier start. Use recorded_at for when the producer asserts the information was recorded. It has meaning independently of the validity interval.

Use RFC 3339 timestamps with Z or a known numerical offset and at most six fractional digits. HotMem stores and returns normalized UTC timestamps with six fractional digits, for example 2026-03-15T00:00:00.000000Z. Unspecified fields are omitted on read. HotMem does not infer them from created_at, updated_at, or event timestamps.

Search accepts either or both selectors. valid_as_of matches valid_from <= valid_as_of and an absent valid_until or valid_as_of < valid_until. known_as_of matches recorded_at <= known_as_of. Each selector excludes records with unknown time in its own dimension. Supplying both requires both conditions to match. Current visibility, TTL, and authorization still apply. The selectors cannot recover deleted records or reconstruct past record versions.

POST /v1/search
Content-Type: application/json

{
  "query": "contract",
  "top_k": 5,
  "valid_as_of": "2026-03-15T00:00:00Z",
  "known_as_of": "2026-04-01T00:00:00Z"
}

For exact recall, pass the same parameters in the query string of GET /v1/memories. With a selector, results order by created_at and then memory ID, both in the requested direction. A timestamp offset containing + must be URL-encoded. Temporal search ranks eligible rows using exact search, including when a vector index is configured. The default scorer breaks equal final scores by descending cosine score, then ascending memory ID.

The Python clients accept the same field names as keyword arguments. The TypeScript client accepts them in the request object. Embedded and relay MCP expose the optional fields on add_memory, search_memories, and list_memories. See CLI examples and the portable record representation.

HTTP returns 400 for an invalid timestamp value or interval. An explicit temporal assertion that differs from one already stored for the same record identity returns 409 temporal_conflict. Writes without temporal assertions deduplicate as before.

Correction history (#143)

Create an original claim with POST /v1/add. Use the returned memory_id as supersedes when you record a correction.

POST /v1/corrections
Content-Type: application/json

{
  "version_id": "d47a9046-fc3e-4128-9e80-56dc184ebca2",
  "supersedes": "<original memory_id>",
  "identifier": "contract",
  "fact": "The revised terms apply from February.",
  "recorded_at": "2026-03-01T00:00:00Z",
  "valid_from": "2026-02-01T00:00:00Z"
}

Generate a fresh version_id for each correction and reuse that ID on retries. A retry with equivalent normalized inputs returns the same ID with deduplicated: true. Different inputs using the same ID return 409 correction_conflict. The predecessor must be readable and writable under the caller's policy, in the same namespace, and filed under the same identifier. The correction's recorded time must be later than the predecessor's known recorded time. Omit both validity fields to inherit the predecessor's interval. Supply a start by itself to replace the interval with an open-ended one.

Use correction_view=true on GET /v1/memories or in the JSON body of POST /v1/search. HotMem applies caller visibility and any inclusive known_as_of cutoff, selects versions with no eligible successor, and then applies valid_as_of. For an original claim recorded in January, a February knowledge cutoff still sees the original at a February valid time. A March 1 knowledge cutoff sees the example correction. If the correction excludes the requested valid time, HotMem returns no result from that branch. Competing visible successors are eligible together. Authority and approval remain with the caller or EMOS.

For history, use GET /v1/memories?identifier=contract and inspect a particular version with GET /v1/memory/{memory_id}. The correction link is stored in metadata["hotmem.correction.v1"].supersedes. Normal retention and disclosure rules still apply. Legacy records without a link remain independent claims, and legacy queries keep their existing behavior.

Snapshot v2, interchange v1, and JSONL or JSONL.GZ swaps carry the link in portable metadata. Restore validates the link using the full staged artifact and existing destination records before committing. A scoped export can omit a predecessor, so restoring that export requires the matching predecessor already present in the destination. Older readers can carry the link as metadata. Use a correction-aware reader to apply supersession during recall.

Derivation lineage (#144)

Attach metadata["hotmem.derivation.v1"] to an ordinary POST /v1/add. The envelope describes the producer's inputs and can coexist with metadata.annotations and the session provenance envelope.

{
  "sources": [
    {"memory_id": "claim-v2", "revision": "episode-r2"},
    {"memory_id": "episode-b", "content_hash": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}
  ],
  "operation": "summarize",
  "operation_version": "1",
  "recorded_at": "2026-03-01T00:00:00Z",
  "model_id": "producer/model",
  "review": {"reference": "review-system/decision/7", "status": "reported"}
}

Supply 1–64 source references in producer order. Each memory_id identifies the exact version, including a specific #143 correction version. Optional content_hash pins the source's lowercase SHA-256 HotMem record digest. An optional revision records a producer's external revision label. HotMem preserves it verbatim. operation and the RFC 3339 derivation recorded_at are required. The operation version, model ID, and review object are optional. The review reference and optional status are opaque producer data. EMOS owns decisions about approval and current authority. Reusing an existing memory identity with a different derivation envelope returns 409 derivation_conflict.

Use GET /v1/memory/{memory_id}/lineage?limit=10 to inspect direct source references. The limit accepts 1–64 and defaults to 64. The response includes total_sources and truncated when lineage is present. It adds one current state to each returned reference and includes zero source bodies.

State Meaning
resolved The current caller can read the local record, its retention period is active, and any supplied HotMem content hash matches. External revision labels remain producer assertions.
stale The readable local record's current content hash differs from the pin.
missing The record is readable but its retention period has expired.
deleted The caller can see a retained tombstone for the referenced ID.
revoked The caller has an explicitly revoked read grant naming this ID and no usable source in this view. The grant establishes the revocation state independently of source existence.
unresolved HotMem could not safely resolve the reference, including absent sources and sources outside current scope.

The detail read checks database state and caller policy. External review records, external revisions, and backing-file bytes are outside that check. The existing bounded memory_map work in #106 owns deeper traversal of these explicit edges. Snapshot v2, interchange v1, and JSONL/JSONL.GZ carry the envelope as metadata. An export scoped to a derived record retains its pins, so omitted sources appear as unresolved after a clean restore.

6. Hydrate

POST /v1/hydrate
Content-Type: application/json

{
  "file": "swap.jsonl"
}

Loads memories from a JSONL or JSONL.GZ swap file. Deduplicates by logical identity (namespace, content_hash); repeating an import in the same namespace skips, while identical records in another namespace are loaded.

7. Snapshot

POST /v1/snapshot
Content-Type: application/json

{
  "file": "swap.jsonl"
}

Exports all memories to a JSONL or JSONL.GZ swap file.

8. Vector Index (optional, derived)

The vector index is an optional acceleration layer — it is disposable, rebuildable, and never canonical storage. SQLite, files, bundles, and manifests remain the source of truth. Losing or deleting the index never loses memory: search transparently falls back to the deterministic SQLite cosine scan, and the index can be fully rebuilt from canonical storage.

Enable it at server start (hotmem serve --db ./my.sqlite --vector-index chroma, requires the optional hotmem[vector] extra). The index only supplies candidate ids; final ranking is always recomputed with the canonical hybrid scorer, so the /v1/search response shape and ranking are identical with or without acceleration.

POST /v1/vector-index/rebuild

Rebuilds the index from SQLite rows (embeddings are reused, never recomputed). Reads no backing files. Returns indexed_count, db_count, skipped_no_embedding, rebuilt_at, and trace_ms. Returns 400 vector_index_disabled when no backend is configured, or 400 vector_dependency_missing when the backend package is not installed. Emits an index.rebuilt event.

GET /v1/vector-index/status

Returns backend, requested_backend, dependency_available, indexed_count, db_count, stale, rebuilt_at, path, and trace_ms. stale: true means search is currently served by the deterministic fallback.

DELETE /v1/vector-index

Clears the index (entries + rebuild marker). Canonical storage is untouched.

9. OpenAPI Spec

Export the machine-readable spec:

hotmem openapi --output openapi.json
hotmem openapi --output openapi.yaml --format yaml

Or fetch it from a running server: GET /openapi.json

10. Session Handoff (#101)

Verified handoff packages (hotmem-handoff-v1) wrap the same core functions as the CLI and MCP tools. Consent is required on prepare and checked before any session content is read.

POST /v1/handoff/prepare

{"source": "./codex_export", "output": "./handoff",
 "mode": "resume", "consent": "I consent to capturing this session",
 "session": "sess-7f3a2b"}

Returns handoff_id, package_id, mode, entries, memories, coverage (omitted/redacted/recoverable counts), path, and timings_ms. A missing or empty consent returns 400 before anything is written.

POST /v1/handoff/verify

{"package": "./handoff"} → {"valid": true, "package_id", "mode", "entries", "memories"}; invalid packages return 409 with the structured body {"error": "handoff_invalid", "reason", "file", "expected", "actual", "message"}.

GET /v1/handoff/inspect?package=…

Read-only report for valid AND invalid packages: identity, source/target, counts, coverage (including full omission/redaction lists), limits, and a failure block when invalid. Nothing is written; invalid packages are reported as data.

POST /v1/handoff/hydrate

{"package": "./handoff"} → hydrates into this sidecar's database atomically and idempotently: {"handoff_id", "package_id", "loaded", "skipped", "invalid", "already_applied", "brief", …embedding dispositions}. Invalid packages return 409 without touching the store. The hydrated resume brief is retrievable through POST /v1/search.

Managing app-owned rows

POST /v1/add and the Python clients' add() accept an optional memory_type. Inline rows default to fact. Custom names start with a lowercase letter and contain up to 32 lowercase letters, digits, underscores, or hyphens. file uses the existing file-reference payload. Add, search, and list responses include the stored type.

GET /v1/memories requires identifier or namespace. Filters combine with exact matches on source and memory_type. For filtered scans, pass the response's next_cursor back as cursor with the same filters and order. In Python, list_with_disclosure() returns the page envelope. Each listed row includes its namespace.

An add whose namespace, identifier and fact text match a live row returns that row with deduplicated: true, even when its metadata differs. An app that mirrors changing documents under the same text should put a version or content hash in the fact text, so a changed document becomes a new row that the app can then replace with delete().

DELETE /v1/memory/{memory_id} accepts an optional reason query parameter. The Python clients expose delete(memory_id, reason=""). Deletion requires write access and returns HTTP 404 for missing or previously deleted IDs. V2 directory snapshots carry checksummed tombstones. Legacy JSONL and interchange package snapshots export live rows. Replica event replay carries deletions through the existing memory.deleted event.