superlocalmemory 2.7.6 → 2.8.0

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 (170) hide show
  1. package/CHANGELOG.md +120 -155
  2. package/README.md +115 -89
  3. package/api_server.py +2 -12
  4. package/docs/PATTERN-LEARNING.md +64 -199
  5. package/docs/example_graph_usage.py +4 -6
  6. package/install.sh +59 -0
  7. package/mcp_server.py +83 -7
  8. package/package.json +1 -8
  9. package/scripts/generate-thumbnails.py +3 -5
  10. package/skills/slm-build-graph/SKILL.md +1 -1
  11. package/skills/slm-list-recent/SKILL.md +1 -1
  12. package/skills/slm-recall/SKILL.md +1 -1
  13. package/skills/slm-remember/SKILL.md +1 -1
  14. package/skills/slm-show-patterns/SKILL.md +1 -1
  15. package/skills/slm-status/SKILL.md +1 -1
  16. package/skills/slm-switch-profile/SKILL.md +1 -1
  17. package/src/agent_registry.py +7 -18
  18. package/src/auth_middleware.py +3 -5
  19. package/src/auto_backup.py +3 -7
  20. package/src/behavioral/__init__.py +49 -0
  21. package/src/behavioral/behavioral_listener.py +203 -0
  22. package/src/behavioral/behavioral_patterns.py +275 -0
  23. package/src/behavioral/cross_project_transfer.py +206 -0
  24. package/src/behavioral/outcome_inference.py +194 -0
  25. package/src/behavioral/outcome_tracker.py +193 -0
  26. package/src/behavioral/tests/__init__.py +4 -0
  27. package/src/behavioral/tests/test_behavioral_integration.py +108 -0
  28. package/src/behavioral/tests/test_behavioral_patterns.py +150 -0
  29. package/src/behavioral/tests/test_cross_project_transfer.py +142 -0
  30. package/src/behavioral/tests/test_mcp_behavioral.py +139 -0
  31. package/src/behavioral/tests/test_mcp_report_outcome.py +117 -0
  32. package/src/behavioral/tests/test_outcome_inference.py +107 -0
  33. package/src/behavioral/tests/test_outcome_tracker.py +96 -0
  34. package/src/cache_manager.py +4 -6
  35. package/src/compliance/__init__.py +48 -0
  36. package/src/compliance/abac_engine.py +149 -0
  37. package/src/compliance/abac_middleware.py +116 -0
  38. package/src/compliance/audit_db.py +215 -0
  39. package/src/compliance/audit_logger.py +148 -0
  40. package/src/compliance/retention_manager.py +289 -0
  41. package/src/compliance/retention_scheduler.py +186 -0
  42. package/src/compliance/tests/__init__.py +4 -0
  43. package/src/compliance/tests/test_abac_enforcement.py +95 -0
  44. package/src/compliance/tests/test_abac_engine.py +124 -0
  45. package/src/compliance/tests/test_abac_mcp_integration.py +118 -0
  46. package/src/compliance/tests/test_audit_db.py +123 -0
  47. package/src/compliance/tests/test_audit_logger.py +98 -0
  48. package/src/compliance/tests/test_mcp_audit.py +128 -0
  49. package/src/compliance/tests/test_mcp_retention_policy.py +125 -0
  50. package/src/compliance/tests/test_retention_manager.py +131 -0
  51. package/src/compliance/tests/test_retention_scheduler.py +99 -0
  52. package/src/db_connection_manager.py +2 -12
  53. package/src/embedding_engine.py +61 -669
  54. package/src/embeddings/__init__.py +47 -0
  55. package/src/embeddings/cache.py +70 -0
  56. package/src/embeddings/cli.py +113 -0
  57. package/src/embeddings/constants.py +47 -0
  58. package/src/embeddings/database.py +91 -0
  59. package/src/embeddings/engine.py +247 -0
  60. package/src/embeddings/model_loader.py +145 -0
  61. package/src/event_bus.py +3 -13
  62. package/src/graph/__init__.py +36 -0
  63. package/src/graph/build_helpers.py +74 -0
  64. package/src/graph/cli.py +87 -0
  65. package/src/graph/cluster_builder.py +188 -0
  66. package/src/graph/cluster_summary.py +148 -0
  67. package/src/graph/constants.py +47 -0
  68. package/src/graph/edge_builder.py +162 -0
  69. package/src/graph/entity_extractor.py +95 -0
  70. package/src/graph/graph_core.py +226 -0
  71. package/src/graph/graph_search.py +231 -0
  72. package/src/graph/hierarchical.py +207 -0
  73. package/src/graph/schema.py +99 -0
  74. package/src/graph_engine.py +45 -1451
  75. package/src/hnsw_index.py +3 -7
  76. package/src/hybrid_search.py +36 -683
  77. package/src/learning/__init__.py +27 -12
  78. package/src/learning/adaptive_ranker.py +50 -12
  79. package/src/learning/cross_project_aggregator.py +2 -12
  80. package/src/learning/engagement_tracker.py +2 -12
  81. package/src/learning/feature_extractor.py +175 -43
  82. package/src/learning/feedback_collector.py +7 -12
  83. package/src/learning/learning_db.py +180 -12
  84. package/src/learning/project_context_manager.py +2 -12
  85. package/src/learning/source_quality_scorer.py +2 -12
  86. package/src/learning/synthetic_bootstrap.py +2 -12
  87. package/src/learning/tests/__init__.py +2 -0
  88. package/src/learning/tests/test_adaptive_ranker.py +2 -6
  89. package/src/learning/tests/test_adaptive_ranker_v28.py +60 -0
  90. package/src/learning/tests/test_aggregator.py +2 -6
  91. package/src/learning/tests/test_auto_retrain_v28.py +35 -0
  92. package/src/learning/tests/test_e2e_ranking_v28.py +82 -0
  93. package/src/learning/tests/test_feature_extractor_v28.py +93 -0
  94. package/src/learning/tests/test_feedback_collector.py +2 -6
  95. package/src/learning/tests/test_learning_db.py +2 -6
  96. package/src/learning/tests/test_learning_db_v28.py +110 -0
  97. package/src/learning/tests/test_learning_init_v28.py +48 -0
  98. package/src/learning/tests/test_outcome_signals.py +48 -0
  99. package/src/learning/tests/test_project_context.py +2 -6
  100. package/src/learning/tests/test_schema_migration.py +319 -0
  101. package/src/learning/tests/test_signal_inference.py +11 -13
  102. package/src/learning/tests/test_source_quality.py +2 -6
  103. package/src/learning/tests/test_synthetic_bootstrap.py +3 -7
  104. package/src/learning/tests/test_workflow_miner.py +2 -6
  105. package/src/learning/workflow_pattern_miner.py +2 -12
  106. package/src/lifecycle/__init__.py +54 -0
  107. package/src/lifecycle/bounded_growth.py +239 -0
  108. package/src/lifecycle/compaction_engine.py +226 -0
  109. package/src/lifecycle/lifecycle_engine.py +302 -0
  110. package/src/lifecycle/lifecycle_evaluator.py +225 -0
  111. package/src/lifecycle/lifecycle_scheduler.py +130 -0
  112. package/src/lifecycle/retention_policy.py +285 -0
  113. package/src/lifecycle/tests/__init__.py +4 -0
  114. package/src/lifecycle/tests/test_bounded_growth.py +193 -0
  115. package/src/lifecycle/tests/test_compaction.py +179 -0
  116. package/src/lifecycle/tests/test_lifecycle_engine.py +137 -0
  117. package/src/lifecycle/tests/test_lifecycle_evaluation.py +177 -0
  118. package/src/lifecycle/tests/test_lifecycle_scheduler.py +127 -0
  119. package/src/lifecycle/tests/test_lifecycle_search.py +109 -0
  120. package/src/lifecycle/tests/test_mcp_compact.py +149 -0
  121. package/src/lifecycle/tests/test_mcp_lifecycle_status.py +114 -0
  122. package/src/lifecycle/tests/test_retention_policy.py +162 -0
  123. package/src/mcp_tools_v28.py +280 -0
  124. package/src/memory-profiles.py +2 -12
  125. package/src/memory-reset.py +2 -12
  126. package/src/memory_compression.py +2 -12
  127. package/src/memory_store_v2.py +76 -20
  128. package/src/migrate_v1_to_v2.py +2 -12
  129. package/src/pattern_learner.py +29 -975
  130. package/src/patterns/__init__.py +24 -0
  131. package/src/patterns/analyzers.py +247 -0
  132. package/src/patterns/learner.py +267 -0
  133. package/src/patterns/scoring.py +167 -0
  134. package/src/patterns/store.py +223 -0
  135. package/src/patterns/terminology.py +138 -0
  136. package/src/provenance_tracker.py +4 -14
  137. package/src/query_optimizer.py +4 -6
  138. package/src/rate_limiter.py +2 -6
  139. package/src/search/__init__.py +20 -0
  140. package/src/search/cli.py +77 -0
  141. package/src/search/constants.py +26 -0
  142. package/src/search/engine.py +239 -0
  143. package/src/search/fusion.py +122 -0
  144. package/src/search/index_loader.py +112 -0
  145. package/src/search/methods.py +162 -0
  146. package/src/search_engine_v2.py +4 -6
  147. package/src/setup_validator.py +7 -13
  148. package/src/subscription_manager.py +2 -12
  149. package/src/tree/__init__.py +59 -0
  150. package/src/tree/builder.py +183 -0
  151. package/src/tree/nodes.py +196 -0
  152. package/src/tree/queries.py +252 -0
  153. package/src/tree/schema.py +76 -0
  154. package/src/tree_manager.py +10 -711
  155. package/src/trust/__init__.py +45 -0
  156. package/src/trust/constants.py +66 -0
  157. package/src/trust/queries.py +157 -0
  158. package/src/trust/schema.py +95 -0
  159. package/src/trust/scorer.py +299 -0
  160. package/src/trust/signals.py +95 -0
  161. package/src/trust_scorer.py +39 -697
  162. package/src/webhook_dispatcher.py +2 -12
  163. package/ui/app.js +1 -1
  164. package/ui/js/agents.js +1 -1
  165. package/ui_server.py +2 -14
  166. package/ATTRIBUTION.md +0 -140
  167. package/docs/ARCHITECTURE-V2.5.md +0 -190
  168. package/docs/GRAPH-ENGINE.md +0 -503
  169. package/docs/architecture-diagram.drawio +0 -405
  170. package/docs/plans/2026-02-13-benchmark-suite.md +0 -1349
