Skip to content

Latest commit

 

History

History
474 lines (373 loc) · 24.4 KB

File metadata and controls

474 lines (373 loc) · 24.4 KB

API Reference

This reference documents the public API surface exported by cortexdb and the optional @cortexdb/openai adapter. All async methods return Promise values unless noted.

Imports and subpaths

import { Cortex } from "cortexdb"
import { MemoryAPI } from "cortexdb/memory"
import { VectorIndex } from "cortexdb/vector"
import { FullTextIndex } from "cortexdb/fulltext"
import { defineCortexPlugin } from "cortexdb/plugins"
import { OpenAIEmbeddingAdapter } from "@cortexdb/openai"

The core package exports public subpaths for agents, cli, config, context, embeddings, errors, eval, facts, fulltext, graph, memory, plugins, provenance, query, records, runs, search, security, storage, tasks, temporal, testing, transactions, and vector.

Cortex

Constructors

Method Signature Description
Cortex.memory static memory(options?: CortexOptions): Promise<Cortex> Creates an isolated in-memory database.
Cortex.open `static open(path: string URL, options?: CortexOptions): Promise`

Properties

mode, path, options, storage, embeddings, runs, agents, tasks, goals, plans, memory, memories, vectors, vectorIndex, text, fulltext, fullTextIndex, graph, graphIndex, entities, relationships, time, temporalIndex, search, context, eval, facts, provenance, plugins, security, redact, query, transactions, and closed.

Methods

