Skip to main content

Class: SqlKnowledgeGraph

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:283

Persistent knowledge graph backed by SQLite via Brain.

Implements the full IKnowledgeGraph interface using the knowledge_nodes and knowledge_edges tables. Extended entity/relation fields that don't have dedicated columns are serialized into the JSON properties / metadata columns.

Example​

const brain = await Brain.openSqlite('/tmp/agent-brain.sqlite');
const graph = new SqlKnowledgeGraph(brain);
await graph.initialize();

const entity = await graph.upsertEntity({
type: 'person',
label: 'Alice',
properties: { role: 'engineer' },
confidence: 0.95,
source: { type: 'user_input', timestamp: new Date().toISOString() },
});

Implements​

Constructors​

Constructor​

new SqlKnowledgeGraph(brain): SqlKnowledgeGraph

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:303

Parameters​

brain​

Brain

A Brain instance whose async StorageAdapter methods are used for all queries.

Returns​

SqlKnowledgeGraph

Methods​

clear()​

clear(): Promise<void>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1570

Delete all rows from knowledge_nodes and knowledge_edges. Wipes the knowledge graph completely.

Returns​

Promise<void>

Implementation of​

IKnowledgeGraph.clear


decayMemories()​

decayMemories(decayFactor?): Promise<number>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1474

Decay the confidence of all memory-type nodes by a multiplicative factor.

This simulates the Ebbinghaus forgetting curve — memories that are not accessed (reinforced) gradually fade.

Parameters​

decayFactor?​

number

Multiplicative factor in (0, 1). Default 0.95.

Returns​

Promise<number>

The number of memory nodes whose confidence was reduced.

Implementation of​

IKnowledgeGraph.decayMemories


deleteEntity()​

deleteEntity(id): Promise<boolean>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:486

Delete an entity and all its associated relations (incoming and outgoing). Returns true if the entity existed and was deleted.

Parameters​

id​

string

Returns​

Promise<boolean>

Implementation of​

IKnowledgeGraph.deleteEntity


deleteMemories()​

deleteMemories(filter): Promise<number>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:737

Delete the memory nodes that copy the filter's traces or scopes, with the relations that name them, as deleteEntity deletes an entity's. A trace's copy is deleted by its key; the first delete by trace id of this instance first gives the copies an older release recorded their key (rekeyOlderCopies), and a copy whose move failed in that pass is deleted by its node id. While that pass fails as a whole, a delete by trace id reads the trace's copies held under another node id by the text their stored JSON holds (olderCopyIds) and deletes them too. A scope's copies are read by the text their stored JSON holds (LIKE with an escape clause, which on SQLite also matches the text in other letter cases) and matched exactly in code, so a malformed properties value is skipped rather than failing the delete.

Parameters​

filter​

MemoryCopyFilter

Returns​

Promise<number>

Implementation of​

IKnowledgeGraph.deleteMemories


deleteRelation()​

deleteRelation(id): Promise<boolean>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:616

Delete a single relation by its ID. Returns true if the relation existed and was deleted.

Parameters​

id​

string

Returns​

Promise<boolean>

Implementation of​

IKnowledgeGraph.deleteRelation


extractFromText()​

extractFromText(_text, _options?): Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1399

Extract entities and relations from text.

This operation requires an LLM and is not supported at the store level. Use the Memory facade for LLM-powered extraction.

Parameters​

_text​

string

_options?​
entityTypes?​

EntityType[]

extractRelations?​

boolean

Returns​

Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>

Throws​

Always — extraction requires an LLM.

Implementation of​

IKnowledgeGraph.extractFromText


findPath()​

findPath(sourceId, targetId, maxDepth?): Promise<object[] | null>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1131

Find the shortest path between two entities using a bidirectional BFS implemented via a recursive CTE.

Returns an ordered array of { entity, relation? } steps from source to target, or null if no path exists within maxDepth hops.

Parameters​

sourceId​

string

targetId​

string

maxDepth?​

number

Returns​

Promise<object[] | null>

Implementation of​

IKnowledgeGraph.findPath


getEntity()​

getEntity(id): Promise<KnowledgeEntity | undefined>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:402

Retrieve a single entity by its ID. Returns undefined if the entity does not exist.

Parameters​

id​

string

Returns​

Promise<KnowledgeEntity | undefined>

Implementation of​

IKnowledgeGraph.getEntity


getMemory()​

getMemory(id): Promise<EpisodicMemory | undefined>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:717

Get an episodic memory by ID.

Looks up the knowledge_node with the given ID and type = 'memory', then unpacks the memory-specific fields from the properties JSON.

Parameters​

id​

string

Returns​

Promise<EpisodicMemory | undefined>

Implementation of​

IKnowledgeGraph.getMemory


getNeighborhood()​

getNeighborhood(entityId, depth?): Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1212

Get the neighbourhood of an entity — all entities and relations within depth hops.

Parameters​

entityId​

string

Centre entity.

depth?​

number

Maximum number of hops (default 1).

Returns​

Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>

Implementation of​

IKnowledgeGraph.getNeighborhood


getRelations()​

getRelations(entityId, options?): Promise<KnowledgeRelation[]>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:580

Get all relations for a given entity.

Parameters​

entityId​

string

The entity whose relations to retrieve.

options?​

Optional filters: direction ('outgoing'|'incoming'|'both'), types.

direction?​

"outgoing" | "incoming" | "both"

types?​

RelationType[]

Returns​

Promise<KnowledgeRelation[]>

Implementation of​

IKnowledgeGraph.getRelations


getStats()​

getStats(): Promise<KnowledgeGraphStats>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1493

