Skip to main content

VSCode KnoxChat — Memory Brain

· 21 min read
Knox Anderson
Knox Dev Team

Give your AI a brain that remembers.

Memory Brain is a local-first, SQLite-powered memory system that gives Knox persistent, structured recall across conversations, sessions, and projects. It replaces the "goldfish memory" of stateless LLMs with a multi-layered cognitive architecture inspired by human memory science.

Try KnoxChat VS Code extension with Memory Brain here >>>

Table of Contents

Why Memory Brain?

Every conversation with an LLM starts from zero. The AI forgets your preferences, past decisions, project context, and the patterns that worked before. You end up repeating yourself, re-explaining your codebase, and losing insights that took hours to reach.

Memory Brain solves this by providing:

ProblemSolution
AI forgets everything between sessionsSemantic memory persists facts, preferences, and decisions
You repeat the same context every timeContext Builder auto-assembles relevant memories
No learning from past mistakesLearning Engine tracks success/failure patterns
AI can't connect concepts across sessionsKnowledge Graph links entities with typed relationships
Conversation history is lostEpisodic memory stores full session transcripts
No way to undo destructive changesCheckpoint system with full rollback capability
Memory grows unbounded5-tier hierarchy with Ebbinghaus decay auto-consolidation

How It Works

The Memory Tool Call Flow

User or Agent


┌─────────────────────┐
│ memory tool call │ action: "store", params: { title, content, ... }
└─────────┬───────────┘


┌─────────────────────┐
│ BrainManager │ dispatch(action, params) → routes to handler
│ (Service Layer) │ emits events, records audit log
└─────────┬───────────┘


┌─────────────────────┐
│ BrainStore │ SQLite CRUD, BM25 search, consolidation
│ (Data Layer) │ 17 tables, 27 indexes, WAL mode
└─────────┬───────────┘


┌─────────────────────┐
│ brain.sqlite │ ~/.knox/memory/brain.sqlite
│ (Local Database) │ Your data. Your machine. No cloud.
└─────────────────────┘
  1. An agent (or user) invokes the memory tool with an action and params.
  2. BrainManager.dispatch() routes to one of 79 action handlers.
  3. The handler calls BrainStore (SQLite layer) or a specialized module (KnowledgeGraph, LearningEngine, CheckpointManager, etc.).
  4. Events are emitted and logged in the audit trail.
  5. A human-readable formatted string is returned to the caller.

Automatic Memory Lifecycle

Memory Brain isn't just storage — it actively manages memory health:

 Store ──► Hot Tier ──► Warm Tier ──► Cold Tier ──► Pruned
(active) (1-7 days) (7-90 days) (>90 days)
▲ │
└─── Promote (frequent retrieval) ◄──────┘

Background: Ebbinghaus decay, spaced repetition, consolidation

Memories that are frequently accessed get promoted back to hot tier. Memories that decay below importance thresholds are gradually consolidated and eventually pruned. This keeps the system fast and relevant.

Architecture Overview

Module Map

core/context/memory/brain/
├── BrainManager.ts # Service layer — 79-action dispatch, event bus
├── BrainStore.ts # SQLite data layer — 17 tables, CRUD, search
├── types.ts # TypeScript interfaces, enums, input/output models
├── ContextBuilder.ts # Token-budgeted multi-source context assembly
├── KnowledgeGraph.ts # Entity/edge CRUD, spreading activation traversal
├── LearningEngine.ts # Pattern recording, Jaccard similarity suggestions
├── AutoMemory.ts # Rule-based extraction, topic segmentation
├── CheckpointManager.ts # Snapshots, rollback, event replay, undo
├── BatchOperations.ts # Bulk store/delete/update, batch audit logging
├── AdvancedFeatures.ts # SessionDiscovery, FiveTierHierarchy, SpacedRepetition,
│ # RootCauseAnalyzer, LruCache, MetricsStorage
├── PerformanceMonitor.ts # MetricsCollector, HealthScorer, PredictiveAnalytics,
│ # HealingEngine, ConsolidationTracker
├── LlmMemoryService.ts # LLM-powered entity extraction, summarization, scoring
├── LlmResilience.ts # CircuitBreaker, rate limiting, decision caching
├── SleepConsolidation.ts # Background scheduler, Ebbinghaus decay application
├── WorkingMemory.ts # In-memory session state, short-term buffer
├── test-memory-tool.ts # 94 integration tests — 100% pass rate
├── test-brain-debug.ts # 202 ultra-comprehensive integration tests
├── test-brain-debug-modules.ts # 59 module-level unit tests
└── test-brain-tool-calls.ts # 88 end-to-end tool call tests