Method Signature
state state(): CortexState
remember remember(input: RememberMemoryInput): Promise<MemoryRecord>
rememberMany rememberMany(inputs: readonly RememberMemoryInput[]): Promise<readonly MemoryRecord[]>
forget forget(id: string, options?: MemoryForgetOptions): Promise<boolean>
updateMemory `updateMemory(id: string, patch: MemoryUpdateInput, options?: MemoryMutationOptions): Promise<MemoryRecord
transaction `transaction(callback: (transaction: Transaction) => TResult
batch batch(operations: readonly TransactionBatchOperation[]): Promise<readonly unknown[]>
getMemory `getMemory(id: string, options?: MemoryGetOptions): Promise<MemoryRecord
listMemories listMemories(options?: MemoryListOptions): Promise<MemoryListResult>
recall recall(input?: MemoryRecallInput): Promise<readonly MemoryRecallResult[]>
pin `pin(id: string): Promise<MemoryRecord
unpin `unpin(id: string): Promise<MemoryRecord
decay decay(options?: MemoryDecayOptions): Promise<MemoryDecayResult>
consolidate consolidate(options?: MemoryConsolidationOptions): Promise<MemoryConsolidationResult>
flush flush(): Promise<void>
compact compact(): Promise<StorageCompactionResult>
snapshot `snapshot(path?: string
restore restore(snapshot: StorageSnapshotInput): Promise<void>
export export(): Promise<string>
import import(data: StorageExportInput): Promise<void>
close close(): Promise<void>

Example:

const db = await Cortex.memory()
const memory = await db.remember({ content: "API reference example" })
const results = await db.recall({ query: "reference", topK: 1 })
await db.close()

Records and validation

Exports include constants CORE_RECORD_TYPES, BASE_RECORD_FIELDS, VISIBILITY_SCOPES, TRUST_LEVELS, MEMORY_KINDS, TASK_STATUSES, GOAL_STATUSES, PLAN_STATUSES, FACT_STATUSES, RUN_STATUSES, and CALL_STATUSES.

Function Signature
generateRecordId generateRecordId(prefix?: string): RecordId
createRecord createRecord(input: RecordCreateInput, options?: CreateRecordOptions): CortexRecord
validateRecord validateRecord(value: unknown): CortexRecord
isRecord isRecord(value: unknown): value is CortexRecord
updateRecord updateRecord(record: CortexRecord, patch: RecordUpdateInput, options?: UpdateRecordOptions): CortexRecord
computeRecordChecksum computeRecordChecksum(record: unknown): string

Per-type validators include validateMemoryRecord, validateFactRecord, validateEntityRecord, validateRelationshipRecord, validateDocumentRecord, validateChunkRecord, validateTaskRecord, validateGoalRecord, validatePlanRecord, validateRunRecord, validateToolCallRecord, validateModelCallRecord, validateObservationRecord, validateReflectionRecord, validatePreferenceRecord, validateArtifactRecord, and validateEvaluationRecord.

Memory API

The high-level Cortex memory methods delegate to db.memory / db.memories.

Method Signature Notes
remember remember(input: RememberMemoryInput): Promise<MemoryRecord> Stores one memory.
rememberMany rememberMany(inputs: readonly RememberMemoryInput[]): Promise<readonly MemoryRecord[]> Atomic batch insert.
forget forget(id: string, options?: MemoryForgetOptions): Promise<boolean> Hard delete by default; mode: "soft" marks deleted.
update `update(id: string, patch: MemoryUpdateInput, options?: MemoryMutationOptions): Promise<MemoryRecord null>`
get `get(id: string, options?: MemoryGetOptions): Promise<MemoryRecord null>`
list list(options?: MemoryListOptions): Promise<MemoryListResult> Filters and paginates.
query query(): MemoryQueryBuilder Fluent query builder.
recall recall(input?: MemoryRecallInput): Promise<readonly MemoryRecallResult[]> Ranked retrieval with filters and scoring.
pin `pin(id: string): Promise<MemoryRecord null>`
unpin `unpin(id: string): Promise<MemoryRecord null>`
decay decay(options?: MemoryDecayOptions): Promise<MemoryDecayResult> Applies time-based importance decay.
consolidate consolidate(options?: MemoryConsolidationOptions): Promise<MemoryConsolidationResult> Merges near-duplicate memories.

Example:

const memory = await db.memory.remember({
  content: "Use confidence and tags to tune retrieval.",
  kind: "semantic",
  tags: ["retrieval"],
  confidence: 0.95,
})

await db.memory.pin(memory.id)
const list = await db.memory.list({ tags: ["retrieval"], tagMode: "all" })
const recall = await db.memory.recall({ query: "tune retrieval", topK: 5 })

Embeddings

API Signature
EmbeddingsAPI.embed embed(input: EmbeddingInput): Promise<number[]>
EmbeddingsAPI.embedMany embedMany(inputs: readonly EmbeddingInput[]): Promise<readonly number[][]>
EmbeddingsAPI.embedBatch embedBatch(inputs: readonly EmbeddingInput[]): Promise<readonly number[][]>
HashEmbeddingAdapter.embed embed(input: EmbeddingInput): Promise<number[]>
HashEmbeddingAdapter.embedBatch embedBatch(inputs: readonly EmbeddingInput[]): Promise<readonly number[][]>
MockEmbeddingAdapter.embed embed(input: EmbeddingInput): Promise<number[]>
MockEmbeddingAdapter.embedBatch embedBatch(inputs: readonly EmbeddingInput[]): Promise<readonly number[][]>

Helper exports: isEmbeddingAdapter, embeddingInputToText, validateEmbeddingDimensions, and normalizeEmbeddingVector.

Example:

import { Cortex, HashEmbeddingAdapter } from "cortexdb"

const db = await Cortex.memory({
  embeddingAdapter: new HashEmbeddingAdapter({ dimensions: 64 }),
})

const vector = await db.embeddings.embed("deterministic local embedding")

Vector index

Method Signature
insert insert(input: VectorIndexInsertInput): Promise<VectorIndexEntry>
get `get(id: string): Promise<VectorIndexEntry
delete delete(id: string): Promise<boolean>
search search(options: VectorIndexSearchOptions): Promise<readonly VectorIndexSearchResult[]>
rebuild rebuild(): Promise<void>
stats stats(): VectorIndexStats

Example:

await db.vectors.insert({ id: "doc-1", vector: [1, 0, 0], metadata: { source: "manual" } })
const neighbors = await db.vectors.search({ vector: [1, 0, 0], metric: "cosine", topK: 5 })

Full-text index

Method Signature
index index(input: FullTextIndexDocumentInput): Promise<FullTextIndexEntry>
insert insert(input: FullTextIndexInsertInput): Promise<FullTextIndexEntry>
get `get(id: string): Promise<FullTextIndexEntry
delete delete(id: string): Promise<boolean>
search `search(query: string
lookup lookup(term: string, options?: FullTextTermLookupOptions): readonly FullTextTermLookupResult[]
termFrequency termFrequency(id: string, term: string): number
documentFrequency documentFrequency(term: string): number
rebuild rebuild(): Promise<void>
stats stats(): FullTextIndexStats

Example:

await db.text.index({ id: "doc-1", content: "CortexDB includes BM25 text search." })
const matches = await db.text.search({ query: "BM25 search", topK: 3 })

Search API

Method Signature
semantic semantic(options: SearchSemanticOptions): Promise<readonly SearchResult[]>
text text(options: SearchTextOptions): Promise<readonly SearchResult[]>
hybrid hybrid(options: SearchHybridOptions): Promise<readonly SearchResult[]>
graph graph(options: SearchGraphOptions): Promise<readonly SearchResult[]>
temporal temporal(options: SearchTemporalOptions): Promise<readonly SearchResult[]>
explain explain(options: SearchExplainOptions): Promise<SearchExplainResult>

Example:

const results = await db.search.hybrid({
  query: "release checklist",
  topK: 10,
  filters: { project: "atlas" },
  weights: { semantic: 0.4, text: 0.6 },
})

const explanation = await db.search.explain({ query: "release checklist", topK: 3 })

Context engine

The ContextEngine class is exposed as db.context and through cortexdb/context.

Method Signature
pack pack(options?: ContextPackOptions): Promise<PackedContext>
estimateTokens estimateTokens(input: ContextTokenEstimatorInput): number
render render(packed: PackedContext, options?: ContextRenderOptions): ContextRenderResult
citations citations(packed: PackedContext): readonly ContextCitation[]
compress compress(packed: PackedContext, options?: ContextCompressOptions): PackedContext

Example:

const packed = await db.context.pack({ query: "onboarding", budget: 1000, topK: 8 })
const rendered = db.context.render(packed, { format: "markdown" })
const citations = db.context.citations(packed)

Graph API

Entity facade methods:

Method Signature
entities.upsert upsert(input: GraphEntityUpsertInput): Promise<EntityRecord>
entities.get `get(id: string): Promise<EntityRecord
entities.getByName `getByName(name: string, options?: GraphEntityLookupOptions): Promise<EntityRecord
entities.update `update(id: string, patch: GraphEntityUpdateInput): Promise<EntityRecord
entities.delete delete(id: string, options?: GraphEntityDeleteOptions): Promise<boolean>
entities.list list(options?: GraphEntityListOptions): Promise<readonly EntityRecord[]>

Relationship facade methods:

Method Signature
relationships.link link(input: GraphRelationshipLinkInput): Promise<GraphRelationship>
relationships.unlink unlink(input: GraphRelationshipUnlinkInput): Promise<boolean>
relationships.get `get(id: string): Promise<GraphRelationship
relationships.delete delete(id: string): Promise<boolean>
relationships.from from(entityId: string, options?: GraphRelationshipQueryOptions): Promise<readonly GraphRelationship[]>
relationships.to to(entityId: string, options?: GraphRelationshipQueryOptions): Promise<readonly GraphRelationship[]>
relationships.list list(options?: GraphRelationshipQueryOptions): Promise<readonly GraphRelationship[]>

Direct GraphIndex methods include upsertEntity, updateEntity, getEntity, getEntityByName, deleteEntity, listEntities, linkRelationship, unlinkRelationship, getRelationship, deleteRelationship, relationshipsFrom, relationshipsTo, listRelationships, neighbors, traverse, path, linkMemory, unlinkMemory, relatedMemories, subgraph, explain, rebuild, stats, and resolveEntityIds.

Example:

const service = await db.entities.upsert({ name: "payments-service", type: "service" })
const database = await db.entities.upsert({ name: "ledger-db", type: "database" })
await db.relationships.link({ from: service.id, to: database.id, type: "depends_on" })
const path = await db.graph.path({ from: service.id, to: database.id })

Temporal API

Method Signature
events events(options?: TemporalEventsOptions): Promise<readonly TemporalRecord[]>
timeline timeline(options?: TemporalTimelineOptions): Promise<readonly TemporalRecord[]>
between `between(from: number
between between(options: TemporalBetweenOptions): Promise<readonly TemporalRecord[]>
recent recent(options?: TemporalRecentOptions): Promise<readonly TemporalRecord[]>
decayed decayed(options?: TemporalDecayedOptions): Promise<readonly TemporalScore[]>
expired expired(options?: TemporalExpiredOptions): Promise<readonly TemporalRecord[]>
activeAt `activeAt(timestamp: number
at `at(timestamp: number
score score(record: TemporalRecord, options?: TemporalScoreOptions): TemporalScore
trackAccess `trackAccess(recordId: string, timestamp?: number
rebuild rebuild(): Promise<void>
stats stats(): TemporalIndexStats

Runs API

Method Signature
start start(input?: RunStartInput): Promise<RunSnapshot>
create create(input?: RunCreateInput): Promise<RunSnapshot>
withRun `withRun(runIdOrInput: string
currentRunId `currentRunId(): string
get `get(runId: string): Promise<RunSnapshot
query query(): RunQueryBuilder
recordStep recordStep(runId: string, input: RunStepInput): Promise<RunStepEvent>
recordToolCall recordToolCall(runId: string, input: RunToolCallInput): Promise<RunToolCallEvent>
recordModelCall recordModelCall(runId: string, input: RunModelCallInput): Promise<RunModelCallEvent>
finish finish(runId: string, input?: RunFinishInput): Promise<RunSnapshot>
fail fail(runId: string, input: RunFailInput): Promise<RunSnapshot>
timeline timeline(runId: string): Promise<readonly RunTimelineEvent[]>
replay replay(runId: string): Promise<RunReplay>
recordMemoryOp recordMemoryOp(runId: string, input: RunManualMemoryOperationInput): Promise<RunMemoryOperation>
recordMemoryOperation recordMemoryOperation(operation: MemoryOperationEvent): Promise<readonly RunMemoryOperation[]>

Example:

const run = await db.runs.start({ name: "docs-run", agentId: "agent-1" })
await db.runs.recordStep(run.id, { name: "retrieve", input: { query: "docs" } })
await db.runs.finish(run.id, { output: { ok: true } })

Tasks, goals, and plans

API Method signatures
TasksAPI create(input), get(taskId), list(options?), claim(taskId, agentId), update(taskId, patch), block(taskId, reason), complete(taskId)
GoalsAPI create(input), get(goalId), update(goalId, patch), complete(goalId, input?)
PlansAPI create(input), get(planId), update(planId, patch)

Example:

const goal = await db.goals.create({ title: "Ship docs", description: "Document public APIs" })
const task = await db.tasks.create({ title: "Write API reference", goalId: goal.id, priority: 1 })
await db.tasks.claim(task.id, "docs-agent")
await db.tasks.complete(task.id)

Facts and provenance

API Method signatures
FactsAPI assert(input), create(input), get(factId, options?), update(factId, patch), retract(factId, reason), dispute(factId, reason?), expire(factId), delete(factId), remove(factId), query(), query(options), queryBuilder(), list(options?), contradictions(factId), linkEvidence(factId, evidence), supportingEvidence(factId)
ProvenanceAPI trace(recordId), sources(recordId), evidence(recordId), lineage(recordId)

Example:

const fact = await db.facts.assert({
  subject: "CortexDB",
  predicate: "supports",
  object: "context packing",
  confidence: 0.99,
})

const evidence = await db.provenance.evidence(fact.id)

Query API

Builder Methods
QueryBuilder where(filter), where(field, operator, value), orderBy(field, direction?), limit(limit), offset(offset), select(selector), run(), all(), first(), count(), sum(field), avg(field)
MemoryQueryBuilder Base methods plus kind(kindOrKinds) and recent(duration, now?)
FactQueryBuilder Base methods plus subject(), predicate(), object(), active(at?), and withEvidence()
RunQueryBuilder Base methods plus agent(), status(), since(), and until()
QueryAPI memories(), facts(), runs()

Example:

const recentSemantic = await db.query.memories()
  .kind("semantic")
  .recent("7d")
  .limit(10)
  .all()

Evaluation API

Method Signature
createDataset createDataset(input: EvalDatasetInput): Promise<EvalDataset>
getDataset `getDataset(datasetId: string): Promise<EvalDataset
listDatasets listDatasets(): Promise<readonly EvalDataset[]>
addCase addCase(datasetId: string, input: EvalCaseInput): Promise<EvalCase>
run run(datasetId: string, options?: EvalRunOptions): Promise<EvalRunResult>
scoreRecall scoreRecall(result: EvalRunResult, options?: EvalScoreOptions): number
scorePrecision scorePrecision(result: EvalRunResult, options?: EvalScoreOptions): number
scoreF1 scoreF1(result: EvalRunResult, options?: EvalScoreOptions): number
scoreMRR scoreMRR(result: EvalRunResult, options?: EvalScoreOptions): number
scoreContext scoreContext(result: EvalRunResult): EvalContextMetrics
report report(result: EvalRunResult): EvalReport
compare compare(baseline: EvalRunResult, candidate: EvalRunResult): EvalComparisonReport
detectRegressions detectRegressions(report: EvalComparisonReport, thresholds?: EvalRegressionThresholds): EvalRegressionDetection

Agents

The AgentAPI class is exposed as db.agents and through cortexdb/agents.

Method Signature
register register(input: AgentRegisterInput): Promise<AgentRecord>
get `get(agentId: string): Promise<AgentRecord
list list(): Promise<readonly AgentRecord[]>
permissions permissions(agentId: string): Promise<AgentPermissions>
updatePermissions updatePermissions(actorAgentId: string, targetAgentId: string, permissions: Partial<AgentPermissions>): Promise<AgentRecord>
remember remember(agentId: string, input: RememberMemoryInput): Promise<MemoryRecord>
memory memory(agentId: string, options?: MemoryListOptions): Promise<readonly MemoryRecord[]>
sharedMemory sharedMemory(agentId: string, options?: MemoryListOptions): Promise<readonly MemoryRecord[]>
listMemories listMemories(agentId: string, options?: MemoryListOptions): Promise<readonly MemoryRecord[]>
recall recall(agentId: string, input?: MemoryRecallInput): Promise<readonly MemoryRecallResult[]>
getMemory `getMemory(agentId: string, memoryId: string, options?: MemoryGetOptions): Promise<MemoryRecord
updateMemory `updateMemory(agentId: string, memoryId: string, patch: MemoryUpdateInput, options?: { expectedVersion?: number }): Promise<MemoryRecord
forget forget(agentId: string, memoryId: string, options?: MemoryForgetOptions): Promise<boolean>
shareMemory `shareMemory(agentId: string, memoryId: string, sharedAgentIds: readonly string[]): Promise<MemoryRecord

Transactions

API Method signatures
TransactionAPI begin(), run(callback), batch(operations)
Transaction status, remember(input), updateMemory(id, patch), forget(id, options?), assertFact(input), upsertEntity(input), linkRelationship(input), linkMemory(input), commit(), rollback()

Example:

await db.transaction(async (tx) => {
  const memory = await tx.remember({ content: "Committed atomically" })
  await tx.assertFact({ subject: memory.id, predicate: "state", object: "committed" })
})

Security and redaction

API Method signatures
SecurityAPI scan(recordId), quarantine(recordId, reason), trust(recordId), untrust(recordId), findRisks(options?), detectSecrets(input), redact(content, options?)
RedactionAPI record(recordId, fields, options?), export(input?), content(content, options?)
Functions detectSecretPaths(input), redactSensitiveContent(content, options?)

Example:

const memory = await db.remember({ content: "API token <redacted-token-placeholder>" })
const labels = await db.security.scan(memory.id)
const safe = db.redact.content(memory.content)

Plugins

API Method signatures
defineCortexPlugin defineCortexPlugin(plugin): CortexPlugin
CortexPluginRegistry register(plugin), unregister(pluginOrName), list(), errors(), clearErrors(), onError(listener)
Helpers withPluginRecordWriteObserver(storage, plugins), createOperationLoggerPlugin(log?, options?), createContextRedactionPlugin(options?)

Hook names: beforeRemember, afterRemember, beforeRecall, afterRecall, beforePack, afterPack, beforeContextPack, afterContextPack, beforeSearch, afterSearch, onRecordWrite, onRiskDetected, and onCompaction.

Configuration API

Function Signature
defineCortexConfig defineCortexConfig(config?: CortexConfigInput): CortexConfig
resolveCortexConfig resolveCortexConfig(config?: CortexConfigInput, options?: CortexConfigResolveOptions): CortexConfig
mergeCortexConfig mergeCortexConfig(...configs: readonly CortexConfigInput[]): CortexConfigInput
validateCortexConfig validateCortexConfig(config: unknown): true
loadCortexConfig loadCortexConfig(configPath?: string, options?: CortexConfigLoadOptions): Promise<CortexConfig>
cortexConfigToOptions cortexConfigToOptions(config: CortexConfig): CortexOptions

Storage API

StorageAdapter methods: open, close, flush, get, set, delete, batch, entries, appendWal, replayWal, truncateWal, walEntries, pendingWalEntries, and storageMetadata.

MemoryStorageAdapter implements the contract in memory. FileStorageAdapter adds simulateCrash, compact, snapshot, restore, exportData, export, importData, and import.

Testing utilities

Test exports include createTestCortex, createTestDB, createTestFixture, withTestDB, seed, seedMemories, seedFacts, seedRuns, installCortexMatchers, cortexMatchers, cortexTestMatchers, and matcher helpers such as expectMemoryExists, expectRecall, expectContext, expectFactExists, expectGraph, expectRunExists, and expectNoSecretLeaks.

Optional OpenAI adapter

Export Signature
OpenAIEmbeddingAdapter new OpenAIEmbeddingAdapter(options?: OpenAIEmbeddingAdapterOptions)
embed embed(input: EmbeddingInput): Promise<number[]>
embedBatch embedBatch(inputs: readonly EmbeddingInput[]): Promise<readonly number[][]>

The adapter requires a provided OpenAI-compatible client with embeddings.create(). Without a client it throws CORTEX_NOT_IMPLEMENTED.