Quick Start
Install the SDK, run the setup wizard, and add persistent cognitive memory to your agent in minutes.
Install
npm install cogdexSetup
npx cogdex initThe setup wizard can configure: Storage backend (required), Embeddings provider (optional), OpenAI Codex-assisted scoring/reconciliation (optional), Solana Devnet checkpoint anchoring (optional), Runtime mode (local, hybrid, checkpointed, full-audit). All non-storage steps are optional. Cogdex degrades gracefully.
Usage
import { Cortex } from 'cogdex';
const brain = new Cortex({
storage: {
url: process.env.COGDEX_STORAGE_URL!,
serviceKey: process.env.COGDEX_STORAGE_SERVICE_KEY!,
},
codex: {
apiKey: process.env.OPENAI_API_KEY, // optional
},
checkpoint: {
cluster: 'solana-devnet', // optional
rpcUrl: process.env.SOLANA_DEVNET_RPC_URL,
signerPrivateKey: process.env.SOLANA_CHECKPOINT_SIGNER_PRIVATE_KEY,
},
runtime: {
mode: 'hybrid',
reconciliationIntervalHours: 6,
},
});
await brain.init();
await brain.store({
type: 'episodic',
content: 'User prefers concise updates but long-form technical architecture analysis.',
summary: 'Scoped response-length preference',
source: 'assistant',
tags: ['preferences', 'communication'],
scope: { userId: 'demo-user' },
});
const results = await brain.recall({
query: 'How detailed should responses be for technical topics?',
scope: { userId: 'demo-user' },
});Only the storage backend is required. Embeddings, OpenAI Codex integration, and Solana Devnet checkpointing are optional.
Configuration
new Cortex(config) accepts a CortexConfig object. Minimal setup requires only storage.
Example Configuration
const brain = new Cortex({
storage: {
url: 'https://your-storage-endpoint',
serviceKey: '...',
}, // required
embedding: {
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'text-embedding-3-large',
dimensions: 3072,
}, // optional
codex: {
apiKey: process.env.OPENAI_API_KEY,
model: 'codex',
}, // optional
checkpoint: {
cluster: 'solana-devnet',
rpcUrl: process.env.SOLANA_DEVNET_RPC_URL,
signerPrivateKey: process.env.SOLANA_CHECKPOINT_SIGNER_PRIVATE_KEY,
confirmCommitment: 'confirmed',
}, // optional
runtime: {
mode: 'hybrid',
reconciliationIntervalHours: 6,
autoDecay: true,
}, // optional
integrity: {
contradictionThreshold: 0.72,
supersessionThreshold: 0.80,
selfModelUpdateThreshold: 0.90,
}, // optional
});Config: storage (required) — url: string, serviceKey: string
Config: embedding (optional) — provider, apiKey, model, dimensions
Config: codex (optional) — apiKey, model?
Config: checkpoint (optional) — cluster: 'off' | 'solana-devnet', rpcUrl, signerPrivateKey, confirmCommitment?
Config: runtime (optional) — mode, reconciliationIntervalHours, autoDecay
Config: integrity (optional) — contradictionThreshold, supersessionThreshold, selfModelUpdateThreshold
Concepts
Cogdex is a cognitive memory runtime focused on belief integrity. It stores and retrieves memory, but also tracks contradictions, scopes beliefs, and preserves supersession history.
Core Concepts
- Memory Classes — Typed memory with different lifecycle behavior.
- Belief Integrity — Beliefs are confidence-scored claims with evidence and contradiction state.
- Reconciliation — Cycles that update beliefs from evidence instead of blind append-only accumulation.
- Verifiable Checkpoints — Important cognitive state transitions can be hashed and anchored to Solana Devnet.
Persistence stores memory. Reconciliation keeps it usable.
Memory Classes
Cogdex uses five memory classes. Each class has different decay and update behavior.
Type 01 — Episodic
Raw interactions and events with context. Use for: conversations, observations, action outcomes. Lifecycle: high-volume, decays faster, feeds reconciliation.
Type 02 — Semantic
Distilled facts and recurring patterns. Use for: generalized knowledge, stable preferences. Lifecycle: promoted from evidence, confidence-aware decay.
Type 03 — Procedural
Learned execution patterns. Use for: workflows, what works. Lifecycle: reinforced by successful reuse.
Type 04 — Self-Model
Identity, constraints, stable preferences. Lifecycle: strict update thresholds, minimal decay.
Type 05 — Belief Ledger
Confidence-scored claims with evidence lineage, contradiction state, supersession history. Lifecycle: evidence-driven updates with preserved history.
Storing Memories
Store typed memories with optional tags, scope, and evidence metadata. Cogdex can score importance/confidence and run contradiction checks during ingestion.
Basic Example
const memoryId = await brain.store({
type: 'episodic',
content: 'User asked for a migration plan with rollback steps.',
summary: 'Migration plan request with rollback requirement',
source: 'assistant',
tags: ['planning', 'migration', 'safety'],
scope: { userId: 'demo-user', project: 'alpha' },
});StoreMemoryOptions
type, content, summary, source, tags?, scope?, importance? (0–1), confidence? (0–1), metadata?, evidenceIds?
On store(), Cogdex may: normalize tags and scope; score importance and confidence (if omitted); detect candidate contradictions; create graph links; update belief ledger state; create a checkpointable event (and optionally anchor it).
Recalling Memories
Cogdex recall combines retrieval and integrity-aware ranking. Results are ranked by relevance and adjusted by confidence, conflict state, graph links, and staleness.
const results = await brain.recall({
query: 'How detailed should responses be for technical work?',
memoryTypes: ['episodic', 'semantic', 'belief'],
scope: { userId: 'demo-user' },
minConfidence: 0.5,
minImportance: 0.3,
includeContradictions: true,
limit: 10,
});RecallOptions: query, memoryTypes?, tags?, scope?, minConfidence?, minImportance?, minDecay?, includeContradictions?, trackAccess?, limit?
Composite scoring: score = (w_r * recency) + (w_k * keyword_match) + (w_v * vector_similarity) + (w_i * importance) + (w_c * confidence) + (w_g * graph_boost) − (w_x * contradiction_penalty) − (w_s * staleness_penalty). Scores are gated by decay factor and scope compatibility.
Belief Ledger
The Belief Ledger is a first-class layer for active claims. It stores confidence, scope, evidence lineage, contradiction state, and supersession history. Memory systems that only append semantic facts tend to accumulate stale or conflicting claims; the Belief Ledger preserves conflict and lineage.
await brain.upsertBelief({
claim: 'Default response preference is concise updates',
summary: 'Global communication preference',
scope: { userId: 'demo-user' },
confidence: 0.84,
evidenceIds: [913, 1022],
});Belief States: active, scoped, superseded, unresolved, quarantined (if implemented)
Cogdex preserves memory history and belief lineage. It links and re-ranks; it does not silently erase conflicting evidence.
Contradiction Graph
Cogdex stores typed, weighted links between memories and beliefs. Contradictions are explicit graph edges.
Link Types: supports, contradicts, follows, elaborates, causes, relates, supersedes
await brain.link(1842, 913, 'contradicts', 0.88);
await brain.link(1842, 1850, 'supports', 0.81);In v1, contradiction detection may be heuristic (scope overlap, preference polarity, keyword patterns) before more advanced semantic checks.
Reconciliation Cycles
Reconciliation cycles consolidate recent memory windows, detect contradictions, update confidence, and promote/supersede beliefs.
const session = await brain.reconcile({
windowHours: 24,
scope: { userId: 'demo-user' },
dryRun: false,
updateSelfModel: false,
anchorCheckpoint: true,
});Phases
- I. Consolidation — Generate focal questions and retrieve evidence sets.
- II. Reconciliation — Detect contradictions, update confidence, mark belief states.
- III. Reflection — Review self-model and procedural memory against outcomes.
- IV. Emergence — Produce an optional synthesis summary or changelog.
Checkpoints & Verification
Cogdex can generate verifiable checkpoints for important cognitive state transitions. Each checkpoint uses: canonical JSON payload, SHA-256 hashing, optional Solana Devnet anchoring. Typical kinds: memory_event, reconciliation_session. Full content does not need to be on-chain; a hash of the checkpoint payload is typically anchored.
Verification guarantees
If checkpointing is enabled and anchoring succeeds: the payload existed; local payload hashes to a specific SHA-256; that hash was anchored on Solana Devnet; verification reproduces the same hash. Cogdex hashes canonical JSON (stable key ordering).
{
"version": 1,
"kind": "memory_event",
"memory_id": 1842,
"memory_type": "episodic",
"summary": "Scoped response-length preference",
"importance": 0.68,
"confidence": 0.73,
"conflict_state": "scoped",
"belief_action": "promoted_scoped_belief",
"linked_belief_ids": [913, 1850],
"timestamp": "2026-02-24T14:42:11.123Z"
}const verification = await brain.verifyCheckpoint({ checkpointId: 1285 });
// { ok: true, status: 'match', checkpointHashDb: '...', txSignature: '...', cluster: 'solana-devnet' }If Devnet anchoring fails: persist the checkpoint record, mark status: failed, store the real error message, do not report CONFIRMED.
API Reference
Base path: /api/demo
POST /api/demo/store
Store a memory event, run scoring + contradiction checks, optionally checkpoint and anchor. Request: type, content, summary, source, tags, scope, anchorCheckpoint. Success: stored, memory_id, timestamp, importance, confidence, conflicts, belief_action, checkpoint (id, hash, cluster, status, tx_signature).
POST /api/demo/recall
Recall with integrity-aware ranking. Request: query, memoryTypes?, scope?, minConfidence?, minImportance?, includeContradictions?, limit. Response: query, results[], composite_scoring.
POST /api/demo/reconcile
Run reconciliation cycle. Request: windowHours, scope?, dryRun?, updateSelfModel?, anchorCheckpoint?. Response: ran, window_hours, promoted, superseded, conflicts_linked, unresolved, self_model_updates, checkpoint.
POST /api/demo/verify-checkpoint
Verify payload hash against DB + anchored Devnet hash. Request: checkpointId or checkpoint_hash. Match: ok, status: 'match', checkpoint_hash_db, recomputed_hash, tx_signature. Mismatch: ok: false, status: 'mismatch'.
POST /api/demo/trigger-memory-event
Creates a realistic memory event and checkpoints it.
POST /api/demo/trigger-conflict-event
Creates a memory likely to conflict with an existing belief.
GET /api/demo/stats, /api/demo/brain-snapshot, /api/demo/checkpoints, /api/demo/runtime-feed
Live runtime metrics, graph summary, recent checkpoints, event stream (SSE or polling).
SDK Reference
Documented methods are implemented.
new Cortex(config)— Create runtime instance.init()— Initialize storage and services.store(opts)— Store typed memory, run scoring/contradiction checks.recall(opts)— Recall with integrity-aware ranking.reconcile(opts?)— Run reconciliation cycle.verifyCheckpoint(opts)— Recompute hash and compare.stats()— Aggregate runtime metrics.link(sourceId, targetId, type, strength?)— Create typed graph edge.upsertBelief(opts)— Create or update belief.destroy()— Close connections.
Events
Cogdex emits runtime events for observability and audit.
brain.on('memory:stored', (payload) => { ... });
brain.on('belief:updated', (payload) => { ... });
brain.on('checkpoint:confirmed', (payload) => { ... });Common events
memory:storedmemory:linkedbelief:createdbelief:updatedbelief:contradictionbelief:supersededreconciliation:startedreconciliation:completedcheckpoint:queuedcheckpoint:submittedcheckpoint:confirmedcheckpoint:failedDatabase Schema
Cogdex uses a relational store for typed memory, graph links, beliefs, reconciliation sessions, and checkpoints.
memories
id, type, content, summary, source, tags, scope_json, importance, confidence, decay_factor, conflict_state, created_at
memory_links
id, source_id, target_id, link_type, strength, created_at
beliefs
id, claim, summary, scope_json, confidence, state, created_at, updated_at
reconciliation_sessions
id, window_hours, promoted, superseded, conflicts_linked, unresolved, self_model_updates, summary, created_at
checkpoints
id, checkpoint_hash, payload_json, payload_kind, cluster, tx_signature, status, error_message, created_at, confirmed_at
Graceful Degradation
Cogdex works with minimal configuration and progressively unlocks capabilities.
With only storage, Cogdex still supports typed memory, contradiction links, belief ledger, recall, and manual reconciliation.
Security Notes
Server-side only
Storage service keys, OpenAI API key, Solana checkpoint signer private key.
Never expose in client
Signer private key, service-role keys.
Recommendation
Use a dedicated Devnet signer funded only for checkpoint writes.
FAQ
No. v1 typically anchors checkpoint payload hashes; full content stays in the runtime database.