Skip to main content

Explicit Facts API

Use for independent structured fact ingestion/search and administration. Runtime extraction/resolution already runs asynchronously under governed model policy. Configure local belief-revision callbacks only in an explicitly owned advanced administrative workflow, never as a second normal app writer.

Usage boundary​

Access the namespace on an explicitly configured root Cortex client. Host JWT and deployment-operator transports are distinct; validate current resource scope and do not infer authority from AuthContext metadata. See administrative operations.

Store, deduplicate and revise​

A stored fact requires a nonempty memorySpaceId and fact, a supported factType, confidence 0–100 and a supported sourceType. Fact types are preference, identity, knowledge, relationship, event, observation and custom; source types include conversation, system, tool, manual, a2a and fact-extraction. IDs used by get/update/delete must start with fact-. Invalid input raises FactsValidationError with code and field, including INVALID_CONFIDENCE, INVALID_FACT_TYPE, INVALID_SOURCE_TYPE and INVALID_FACT_ID_FORMAT. Fact pagination limit/offset must be nonnegative integers.

sourceRef links the conversation/messages/memory that supplied the fact. subject, predicate and object support structured matching. Optional tags, category, aliases, semantic context, entities and relations enrich retrieval. The persisted FactRecord includes factId, version, timestamps, provenance and temporal validity; expired/superseded facts remain distinct from active facts.

storeWithDedup(params, { deduplication }) accepts the following choices:

ChoiceMatching and behavior
false or "none"Store a new record without duplicate matching.
"exact"Compare normalized fact text.
"structural"Compare the subject/predicate/object triple, with exact text fallback.
"semantic"Try structural and exact matching, then embedding similarity.
{ strategy: "semantic", similarityThreshold, generateEmbedding }Use a supplied operator embedding callback with a 0–1 threshold, default 0.85.

The default strategy is semantic. Without an embedding callback, it warns and falls back to structural matching. Searches retain memory-space, tenant and user scope. A matching fact is updated only when the new confidence is higher; the update merges supplied tags. Otherwise the existing fact is returned unchanged. wasUpdated: false can mean either a new fact or an unchanged duplicate: inspect deduplication?.matchedExisting. similarityScore is optional. Semantic callbacks are advanced operator work and should be governed by the operator's budgets; they are not an additional application memory pipeline for remote Agent turns.

import type { Cortex } from '@cortexmemory/sdk';

export async function storeApprovedFact(cortex: Cortex, memorySpaceId: string) {
const result = await cortex.facts.storeWithDedup({
memorySpaceId, userId: 'user-123',
fact: 'Alex prefers Tuesday morning deliveries', factType: 'preference',
subject: 'user-123', predicate: 'delivery_window', object: 'Tuesday morning',
confidence: 95, sourceType: 'manual', tags: ['delivery'],
}, { deduplication: 'structural' });
return { factId: result.fact.factId, updated: result.wasUpdated,
matchedExisting: result.deduplication?.matchedExisting ?? false };
}

Belief revision handles changed knowledge rather than merely duplicate text. Call configureBeliefRevision(llmClient?, config?) before revise, or use the service configured on the root client. checkConflicts previews slot and semantic conflicts and returns a recommended action without committing the revision. Slot matching is enabled by default; semantic matching uses default threshold 0.7, and LLM resolution is enabled when a client is supplied. ReviseResult reports ADD/UPDATE/SUPERSEDE/NONE, the resulting fact, superseded records, reason/confidence and which pipeline stages ran. History retains the decision's provenance.

import type { Cortex } from '@cortexmemory/sdk';

export async function reviseApprovedFact(cortex: Cortex, memorySpaceId: string) {
cortex.facts.configureBeliefRevision(undefined, {
semanticMatching: { enabled: false }, llmResolution: { enabled: false },
});
const input = { memorySpaceId, userId: 'user-123', sourceType: 'manual' as const,
fact: { fact: 'Alex now prefers Wednesday deliveries', factType: 'preference',
subject: 'user-123', predicate: 'delivery_window', object: 'Wednesday', confidence: 95 } };
const preview = await cortex.facts.checkConflicts(input);
const revision = await cortex.facts.revise(input);
return { preview, action: revision.action, superseded: revision.superseded,
pipeline: revision.pipeline, reason: revision.reason };
}

revise throws when the service is unconfigured. A history-write error can occur after the fact mutation committed: use the returned history receipt/repair operation where provided; do not replay the fact mutation as a new decision. Subject/relationship queries, semantic search, version history and timestamp reads are supported explicit APIs. Get/version/timestamp calls return null when no record/version exists. Archive/delete operations can report partial selected-domain outcomes; preserve their intent and physical IDs for reconciliation.

Parameter and result contracts​