Design Principles

  • Local-first: All data in ~/.knox/memory/brain.sqlite. Nothing leaves your machine.
  • Zero-config: Works out of the box with sensible defaults.
  • LLM-optional: Every LLM-enhanced feature has a rule-based fallback.
  • Audit everything: Every write operation is logged with full undo support.
  • Fail gracefully: Circuit breakers, rate limits, and resilient fallback chains.

Memory Types

1. Semantic Memory — What you know

Long-term facts, decisions, and knowledge extracted from conversations.

CategoryExample
fact"TypeScript strict mode enables stricter type checking"
preference"User prefers tabs over spaces"
decision"We chose PostgreSQL over MySQL for this project"
code_pattern"Use Result<T, E> for error handling in Rust"
error_fix"CORS error fixed by adding Access-Control-Allow-Origin header"
insight"BM25 outperforms TF-IDF for short-document ranking"
project_context"The knox-ms service handles user authentication"
workflow"Deploy sequence: lint → test → build → push → tag"
summarySession summary with key decisions and outcomes

Features: BM25-inspired re-ranking, importance scoring, emotional valence tagging (positive, negative, neutral, surprise, urgency, curiosity), salience weighting, TTL expiration, keyword indexing.

2. Episodic Memory — What happened

Full conversation history: every user message, assistant response, tool call, and tool result, stored per session.

  • Tracks role, token_count, importance_score, emotional_valence
  • Links to sessions via foreign key
  • Supports cross-session search (search_backlogs)
  • Auto-detects topic shifts within sessions (get_session_topics)

3. Knowledge Graph — How things connect

Entities and their relationships, modeled as a directed graph.

 ┌──────────┐   uses    ┌─────────────┐   depends_on   ┌──────────┐
│ Knox ├──────────►│ TypeScript ├───────────────►│ SQLite │
│ (person) │ │ (technology)│ │ (tech) │
└──────────┘ └─────────────┘ └──────────┘

13 entity types: person, organization, technology, concept, project, file, function, class, variable, location, event, product, custom.

Graph traversal: Spreading activation — explore from any entity and discover connected nodes weighted by edge strength.

4. Learning Patterns — What works and what doesn't

Tracks approach success/failure rates by goal type (coding, debugging, analysis, research, etc.). Uses Jaccard similarity to suggest the best approach for new problems based on past outcomes.

5. Procedural Memory — How to do things

Named, ordered workflows with steps. Tracks execution count and success rate.

{
"name": "deploy-to-production",
"steps": ["Run lint", "Run tests", "Build", "Push to registry", "Deploy"],
"success_rate": 0.92,
"execution_count": 13
}

6. Working Memory — Right now

In-memory session state and short-term buffer that flushes to disk. Provides fast access to the current conversation context without DB queries.

The 5-Tier Memory Hierarchy

Inspired by CPU cache hierarchies and Ebbinghaus forgetting curves.

┌─────────────────────────────────────────────────┐
│ TIER 1: ACTIVE │ Currently in-session │ Working Memory
├───────────────────┼─────────────────────────────┤
│ TIER 2: HOT │ Frequently accessed, recent │ Full fidelity
├───────────────────┼─────────────────────────────┤
│ TIER 3: WARM │ 1-7 days old, moderate use │ Full fidelity
├───────────────────┼─────────────────────────────┤
│ TIER 4: COLD │ 7-90 days old, low access │ Compressed
├───────────────────┼─────────────────────────────┤
│ TIER 5: FROZEN │ Archived, rarely accessed │ Compressed
└───────────────────┴─────────────────────────────┘

