Skip to main content

Class: Memory

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:201

Unified public API for the AgentOS memory system.

One Memory instance 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​

const mem = await Memory.create({ store: 'sqlite', path: './brain.sqlite' });

await mem.remember('The user prefers dark mode');
const results = await mem.recall('dark mode preference');
console.log(results[0].trace.content);

await mem.close();

Accessors​

graph​

Get Signature​

get graph(): IKnowledgeGraph

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1140

Access the underlying IKnowledgeGraph implementation.

Useful for advanced queries (traversal, semantic search, neighbourhood lookups) that are not exposed on the facade directly.

Returns​

IKnowledgeGraph

Methods​

addEntity()​

addEntity(entity): Promise<KnowledgeEntity>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1079

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.

Parameters​

entity​

Partial<KnowledgeEntity>

Partial entity descriptor.

Returns​

Promise<KnowledgeEntity>

The complete, persisted entity.


addRelation()​

addRelation(relation): Promise<KnowledgeRelation>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1110

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.

Parameters​

relation​

Partial<KnowledgeRelation>

Partial relation descriptor.

Returns​

Promise<KnowledgeRelation>

The complete, persisted relation.


attachWiki()​

attachWiki(wiki): void

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:882

Attach a markdown wiki store + compiler. Called by the agent at boot once the memory/ workspace directory is known. Idempotent (last call wins).

Parameters​

wiki​
compiler​

{ compile: (input) => Promise<WikiCompileResult>; }

compiler.compile​

(input) => Promise<WikiCompileResult>

store​

{ index: (o?) => Promise<unknown>; readMetaWatermark: () => Promise<string | null>; writeMetaWatermark: (iso) => Promise<void>; }

store.index​

(o?) => Promise<unknown>

store.readMetaWatermark​

() => Promise<string | null>

store.writeMetaWatermark​

(iso) => Promise<void>

Returns​

void


close()​

close(): Promise<void>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1574

Close the Memory instance and release all resources.

Flushes the SQLite WAL and releases the file lock. Must be called when the agent shuts down.

Returns​

Promise<void>


compileWiki()​

compileWiki(opts?): Promise<WikiCompileResult>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:893

Compile 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.

Parameters​

opts?​
reason?​

"explicit" | "consolidation" | "session-end"

What triggered this compile (telemetry + compiler hint).

Returns​

Promise<WikiCompileResult>


consolidate()​

consolidate(options?): Promise<MemoryConsolidationResult>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1156

Run one consolidation cycle (prune, merge, strengthen, derive, compact, re-index).

Parameters​

options?​

Optional topic filter (reserved for future use).

topic?​

string

Returns​

Promise<MemoryConsolidationResult>

Statistics from the consolidation run.

Throws​

When selfImprove was set to false in the config.


createTools()​

createTools(options?): ITool<any, any>[]

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1453

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);
}

When self-improvement is disabled, memory_reflect is omitted because there is no backing ConsolidationLoop instance.

Parameters​

options?​
includeReflect?​

boolean

Returns​

ITool<any, any>[]


export()​

export(outputPath, options?): Promise<void>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1286

Export the memory store to a file or directory.

Format is detected from options.format or the file extension:

  • .json -> JSON
  • .sqlite / .db -> SQLite file copy
  • directory path -> Markdown or Obsidian (based on options.format)

Parameters​

outputPath​

string

Path to write the export to.

options?​

ExportOptions

Optional format and content controls.

Returns​

Promise<void>


exportToString()​

exportToString(options?): Promise<string>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1426

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.

Parameters​

options?​

ExportOptions

Optional export configuration (embeddings, conversations).

Returns​

Promise<string>

Pretty-printed JSON string of the full brain payload.


feedback()​

feedback(traceId, signal, query?): Promise<void>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1183

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.

Parameters​

traceId​

string

The ID of the trace being evaluated.

signal​

Whether the trace was 'used' or 'ignored' by the LLM.

"used" | "ignored"

query?​

string

Optional retrieval context, typically the original user query.

Returns​

Promise<void>


feedbackFromResponse()​

feedbackFromResponse(injectedTraces, response, query?): Promise<RetrievalFeedback[]>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1262

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.

Parameters​

injectedTraces​

MemoryTrace[]

response​

string

query?​

string

Returns​

