The id of the brain this facade reads and writes; a ledger row names it for the writes it records.
Access the underlying IKnowledgeGraph implementation.
Useful for advanced queries (traversal, semantic search, neighbourhood lookups) that are not exposed on the facade directly.
Static createBackwards-compatible alias for Memory.createSqlite. The earlier
surface accepted Memory.create(config) and several published docs and
blog posts still reference it; rather than break those examples we
forward to createSqlite (the modern, more explicit factory).
For non-SQLite backends call Memory.createPostgres or Memory.createWithAdapter directly.
Optional pathOrConfig: string | MemoryConfigStatic createOptional pathOrConfig: string | MemoryConfigStatic createOpen a Memory backed by PostgreSQL. Requires the pg npm package.
Standard Postgres connection URL.
Plus standard Memory options (graph, selfImprove, decay, embeddings).
Static createOpen a Memory with a pre-resolved StorageAdapter. Use when sharing an adapter across subsystems or when you need full control over adapter resolution.
Store a new memory trace.
Creates a trace in the memory_traces table with a unique ID, content
hash for deduplication, and optional type/scope/tags metadata. If the
memory graph is available the trace is also added as a graph node.
The text content to remember.
Optional options: RememberOptionsOptional metadata (type, scope, tags, importance, etc.).
The created MemoryTrace-like object.
Search for memory traces matching a natural-language query.
Uses FTS5 full-text search with the Porter tokenizer, ranked by
strength * abs(fts_rank). With the HNSW index active and an embedder,
the vector index's candidates and the full-text ones are fused by
reciprocal rank. The filters bind both halves: a trace of another type,
scope or scope id, weaker than minStrength or outside after and
before is never returned, however near its vector.
Natural-language search query.
Optional options: RecallOptionsOptional filters (limit, type, scope, scopeId, minStrength, after, before).
Ranked array of ScoredTrace results.
Soft-delete a memory trace by setting deleted = 1.
The trace remains in the database for audit/recovery purposes but is excluded from all recall queries and health reports. Its knowledge-graph copy goes (deleteGraphCopies), so its words do not stay in the graph.
The ID of the trace to forget.
Deletes the knowledge-graph copies of the given traces and leaves the traces: the episodic record a memory
manager on this facade's Brain writes of each trace it stores (SqlKnowledgeGraph.recordMemory). A soft delete
calls it (forget, and the memory tools' memory_delete and memory_merge), so a deleted trace's words do
not stay in the graph; a trace a revert brings back needs no copy, since no recall reads one. Best-effort: a graph
that cannot be reached leaves its copies, which a later delete by trace id or by scope finds.
How many copies it deleted.
Deletes every trace of one scope for good: the rows, their memory-graph nodes and knowledge-graph copies, and
the full-text index entries. With turnUserId, only the scope's traces whose metadata names that user, as the
second user a memory write on another user's session records, or among the contributors of a summary the
rolling-summary sink filed. Account deletion calls it.
It reads the rows by their scope_id column, after filing the brain's rows that hold '' there while their
metadata names a scope id: a release older than the column writes those, to a Brain this facade holds open too.
Optional turnTypeError when scopeId is empty, so a caller's missing id never deletes every trace filed under no scope
id, or when turnUserId is given and is not a non-empty string.
When the knowledge graph cannot delete the copies: of the traces, before any row is deleted; of the scope, once the traces are deleted, so a second call finds the copies alone.
Deletes the given traces for good, as deleteScope does for a scope. The rows that name a trace go first,
as the Brain's foreign keys require: its retrieval_feedback rows are deleted, and a document_chunks row it was
filed from lets go of it and keeps its text. Each trace's memory-graph node goes with its edges, whichever facade
on the Brain wrote them, a relation a host made to the node (addRelation) included. Each trace's
knowledge-graph copy goes before its row. Unknown ids are skipped.
How many trace rows it deleted, so a call made again counts none.
When the knowledge graph cannot delete the copies: no row is deleted, so a later call deletes them.
Brings one trace back to the state a snapshot holds (readTraceSnapshot): its content, tags, scope and
metadata, live again. A ledger revert of a memory tool's update, delete or merge calls it with the before-state
its row recorded; a revert of an add calls forget. The full-text index then matches the restored words:
SQLite rebuilds its index, and Postgres re-indexes the restored row alone.
A snapshot read before the Brain was re-filed in the encoded scope-id form (ensureEncodedScopeIds) is
written under the encoded id, as the re-file wrote the row: once the Brain holds the record, the plain form of an
id that holds a / names a namespaced user (team/ana is user ana of namespace team), so the trace stays the
plain user's. On Postgres the restore reads the record under the lock a re-file takes, so a re-file another process
makes meanwhile comes before or after it.
When the snapshot is of another trace.
Re-files this facade's Brain in the encoded form a learning layer reads, once per Brain
(refileBrainScopeIds); every live MemoryStore on the Brain in this process then moves what it holds of the
traces the re-file moved. The layer calls it when it is first handed the facade.
How many traces it moved: none when the Brain held the record already.
One row of this facade's Brain as a snapshot, live or deleted; undefined when there is none.
List traces created strictly after sinceMs (Unix-ms). Newest-first by
default; pass order: 'asc' for oldest-first (used by the wiki compiler to
drain the window in chronological batches).
Unlike recall, this performs no FTS match — it is a time-window scan, used by the wiki compiler to fold recent activity into pages.
Exclusive lower bound on created_at (Unix ms). Use 0 for "all".
Optional options: { Optional scope filter, result cap (default 200), and sort order.
Optional limit?: numberOptional scope?: stringOptional order?: "asc" | "desc"Attach a markdown wiki store + compiler. Called by the agent at boot once the memory/ workspace directory is known. Idempotent (last call wins).
Optional o: { Optional force?: booleanCompile recent (non-wiki) traces into the markdown wiki, then re-index. Reads the wiki's watermark, folds every trace created since into pages, and advances the watermark. No-op when no wiki is attached. A batch whose compile rejects, such as on a page write that fails for want of disk space or permission, leaves the watermark where it was, so the next compile starts from that batch again.
Optional opts: { Optional reason?: "consolidation" | "session-end" | "explicit"What triggered this compile (telemetry + compiler hint).
Ingest documents from a file, directory, or URL.
Workflow:
document_chunks, create a memory trace.documents table.File path, directory path, or URL.
Optional options: IngestOptionsOptional ingestion settings (recursive, include/exclude globs).
Summary of the ingestion run.
Add or update an entity in the knowledge graph.
Delegates to SqlKnowledgeGraph.upsertEntity(). Accepts a partial
entity; id, createdAt, and updatedAt are auto-generated when omitted.
Partial entity descriptor.
The complete, persisted entity.
Add or update a relation (edge) in the knowledge graph.
Delegates to SqlKnowledgeGraph.upsertRelation(). Accepts a partial
relation; id and createdAt are auto-generated when omitted.
Partial relation descriptor.
The complete, persisted relation.
Run one consolidation cycle (prune, merge, strengthen, derive, compact, re-index).
Optional options: { Optional topic filter (reserved for future use).
Optional topic?: stringStatistics from the consolidation run.
When selfImprove was set to false in the config.
Record retrieval feedback for a memory trace.
The feedback is persisted asynchronously. This method returns a Promise that resolves once the feedback has been written.
The ID of the trace being evaluated.
Whether the trace was 'used' or 'ignored' by the LLM.
Optional query: stringOptional retrieval context, typically the original user query.
Detect and persist used/ignored feedback for a batch of injected traces based on the assistant's final response text.
This is the high-level bridge used by long-term-memory integrations that already know which traces were injected into the prompt.
Optional query: stringExport the memory store to a file or directory.
Format is detected from options.format or the file extension:
.json -> JSON.sqlite / .db -> a new SQLite file holding this brain's own rowsoptions.format)A SQLite export writes this brain's rows of every portable table, from a
SQLite or a Postgres brain; another brain in the same database is left
out. Nothing may exist at outputPath yet.
A Markdown or Obsidian export writes one file per trace, in folders named after the trace's scope and type, and leaves out a trace whose scope, type or id is not a safe file or folder name, whose place in the export folder holds a link, symbolic or hard, or anything but a regular file, or whose file would be an older trace's, where names ignore case or by the file system's own reckoning; the result lists each one left out. No file is written outside the export folder.
Path to write the export to.
Optional options: ExportOptionsOptional format and content controls.
The traces the export left out, with the reason for each.
Import memory data from a file or directory.
Format is detected from options.format, the file extension, or by
inspecting the content.
A SQLite source is read one brain at a time: a file whose rows carry
several brain ids imports nothing, and errors names the ids.
Path to the import source (file or directory).
Optional options: ImportOptionsOptional format hint and dedup settings.
Summary of the import operation.
Import memory data from a string without filesystem access.
Supports JSON and CSV formats. Useful in browser environments or when the data is already in memory.
The raw string content to import.
The format of the content: 'json' or 'csv'.
Optional options: Pick<ImportOptions, "dedup">Optional deduplication controls.
Summary of the import operation.
Export the full brain state as a JSON string without filesystem access.
Useful in browser environments or when the data needs to be sent over a network connection.
Optional options: ExportOptionsOptional export configuration (embeddings, conversations).
Pretty-printed JSON string of the full brain payload.
Create runtime ITool instances backed by this memory facade's SQLite brain.
This is the supported bridge from the standalone memory engine into
AgentOS tool registration. The returned tools share this Memory
instance's underlying SQLite database and consolidation loop.
Typical usage:
for (const tool of memory.createTools()) {
await agentos.getToolOrchestrator().registerTool(tool);
}
Where a learning layer puts a turn's scope ids on a call, the tools file
and read under them and record each write in the layer's ledger, and
memory_reflect refuses (withdrawn); a host that registers the tools
itself leaves memory_reflect out (includeReflect: false).
When self-improvement is disabled, memory_reflect is omitted because
there is no backing ConsolidationLoop instance.
Optional options: { Optional includeReturn a health snapshot of this brain.
Queries aggregate statistics from this brain's rows of every table (a
database can hold several brains) and returns a MemoryHealth
report. Counts are read through Number(): Postgres returns COUNT(*)
and BIGINT columns as strings.
Unified public API for the AgentOS memory system.
One
Memoryinstance manages the full lifecycle of an agent's memories: storing, retrieving, ingesting documents, building a knowledge graph, self-improving through consolidation, and importing/exporting data.Quick start