Automatic Transitions

FromToTrigger
HotWarmAge > 24h, importance < 0.7
WarmColdAge > 7 days, importance < 0.5
ColdPrunedAge > 90 days, importance < 0.3
Semantic HotWarmNo access for 7 days, importance < 0.6
Semantic WarmColdNo access for 30 days, retrieval count < 3
ColdHot (promote)Retrieval count ≥ 5, accessed within 3 days

Spaced Repetition

Memories due for review are surfaced automatically. Each retrieval boosts a memory's importance score, preventing decay — the more you access it, the longer it stays.

Core Features

1. Context Builder

Automatically assembles the most relevant memories within a token budget. Used to prime the AI with context at the start of each conversation.

Budget allocation (default 4000 tokens):

SourceSharePurpose
Semantic memories40%Facts, decisions, code patterns
Episodic history25%Recent conversation context
Knowledge graph15%Entity relationships
Procedures10%Relevant workflows
Learning patterns10%Past approach success rates
memory({ action: "build_context", query: "TypeScript migration", max_tokens: 4000 })

2. Checkpoint & Rollback

Full memory state snapshots with point-in-time recovery.

  • Create: Snapshots all semantic memories, entities, and learning patterns
  • Diff: See what changed since a checkpoint (added, removed, modified)
  • Rollback: Restore memory to any checkpoint — conversation history preserved
  • Compress: gzip compression for space-efficient long-term storage
  • Lifecycle cleanup: Automatically prune old checkpoints

Checkpoint strategies:

  • manual — Create checkpoints explicitly
  • time_based — Auto-create at configurable intervals
  • adaptive — Auto-create when change threshold is exceeded
  • hybrid — Combine time and adaptive triggers
memory({ action: "create_checkpoint", label: "before-refactor-v2" })
memory({ action: "rollback_checkpoint", checkpoint_id: 4 })

3. Full Audit Trail

Every write operation is logged with target type, target ID, and details. Supports filtering by action, time range, and target. Enables:

  • Undo: Reverse any specific operation
  • Event replay: Replay changes from a checkpoint forward
  • Forensics: Understand exactly what changed and when

4. Auto-Extract

Pass raw text (conversation, code review, meeting notes) and Memory Brain automatically extracts:

  • Semantic memories (facts, decisions, insights)
  • Named entities (people, technologies, projects)
  • Emotional valence
  • Topic segmentation

Works rule-based by default. LLM-enhanced extraction available when an LLM is configured (with automatic fallback to rules if the LLM is unavailable).

Search across ALL past conversation sessions with filters:

  • Query text (full-text search)
  • Date range (from_date, to_date)
  • Role filter (user, assistant, tool)
  • Session ID filter

6. Performance Monitor

Real-time health monitoring and self-healing capabilities:

  • Metrics: Track operation counts, latency, cache hit rates
  • Health Score: Weighted composite of fragmentation, stale data, capacity
  • Capacity Forecast: Predict when storage or memory limits will be reached
  • Auto-Heal: Detect and fix common issues (orphaned records, index fragmentation)
  • Trend Analysis: Historical metrics with 24h lookback

7. Batch Operations

Bulk operations for efficiency:

  • batch_store — Store multiple memories in one call
  • batch_delete — Delete multiple memories by ID list
  • batch_update_importance — Update importance scores in bulk
  • batch_move_tier — Move memories between tiers
  • batch_audit_log — Log multiple events at once

8. LLM-Enhanced Features (Optional)

When an LLM is connected, unlock advanced capabilities:

FeatureWith LLMWithout LLM (Fallback)
Entity ExtractionNER-powered extractionRegex + heuristic rules
Session SummaryTopic detection, decision extractionMessage count + title
Importance ScoringContext-aware relevanceKeyword density + length
Post-Action MemoryLLM decides what to rememberManual store calls

