Class: Memory
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:446
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
brainId
Get Signature
get brainId():
string
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1145
The id of the brain this facade reads and writes; a ledger row names it for the writes it records.
Returns
string
forgotten
Get Signature
get forgotten():
ForgottenLedger|undefined
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1574
The ledger the store was opened with; undefined for a store opened without one.
Returns
ForgottenLedger | undefined
graph
Get Signature
get graph():
IKnowledgeGraph
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2694
Access the underlying IKnowledgeGraph implementation.
Useful for advanced queries (traversal, semantic search, neighbourhood lookups) that are not exposed on the facade directly.
Returns
Methods
addEntity()
addEntity(
entity):Promise<KnowledgeEntity>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2633
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.
addRebuildSources()
addRebuildSources(
scopeId,traceIds):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2188
Names traces of a conversation scope for its next compile to read by id, beside the traces after its watermark:
the traces a deleted page was built from that are still there, so the page is rebuilt from them. The ids are
added to the scope's registry row (rebuild_sources), each once; a scope with no registry row takes none.
Parameters
scopeId
string
traceIds
readonly string[]
Returns
Promise<void>
addRelation()
addRelation(
relation):Promise<KnowledgeRelation>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2664
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:2225
Attach a wiki: a page store per conversation scope, a compiler, and its two optional hooks. Called by the agent at boot. Idempotent (last call wins).
Parameters
wiki
Returns
void
checkpointLog()
checkpointLog():
Promise<{log:"none"|"busy"|"emptied"; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1479
Moves the store's write-ahead log into its file and empties the log. A row deleted for good is overwritten in the page the delete wrote, and the log still holds the pages written before it until a checkpoint: a person's deletion calls this once its deletes are done, so neither file holds the deleted text.
Returns
Promise<{ log: "none" | "busy" | "emptied"; }>
'emptied' when the log holds nothing more; 'busy' when a reader or a writer of another connection held
it, and the deleted bytes stay in it until a later checkpoint; 'none' for a database that keeps no such log
(PostgreSQL).
clearLegacyOwner()
clearLegacyOwner(
agentId):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1664
Removes the attribution of the agent's older memory: the owner's deletion does, once that memory is gone.
Parameters
agentId
string
Returns
Promise<void>
close()
close():
Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:3175
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:2250
Compile new traces into wiki pages, one conversation scope at a time: each scope's traces go to the compiler
with that scope's own page store, and each scope keeps its own watermark, compiled_at in its row of
memory_scopes. No-op when no wiki is attached.
Only the scopes of a user or a session are compiled; the operator's scope never is. For each scope the traces
stored after its watermark are read oldest first, in batches. The scope's own page chunks (tagged wiki) are
left out, so a scope whose only new traces are its chunks makes no model call. The watermark then moves to the
newest trace of the batch read, not to wall-clock now.
A scope whose compile throws keeps its watermark where it was, so the next compile takes up the same traces,
and the other scopes go on. When the wiki's compileSkipReasonOf names a reason for the error, such as a spend
budget's refusal, the scope is skipped; any other error is thrown once every scope has run, the first of them
when several scopes failed. A scope the wiki's beforeScopeCompile skips keeps its watermark too. Each reason a
scope was skipped for is logged once a call, as one memory.compile_skipped line that names no scope.
Parameters
opts?
reason?
"explicit" | "consolidation" | "session-end"
What triggered this compile (telemetry + compiler hint).
scopes?
readonly string[]
The scope ids to compile. Unset: every user or session scope that holds a trace newer than its watermark. An id with no registry row, and the operator's, is left out. An empty list compiles nothing.
Returns
Promise<WikiCompileResult>
The pages written, the traces consumed and the conflicts, summed over the scopes that compiled.
consolidate()
consolidate(
options?):Promise<MemoryConsolidationResult>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2710
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.
countScope()
countScope(
scope,scopeId,options?):Promise<number>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1734
How many live traces one scope holds in this facade's Brain; with includeDeleted, the soft-deleted ones too,
which still hold their words until a delete for good (deleteScope) removes them.
Parameters
scope
string
scopeId
string
options?
includeDeleted?
boolean
Returns
Promise<number>
createTools()
createTools(
options?):ITool<any,any>[]
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:3038
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.
Parameters
options?
includeReflect?
boolean
Returns
ITool<any, any>[]
deleteGraphCopies()
deleteGraphCopies(
traceIds):Promise<number>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1133
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.
Parameters
traceIds
readonly string[]
Returns
Promise<number>
How many copies it deleted.
deletePageRows()
deletePageRows(
scopeId,pageId?):Promise<{chunks:number;pages:number; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2066
Deletes one wiki page row of a user's or a session's conversation scope, or every page row of the scope, for good: the pages' chunks first (deleteTraces), then the rows. Another scope's pages are never touched.
Parameters
scopeId
string
pageId?
string
The one page to delete; every page of the scope when left out.
Returns
Promise<{ chunks: number; pages: number; }>
How many page rows and how many chunk traces it deleted.
Throws
TypeError when scopeId is not the conversation key of a user or of a session.
Throws
InvalidWikiPageIdError for a refused page id.
Throws
When the knowledge graph cannot delete the chunks' copies: no row is deleted.
Throws
When other writers rewrote a page's row under each of its attempts to delete it: that row is kept.
deleteScope()
deleteScope(
scope,scopeId,options?):Promise<{deleted:number; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1168
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. A whole 'conversation' scope loses its row of
memory_scopes with its traces; a delete of one user's traces in it (turnUserId) keeps the row, and so does a
scope that still holds a wiki page (memory_pages): this call deletes no page row, and the registry goes on
naming the scope until its pages are deleted and the call is made again. A document chunk one of the scope's
traces was filed from lets go of it and keeps its text: to delete those chunks too, delete the scope's traces
first with deleteTraces and documentChunks: 'delete' (tracesStoredBefore lists them).
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.
Parameters
scope
string
scopeId
string
options?
turnUserId?
string
Returns
Promise<{ deleted: number; }>
Throws
TypeError 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.
Throws
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.
deleteTraces()
deleteTraces(
traceIds,options?):Promise<{deleted:number; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1234
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.
With documentChunks: 'delete' the document chunks the traces were filed from are deleted with their text, the
pictures of those chunks, and each document left with no chunk: a person's deletion and the retention sweep pass
it. On an adapter with transactions those deletes share one, so a failure among them deletes none and a later call
finds them again.
A delete only marks a trace's vector in the vector index, which keeps the numbers in its files until it is written again: rebuildVectorIndex writes it from the traces that are left.
Parameters
traceIds
readonly string[]
options?
documentChunks?
"delete"
Returns
Promise<{ deleted: number; }>
How many trace rows it deleted, so a call made again counts none.
Throws
When the knowledge graph cannot delete the copies: no row is deleted, so a later call deletes them.
deleteTracesNamingUser()
deleteTracesNamingUser(
userId):Promise<{deleted:number; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1406
Deletes for good every trace whose metadata names the user as turnUserId, under any scope and under none, live
or soft-deleted, with the document chunks those traces were filed from (deleteTraces with
documentChunks: 'delete'). A person's deletion calls it for what they said on someone else's session.
Parameters
userId
string
Returns
Promise<{ deleted: number; }>
How many trace rows it deleted.
Throws
TypeError when userId is not a non-empty string.
ensureEncodedScopeIds()
ensureEncodedScopeIds():
Promise<number>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1718
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.
Returns
Promise<number>
How many traces it moved: none when the Brain held the record already.
export()
export(
outputPath,options?):Promise<ExportResult>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2853
Export 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 rows- directory path -> Markdown or Obsidian (based on
options.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.
Parameters
outputPath
string
Path to write the export to.
options?
Optional format and content controls.
Returns
Promise<ExportResult>
The traces the export left out, with the reason for each.
exportToString()
exportToString(
options?):Promise<string>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:3006
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?
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:2737
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:2816
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
response
string
query?
string
Returns
Promise<RetrievalFeedback[]>
finishErasure()
finishErasure():
Promise<{fullText:"rebuilt"|"not owed";log:"none"|"busy"|"not owed"|"emptied";vectorIndex:"not owed"|"rewritten"; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1508
Finishes what deletes for good left in the store's files: on SQLite the full-text index is rebuilt (finishFullTextIndex) when a delete's own rebuild failed; the vector index is written again (rebuildVectorIndex) when a delete, or an open whose check of the index failed, left it naming a trace that is gone; the write-ahead log is emptied (checkpointLog) when deletes were made after the last checkpoint that emptied it, or the full-text index was rebuilt here. Nothing owed, nothing runs. A retention sweep, a correction and a re-application of the tombstones call it, so a rebuild, a rewrite or a checkpoint that failed in an earlier call runs again.
Returns
Promise<{ fullText: "rebuilt" | "not owed"; log: "none" | "busy" | "not owed" | "emptied"; vectorIndex: "not owed" | "rewritten"; }>
Whether the full-text index was rebuilt and the vector index written again, and what the checkpoint
answered; 'not owed' for a step that had nothing to do.
Throws
What the first failed step throws, once every step was tried. A step that fails, and a checkpoint another
connection held ('busy'), stay owed.
finishFullTextIndex()
finishFullTextIndex():
Promise<{fullText:"rebuilt"|"not owed"; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1296
Rebuilds the full-text index when a delete for good could not: until a rebuild succeeds, the index keeps the words of the rows deleted. Nothing owed, nothing runs; PostgreSQL keeps the index in each row, which goes with the row. A person's deletion calls it once its deletes are done, and finishErasure calls it too.
Returns
Promise<{ fullText: "rebuilt" | "not owed"; }>
'rebuilt', or 'not owed'.
Throws
What the rebuild throws; it stays owed.
forget()
forget(
traceId):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1114
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.
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:3070
Return 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.
Returns
Promise<MemoryHealth>
importFrom()
importFrom(
source,options?):Promise<ImportResult>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2900
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.
Parameters
source
string
Path to the import source (file or directory).
options?
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:2971
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:2503
Ingest documents from a file, directory, or URL.
Workflow:
- Detect source type (file, directory, or URL).
- Load document(s) using the appropriate loader.
- Chunk each document using the configured strategy.
- For each chunk: insert into
document_chunks, create a memory trace. - Record the document in the
documentstable.
Parameters
source
string
File path, directory path, or URL.
options?
Optional ingestion settings (recursive, include/exclude globs).
Returns
Promise<IngestResult>
Summary of the ingestion run.
isForgotten()
isForgotten(
subject):Promise<boolean>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1568
Whether this store's ledger holds a tombstone of the subject, in any form.
Parameters
subject
Returns
Promise<boolean>
Throws
When the store was opened without a ledger (forgotten in its config).
legacyOwner()
legacyOwner(
agentId):Promise<string|undefined>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1638
The conversation key of the user the agent's memory from before per-user scope is attributed to; undefined when it is attributed to nobody. An attribution stands for the store's life, whatever later opens pass.
Parameters
agentId
string
Returns
Promise<string | undefined>
listHeldSubjects()
listHeldSubjects():
Promise<SuppressionSubject[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1588
Every subject this store holds anything of, each once: the users and sessions whose conversation key names a
registry row, a trace or a wiki page of this brain (a registry row may be gone after a deletion that did not
finish), the users a trace's metadata names as turnUserId, and, where the store's database holds the learning
tables, the users any learner row names (sessions, chain heads, the ledger and its turn users, traits, freezes,
outcomes, lessons and skills), so a restore that put back one row of a learner alone leads back to them, and the
user memory from before per-user scope is
attributed to (legacyOwner). The operator's key names no subject. The re-application of the tombstones asks
the ledger about each.
Returns
Promise<SuppressionSubject[]>
listPageRows()
listPageRows(
scopeId):Promise<MemoryPageRow[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1803
Every wiki page row of one conversation scope, by page id. The scope's key is matched by equality.
Parameters
scopeId
string
Returns
Promise<MemoryPageRow[]>
listScopes()
listScopes(
filter?):Promise<MemoryScopeRow[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1753
The registered scopes of this facade's Brain, by scope id: each conversation scope gets its row of
memory_scopes with its first trace (remember), and loses it when the scope is deleted
(deleteScope).
Parameters
filter?
kind?
string
Only the scopes of one kind of subject: 'user', 'session' or 'operator'.
scope?
string
The scope to list. Defaults to 'conversation', the one scope that is registered.
Returns
Promise<MemoryScopeRow[]>
Each scope's id, the kind and agent id its key holds, when it was first written (Unix ms) and when it was last compiled into wiki pages (Unix ms; null before its first compile).
liveTraceIdsOf()
liveTraceIdsOf(
scope,scopeId,traceIds):Promise<string[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1335
Which of the given ids are live traces of one scope, a wiki page's chunks left out: a chunk is not a statement a person made. A correction checks with it that every trace it names is the person's own before it changes anything. The scope id is matched by equality, 400 ids a statement.
Parameters
scope
string
scopeId
string
traceIds
readonly string[]
Returns
Promise<string[]>
The ids found, each once, in no set order.
Throws
TypeError when scopeId is empty.
markForgotten()
markForgotten(
subject):Promise<{form:"keyed"|"unkeyed";written:boolean; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1558
Records a subject as forgotten in this store's ledger: its copy first, then the store.
Parameters
subject
Returns
Promise<{ form: "keyed" | "unkeyed"; written: boolean; }>
Throws
When the store was opened without a ledger (forgotten in its config), or when either write fails.
pageExistsOutside()
pageExistsOutside(
scopeId,pageId):Promise<boolean>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2120
Whether a conversation scope other than scopeId holds a wiki page row of that id; with null, whether any
conversation scope does. The answer says why a page was not found for one asker, for a log line: nothing a
caller is served depends on it, and it names no scope.
Parameters
scopeId
The asker's own key, left out of the search; null to search every scope.
string | null
pageId
string
Returns
Promise<boolean>
Throws
InvalidWikiPageIdError for a refused page id; nothing is read.
readPageRow()
readPageRow(
scopeId,pageId):Promise<MemoryPageRow|null>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1790
One wiki page row of one conversation scope; null when the scope holds no page of that id.
Parameters
scopeId
string
The scope's key, matched by equality.
pageId
string
Returns
Promise<MemoryPageRow | null>
Throws
InvalidWikiPageIdError for a refused page id; nothing is read.
readTrace()
readTrace(
traceId):Promise<TraceSnapshot|undefined>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1725
One row of this facade's Brain as a snapshot, live or deleted; undefined when there is none.
Parameters
traceId
string
Returns
Promise<TraceSnapshot | undefined>
rebuildVectorIndex()
rebuildVectorIndex():
Promise<{vectors:number; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1459
Writes the vector index again from the live traces that are left, or removes its files when none is left. A delete only marks a vector in the index, so the numbers of a deleted trace stay in the index files until this runs: call it after deleting for good.
It runs after the vector index's other work and reads the traces inside its own step: a trace deleted while an earlier rewrite runs is not written back by this one, and a trace remembered while it runs is indexed after it.
Returns
Promise<{ vectors: number; }>
How many vectors the index holds afterwards: 0 for a store with no file path, and where hnswlib-node
is not installed (no index file is written there).
Throws
When an index file cannot be removed, or when the rebuilt index did not save.
recall()
recall(
query,options?):Promise<ScoredTrace[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:894
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.
Parameters
query
string
Natural-language search query.
options?
Optional filters (limit, type, scope, scopeId, minStrength, after, before).
Returns
Promise<ScoredTrace[]>
Ranked array of ScoredTrace results. A call with no scope and no scope id reads the whole brain, every subject's conversation traces among them: the host's own read of its store. No turn, tool or prompt of a souled agent makes one; pass the scope and a key to read one subject.
Throws
TypeError when options.scope is 'conversation' and no scopeId is given: the conversation scope
holds each subject's memory under a key of its own and is read one key at a time, never as a whole.
recentTraces()
recentTraces(
sinceMs,options?):Promise<MemoryTrace[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:2150
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, scope id filter (equality on the scope_id column), result cap
(default 200), and sort order.
limit?
number
order?
"asc" | "desc"
scope?
string
scopeId?
string
Returns
Promise<MemoryTrace[]>
Throws
TypeError when options.scope is 'conversation' and no scopeId is given: that scope is read one
key at a time.
reindexPageRow()
reindexPageRow(
scopeId,pageId,chunksOf):Promise<{chunkIds:string[];removed:string[]; } |null>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1860
Files a page's chunks again from the text its row holds when the write runs, and keeps that text: a page another write changed after a caller listed it is chunked as it is now, and never written back as it was listed. The old chunks are deleted for good, as writePageRow deletes them.
Parameters
scopeId
string
pageId
string
chunksOf
(content) => readonly MemoryPageChunk[] | null
The chunks of a row's stored text; null when the text does not parse, which writes nothing.
Returns
Promise<{ chunkIds: string[]; removed: string[]; } | null>
The ids of the chunks the row lists and of the chunks it listed before; null when the scope holds no page
of that id or chunksOf answered null.
Throws
TypeError when scopeId is not the conversation key of a user or of a session.
Throws
InvalidWikiPageIdError for a refused page id.
remember()
remember(
content,options?):Promise<MemoryTrace>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:773
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.
A trace of the 'conversation' scope is filed under a key conversationScopeKey built, and the scope's row
of memory_scopes is written with its first trace: in one transaction where the adapter has them, and before
the trace where it has none, so no conversation trace is stored under a scope the registry does not name.
Parameters
content
string
The text content to remember.
options?
Optional metadata (type, scope, tags, importance, etc.).
Returns
Promise<MemoryTrace>
The created MemoryTrace-like object.
Throws
TypeError when options.scope is 'conversation' and options.scopeId is not a key
conversationScopeKey built; nothing is stored.
restoreTrace()
restoreTrace(
traceId,before):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1683
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.
Parameters
traceId
string
before
Returns
Promise<void>
Throws
When the snapshot is of another trace.
setLegacyOwner()
setLegacyOwner(
agentId,ownerKey):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1651
Attributes the agent's memory from before per-user scope to one user, by their conversation key. An attribution already made is never moved: the call then writes nothing.
Parameters
agentId
string
ownerKey
string
Returns
Promise<void>
tracesNamingUser()
tracesNamingUser(
userId):Promise<object[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1423
Every trace whose metadata names the user as turnUserId, under any scope and under none, live or soft-deleted,
each with the scope and the scope id it is filed under ('' for none). A person's deletion reads them first, to
find the pages of another person's conversation that were compiled from them.
Parameters
userId
string
Returns
Promise<object[]>
Throws
TypeError when userId is not a non-empty string.
tracesStoredBefore()
tracesStoredBefore(
scope,scopeId,beforeMs):Promise<string[]>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1314
The ids of one scope's traces stored before a time, live or soft-deleted, a wiki page's chunks left out: a chunk
follows its page, never its own age. A person's deletion lists every trace of theirs with it (a bound past any
time a trace was stored), and a retention sweep the traces that expired. Like deleteScope, it first files
the brain's rows that hold '' as their scope id while their metadata names one.
Parameters
scope
string
scopeId
string
beforeMs
number
Exclusive upper bound on the time a trace was stored (Unix ms).
Returns
Promise<string[]>
Throws
TypeError when scopeId is empty.
waitForScopeChanges()
waitForScopeChanges(
scopeId):Promise<void>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1442
Resolves once every compile, scope delete and page delete of one conversation scope that this store's facades in this process started before the call has settled. A person's deletion waits with it for a compile of another person's conversation that read what the person said before it was deleted, and then deletes the page that compile wrote. Writers in other processes are not waited for.
Parameters
scopeId
string
Returns
Promise<void>
writePageRow()
writePageRow(
scopeId,page):Promise<{chunkIds:string[]; }>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:1833
Writes one wiki page row of a user's or a session's conversation scope, with its chunks. With chunks, the
page's old chunks are deleted for good, the new ones are filed as traces under the scope's key with the tags
wiki and page:<id>, and the row lists them; without, the row's content is replaced and its chunks are kept.
With chunks and keepChunksIfUnchanged, the stored row is compared once the scope's earlier page writes have
settled: a row whose contentHash is the one given keeps its chunks, and any other row gets the new ones.
The scope's registry row, the new chunks, the page row and the delete of the old chunks are one transaction
where the adapter has them; where it has none they run in that order, so the row never lists a chunk that is
not stored. The row is replaced only while it holds the text and the chunks the write read: a writer in another
process that changed it meanwhile makes the write read it again and start over, so no chunk that writer filed is
left unlisted.
Parameters
scopeId
string
page
chunks?
readonly MemoryPageChunk[]
content
string
contentHash
string
keepChunksIfUnchanged?
boolean
pageId
string
Returns
Promise<{ chunkIds: string[]; }>
The ids of the chunks the row lists.
Throws
TypeError when scopeId is not the conversation key of a user or of a session.
Throws
InvalidWikiPageIdError for a refused page id.
Throws
When the knowledge graph cannot delete the old chunks' copies: nothing is changed.
Throws
Error when other writers changed the row under each of the write's attempts.
create()
staticcreate(pathOrConfig?,opts?):Promise<Memory>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:607
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, "store" | "path"> & object = {}
Returns
Promise<Memory>
createPostgres()
staticcreatePostgres(connectionString,opts):Promise<Memory>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:663
Open a Memory backed by PostgreSQL. Requires the pg npm package.
Parameters
connectionString
string
Standard Postgres connection URL.
opts
Omit<MemoryConfig, "store" | "path"> & object
Plus standard Memory options (graph, selfImprove, decay, embeddings).
Returns
Promise<Memory>
createSqlite()
staticcreateSqlite(pathOrConfig?,opts?):Promise<Memory>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:617
Parameters
pathOrConfig?
string | MemoryConfig
opts?
Omit<MemoryConfig, "store" | "path"> & object = {}
Returns
Promise<Memory>
createWithAdapter()
staticcreateWithAdapter(adapter,opts?):Promise<Memory>
Defined in: packages/agentos/src/cognition/memory/io/facade/Memory.ts:682
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, "store" | "path"> & object = {}
Returns
Promise<Memory>