Get aggregate statistics about the knowledge graph.

Returns counts of entities, relations, memories, breakdowns by type, average confidence, and oldest/newest entry timestamps.

Returns​

Promise<KnowledgeGraphStats>

Implementation of​

IKnowledgeGraph.getStats


initialize()​

initialize(): Promise<void>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:317

Initialize the knowledge graph.

The schema is already created by Brain's constructor, so this is effectively a no-op. Provided to satisfy the IKnowledgeGraph contract.

Returns​

Promise<void>

Implementation of​

IKnowledgeGraph.initialize


mergeEntities()​

mergeEntities(entityIds, primaryId): Promise<KnowledgeEntity>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1421

Merge multiple entities into one primary entity.

All relations (edges) pointing to or from the non-primary entities are re-linked to the primary entity. The non-primary entities are then deleted.

Parameters​

entityIds​

string[]

All entity IDs involved in the merge.

primaryId​

string

The ID that survives the merge.

Returns​

Promise<KnowledgeEntity>

Implementation of​

IKnowledgeGraph.mergeEntities


queryEntities()​

queryEntities(options?): Promise<KnowledgeEntity[]>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:418

Query entities with optional filters.

Supports filtering by entity type, tags, owner, minimum confidence, full-text search, pagination (limit/offset), and time ranges.

Parameters​

options?​

KnowledgeQueryOptions

Returns​

Promise<KnowledgeEntity[]>

Implementation of​

IKnowledgeGraph.queryEntities


queryMemories()​

queryMemories(options?): Promise<EpisodicMemory[]>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:876

Query episodic memories with optional filters.

Supports filtering by memory sub-type, participants, minimum importance, time range, and result limit.

Parameters​

options?​
limit?​

number

minImportance?​

number

participants?​

string[]

timeRange?​

{ from?: string; to?: string; }

timeRange.from?​

string

timeRange.to?​

string

types?​

("discovery" | "success" | "error" | "conversation" | "task" | "interaction")[]

Returns​

Promise<EpisodicMemory[]>

Implementation of​

IKnowledgeGraph.queryMemories


recallMemories()​

recallMemories(query, topK?): Promise<EpisodicMemory[]>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:934

Recall relevant memories via keyword search against summaries.

Performs a case-insensitive substring match on the label (which contains the summary text). Increments accessCount and updates lastAccessedAt for each returned memory (Hebbian reinforcement).

Full semantic (embedding-based) recall requires the Memory facade.

Parameters​

query​

string

topK?​

number

Returns​

Promise<EpisodicMemory[]>

Implementation of​

IKnowledgeGraph.recallMemories


recordMemory()​

recordMemory(memory): Promise<EpisodicMemory>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:637

Record an episodic memory.

Memories are stored as knowledge_nodes with type = 'memory'. The memory-specific fields are packed into the properties JSON column. A memory trace's copy (a context that names the trace, memoryTraceId) is keyed by the trace (trace:<traceId>): recording the trace again replaces the copy, and a delete by trace id finds it by key.

Parameters​

memory​

Omit<EpisodicMemory, "id" | "createdAt" | "accessCount" | "lastAccessedAt">

Returns​

Promise<EpisodicMemory>

Implementation of​

IKnowledgeGraph.recordMemory


semanticSearch()​

semanticSearch(options): Promise<SemanticSearchResult[]>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:1276

Semantic search across entities and/or memories.

Loads all embeddings from knowledge_nodes, computes cosine similarity against the query embedding (if present in options), and returns the top-K results above the minimum similarity threshold.

NOTE: This implementation requires the caller to provide a query embedding via a pre-processing step. If no nodes have embeddings, an empty array is returned. For full text-to-embedding semantic search, use the Memory facade.

Parameters​

options​

SemanticSearchOptions

Returns​

Promise<SemanticSearchResult[]>

Implementation of​

IKnowledgeGraph.semanticSearch


traverse()​

traverse(startEntityId, options?): Promise<TraversalResult>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:987

Traverse the graph from a starting entity using BFS.

Uses a recursive CTE (Common Table Expression) to walk the graph up to maxDepth hops from the start node. Results are grouped by depth level.

Parameters​

startEntityId​

string

ID of the entity to start traversal from.

options?​

TraversalOptions

Optional: maxDepth, relationTypes, direction, minWeight, maxNodes.

Returns​

Promise<TraversalResult>

Implementation of​

IKnowledgeGraph.traverse


upsertEntity()​

upsertEntity(entity): Promise<KnowledgeEntity>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:336

Insert or update a knowledge entity.

If entity.id is provided and exists, the row is updated (INSERT OR REPLACE). If omitted, a new UUID is generated.

Extended fields (ownerId, tags, metadata, updatedAt) are packed into the properties JSON column as underscore-prefixed keys to avoid collisions with user-supplied properties.

Parameters​

entity​

Omit<KnowledgeEntity, "id" | "updatedAt" | "createdAt"> & object

Returns​

Promise<KnowledgeEntity>

Implementation of​

IKnowledgeGraph.upsertEntity


upsertRelation()​

upsertRelation(relation): Promise<KnowledgeRelation>

Defined in: packages/agentos/src/cognition/memory/retrieval/store/SqlKnowledgeGraph.ts:515

Insert or update a knowledge relation (edge).

Extended edge fields (label, properties, confidence, source, validFrom, validTo) are packed into the metadata JSON column.

Parameters​

relation​

Omit<KnowledgeRelation, "id" | "createdAt"> & object

Returns​

Promise<KnowledgeRelation>

Implementation of​

IKnowledgeGraph.upsertRelation