All LLM features include:

  • Rate limiting: Configurable calls/tokens per hour
  • Circuit breaker: Automatically disables after repeated failures
  • Decision cache: Avoids redundant LLM calls for similar inputs

All 79 Actions Reference

Core Memory (6 actions)

ActionDescriptionKey Parameters
storeSave a semantic memorycategory, title, content, keywords, importance, ttl_hours
recallRetrieve relevant memories (semantic + episodic + associations)query, category, limit
searchFull-text search semantic memoriesquery, category, limit
deleteRemove a memory by IDid
build_contextToken-budgeted context assemblyquery, max_tokens, include_graph, include_procedures, include_patterns
get_statsComprehensive brain statistics

Session Management (5 actions)

ActionDescriptionKey Parameters
summarize_sessionGenerate session summarysession_id, title, workspace_directory
list_sessionsList tracked sessionslimit, workspace_directory
get_sessionSession details + historysession_id, limit
close_sessionClose and auto-summarizesession_id
get_session_topicsView topic shiftssession_id

Knowledge Graph (6 actions)

ActionDescriptionKey Parameters
add_entityAdd entity nodename, entity_type, description, properties, confidence
search_entitiesSearch entitiesquery, entity_type, limit
add_edgeCreate relationshipsource_entity_id, target_entity_id, relationship, weight
explore_graphSpreading activation traversalentity_id, depth, min_weight
get_graph_statsGraph statistics
extract_entitiesAuto-extract from texttext

Learning Engine (3 actions)

ActionDescriptionKey Parameters
learn_patternRecord success/failuregoal_type, description, success, tokens_used, pattern_signature
suggest_approachGet approach suggestionsquery, goal_type
get_patternsList learned patternsgoal_type, limit

Procedural Memory (3 actions)

ActionDescriptionKey Parameters
store_procedureStore named workflowname, description, steps, trigger_pattern, category
get_proceduresList procedurescategory, limit
execute_procedureRecord executionprocedure_id, success

Tags & Collections (6 actions)

ActionDescriptionKey Parameters
tagAdd tag to memorymemory_type, memory_id, tag
untagRemove tagmemory_type, memory_id, tag
search_by_tagFind by tagtag, memory_type
create_collectionCreate collectionname, description
list_collectionsList collections
add_to_collectionAdd memory to collectioncollection_id, memory_type, memory_id

Associations (1 action)

ActionDescriptionKey Parameters
associateLink two memoriessource_type, source_id, target_type, target_id, relationship, strength

Auto-Memory (1 action)

ActionDescriptionKey Parameters
auto_extractExtract memories + entities from texttext, session_id

Maintenance (5 actions)

ActionDescriptionKey Parameters
consolidateRun memory tiering + cleanup
get_healthHealth check with recommendations
optimizeVACUUM + REINDEX + ANALYZE
get_configView configurationkey
update_configUpdate configurationkey, value

Checkpoint & Rollback (5 actions)

ActionDescriptionKey Parameters
create_checkpointSnapshot memory statelabel
list_checkpointsList all checkpointslimit
rollback_checkpointRestore to checkpointcheckpoint_id
delete_checkpointRemove checkpointcheckpoint_id
compress_checkpointgzip-compress snapshotcheckpoint_id

Audit & Undo (4 actions)

ActionDescriptionKey Parameters
get_audit_logView audit trailaction, target_type, limit
undo_operationReverse a specific operationaudit_id
get_undoable_operationsList undo-eligible entrieslimit
replay_eventsReplay events from checkpointcheckpoint_id, from_time, to_time

Cross-Session Search (1 action)

ActionDescriptionKey Parameters
search_backlogsSearch across all sessionsquery, from_date, to_date, role, session_id, limit

Export / Import (2 actions)

ActionDescriptionKey Parameters
exportExport all memories to JSON
importImport memories from JSONdata

Checkpoint Strategy (4 actions)

