Skip to content

Memori Checkpoints

scarecr0w12 edited this page Jun 19, 2026 · 2 revisions

Memori Checkpoints

Persistent agent checkpointing system for CortexPrism, enabling full agent state serialization for survival across restarts, crashes, and context window resets.

Architecture

Five files in src/memori/:

File Purpose
types.ts Checkpoint data model: 6 dimensions, summaries, filters
checkpoint.ts Capture flow — serialize full agent state into an AgentCheckpoint
store.ts SQLite persistence layer with indexed queries
restore.ts Restore state and build resume prompts
mod.ts Module barrel exports

Checkpoint Model (6 Dimensions)

1. Conversation

Field Description
messages Full message history with roles, content (truncated to 50KB), and tool calls
currentPrompt Active system prompt (truncated to 20KB)
contextWindowRemaining Remaining context window capacity

2. Memory

Field Description
episodicEntries Episodic memories with importance scores
semanticEntries Semantic memories with categories and confidence
graphEntities Entity graph nodes with typed relations
activeSkills Currently loaded skill identifiers

3. Tools

Field Description
availableTools Names of registered tools
toolCallHistory Full tool invocation log with args, results, timing
pendingApprovals Awaiting-approval tool requests

4. Reasoning

Field Description
currentGoal Active task goal string
subGoals Remaining sub-goals
completedGoals Finished sub-goals
confidence Agent confidence score (0–1)
reflectionNotes Self-reflection annotations

5. Workspace

Field Description
workingDir Current working directory
openFiles Files open in editor
recentChanges File system mutations (create/modify/delete)
gitBranch Active git branch
gitHeadCommit HEAD commit SHA

6. Metadata

Field Description
cortexVersion Running Cortex version
providerName LLM provider
modelName Model identifier
totalTokensUsed Cumulative token usage
totalCostUsd Estimated cost
elapsedMs Session elapsed time
tags User-defined labels

Capture Flow

captureCheckpoint() takes a CaptureContext and produces an AgentCheckpoint:

  1. Generates checkpoint ID: memori-<sessionId>-turn-<n>-<timestamp>
  2. Truncates message content to 50KB, tool results to 10KB
  3. Serializes all 6 dimensions into the checkpoint object
  4. Returns complete checkpoint for storage

SQLite Storage

Migration 032memori_checkpoints table:

CREATE TABLE memori_checkpoints (
  id TEXT PRIMARY KEY,
  session_id TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  turn_number INTEGER NOT NULL,
  timestamp TEXT NOT NULL,
  data_json TEXT NOT NULL,           -- Full checkpoint JSON blob
  goal_snapshot TEXT NOT NULL,       -- Truncated to 500 chars
  message_count INTEGER NOT NULL,
  tool_call_count INTEGER NOT NULL,
  tokens_used INTEGER NOT NULL,
  tags TEXT NOT NULL DEFAULT '[]',
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

Indexes:

  • idx_memori_session on (session_id, turn_number DESC)
  • idx_memori_agent on (agent_id, timestamp DESC)

Store Operations

Function Description
initCheckpointStore(db) Create table and indexes
saveCheckpoint(db, checkpoint) INSERT OR REPLACE
loadCheckpoint(db, id) Load full checkpoint by ID
loadLatestCheckpoint(db, sessionId) Load most recent checkpoint for session
listCheckpoints(db, filter) Query with session, agent, time range, tag filters
deleteCheckpoint(db, id) Delete single checkpoint
deleteSessionCheckpoints(db, sessionId) Delete all checkpoints for a session
pruneOldCheckpoints(db, sessionId, keepCount) Keep N most recent, delete older

Restore and Resume

restoreCheckpoint() produces a RestoredState containing:

  • Full message history
  • Current goals, completed goals, sub-goals
  • Confidence and reflection notes
  • Open files and active skills
  • Tool call history
  • Token/cost/elapsed metrics
  • Working directory and git state
  • Resume context: synthesized summary of goals, completed tasks, remaining tasks, reflection notes, and recent messages (last 4, truncated to 200 chars each)

buildResumePrompt() generates a system prompt append with resume context, working directory, git branch, commit, open files, and active skills.

REST API

Method Path Description
POST /api/memori/checkpoints Capture a new checkpoint
GET /api/memori/checkpoints List checkpoints (filter: ?sessionId=, ?agentId=, ?before=, ?after=, ?tags=, ?limit=)
GET /api/memori/checkpoints/:id Load full checkpoint
GET /api/memori/checkpoints/latest/:sessionId Latest checkpoint for session
POST /api/memori/checkpoints/:id/restore Restore from checkpoint
DELETE /api/memori/checkpoints/:id Delete checkpoint
DELETE /api/memori/sessions/:sessionId/checkpoints Prune all for session

See Also

Clone this wiki locally