Promise<RetrievalFeedback[]>


forget()​

forget(traceId): Promise<void>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:815

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.

Parameters​

traceId​

string

The ID of the trace to forget.

Returns​

Promise<void>


health()​

health(): Promise<MemoryHealth>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1480

Return a health snapshot of the memory store.

Queries aggregate statistics from all tables and returns a MemoryHealth report.

Returns​

Promise<MemoryHealth>


importFrom()​

importFrom(source, options?): Promise<ImportResult>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1332

Import memory data from a file or directory.

Format is detected from options.format, the file extension, or by inspecting the content.

Parameters​

source​

string

Path to the import source (file or directory).

options?​

ImportOptions

Optional format hint and dedup settings.

Returns​

Promise<ImportResult>

Summary of the import operation.


importFromString()​

importFromString(content, format, options?): Promise<ImportResult>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1393

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.

Parameters​

content​

string

The raw string content to import.

format​

The format of the content: 'json' or 'csv'.

"json" | "csv"

options?​

Pick<ImportOptions, "dedup">

Optional deduplication controls.

Returns​

Promise<ImportResult>

Summary of the import operation.


ingest()​

ingest(source, options?): Promise<IngestResult>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:949

Ingest documents from a file, directory, or URL.

Workflow:

  1. Detect source type (file, directory, or URL).
  2. Load document(s) using the appropriate loader.
  3. Chunk each document using the configured strategy.
  4. For each chunk: insert into document_chunks, create a memory trace.
  5. Record the document in the documents table.

Parameters​

source​

string

File path, directory path, or URL.

options?​

IngestOptions

Optional ingestion settings (recursive, include/exclude globs).

Returns​

Promise<IngestResult>

Summary of the ingestion run.


recall()​

recall(query, options?): Promise<ScoredTrace[]>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:616

Search for memory traces matching a natural-language query.

Uses FTS5 full-text search with the Porter tokenizer. Results are ranked by strength * abs(fts_rank) and filtered by optional type/scope/strength criteria.

Parameters​

query​

string

Natural-language search query.

options?​

RecallOptions

Optional filters (limit, type, scope, minStrength).

Returns​

Promise<ScoredTrace[]>

Ranked array of ScoredTrace results.


recentTraces()​

recentTraces(sinceMs, options?): Promise<MemoryTrace[]>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:835

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.

Parameters​

sinceMs​

number

Exclusive lower bound on created_at (Unix ms). Use 0 for "all".

options?​

Optional scope filter, result cap (default 200), and sort order.

limit?​

number

order?​

"asc" | "desc"

scope?​

string

Returns​

Promise<MemoryTrace[]>


remember()​

remember(content, options?): Promise<MemoryTrace>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:468

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.

Parameters​

content​

string

The text content to remember.

options?​

RememberOptions

Optional metadata (type, scope, tags, importance, etc.).

Returns​

Promise<MemoryTrace>

The created MemoryTrace-like object.


create()​

static create(pathOrConfig?, opts?): Promise<Memory>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:325

Backwards-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.

Parameters​

pathOrConfig?​

string | MemoryConfig

opts?​

Omit<MemoryConfig, "path" | "store"> & object = {}

Returns​

Promise<Memory>


createPostgres()​

static createPostgres(connectionString, opts): Promise<Memory>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:381

Open a Memory backed by PostgreSQL. Requires the pg npm package.

Parameters​

connectionString​

string

Standard Postgres connection URL.

opts​

Omit<MemoryConfig, "path" | "store"> & object

Plus standard Memory options (graph, selfImprove, decay, embeddings).

Returns​

Promise<Memory>


createSqlite()​

static createSqlite(pathOrConfig?, opts?): Promise<Memory>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:335

Parameters​

pathOrConfig?​

string | MemoryConfig

opts?​

Omit<MemoryConfig, "path" | "store"> & object = {}

Returns​

Promise<Memory>


createWithAdapter()​

static createWithAdapter(adapter, opts?): Promise<Memory>

Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:400

Open a Memory with a pre-resolved StorageAdapter. Use when sharing an adapter across subsystems or when you need full control over adapter resolution.

Parameters​

adapter​

StorageAdapter

opts?​

Omit<MemoryConfig, "path" | "store"> & object = {}

Returns​

Promise<Memory>