ActionDescriptionKey Parameters
checkpoint_strategy_configGet strategy configuration
update_checkpoint_strategySet strategy modemode, interval_minutes, max_checkpoints, compress_snapshots
checkpoint_lifecycle_cleanupPrune old checkpoints
diff_checkpointShow changes since checkpointcheckpoint_id

Batch Operations (5 actions)

ActionDescriptionKey Parameters
batch_storeStore multiple memoriesitems[]
batch_deleteDelete by ID listids[]
batch_update_importanceBulk importance updateupdates[]
batch_move_tierMove memories between tiersids[], target_tier
batch_audit_logLog multiple eventsevents[]

Advanced Features (7 actions)

ActionDescriptionKey Parameters
find_related_sessionsDiscover related sessionssession_id, limit
five_tier_consolidateRun 5-tier consolidation
get_tier_distributionMemory counts per tier
get_tier_configsView tier configurations
update_tier_configUpdate tier settingstier, max_age_hours, importance_threshold
root_cause_analysisAnalyze memory issues
get_review_dueSpaced repetition due listlimit

Performance & Health (11 actions)

ActionDescriptionKey Parameters
boost_memorySpaced repetition boostmemory_id
get_cache_statsLRU cache statistics
clear_cacheClear LRU cache
get_metricsPerformance metrics
get_health_scoreWeighted health score
get_capacity_forecastStorage growth prediction
healAuto-heal detected issues
get_healing_strategiesHealing effectiveness
get_consolidation_statsConsolidation metadata
store_metrics_snapshotStore periodic metrics
get_metrics_trendHistorical metrics trendhours

LLM-Enhanced (4 actions)

ActionDescriptionKey Parameters
llm_extract_entitiesLLM NER entity extractiontext
llm_summarize_sessionLLM session summarysession_id
llm_evaluate_importanceLLM importance scoringcontent, context
llm_post_action_memoryLLM post-action memoryaction_type, input, output, context

Database Schema

17 tables with 27 optimized indexes, running on SQLite with WAL mode and foreign key constraints enabled.

brain_sessions           — Conversation sessions
brain_episodic — Conversation turns (messages, tool calls)
brain_semantic — Long-term factual memories
brain_associations — Cross-memory links
brain_entities — Knowledge graph nodes
brain_graph_edges — Knowledge graph relationships
brain_learning_patterns — Success/failure patterns
brain_procedures — Named workflows
brain_tags — Memory tags (many-to-many)
brain_collections — Named memory groups
brain_collection_items — Collection membership
brain_config — Configuration key/value store
brain_checkpoints — Memory state snapshots
brain_rate_limits — LLM rate limit tracking
brain_audit_log — Full audit trail
brain_session_topics — Auto-detected topic shifts
brain_metrics_snapshots — Performance metrics history

Storage: Single file at ~/.knox/memory/brain.sqlite. Typical size is 1-10 MB after months of active use.

Advantages

vs. Vector Databases (Pinecone, Chroma, Weaviate)

AspectMemory BrainVector DB
SetupZero config, single SQLite fileRequires server, API keys, embeddings
Privacy100% localCloud-hosted or self-hosted server
CostFreeEmbedding API costs + hosting
Latency< 1ms for most queriesNetwork round-trip + embedding
SearchBM25 + TF-IDF (no embeddings needed)Semantic vector similarity
StructureKnowledge graph + typed categoriesFlat vector space
PortabilityCopy one fileExport/import pipeline

vs. File-Based Memory (.md files, JSON)

AspectMemory BrainFile-Based
SearchFull-text with BM25 rankinggrep / string match
Organization9 semantic categories + tags + collectionsManual folder structure
LifecycleAutomatic tiering + decay + promotionManual cleanup
RelationshipsKnowledge graph + associationsNone
UndoFull audit trail + checkpoint rollbackGit history
Performance27 indexed queries, WAL modeFile I/O bottleneck

vs. No Memory (Stateless LLM)