These are reference definitions for the explicit server APIs. Optional fields use ?; timestamps are milliseconds since epoch unless an operation accepts a Date. Resource identifiers and participant metadata do not grant runtime authority.

StoreFactParams​

export interface StoreFactParams {
memorySpaceId: string;
tenantId?: string;
participantId?: string;
userId?: string;
fact: string;
factType:
| "preference"
| "identity"
| "knowledge"
| "relationship"
| "event"
| "observation"
| "custom";
subject?: string;
predicate?: string;
object?: string;
confidence: number;
sourceType: "conversation" | "system" | "tool" | "manual" | "a2a" | "fact-extraction";
sourceRef?: {
conversationId?: string;
messageIds?: string[];
memoryId?: string;
};
metadata?: Record<string, unknown>;
tags?: string[];
category?: string;
searchAliases?: string[];
semanticContext?: string;
entities?: EnrichedEntity[];
relations?: EnrichedRelation[];
validFrom?: number;
validUntil?: number;
embedding?: number[];
}

StoreFactOptions​

export interface StoreFactOptions extends GraphSyncOption {}

Also inherits GraphSyncOption. See shared contracts.

DeduplicationStrategy​

export type DeduplicationStrategy =
| "none"
| "exact"
| "structural"
| "semantic";

DeduplicationConfig​

export interface DeduplicationConfig {
strategy: DeduplicationStrategy;
similarityThreshold?: number;
generateEmbedding?: (text: string) => Promise<number[]>;
}
FieldMeaning and defaults
strategyDeduplication strategy to use
similarityThresholdSimilarity threshold for semantic matching (0-1) Only used when strategy is 'semantic'
generateEmbeddingFunction to generate embeddings for semantic matching Required when strategy is 'semantic', otherwise ignored

StoreWithDedupResult​

export interface StoreWithDedupResult {
fact: FactRecord;
wasUpdated: boolean;
deduplication?: {
strategy: DeduplicationStrategy;
matchedExisting: boolean;
similarityScore?: number;
};
}
FieldMeaning and defaults
factThe fact record (new or existing)
wasUpdatedWhether an existing fact was updated instead of creating new
deduplicationDeduplication details

FactRecord​

export interface FactRecord extends GraphCaptureMetadata {
_id: string;
factId: string;
memorySpaceId: string;
tenantId?: string;
participantId?: string;
userId?: string;
fact: string;
factType:
| "preference"
| "identity"
| "knowledge"
| "relationship"
| "event"
| "observation"
| "custom";
subject?: string;
predicate?: string;
object?: string;
confidence: number;
sourceType: "conversation" | "system" | "tool" | "manual" | "a2a" | "fact-extraction";
sourceRef?: {
conversationId?: string;
messageIds?: string[];
memoryId?: string;
};
metadata?: Record<string, unknown>;
tags: string[];
category?: string;
searchAliases?: string[];
semanticContext?: string;
entities?: EnrichedEntity[];
relations?: EnrichedRelation[];
validFrom?: number;
validUntil?: number;
version: number;
supersededBy?: string;
supersedes?: string;
createdAt: number;
updatedAt: number;
embedding?: number[];
supersedesEndpoint?: import("../facts/history").PendingRichEventV1["payload"]["supersedesEndpoint"];
supersededByEndpoint?: import("../facts/history").PendingRichEventV1["payload"]["supersededByEndpoint"];
historyReceipt?: import("../facts/history").HistoryReceipt;
}

Also inherits GraphCaptureMetadata. See shared contracts.

ListFactsFilter​

export interface ListFactsFilter {
memorySpaceId: string;
tenantId?: string;
factType?:
| "preference"
| "identity"
| "knowledge"
| "relationship"
| "event"
| "observation"
| "custom";
subject?: string;
predicate?: string;
object?: string;
minConfidence?: number;
confidence?: number;
userId?: string;
participantId?: string;
tags?: string[];
tagMatch?: "any" | "all";
sourceType?: "conversation" | "system" | "tool" | "manual";
createdBefore?: Date;
createdAfter?: Date;
updatedBefore?: Date;
updatedAfter?: Date;
version?: number;
includeSuperseded?: boolean;
validAt?: Date;
metadata?: Record<string, unknown>;
limit?: number;
offset?: number;
sortBy?: "createdAt" | "updatedAt" | "confidence" | "version";
sortOrder?: "asc" | "desc";
}

SearchFactsOptions​

export interface SearchFactsOptions {
tenantId?: string;
factType?:
| "preference"
| "identity"
| "knowledge"
| "relationship"
| "event"
| "observation"
| "custom";
subject?: string;
predicate?: string;
object?: string;
minConfidence?: number;
confidence?: number;
userId?: string;
participantId?: string;
tags?: string[];
tagMatch?: "any" | "all";
sourceType?: "conversation" | "system" | "tool" | "manual";
createdBefore?: Date;
createdAfter?: Date;
updatedBefore?: Date;
updatedAfter?: Date;
version?: number;
includeSuperseded?: boolean;
validAt?: Date;
metadata?: Record<string, unknown>;
limit?: number;
offset?: number;
sortBy?: "confidence" | "createdAt" | "updatedAt";
sortOrder?: "asc" | "desc";
}