@@ -0,0 +1,108 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Tests for behavioral engine EventBus integration.
4
+ """
5
+ import sqlite3
6
+ import tempfile
7
+ import os
8
+ import sys
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from unittest.mock import MagicMock, patch
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
14
+
15
+
16
+ class TestBehavioralIntegration:
17
+ """Test behavioral engine wiring with EventBus."""
18
+
19
+ def setup_method(self):
20
+ self.tmp_dir = tempfile.mkdtemp()
21
+ self.db_path = os.path.join(self.tmp_dir, "learning.db")
22
+
23
+ def teardown_method(self):
24
+ import shutil
25
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
26
+
27
+ def test_create_behavioral_listener(self):
28
+ """BehavioralListener can be instantiated."""
29
+ from behavioral.behavioral_listener import BehavioralListener
30
+ listener = BehavioralListener(self.db_path)
31
+ assert listener is not None
32
+
33
+ def test_listener_handles_recall_event(self):
34
+ """Listener processes memory.recalled events."""
35
+ from behavioral.behavioral_listener import BehavioralListener
36
+ listener = BehavioralListener(self.db_path)
37
+ event = {
38
+ "event_type": "memory.recalled",
39
+ "memory_id": 1,
40
+ "payload": {"query": "test query", "memory_ids": [1, 2]},
41
+ "timestamp": datetime.now().isoformat(),
42
+ }
43
+ # Should not raise
44
+ listener.handle_event(event)
45
+ assert listener.events_processed >= 1
46
+
47
+ def test_listener_ignores_irrelevant_events(self):
48
+ """Listener ignores non-recall events."""
49
+ from behavioral.behavioral_listener import BehavioralListener
50
+ listener = BehavioralListener(self.db_path)
51
+ event = {
52
+ "event_type": "memory.created",
53
+ "memory_id": 1,
54
+ "payload": {},
55
+ "timestamp": datetime.now().isoformat(),
56
+ }
57
+ listener.handle_event(event)
58
+ assert listener.recall_events_processed == 0
59
+
60
+ def test_listener_handles_deletion_event(self):
61
+ """Listener records deletion events for inference."""
62
+ from behavioral.behavioral_listener import BehavioralListener
63
+ listener = BehavioralListener(self.db_path)
64
+ event = {
65
+ "event_type": "memory.deleted",
66
+ "memory_id": 5,
67
+ "payload": {},
68
+ "timestamp": datetime.now().isoformat(),
69
+ }
70
+ listener.handle_event(event)
71
+ assert listener.deletion_events_processed >= 1
72
+
73
+ def test_listener_tracks_usage_signals(self):
74
+ """Listener records usage signals (memory_used) for inference."""
75
+ from behavioral.behavioral_listener import BehavioralListener
76
+ listener = BehavioralListener(self.db_path)
77
+ event = {
78
+ "event_type": "memory.recalled",
79
+ "memory_id": 1,
80
+ "payload": {"query": "test", "memory_ids": [1], "signal": "mcp_used_high"},
81
+ "timestamp": datetime.now().isoformat(),
82
+ }
83
+ listener.handle_event(event)
84
+ assert listener.events_processed >= 1
85
+
86
+ def test_graceful_degradation_no_eventbus(self):
87
+ """If EventBus unavailable, behavioral engine still works."""
88
+ from behavioral.behavioral_listener import BehavioralListener
89
+ listener = BehavioralListener(self.db_path)
90
+ # register_with_eventbus should not crash even if EventBus fails
91
+ result = listener.register_with_eventbus()
92
+ # Result depends on whether EventBus is importable in test env
93
+ assert isinstance(result, bool)
94
+
95
+ def test_pattern_extraction_threshold(self):
96
+ """Pattern extraction triggers after outcome count threshold."""
97
+ from behavioral.behavioral_listener import BehavioralListener
98
+ listener = BehavioralListener(self.db_path, extraction_threshold=5)
99
+ assert listener.extraction_threshold == 5
100
+
101
+ def test_get_status(self):
102
+ """Listener reports its status."""
103
+ from behavioral.behavioral_listener import BehavioralListener
104
+ listener = BehavioralListener(self.db_path)
105
+ status = listener.get_status()
106
+ assert "events_processed" in status
107
+ assert "recall_events_processed" in status
108
+ assert "registered" in status
@@ -0,0 +1,150 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Tests for behavioral pattern extraction from outcomes.
4
+ """
5
+ import sqlite3
6
+ import tempfile
7
+ import os
8
+ import sys
9
+ import json
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
13
+
14
+
15
+ class TestBehavioralPatterns:
16
+ """Test pattern extraction from action outcomes."""
17
+
18
+ def setup_method(self):
19
+ self.tmp_dir = tempfile.mkdtemp()
20
+ self.db_path = os.path.join(self.tmp_dir, "learning.db")
21
+ conn = sqlite3.connect(self.db_path)
22
+ # Create action_outcomes table (populated by OutcomeTracker)
23
+ conn.execute("""
24
+ CREATE TABLE IF NOT EXISTS action_outcomes (
25
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
26
+ memory_ids TEXT NOT NULL,
27
+ outcome TEXT NOT NULL,
28
+ action_type TEXT DEFAULT 'other',
29
+ context TEXT DEFAULT '{}',
30
+ confidence REAL DEFAULT 0.9,
31
+ agent_id TEXT DEFAULT 'user',
32
+ project TEXT,
33
+ profile TEXT DEFAULT 'default',
34
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
35
+ )
36
+ """)
37
+ # Create behavioral_patterns table
38
+ conn.execute("""
39
+ CREATE TABLE IF NOT EXISTS behavioral_patterns (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ pattern_type TEXT NOT NULL,
42
+ pattern_key TEXT NOT NULL,
43
+ success_rate REAL DEFAULT 0.0,
44
+ evidence_count INTEGER DEFAULT 0,
45
+ confidence REAL DEFAULT 0.0,
46
+ metadata TEXT DEFAULT '{}',
47
+ project TEXT,
48
+ profile TEXT DEFAULT 'default',
49
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
50
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
51
+ )
52
+ """)
53
+ # Insert sample outcomes for pattern extraction
54
+ # Project A: 8 success, 2 failure -> 80% success
55
+ for i in range(8):
56
+ conn.execute("INSERT INTO action_outcomes (memory_ids, outcome, project, action_type) VALUES (?, ?, ?, ?)",
57
+ (json.dumps([i+1]), "success", "project_a", "code_written"))
58
+ for i in range(2):
59
+ conn.execute("INSERT INTO action_outcomes (memory_ids, outcome, project, action_type) VALUES (?, ?, ?, ?)",
60
+ (json.dumps([i+20]), "failure", "project_a", "code_written"))
61
+ # Project B: 2 success, 8 failure -> 20% success
62
+ for i in range(2):
63
+ conn.execute("INSERT INTO action_outcomes (memory_ids, outcome, project, action_type) VALUES (?, ?, ?, ?)",
64
+ (json.dumps([i+30]), "success", "project_b", "debug_resolved"))
65
+ for i in range(8):
66
+ conn.execute("INSERT INTO action_outcomes (memory_ids, outcome, project, action_type) VALUES (?, ?, ?, ?)",
67
+ (json.dumps([i+40]), "failure", "project_b", "debug_resolved"))
68
+ conn.commit()
69
+ conn.close()
70
+
71
+ def teardown_method(self):
72
+ import shutil
73
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
74
+
75
+ def test_extract_patterns(self):
76
+ """extract_patterns returns list of discovered patterns."""
77
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
78
+ extractor = BehavioralPatternExtractor(self.db_path)
79
+ patterns = extractor.extract_patterns()
80
+ assert isinstance(patterns, list)
81
+ assert len(patterns) >= 2 # At least project_a and project_b patterns
82
+
83
+ def test_project_success_rate(self):
84
+ """Patterns should reflect actual success rates per project."""
85
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
86
+ extractor = BehavioralPatternExtractor(self.db_path)
87
+ patterns = extractor.extract_patterns()
88
+ proj_a = [p for p in patterns if p["pattern_key"] == "project_a" and p["pattern_type"] == "project_success"]
89
+ assert len(proj_a) == 1
90
+ assert abs(proj_a[0]["success_rate"] - 0.8) < 0.01
91
+
92
+ def test_success_pattern_high_rate(self):
93
+ """Projects with >70% success and 5+ evidence -> success pattern."""
94
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
95
+ extractor = BehavioralPatternExtractor(self.db_path)
96
+ patterns = extractor.extract_patterns()
97
+ proj_a = [p for p in patterns if p["pattern_key"] == "project_a" and p["pattern_type"] == "project_success"]
98
+ assert proj_a[0]["success_rate"] > 0.7
99
+ assert proj_a[0]["evidence_count"] >= 5
100
+
101
+ def test_failure_pattern_low_rate(self):
102
+ """Projects with <30% success and 5+ evidence -> failure pattern."""
103
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
104
+ extractor = BehavioralPatternExtractor(self.db_path)
105
+ patterns = extractor.extract_patterns()
106
+ proj_b = [p for p in patterns if p["pattern_key"] == "project_b" and p["pattern_type"] == "project_success"]
107
+ assert proj_b[0]["success_rate"] < 0.3
108
+
109
+ def test_action_type_patterns(self):
110
+ """Should extract patterns grouped by action_type."""
111
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
112
+ extractor = BehavioralPatternExtractor(self.db_path)
113
+ patterns = extractor.extract_patterns()
114
+ action_patterns = [p for p in patterns if p["pattern_type"] == "action_type_success"]
115
+ assert len(action_patterns) >= 1
116
+
117
+ def test_get_patterns_with_min_confidence(self):
118
+ """get_patterns filters by minimum confidence."""
119
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
120
+ extractor = BehavioralPatternExtractor(self.db_path)
121
+ extractor.extract_patterns()
122
+ # Store patterns to DB first
123
+ extractor.save_patterns()
124
+ high_conf = extractor.get_patterns(min_confidence=0.5)
125
+ all_patterns = extractor.get_patterns(min_confidence=0.0)
126
+ assert len(high_conf) <= len(all_patterns)
127
+
128
+ def test_pattern_confidence_scoring(self):
129
+ """Patterns with more evidence should have higher confidence."""
130
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
131
+ extractor = BehavioralPatternExtractor(self.db_path)
132
+ patterns = extractor.extract_patterns()
133
+ for p in patterns:
134
+ assert 0.0 <= p["confidence"] <= 1.0
135
+ # Confidence should increase with evidence
136
+ if p["evidence_count"] >= 10:
137
+ assert p["confidence"] >= 0.5
138
+
139
+ def test_save_patterns_to_db(self):
140
+ """save_patterns stores extracted patterns in behavioral_patterns table."""
141
+ from behavioral.behavioral_patterns import BehavioralPatternExtractor
142
+ extractor = BehavioralPatternExtractor(self.db_path)
143
+ extractor.extract_patterns()
144
+ count = extractor.save_patterns()
145
+ assert count >= 2
146
+ # Verify in DB
147
+ conn = sqlite3.connect(self.db_path)
148
+ rows = conn.execute("SELECT COUNT(*) FROM behavioral_patterns").fetchone()
149
+ conn.close()
150
+ assert rows[0] >= 2
@@ -0,0 +1,142 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Tests for privacy-safe cross-project behavioral transfer.
4
+ """
5
+ import sqlite3
6
+ import tempfile
7
+ import os
8
+ import sys
9
+ import json
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
13
+
14
+
15
+ class TestCrossProjectTransfer:
16
+ """Test cross-project behavioral pattern transfer."""
17
+
18
+ def setup_method(self):
19
+ self.tmp_dir = tempfile.mkdtemp()
20
+ self.db_path = os.path.join(self.tmp_dir, "learning.db")
21
+ conn = sqlite3.connect(self.db_path)
22
+ conn.execute("""
23
+ CREATE TABLE IF NOT EXISTS behavioral_patterns (
24
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
25
+ pattern_type TEXT NOT NULL,
26
+ pattern_key TEXT NOT NULL,
27
+ success_rate REAL DEFAULT 0.0,
28
+ evidence_count INTEGER DEFAULT 0,
29
+ confidence REAL DEFAULT 0.0,
30
+ metadata TEXT DEFAULT '{}',
31
+ project TEXT,
32
+ profile TEXT DEFAULT 'default',
33
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
34
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
35
+ )
36
+ """)
37
+ conn.execute("""
38
+ CREATE TABLE IF NOT EXISTS cross_project_behaviors (
39
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
40
+ source_project TEXT NOT NULL,
41
+ target_project TEXT NOT NULL,
42
+ pattern_id INTEGER NOT NULL,
43
+ transfer_type TEXT DEFAULT 'metadata',
44
+ confidence REAL DEFAULT 0.0,
45
+ profile TEXT DEFAULT 'default',
46
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
47
+ FOREIGN KEY (pattern_id) REFERENCES behavioral_patterns(id)
48
+ )
49
+ """)
50
+ # Insert patterns: high-confidence pattern in project_a
51
+ conn.execute(
52
+ "INSERT INTO behavioral_patterns (pattern_type, pattern_key, success_rate, evidence_count, confidence, project) VALUES (?, ?, ?, ?, ?, ?)",
53
+ ("action_type_success", "code_written", 0.85, 12, 0.9, "project_a"),
54
+ )
55
+ # Low-confidence pattern (should NOT transfer)
56
+ conn.execute(
57
+ "INSERT INTO behavioral_patterns (pattern_type, pattern_key, success_rate, evidence_count, confidence, project) VALUES (?, ?, ?, ?, ?, ?)",
58
+ ("action_type_success", "debug_resolved", 0.4, 3, 0.2, "project_a"),
59
+ )
60
+ # High-confidence pattern for project_b
61
+ conn.execute(
62
+ "INSERT INTO behavioral_patterns (pattern_type, pattern_key, success_rate, evidence_count, confidence, project) VALUES (?, ?, ?, ?, ?, ?)",
63
+ ("project_success", "project_b", 0.9, 15, 0.95, "project_b"),
64
+ )
65
+ conn.commit()
66
+ conn.close()
67
+
68
+ def teardown_method(self):
69
+ import shutil
70
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
71
+
72
+ def test_evaluate_transfers(self):
73
+ """evaluate_transfers returns eligible patterns."""
74
+ from behavioral.cross_project_transfer import CrossProjectTransfer
75
+ transfer = CrossProjectTransfer(self.db_path)
76
+ eligible = transfer.evaluate_transfers(target_project="project_c")
77
+ assert isinstance(eligible, list)
78
+ assert len(eligible) >= 1 # At least the high-confidence pattern
79
+
80
+ def test_only_high_confidence_transfers(self):
81
+ """Only patterns with confidence >= 0.7 and evidence >= 5 transfer."""
82
+ from behavioral.cross_project_transfer import CrossProjectTransfer
83
+ transfer = CrossProjectTransfer(self.db_path)
84
+ eligible = transfer.evaluate_transfers(target_project="project_c")
85
+ for e in eligible:
86
+ assert e["confidence"] >= 0.7
87
+ assert e["evidence_count"] >= 5
88
+
89
+ def test_low_confidence_excluded(self):
90
+ """Low confidence patterns (id=2, confidence=0.2) should NOT transfer."""
91
+ from behavioral.cross_project_transfer import CrossProjectTransfer
92
+ transfer = CrossProjectTransfer(self.db_path)
93
+ eligible = transfer.evaluate_transfers(target_project="project_c")
94
+ pattern_ids = {e["pattern_id"] for e in eligible}
95
+ assert 2 not in pattern_ids # Low confidence pattern excluded
96
+
97
+ def test_only_metadata_transfers(self):
98
+ """Transfers must be metadata-only — never content."""
99
+ from behavioral.cross_project_transfer import CrossProjectTransfer
100
+ transfer = CrossProjectTransfer(self.db_path)
101
+ eligible = transfer.evaluate_transfers(target_project="project_c")
102
+ for e in eligible:
103
+ assert e["transfer_type"] == "metadata"
104
+ assert "content" not in e # No content field
105
+ assert "content_hash" not in e # No content hashes
106
+
107
+ def test_apply_transfer(self):
108
+ """apply_transfer records the transfer in cross_project_behaviors."""
109
+ from behavioral.cross_project_transfer import CrossProjectTransfer
110
+ transfer = CrossProjectTransfer(self.db_path)
111
+ result = transfer.apply_transfer(pattern_id=1, target_project="project_c")
112
+ assert result["success"] is True
113
+ # Verify in DB
114
+ conn = sqlite3.connect(self.db_path)
115
+ row = conn.execute("SELECT * FROM cross_project_behaviors WHERE target_project='project_c'").fetchone()
116
+ conn.close()
117
+ assert row is not None
118
+
119
+ def test_transfer_logged(self):
120
+ """Transfers are logged with source and target projects."""
121
+ from behavioral.cross_project_transfer import CrossProjectTransfer
122
+ transfer = CrossProjectTransfer(self.db_path)
123
+ transfer.apply_transfer(pattern_id=1, target_project="project_c")
124
+ transfers = transfer.get_transfers(target_project="project_c")
125
+ assert len(transfers) == 1
126
+ assert transfers[0]["source_project"] == "project_a"
127
+
128
+ def test_no_self_transfer(self):
129
+ """Patterns should not transfer to their own project."""
130
+ from behavioral.cross_project_transfer import CrossProjectTransfer
131
+ transfer = CrossProjectTransfer(self.db_path)
132
+ eligible = transfer.evaluate_transfers(target_project="project_a")
133
+ # Pattern 1 is from project_a — should not be eligible for project_a
134
+ source_projects = {e.get("source_project") for e in eligible}
135
+ assert "project_a" not in source_projects
136
+
137
+ def test_disable_via_config(self):
138
+ """Transfers can be disabled via config."""
139
+ from behavioral.cross_project_transfer import CrossProjectTransfer
140
+ transfer = CrossProjectTransfer(self.db_path, enabled=False)
141
+ eligible = transfer.evaluate_transfers(target_project="project_c")
142
+ assert eligible == []
@@ -0,0 +1,139 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Tests for get_behavioral_patterns MCP tool handler.
4
+
5
+ Validates the MCP wrapper around BehavioralPatternExtractor — tests
6
+ pattern retrieval, confidence filtering, and project filtering.
7
+ """
8
+ import asyncio
9
+ import os
10
+ import shutil
11
+ import sqlite3
12
+ import sys
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ import pytest
17
+
18
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
19
+
20
+
21
+ def _create_learning_db_with_patterns(db_path: str) -> None:
22
+ """Create learning.db with pre-seeded behavioral patterns."""
23
+ conn = sqlite3.connect(db_path)
24
+ # The BehavioralPatternExtractor creates this table itself, but we need
25
+ # pre-seeded data for read-only tests. Create it manually.
26
+ conn.execute(
27
+ """CREATE TABLE IF NOT EXISTS behavioral_patterns (
28
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
29
+ pattern_type TEXT NOT NULL,
30
+ pattern_key TEXT NOT NULL,
31
+ success_rate REAL DEFAULT 0.0,
32
+ evidence_count INTEGER DEFAULT 0,
33
+ confidence REAL DEFAULT 0.0,
34
+ metadata TEXT DEFAULT '{}',
35
+ project TEXT,
36
+ profile TEXT DEFAULT 'default',
37
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
38
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
39
+ )"""
40
+ )
41
+ # Pattern 1: high confidence, project-scoped
42
+ conn.execute(
43
+ "INSERT INTO behavioral_patterns "
44
+ "(pattern_type, pattern_key, success_rate, evidence_count, confidence, project) "
45
+ "VALUES (?, ?, ?, ?, ?, ?)",
46
+ ("project_success", "slm-v28", 0.85, 12, 0.8, "slm-v28"),
47
+ )
48
+ # Pattern 2: low confidence, no project
49
+ conn.execute(
50
+ "INSERT INTO behavioral_patterns "
51
+ "(pattern_type, pattern_key, success_rate, evidence_count, confidence, project) "
52
+ "VALUES (?, ?, ?, ?, ?, ?)",
53
+ ("action_type_success", "code_written", 0.55, 4, 0.15, None),
54
+ )
55
+ conn.commit()
56
+ conn.close()
57
+
58
+
59
+ class TestMCPBehavioralPatterns:
60
+ """Tests for the get_behavioral_patterns tool handler."""
61
+
62
+ def setup_method(self):
63
+ self.tmp_dir = tempfile.mkdtemp()
64
+ self.db_path = os.path.join(self.tmp_dir, "learning.db")
65
+ _create_learning_db_with_patterns(self.db_path)
66
+
67
+ def teardown_method(self):
68
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
69
+
70
+ def _run(self, coro):
71
+ return asyncio.get_event_loop().run_until_complete(coro)
72
+
73
+ def test_get_all_patterns(self):
74
+ """Without filters, should return all patterns."""
75
+ import mcp_tools_v28 as tools
76
+ tools.DEFAULT_LEARNING_DB = self.db_path
77
+
78
+ result = self._run(tools.get_behavioral_patterns())
79
+ assert result["success"] is True
80
+ assert result["count"] == 2
81
+
82
+ def test_filter_by_high_confidence(self):
83
+ """Filtering with min_confidence=0.9 should return 0 (none that high)."""
84
+ import mcp_tools_v28 as tools
85
+ tools.DEFAULT_LEARNING_DB = self.db_path
86
+
87
+ result = self._run(tools.get_behavioral_patterns(min_confidence=0.9))
88
+ assert result["success"] is True
89
+ assert result["count"] == 0
90
+
91
+ def test_filter_by_medium_confidence(self):
92
+ """Filtering with min_confidence=0.5 should return only the high-confidence one."""
93
+ import mcp_tools_v28 as tools
94
+ tools.DEFAULT_LEARNING_DB = self.db_path
95
+
96
+ result = self._run(tools.get_behavioral_patterns(min_confidence=0.5))
97
+ assert result["success"] is True
98
+ assert result["count"] == 1
99
+ assert result["patterns"][0]["pattern_key"] == "slm-v28"
100
+
101
+ def test_filter_by_project(self):
102
+ """Filtering by project should scope results."""
103
+ import mcp_tools_v28 as tools
104
+ tools.DEFAULT_LEARNING_DB = self.db_path
105
+
106
+ result = self._run(tools.get_behavioral_patterns(project="slm-v28"))
107
+ assert result["success"] is True
108
+ assert result["count"] == 1
109
+
110
+ def test_filter_by_nonexistent_project(self):
111
+ """Filtering by a project with no patterns should return 0."""
112
+ import mcp_tools_v28 as tools
113
+ tools.DEFAULT_LEARNING_DB = self.db_path
114
+
115
+ result = self._run(tools.get_behavioral_patterns(project="nonexistent"))
116
+ assert result["success"] is True
117
+ assert result["count"] == 0
118
+
119
+ def test_patterns_have_required_keys(self):
120
+ """Each returned pattern should have standard keys."""
121
+ import mcp_tools_v28 as tools
122
+ tools.DEFAULT_LEARNING_DB = self.db_path
123
+
124
+ result = self._run(tools.get_behavioral_patterns())
125
+ for pattern in result["patterns"]:
126
+ assert "pattern_type" in pattern
127
+ assert "pattern_key" in pattern
128
+ assert "success_rate" in pattern
129
+ assert "confidence" in pattern
130
+
131
+ def test_empty_db_returns_zero(self):
132
+ """An empty learning DB should return count=0."""
133
+ import mcp_tools_v28 as tools
134
+ empty_path = os.path.join(self.tmp_dir, "empty_learning.db")
135
+ tools.DEFAULT_LEARNING_DB = empty_path
136
+
137
+ result = self._run(tools.get_behavioral_patterns())
138
+ assert result["success"] is True
139
+ assert result["count"] == 0
@@ -0,0 +1,117 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Tests for report_outcome MCP tool handler.
4
+
5
+ Validates the MCP wrapper around OutcomeTracker — tests success/failure/partial
6
+ outcomes, context handling, and invalid outcome rejection.
7
+ """
8
+ import asyncio
9
+ import os
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ import pytest
16
+
17
+ # Ensure src/ is importable
18
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
19
+
20
+
21
+ class TestMCPReportOutcome:
22
+ """Tests for the report_outcome tool handler."""
23
+
24
+ def setup_method(self):
25
+ self.tmp_dir = tempfile.mkdtemp()
26
+ self.db_path = os.path.join(self.tmp_dir, "learning.db")
27
+
28
+ def teardown_method(self):
29
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
30
+
31
+ def _run(self, coro):
32
+ """Helper to run async functions synchronously."""
33
+ return asyncio.get_event_loop().run_until_complete(coro)
34
+
35
+ def test_report_success_outcome(self):
36
+ """Reporting a 'success' outcome should return success=True and an outcome_id."""
37
+ import mcp_tools_v28 as tools
38
+ tools.DEFAULT_LEARNING_DB = self.db_path
39
+
40
+ result = self._run(tools.report_outcome([1, 2], "success"))
41
+ assert result["success"] is True
42
+ assert isinstance(result["outcome_id"], int)
43
+ assert result["outcome_id"] > 0
44
+ assert result["outcome"] == "success"
45
+ assert result["memory_ids"] == [1, 2]
46
+
47
+ def test_report_failure_outcome(self):
48
+ """Reporting a 'failure' outcome should succeed."""
49
+ import mcp_tools_v28 as tools
50
+ tools.DEFAULT_LEARNING_DB = self.db_path
51
+
52
+ result = self._run(tools.report_outcome([5], "failure"))
53
+ assert result["success"] is True
54
+ assert result["outcome"] == "failure"
55
+
56
+ def test_report_partial_outcome(self):
57
+ """Reporting a 'partial' outcome should succeed."""
58
+ import mcp_tools_v28 as tools
59
+ tools.DEFAULT_LEARNING_DB = self.db_path
60
+
61
+ result = self._run(tools.report_outcome([3], "partial"))
62
+ assert result["success"] is True
63
+ assert result["outcome"] == "partial"
64
+
65
+ def test_report_invalid_outcome(self):
66
+ """An invalid outcome label should return success=False."""
67
+ import mcp_tools_v28 as tools
68
+ tools.DEFAULT_LEARNING_DB = self.db_path
69
+
70
+ result = self._run(tools.report_outcome([1], "invalid"))
71
+ assert result["success"] is False
72
+ assert "Invalid outcome" in result["error"]
73
+
74
+ def test_report_with_context_json(self):
75
+ """Context passed as JSON string should be accepted."""
76
+ import mcp_tools_v28 as tools
77
+ tools.DEFAULT_LEARNING_DB = self.db_path
78
+
79
+ result = self._run(
80
+ tools.report_outcome(
81
+ [1], "partial", context='{"note": "worked partially"}'
82
+ )
83
+ )
84
+ assert result["success"] is True
85
+
86
+ def test_report_with_action_type(self):
87
+ """Custom action_type should be accepted."""
88
+ import mcp_tools_v28 as tools
89
+ tools.DEFAULT_LEARNING_DB = self.db_path
90
+
91
+ result = self._run(
92
+ tools.report_outcome(
93
+ [1, 2, 3], "success", action_type="code_written"
94
+ )
95
+ )
96
+ assert result["success"] is True
97
+
98
+ def test_report_with_agent_and_project(self):
99
+ """agent_id and project parameters should be forwarded."""
100
+ import mcp_tools_v28 as tools
101
+ tools.DEFAULT_LEARNING_DB = self.db_path
102
+
103
+ result = self._run(
104
+ tools.report_outcome(
105
+ [1], "success", agent_id="agent_a", project="slm-v28"
106
+ )
107
+ )
108
+ assert result["success"] is True
109
+
110
+ def test_multiple_outcomes_unique_ids(self):
111
+ """Consecutive outcomes should get distinct IDs."""
112
+ import mcp_tools_v28 as tools
113
+ tools.DEFAULT_LEARNING_DB = self.db_path
114
+
115
+ r1 = self._run(tools.report_outcome([1], "success"))
116
+ r2 = self._run(tools.report_outcome([2], "failure"))
117
+ assert r1["outcome_id"] != r2["outcome_id"]