CapabilityWith Memory BrainWithout
Remember past decisions✓ Automatically✗ Repeat every session
Learn from mistakes✓ Pattern tracking✗ Same mistakes repeatedly
Connect concepts✓ Knowledge graph✗ No cross-reference
Resume interrupted work✓ Session history✗ Start from scratch
Personalize responses✓ Preferences stored✗ Generic responses
Scale with usage✓ Auto-consolidationN/A

Key Pros

  1. Privacy-first — Everything stored locally. No API calls for core features.
  2. Self-maintaining — Automatic consolidation, decay, promotion, and healing.
  3. Resilient — Circuit breakers, fallbacks, rate limits. No single point of failure.
  4. Observable — Full audit trail, health metrics, performance monitoring.
  5. Reversible — Checkpoint/rollback for any destructive operation.
  6. Token-efficient — Context Builder assembles only what fits in your budget.
  7. Structured — Not just text blobs: typed entities, weighted edges, categorized facts.
  8. Tested — 443 integration tests across 4 test suites covering all 79 actions at 100% pass rate.
  9. LLM-optional — Every feature works without an LLM. Enhanced features degrade gracefully.
  10. Portable — Export/import everything as JSON. Move between machines freely.

Configuration

All settings are stored in brain_config table and can be read/updated via tool calls.

KeyDefaultDescription
auto_extract_enabledtrueAuto-extract memories from conversations
consolidation_interval_hours24Hours between auto-consolidation runs
max_episodic_per_session1000Max episodic entries per session
max_hot_memories500Hot memory cap (triggers consolidation)
hot_to_warm_hours24Hours before episodic demotion to warm
warm_to_cold_days7Days before demotion to cold
cold_prune_days90Days before cold memories are pruned
graph_enabledtrueEnable knowledge graph
learning_enabledtrueEnable learning pattern tracking
context_max_tokens4000Default token budget for context builder
llm_calls_per_hour_limit60Max LLM calls per hour
llm_tokens_per_hour_limit50000Max LLM tokens per hour
memory({ action: "get_config" })
memory({ action: "update_config", key: "max_hot_memories", value: "1000" })

Test Coverage

Four test suites exercise 443 integration tests across all 79 actions, calling every action through the actual dispatch pipeline against a real SQLite database.

Suite 1: test-memory-tool.ts — 94 tests

The original integration test covering all core dispatch actions.

SectionTestsCoverage
Core Memory Operations6store, recall, search, delete
Session Operations2list, stats
Knowledge Graph8entities, edges, search, traverse, extract
Learning Engine4patterns, suggestions
Procedural Memory3store, list, execute
Auto-Extract1Full extraction pipeline
Context Builder2Full and minimal context
Tags & Collections5tag/untag, search, collections
Associations1Cross-memory links
Maintenance3health, optimize, config, consolidate
Checkpoint & Rollback5create, diff, compress, rollback, verify
Audit & Topics2Audit log, filtering
Cross-Session Search1Backlog search
Export / Import1JSON export
Checkpoint Strategy & Batch6Strategy config, batch operations
Advanced Features (Tier D)75-tier, spaced repetition, cache
Performance Monitor7Metrics, health, forecast, healing
LLM-Enhanced (Fallback)2Entity extraction, importance scoring
Edge Cases5Non-existent IDs, empty queries
Batch Delete2Batch delete, unknown action
Total94100% pass rate

Suite 2: test-brain-debug.ts — 202 tests

Ultra-comprehensive integration tests exercising every dispatch action with deep output validation, edge cases, and multi-step workflows.

SectionTestsCoverage
Core Memory (CRUD)12store, recall, search, delete, duplicates
Session Lifecycle10create, list, get, close, summarize, topics
Knowledge Graph16entities, edges, traversal, stats, extraction
Learning Engine10patterns, suggestions, goal types, similarity
Procedural Memory8store, list, execute, success tracking
Auto-Extract Pipeline6text extraction, entity detection, valence
Context Builder8token budgets, source allocation, filters
Tags & Collections12tag, untag, search, collections, membership
Associations6cross-memory links, relationship types
Maintenance10health, optimize, config CRUD, consolidation
Checkpoint & Rollback14create, diff, compress, rollback, lifecycle
Audit Trail & Undo12audit log, filtering, undo, replay
Cross-Session Search6backlog search, date/role filters
Export / Import4JSON export, import, round-trip
Batch Operations14batch store, delete, update, move, audit
Advanced Features185-tier, spaced rep, cache, root cause
Performance Monitor20metrics, health score, forecast, healing
LLM-Enhanced Fallback8entity extraction, summarize, importance
Checkpoint Strategies10manual, time, adaptive, hybrid modes
Edge Cases & Errors18invalid IDs, empty inputs, concurrency
Total202100% pass rate