SemanticSearchFactsOptions​

export interface SemanticSearchFactsOptions {
tenantId?: string;
userId?: string;
minConfidence?: number;
includeSuperseded?: boolean;
minScore?: number;
limit?: number;
tags?: string[];
createdAfter?: Date;
createdBefore?: Date;
}
FieldMeaning and defaults
tenantIdMulti-tenancy filter
userIdFilter by user who created the fact
minConfidenceMinimum confidence threshold (0-100)
includeSupersededInclude superseded facts (default: false)
minScoreMinimum similarity score (0-1, default: 0.3)
limitMaximum results to return (default: 20)
tagsFilter by tags (any match)
createdAfterFilter facts created after this date
createdBeforeFilter facts created before this date

UpdateFactInput​

export interface UpdateFactInput {
fact?: string;
confidence?: number;
tags?: string[];
validUntil?: number;
metadata?: Record<string, unknown>;
category?: string;
searchAliases?: string[];
semanticContext?: string;
entities?: EnrichedEntity[];
relations?: EnrichedRelation[];
embedding?: number[];
}

ReviseParams​

export interface ReviseParams {
syncToGraph?: boolean;
memorySpaceId: string;
fact: ConflictCandidate;
userId?: string;
participantId?: string;
tenantId?: string;
sourceType?: "conversation" | "system" | "tool" | "manual" | "a2a";
sourceRef?: {
conversationId?: string;
messageIds?: string[];
memoryId?: string;
};
}
FieldMeaning and defaults
memorySpaceIdMemory space to operate in
factThe new fact to evaluate
userIdOptional user ID filter
participantIdOptional participant ID
tenantIdMulti-tenancy: SaaS platform isolation
sourceTypeSource type for provenance tracking
sourceRefSource reference for provenance tracking

ConflictCandidate​

interface ConflictCandidate {
fact: string;
factType?: string;
subject?: string;
predicate?: string;
object?: string;
confidence: number;
tags?: string[];
embedding?: number[];
entities?: Array<{
name: string;
type: string;
fullValue?: string;
}>;
relations?: Array<{
subject: string;
predicate: string;
object: string;
}>;
}

ReviseResult​

export interface ReviseResult {
action: ConflictAction;
fact: FactRecord;
superseded: FactRecord[];
reason: string;
confidence: number;
pipeline: {
slotMatching?: { executed: boolean; matched: boolean; factIds?: string[] };
semanticMatching?: {
executed: boolean;
matched: boolean;
factIds?: string[];
};
subjectTypeMatching?: {
executed: boolean;
matched: boolean;
factIds?: string[];
};
llmResolution?: { executed: boolean; decision?: ConflictAction };
};
}
FieldMeaning and defaults
actionThe action that was taken
factThe resulting fact record
supersededFacts that were superseded (if any)
reasonExplanation for the decision
confidenceConfidence in the decision
pipelinePipeline stages that were executed

BeliefRevisionConfig​

export interface BeliefRevisionConfig {
slotMatching?: {
enabled?: boolean;
predicateClasses?: Record<string, string[]>;
};
semanticMatching?: {
enabled?: boolean;
threshold?: number;
limit?: number;
generateEmbedding?: (text: string) => Promise<number[]>;
};
llmResolution?: {
enabled?: boolean;
model?: string;
};
history?: {
enabled?: boolean;
retentionDays?: number;
};
}
FieldMeaning and defaults
slotMatchingSlot matching configuration
semanticMatchingSemantic matching configuration
llmResolutionLLM resolution configuration
historyHistory logging configuration

ConflictCheckResult​

export interface ConflictCheckResult {
hasConflicts: boolean;
slotConflicts: FactRecord[];
semanticConflicts: Array<{ fact: FactRecord; score: number }>;
recommendedAction: ConflictAction;
reason: string;
}
FieldMeaning and defaults
hasConflictsWhether conflicts were found
slotConflictsSlot-based conflicts
semanticConflictsSemantic conflicts
recommendedActionRecommended action (without executing)
reasonRecommendation reason

Public methods​

The following signatures describe the TypeScript namespace. Parameter and result fields are defined on this page; the installed @cortexmemory/sdk declarations also provide their compile-time types. Signatures are reference notation, not application code to execute.

configureBeliefRevision​

Configure or update the belief revision service

cortex.facts.configureBeliefRevision(llmClient?: BeliefRevisionLLMClient, config?: BeliefRevisionConfig): void

