cozo-memory 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +54 -126
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3422,37 +3422,15 @@ Format MUST start with "ExecutiveSummary: " followed by the consolidated content
3422
3422
  this.mcp.addTool({
3423
3423
  name: "mutate_memory",
3424
3424
  description: `Write access to memory. Select operation via 'action'.
3425
- Supported actions:
3426
- - 'create_entity': Creates a new entity. Params: { name: string, type: string, metadata?: object }
3427
- - 'update_entity': Updates an existing entity. Params: { id: string, name?: string, type?: string, metadata?: object }
3428
- - 'delete_entity': Deletes an entity and its observations. Params: { entity_id: string }
3429
- - 'add_observation': Stores a fact. Params: { entity_id?: string, entity_name?: string, entity_type?: string, text: string, metadata?: object, deduplicate?: boolean }. Automatic deduplication active (can be disabled).
3430
- NOTE: Use special 'entity_id': 'global_user_profile' to store persistent user preferences (likes, work style, dislikes). These are prioritized in searches.
3431
- - 'create_relation': Creates a connection between entities. Params: { from_id: string, to_id: string, relation_type: string, strength?: number (0-1), metadata?: object }. No self-references allowed.
3432
- - 'run_transaction': Executes multiple operations atomically in one transaction. Params: { operations: Array<{ action: "create_entity"|"add_observation"|"create_relation", params: object }> }. Ideal for complex, related changes.
3433
- - 'add_inference_rule': Adds a custom Datalog inference rule. Params: { name: string, datalog: string }.
3434
- IMPORTANT: The Datalog result set MUST return exactly 5 columns: [from_id, to_id, relation_type, confidence, reason].
3435
- Use '$id' as placeholder for the start entity.
3436
- Available tables:
3437
- - *entity{id, name, type, metadata, @ "NOW"}
3438
- - *relationship{from_id, to_id, relation_type, strength, metadata, @ "NOW"}
3439
- - *observation{id, entity_id, text, metadata, @ "NOW"}
3440
- Example (Manager Transitivity):
3441
- '?[from_id, to_id, relation_type, confidence, reason] := *relationship{from_id: $id, to_id: mid, relation_type: "manager_of", @ "NOW"}, *relationship{from_id: mid, to_id: target, relation_type: "manager_of", @ "NOW"}, from_id = $id, to_id = target, relation_type = "ober_manager_von", confidence = 0.6, reason = "Transitive Manager Path"'
3442
- - 'ingest_file': Bulk import of documents (Markdown/JSON). Supports chunking (paragraphs) and automatic entity creation. Params: { entity_id | entity_name (required), format, content, ... }. Ideal for quickly populating memory from existing notes.
3443
- - 'start_session': Initializes a new session for context tracking. Params: { name?: string, metadata?: object }.
3444
- - 'stop_session': Closes a session. Params: { id: string }.
3445
- - 'start_task': Initializes a new task within a session. Params: { name: string, session_id?: string, metadata?: object }.
3446
- - 'stop_task': Marks a task as completed. Params: { id: string }.
3447
- - 'invalidate_observation': Invalidates (soft-deletes) an observation at the current time. Params: { observation_id: string }.
3448
- - 'invalidate_relation': Invalidates (soft-deletes) a relationship at the current time. Params: { from_id: string, to_id: string, relation_type: string }.
3449
- - 'enrich_observation': Manually trigger Zettelkasten enrichment for an observation. Params: { observation_id: string }. Extracts keywords/tags, finds related observations, creates bidirectional links, and updates metadata.
3450
- - 'record_memory_access': Record access to an observation for ACT-R memory activation tracking. Params: { observation_id: string }. Updates access_count and last_access_time metadata.
3451
- - 'prune_weak_memories': Delete observations with activation below retention threshold. Params: { dry_run?: boolean (default: true), entity_id?: string }. Returns: { pruned: number, preserved: number, candidates: ActivationScore[] }.
3452
- - 'detect_conflicts': Detect temporal conflicts for an entity. Params: { entity_id: string }. Returns: { conflicts: [{ older_observation_id, newer_observation_id, conflict_type, confidence, reason }], count }. Detects redundancy, contradictions, and superseded facts.
3453
- - 'resolve_conflicts': Resolve temporal conflicts by invalidating older observations. Params: { entity_id: string, auto_resolve?: boolean }. Returns: { resolved_conflicts, invalidated_observations, audit_observations }. Creates audit trail if enabled.
3454
3425
 
3455
- Validation: Invalid syntax or missing columns in inference rules will result in errors.`,
3426
+ Common actions: create_entity, add_observation, create_relation, update_entity, delete_entity
3427
+ Advanced: run_transaction, add_inference_rule, ingest_file, session/task management, conflict detection
3428
+
3429
+ Use entity_id='global_user_profile' for storing persistent user preferences (automatically boosted in searches).
3430
+
3431
+ For detailed action descriptions, parameters, and examples, see the cozo-memory-guide steering file.
3432
+
3433
+ Note: Inference rules must return exactly 5 columns: [from_id, to_id, relation_type, confidence, reason]. Invalid syntax will result in errors.`,
3456
3434
  parameters: MutateMemoryParameters,
3457
3435
  execute: async (args) => {
3458
3436
  await this.initPromise;
@@ -3774,49 +3752,35 @@ Validation: Invalid syntax or missing columns in inference rules will result in
3774
3752
  const QueryMemoryParameters = zod_1.z.object({
3775
3753
  action: zod_1.z
3776
3754
  .enum(["search", "advancedSearch", "context", "entity_details", "history", "graph_rag", "graph_walking", "agentic_search", "dynamic_fusion", "adaptive_retrieval", "get_zettelkasten_stats", "get_activation_stats", "get_salience_stats", "suggest_connections", "spreading_activation", "qafd_search", "hierarchical_memory_query"])
3777
- .describe("Action (determines which fields are required)"),
3778
- query: zod_1.z.string().optional().describe("Required for search/advancedSearch/context/graph_rag/graph_walking/agentic_search/dynamic_fusion/adaptive_retrieval"),
3779
- limit: zod_1.z.number().optional().describe("Only for search/advancedSearch/graph_rag/graph_walking/dynamic_fusion/adaptive_retrieval"),
3780
- session_id: zod_1.z.string().optional().describe("Optional session ID for context boosting"),
3781
- task_id: zod_1.z.string().optional().describe("Optional task ID for context boosting"),
3782
- filters: zod_1.z.any().optional().describe("Only for advancedSearch"),
3783
- graphConstraints: zod_1.z.any().optional().describe("Only for advancedSearch"),
3784
- vectorOptions: zod_1.z.any().optional().describe("Only for advancedSearch"),
3785
- entity_types: zod_1.z.array(zod_1.z.string()).optional().describe("Only for search"),
3786
- include_entities: zod_1.z.boolean().optional().describe("Only for search"),
3787
- include_observations: zod_1.z.boolean().optional().describe("Only for search"),
3788
- context_window: zod_1.z.number().optional().describe("Only for context"),
3789
- time_range_hours: zod_1.z.number().optional().describe("Only for context"),
3790
- entity_id: zod_1.z.string().optional().describe("Required for entity_details/history"),
3791
- as_of: zod_1.z.string().optional().describe("Only for entity_details: ISO string or 'NOW'"),
3792
- max_depth: zod_1.z.number().optional().describe("Only for graph_rag/graph_walking: Maximum expansion depth"),
3793
- start_entity_id: zod_1.z.string().optional().describe("Only for graph_walking: Start entity"),
3794
- rerank: zod_1.z.boolean().optional().describe("Only for search/advancedSearch/agentic_search: Enable Cross-Encoder reranking"),
3795
- config: zod_1.z.any().optional().describe("Only for dynamic_fusion: Fusion configuration object"),
3755
+ .describe("Retrieval strategy - use 'search' for simple queries, 'adaptive_retrieval' for auto-optimization, 'context' for exploration"),
3756
+ query: zod_1.z.string().optional().describe("Search query text (required for most actions)"),
3757
+ limit: zod_1.z.number().optional().describe("Maximum number of results to return (default: 10)"),
3758
+ session_id: zod_1.z.string().optional().describe("Session ID for context boosting - prioritizes results from this session"),
3759
+ task_id: zod_1.z.string().optional().describe("Task ID for context boosting - prioritizes results from this task"),
3760
+ filters: zod_1.z.any().optional().describe("For advancedSearch: Filter by entity types, metadata conditions"),
3761
+ graphConstraints: zod_1.z.any().optional().describe("For advancedSearch: Require specific relationships or target entities"),
3762
+ vectorOptions: zod_1.z.any().optional().describe("For advancedSearch: Vector search tuning (topk, efSearch)"),
3763
+ entity_types: zod_1.z.array(zod_1.z.string()).optional().describe("For search: Filter results by entity type"),
3764
+ include_entities: zod_1.z.boolean().optional().describe("For search: Include entities in results (default: true)"),
3765
+ include_observations: zod_1.z.boolean().optional().describe("For search: Include observations in results (default: true)"),
3766
+ context_window: zod_1.z.number().optional().describe("For context: Number of related entities to include (default: 5)"),
3767
+ time_range_hours: zod_1.z.number().optional().describe("For context: Time window in hours for temporal filtering"),
3768
+ entity_id: zod_1.z.string().optional().describe("For entity_details/history: Entity ID to query"),
3769
+ as_of: zod_1.z.string().optional().describe("For entity_details: Point-in-time query (ISO timestamp or 'NOW')"),
3770
+ max_depth: zod_1.z.number().optional().describe("For graph_rag/graph_walking: Maximum traversal depth (hops)"),
3771
+ start_entity_id: zod_1.z.string().optional().describe("For graph_walking: Starting entity for traversal"),
3772
+ rerank: zod_1.z.boolean().optional().describe("For search/advancedSearch: Enable Cross-Encoder reranking for higher precision"),
3773
+ config: zod_1.z.any().optional().describe("For dynamic_fusion: Fine-tune vector/sparse/FTS/graph weights and fusion strategy"),
3796
3774
  });
3797
3775
  this.mcp.addTool({
3798
3776
  name: "query_memory",
3799
- description: `Read access to memory. Select operation via 'action'.
3800
- Supported actions:
3801
- - 'search': Hybrid search (Vector + Keyword + Graph). Params: { query: string, limit?: number, entity_types?: string[], include_entities?: boolean, include_observations?: boolean }.
3802
- NOTE: Results from user profile ('global_user_profile') are automatically boosted and prioritized.
3803
- - 'advancedSearch': Advanced search with metadata filters and graph constraints. Params: { query: string, limit?: number, filters?: { entityTypes?: string[], metadata?: object }, graphConstraints?: { requiredRelations?: string[], targetEntityIds?: string[] }, vectorOptions?: { topk?: number, efSearch?: number } }.
3804
- - 'context': Retrieves comprehensive context. Params: { query: string, context_window?: number, time_range_hours?: number }. Returns entities, observations, graph relationships, and implicit inference suggestions.
3805
- NOTE: User profile is automatically included in context if relevant to enable personalization.
3806
- - 'entity_details': Detailed view of an entity. Params: { entity_id: string, as_of?: string ('ISO-String' or 'NOW') }.
3807
- - 'history': Retrieve historical evolution of an entity. Params: { entity_id: string }.
3808
- - 'graph_rag': Graph-based reasoning (Hybrid RAG). Finds semantic vector seeds first, then expands via graph traversals. Ideal for multi-hop reasoning. Params: { query: string, max_depth?: number, limit?: number }.
3809
- - 'graph_walking': Recursive semantic graph search. Starts at vector seeds or an entity and follows relationships to other semantically relevant entities. Params: { query: string, start_entity_id?: string, max_depth?: number, limit?: number }.
3810
- - 'agentic_search': Auto-Routing Search. Uses local LLM to analyze intent and routes the query automatically to the best strategy (Vector, Graph, or Community Summaries). Params: { query: string, limit?: number }.
3811
- - 'adaptive_retrieval': GraphRAG-R1 inspired adaptive retrieval with Progressive Retrieval Attenuation (PRA) and Cost-Aware F1 (CAF) scoring. Automatically selects optimal strategy based on query complexity and historical performance. Params: { query: string, limit?: number }.
3812
- - 'dynamic_fusion': Advanced multi-path fusion search combining Vector (HNSW), Sparse (keyword), FTS (full-text), and Graph traversal with configurable weights and strategies. Params: { query: string, config?: { vector?, sparse?, fts?, graph?, fusion? }, limit?: number }. Each path can be enabled/disabled and weighted independently. Fusion strategies: 'rrf' (Reciprocal Rank Fusion), 'weighted_sum', 'max', 'adaptive'. Returns results with path contribution details and performance stats.
3813
- - 'get_zettelkasten_stats': Get Zettelkasten Memory Evolution statistics. No params required. Returns: { totalObservations, enrichedObservations, totalLinks, averageLinksPerNote, topKeywords, topTags, connectionTypes }.
3814
- - 'get_activation_stats': Get ACT-R Memory Activation statistics. Params: { entity_id?: string }. Returns: { totalObservations, averageActivation, averageStrength, belowThreshold, aboveThreshold, distribution }.
3815
- - 'get_salience_stats': Get Emotional Salience statistics. No params required. Returns: { totalObservations, withSalience, distribution, averageSalience, topKeywords }.
3816
- - 'suggest_connections': Proactive connection suggestions for an entity. Params: { entity_id: string, max_suggestions?: number, min_confidence?: number }. Returns: { entity_id, suggestions: [{ entity_id, entity_name, entity_type, source, confidence, confidence_level, reason, metadata }], count }. Combines vector similarity, common neighbors, graph proximity, and inference strategies.
3817
- - 'spreading_activation': SYNAPSE spreading activation search. Params: { query: string, seed_top_k?: number, limit?: number }. Returns: { scores: [{ entityId, activation, potential, source, hops }], iterations, converged, seedNodes }. Implements neural-inspired activation spreading with fan effect, lateral inhibition, and sigmoid activation.
3777
+ description: `Read access to memory with multiple retrieval strategies.
3778
+
3779
+ Use 'search' for quick lookups, 'adaptive_retrieval' for auto-optimization, or 'context' for comprehensive exploration.
3780
+
3781
+ Available actions: search, advancedSearch, context, entity_details, history, graph_rag, graph_walking, adaptive_retrieval, dynamic_fusion, agentic_search, spreading_activation, suggest_connections, get_zettelkasten_stats, get_activation_stats, get_salience_stats, qafd_search, hierarchical_memory_query.
3818
3782
 
3819
- Notes: 'adaptive_retrieval' learns from usage and optimizes over time. 'dynamic_fusion' provides the most control and transparency over retrieval paths. 'agentic_search' is the most adaptive. 'context' is ideal for exploratory questions. 'search' and 'advancedSearch' are better for targeted fact retrieval.`,
3783
+ Note: User profile observations (entity_id='global_user_profile') are automatically boosted in searches. For detailed action descriptions and parameters, see the cozo-memory-guide steering file.`,
3820
3784
  parameters: QueryMemoryParameters,
3821
3785
  execute: async (args) => {
3822
3786
  await this.initPromise;
@@ -4466,24 +4430,13 @@ Notes: 'adaptive_retrieval' learns from usage and optimizes over time. 'dynamic_
4466
4430
  this.mcp.addTool({
4467
4431
  name: "analyze_graph",
4468
4432
  description: `Graph analysis and advanced retrieval strategies. Select operation via 'action'.
4469
- Supported actions:
4470
- - 'explore': Navigates through the graph. Params: { start_entity: string, end_entity?: string, max_hops?: number, relation_types?: string[] }.
4471
- * Without end_entity: Returns the neighborhood (up to 5 hops).
4472
- * With end_entity: Finds the shortest path (BFS).
4473
- - 'communities': Recomputes entity groups (communities) using Label Propagation.
4474
- - 'pagerank': Calculates the importance of entities (Top 10).
4475
- - 'betweenness': Finds central bridge entities (Betweenness Centrality).
4476
- - 'hits': Identifies Hubs and Authorities.
4477
- - 'connected_components': Identifies isolated subgraphs.
4478
- - 'shortest_path': Calculates the shortest path between two entities (Dijkstra). Params: { start_entity: string, end_entity: string }.
4479
- - 'bridge_discovery': Identifies bridge entities between communities.
4480
- - 'infer_relations': Starts the inference engine for an entity. Params: { entity_id: string }.
4481
- - 'get_relation_evolution': Tracks the temporal evolution of relationships. Params: { from_id: string, to_id?: string }.
4482
- - 'semantic_walk': Performs a recursive "Graph Walk" that follows both explicit relationships and semantic similarity. Params: { start_entity: string, max_depth?: number, min_similarity?: number }.
4483
- - 'hnsw_clusters': Analyzes clusters directly on the HNSW graph (Layer 0). Extremely fast as no vector calculations are needed.
4484
- - 'discover_logical_edges': Discovers implicit logical edges for an entity (same category, type, hierarchical, contextual, transitive). Params: { entity_id: string }.
4485
- - 'materialize_logical_edges': Materializes discovered logical edges as actual relationships in the graph. Params: { entity_id: string }.
4486
- - 'detect_temporal_patterns': Detects temporal patterns in entity observations (periodic, trending, seasonal). Params: { entity_id: string }.`,
4433
+
4434
+ Common operations: explore (navigate/find paths), communities (detect groups), pagerank (entity importance), shortest_path
4435
+ Advanced: semantic_walk, infer_relations, bridge_discovery, hnsw_clusters, temporal patterns
4436
+
4437
+ Use 'explore' without end_entity for neighborhood, with end_entity for shortest path.
4438
+
4439
+ For detailed action descriptions and parameters, see the cozo-memory-guide steering file.`,
4487
4440
  parameters: AnalyzeGraphParameters,
4488
4441
  execute: async (args) => {
4489
4442
  await this.initPromise;
@@ -4939,32 +4892,16 @@ Supported actions:
4939
4892
  this.mcp.addTool({
4940
4893
  name: "manage_system",
4941
4894
  description: `System maintenance and memory management. Select operation via 'action'.
4942
- Supported actions:
4943
- - 'health': Status check. Returns DB counts, embedding cache statistics, and performance metrics.
4944
- - 'metrics': Detailed metrics. Returns operation counts, error statistics, and performance data.
4945
- - 'export_memory': Export memory to various formats. Params: { format: 'json'|'markdown'|'obsidian', includeMetadata?: boolean, includeRelationships?: boolean, includeObservations?: boolean, entityTypes?: string[], since?: number }.
4946
- * format='json': Native Cozo format (re-importable)
4947
- * format='markdown': Human-readable markdown document
4948
- * format='obsidian': ZIP archive with wiki-links, ready for Obsidian vault
4949
- - 'import_memory': Import memory from external sources. Params: { data: string|object, sourceFormat: 'mem0'|'memgpt'|'markdown'|'cozo', mergeStrategy?: 'skip'|'overwrite'|'merge', defaultEntityType?: string }.
4950
- * sourceFormat='mem0': Import from Mem0 format (user_id becomes entity)
4951
- * sourceFormat='memgpt': Import from MemGPT archival/recall memory
4952
- * sourceFormat='markdown': Parse markdown sections as entities
4953
- * sourceFormat='cozo': Import from native Cozo JSON export
4954
- - 'snapshot_create': Creates a backup point. Params: { metadata?: object }.
4955
- - 'snapshot_list': Lists all available snapshots.
4956
- - 'snapshot_diff': Compares two snapshots. Params: { snapshot_id_a: string, snapshot_id_b: string }.
4957
- - 'cleanup': Janitor service for consolidation. Params: { confirm: boolean, older_than_days?: number, max_observations?: number, min_entity_degree?: number, model?: string }.
4958
- * With confirm=false: Dry-Run (shows candidates).
4959
- * With confirm=true: Merges old/isolated fragments using LLM (Executive Summary) and removes noise.
4960
- - 'defrag': Memory defragmentation. Reorganizes memory structure by detecting/merging duplicates, connecting fragmented knowledge islands, and removing orphaned entities. Params: { confirm: boolean, similarity_threshold?: number (0.8-1.0, default 0.95), min_island_size?: number (1-10, default 3) }.
4961
- * With confirm=false: Dry-Run (shows analysis and candidates).
4962
- * With confirm=true: Executes defragmentation and returns statistics.
4963
- - 'reflect': Reflection service. Analyzes memory for contradictions and insights. Params: { entity_id?: string, model?: string }.
4964
- - 'clear_memory': Resets the entire database. Params: { confirm: boolean (must be true) }.
4965
- - 'summarize_communities': Hierarchical GraphRAG. Generates summaries for entity clusters. Params: { model?: string, min_community_size?: number }.
4966
- - 'compress_memory_levels': Hierarchical memory compression. Compresses observations at a specific memory level using LLM summarization. Params: { entity_id: string, level: number (0-3) }.
4967
- - 'analyze_memory_distribution': Analyzes memory distribution across hierarchical levels. Params: { entity_id: string }.`,
4895
+
4896
+ Monitoring: health (status check), metrics (detailed stats)
4897
+ Data portability: export_memory (JSON/Markdown/Obsidian), import_memory (Mem0/MemGPT/Cozo)
4898
+ Backups: snapshot_create, snapshot_list, snapshot_diff
4899
+ Optimization: cleanup (LLM consolidation), defrag (merge duplicates), reflect (find contradictions)
4900
+ Advanced: summarize_communities, compress_memory_levels, analyze_memory_distribution
4901
+
4902
+ Important: Use confirm=false for dry-run before cleanup/defrag. clear_memory requires confirm=true.
4903
+
4904
+ For detailed action descriptions and parameters, see the cozo-memory-guide steering file.`,
4968
4905
  parameters: ManageSystemParameters,
4969
4906
  execute: async (args) => {
4970
4907
  await this.initPromise;
@@ -5297,23 +5234,14 @@ Supported actions:
5297
5234
  this.mcp.addTool({
5298
5235
  name: "edit_user_profile",
5299
5236
  description: `Direct management of the global user profile ('global_user_profile').
5300
- This tool allows manual editing of user preferences, work style, and profile metadata.
5301
5237
 
5302
- The user profile is automatically boosted in all searches (50% score boost) and used for personalization.
5238
+ Edit user preferences, work style, and profile metadata. The user profile is automatically boosted in all searches (50% score boost).
5303
5239
 
5304
- Parameters:
5305
- - name?: string - Update the profile name (default: "The User")
5306
- - type?: string - Update the profile type (default: "User")
5307
- - metadata?: object - Update or merge profile metadata
5308
- - observations?: Array<{ text: string, metadata?: object }> - Add new preference observations
5309
- - clear_observations?: boolean - Remove all existing observations before adding new ones
5240
+ Parameters: name, type, metadata, observations (array), clear_observations (boolean)
5310
5241
 
5311
- Examples:
5312
- - Add preferences: { observations: [{ text: "Prefers TypeScript over JavaScript" }] }
5313
- - Update metadata: { metadata: { timezone: "Europe/Berlin", language: "de" } }
5314
- - Reset and set new preferences: { clear_observations: true, observations: [{ text: "New preference" }] }
5242
+ Example: { observations: [{ text: "Prefers TypeScript over JavaScript" }] }
5315
5243
 
5316
- Note: Use 'mutate_memory' with action='add_observation' and entity_id='global_user_profile' for implicit preference updates.`,
5244
+ Note: Use mutate_memory with action='add_observation' and entity_id='global_user_profile' for implicit updates.`,
5317
5245
  parameters: zod_1.z.object({
5318
5246
  name: zod_1.z.string().optional().describe("New name for the user profile"),
5319
5247
  type: zod_1.z.string().optional().describe("New type for the user profile"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cozo-memory",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "mcpName": "io.github.tobs-code/cozo-memory",
5
5
  "description": "Local-first persistent memory system for AI agents with hybrid search, graph reasoning, and MCP integration",
6
6
  "main": "dist/index.js",