Suite 3: test-brain-debug-modules.ts — 59 tests

Module-level unit tests for individual classes (BrainStore, KnowledgeGraph, LearningEngine, ContextBuilder, CheckpointManager, BatchOperations, AdvancedFeatures, PerformanceMonitor).

ModuleTestsCoverage
BrainStore10Table creation, CRUD, indexes, WAL mode
KnowledgeGraph8Entity/edge CRUD, spreading activation
LearningEngine6Pattern recording, Jaccard similarity
ContextBuilder8Token budgeting, source allocation
CheckpointManager7Snapshot, rollback, compression
BatchOperations6Bulk store, delete, update, move
AdvancedFeatures85-tier hierarchy, spaced rep, LRU cache
PerformanceMonitor6MetricsCollector, HealthScorer, healing
Total59100% pass rate

Suite 4: test-brain-tool-calls.ts — 88 tests

End-to-end tests verifying all 79 tool enum actions work through BrainManager.dispatch(), organized by action tier.

TierTestsCoverage
Tier A — Core Memory6store, recall, search, delete, context, stats
Tier A — Sessions5summarize, list, get, close, topics
Tier A — Maintenance5consolidate, health, optimize, config
Tier A — Knowledge Graph6entity, edge, search, explore, stats, extract
Tier A — Learning Engine3learn, suggest, get patterns
Tier A — Procedures3store, list, execute
Tier A — Auto-Extract1Full pipeline
Tier A — Tags & Collections6tag, untag, search, collection CRUD
Tier A — Export/Import2JSON round-trip
Tier A — Self-Management5checkpoint, rollback, audit, undo
Tier A — LLM-Enhanced4entity extract, summarize, importance, post-action
Tier A — Checkpoints5list, delete, compress, diff, replay
Tier B — Performance6metrics, health score, forecast, heal, strategies
Tier C — Checkpoint Strategies4config, update, lifecycle, consolidation stats
Tier C — Event Replay/Undo3replay, undo, undoable operations
Tier C — Batch Operations5store, delete, update, move, audit
Tier D — Hierarchy55-tier, distribution, configs, update, related
Tier D — Root Cause & Rep3root cause, review due, boost
Tier D — Cache & Metrics5cache stats, clear, metrics snapshot, trend
Coverage Verification1Validates all 79 enum values dispatched
Total88100% pass rate

Summary

SuiteTestsFocus
test-memory-tool.ts94Original integration tests
test-brain-debug.ts202Ultra-comprehensive deep validation
test-brain-debug-modules.ts59Module-level unit tests
test-brain-tool-calls.ts88End-to-end tool enum coverage
Grand Total443All 79 actions — 100% pass rate

Each test suite uses a fresh temporary database, validates output format, and cleans up after itself.

Quick Start

Store a memory

memory({ action: "store", category: "decision", title: "Use SQLite for memory",
content: "Chose SQLite over Postgres for zero-config local storage.",
keywords: "database,sqlite,architecture", importance: 0.9 })

Recall relevant context

memory({ action: "recall", query: "database choice", limit: 5 })

Build pre-conversation context

memory({ action: "build_context", query: "TypeScript migration project",
max_tokens: 4000 })

Create a safety checkpoint before risky work

memory({ action: "create_checkpoint", label: "before-major-refactor" })
// ... do risky work ...
memory({ action: "rollback_checkpoint", checkpoint_id: 1 }) // oops, undo

Track what works