hasBeliefRevision​

Check if belief revision is configured and available

cortex.facts.hasBeliefRevision(): boolean

store​

Store a new fact

cortex.facts.store(params: StoreFactParams, _options?: StoreFactOptions): Promise<FactRecord>

storeWithDedup​

Store a fact with cross-session deduplication

cortex.facts.storeWithDedup(params: StoreFactParams, options?: StoreFactWithDedupOptions): Promise<StoreWithDedupResult>

get​

Get fact by ID

cortex.facts.get(memorySpaceId: string, factId: string, options?: DomainReadOptions): Promise<FactRecord | null>

list​

List facts with filters

cortex.facts.list(filter: ListFactsFilter): Promise<FactRecord[]>

count​

Count facts

cortex.facts.count(filter: CountFactsFilter): Promise<number>

Search facts

cortex.facts.search(memorySpaceId: string, query: string, options?: SearchFactsOptions): Promise<FactRecord[]>

semanticSearch​

Semantic search for facts using vector embeddings (v0.30.0+)

cortex.facts.semanticSearch(memorySpaceId: string, embedding: number[], options?: SemanticSearchFactsOptions): Promise<FactRecord[]>

update​

Update fact (creates new version)

cortex.facts.update(memorySpaceId: string, factId: string, updates: UpdateFactInput, _options?: UpdateFactOptions): Promise<FactRecord>

delete​

Delete fact (soft delete - marks as invalidated)

cortex.facts.delete(memorySpaceId: string, factId: string, _options?: DeleteFactOptions): Promise<{ deleted: boolean; factId: string }>

deleteMany​

Delete multiple facts matching filters in a single operation

cortex.facts.deleteMany(params: DeleteManyFactsParams): Promise<DeleteManyFactsResult & {partial?: DomainPartial}>

getHistory​

Get fact version history

cortex.facts.getHistory(memorySpaceId: string, factId: string, selector: Pick<HistorySelector, "tenantId"> = {}): Promise<FactRecord[]>

queryBySubject​

Query facts by subject (entity-centric view)

cortex.facts.queryBySubject(filter: QueryBySubjectFilter): Promise<FactRecord[]>

queryByRelationship​

Query facts by relationship (graph traversal)

cortex.facts.queryByRelationship(filter: QueryByRelationshipFilter): Promise<FactRecord[]>

export​

Export facts

cortex.facts.export(options: {memorySpaceId: string; format: "json" | "jsonld" | "csv"; factType?: ListFactsFilter["factType"]} & DomainReadOptions): Promise<{format: string; data: string; count: number; exportedAt: number}>

consolidate​

Consolidate duplicate facts

cortex.facts.consolidate(params: { memorySpaceId: string; factIds: string[]; keepFactId: string; tenantId?: string; operationId?: string; expectedFactIds?: Array<{ factId: string; factDocumentId: Id<"facts"> }>; }): Promise<{ consolidated: boolean; keptFactId: string; mergedCount: number; }>

revise​

Revise a fact using the belief revision pipeline

cortex.facts.revise(params: ReviseParams): Promise<ReviseResult>

checkConflicts​

Check for conflicts without executing (preview mode)

cortex.facts.checkConflicts(params: ReviseParams): Promise<ConflictCheckResult>

supersede​

Manually supersede a fact

cortex.facts.supersede(params: { memorySpaceId: string; oldFactId: string; newFactId: string; reason?: string; tenantId?: string; operationId?: string; expectedOldFactId?: Id<"facts">; expectedNewFactId?: Id<"facts">; }): Promise<{ superseded: boolean; oldFactId: string; newFactId: string }>

retryHistory​

Get change history for a fact

cortex.facts.retryHistory(receipt: HistoryReceipt): inferred

getHistoryOperationReceipt​

cortex.facts.getHistoryOperationReceipt(memorySpaceId: string, operationId: string, phase: string): inferred

history​

cortex.facts.history(factId: string, limit?: number): Promise<FactChangeEvent[]>

getChanges​

Get change events for a memory space in a time range

cortex.facts.getChanges(filter: ChangeFilter): Promise<FactChangeEvent[]>

getSupersessionChain​

Get the supersession chain for a fact

cortex.facts.getSupersessionChain(factId: string, selector?: HistorySelector): Promise<SupersessionChainEntry[]>

getActivitySummary​

Get activity summary for a memory space

cortex.facts.getActivitySummary(memorySpaceId: string, hours?: number): Promise<ActivitySummary>

Errors and lifecycle​

Validation, missing capability, authorization, stale version and partial/unknown committed outcomes are explicit. Inspect operation/write/deletion receipts before recovery; do not repeat an external effect under a new identity after uncertainty. Close owned clients and graph resources at the end of the server workflow.

See runtime client for ordinary app execution and error handling for recovery boundaries.