memory({ action: "learn_pattern", goal_type: "debugging",
description: "Binary search through git history to isolate regression",
success: true, tokens_used: 1200 })

// Next time:
memory({ action: "suggest_approach", query: "find regression", goal_type: "debugging" })

Tool Integration

Memory Brain is fully integrated into the Knox tool call system as a first-class built-in tool with its own UI category, interceptor validation, and permission controls.

Registration Architecture

core/tools/definitions/memory.ts     → Tool definition (schema, 79 actions, params)
core/tools/implementations/memory.ts → Implementation (routes to BrainManager.dispatch)
core/tools/callTool.ts → Dispatch (BuiltInToolNames.Memory → memoryImpl)
core/tools/builtIn.ts → Enum (Memory = "builtin_memory")
core/tools/index.ts → allTools array (includes memoryTool)
core/config/load.ts → Config (tools: [...allTools])

Tool Identity

PropertyValue
Internal namebuiltin_memory
Display titleMemory
UI category[Memory]
Permission groupPermissions (built-in)
Default permissionallowedWithoutPermission (Auto-Approve)
Read-onlyfalse

How It Appears in the UI

The memory tool shows up in the Tools panel under the Permissions group:

● Permissions  [12]                              ⬤ ON
[Files] Read File Auto-Approve
[Files] Create New File Auto-Approve
[Terminal] Run Terminal Command Auto-Approve
[Files] View Subdirectory Auto-Approve
[Files] View Repo Structure Auto-Approve
[Search] Exact Search Auto-Approve
[Search] Web Search Auto-Approve
[Diff] View Diff Auto-Approve
[Files] Read Currently Open File Auto-Approve
[Tool] Load Skill Auto-Approve
[Tool] LSP Auto-Approve
[Memory] Memory Auto-Approve

File Locations

ComponentPathPurpose
Tool definitioncore/tools/definitions/memory.tsLLM-facing schema: 79 actions, all parameters
Tool implementationcore/tools/implementations/memory.tsRoutes args.actionBrainManager.dispatch()
Tool dispatchcore/tools/callTool.tsBuiltInToolNames.MemorymemoryImpl()
Tool enumcore/tools/builtIn.tsMemory = "builtin_memory"
Tool registrycore/tools/index.tsallTools array, allAvailableTools
Config loadercore/config/load.tstools: [...allTools] in KnoxConfig
Interceptorextensions/vscode/src/agent/ToolCallInterceptor.tsValidation, logging, metrics
UI permissionsgui/src/redux/slices/uiSlice.tstoolSettings initial state
UI categorygui/src/util/toolNameFormatter.ts[Memory] category prefix
UI dialoggui/src/components/.../ToolPermissionsDialog.tsxRenders tool permission toggles

Permission States

Each tool can be in one of three permission states, cycled by clicking:

StateBehavior
allowedWithoutPermissionAuto-Approve — tool calls execute without confirmation
allowedWithPermissionAsk — user must approve each tool call
disabledDisabled — tool is never called

The entire Permissions group can also be toggled on/off via the group switch.

Tool Call Flow (End-to-End)

1. LLM generates tool call:
{ name: "builtin_memory", arguments: { action: "store", ... } }

2. ToolCallInterceptor validates:
- Tool exists in registry ✓
- Required params present (action) ✓
- Logs call to history, tracks metrics

3. Permission check:
- toolSettings["builtin_memory"] === "allowedWithoutPermission"
- Auto-approved (no user prompt)

4. callTool() dispatches:
- Matches BuiltInToolNames.Memory
- Calls memoryImpl(args, extras)

5. memoryImpl() routes:
- Gets BrainManager singleton
- Calls brain.dispatch(args.action, args)

6. BrainManager.dispatch() handles:
- Routes to appropriate handler (store, recall, search, etc.)
- Records audit trail
- Emits events
- Returns formatted string

7. Result returned to LLM as ContextItem[]

Try KnoxChat VS Code extension with Memory Brain here >>>

Memory Brain is part of the KnoxCore platform. All data stays on your machine.