superlocalmemory 2.7.5 → 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 (174) 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.ps1 +226 -0
  7. package/install.sh +59 -0
  8. package/mcp_server.py +83 -7
  9. package/package.json +3 -10
  10. package/scripts/generate-thumbnails.py +3 -5
  11. package/skills/slm-build-graph/SKILL.md +1 -1
  12. package/skills/slm-list-recent/SKILL.md +1 -1
  13. package/skills/slm-recall/SKILL.md +1 -1
  14. package/skills/slm-remember/SKILL.md +1 -1
  15. package/skills/slm-show-patterns/SKILL.md +1 -1
  16. package/skills/slm-status/SKILL.md +1 -1
  17. package/skills/slm-switch-profile/SKILL.md +1 -1
  18. package/src/agent_registry.py +7 -18
  19. package/src/auth_middleware.py +3 -5
  20. package/src/auto_backup.py +3 -7
  21. package/src/behavioral/__init__.py +49 -0
  22. package/src/behavioral/behavioral_listener.py +203 -0
  23. package/src/behavioral/behavioral_patterns.py +275 -0
  24. package/src/behavioral/cross_project_transfer.py +206 -0
  25. package/src/behavioral/outcome_inference.py +194 -0
  26. package/src/behavioral/outcome_tracker.py +193 -0
  27. package/src/behavioral/tests/__init__.py +4 -0
  28. package/src/behavioral/tests/test_behavioral_integration.py +108 -0
  29. package/src/behavioral/tests/test_behavioral_patterns.py +150 -0
  30. package/src/behavioral/tests/test_cross_project_transfer.py +142 -0
  31. package/src/behavioral/tests/test_mcp_behavioral.py +139 -0
  32. package/src/behavioral/tests/test_mcp_report_outcome.py +117 -0
  33. package/src/behavioral/tests/test_outcome_inference.py +107 -0
  34. package/src/behavioral/tests/test_outcome_tracker.py +96 -0
  35. package/src/cache_manager.py +4 -6
  36. package/src/compliance/__init__.py +48 -0
  37. package/src/compliance/abac_engine.py +149 -0
  38. package/src/compliance/abac_middleware.py +116 -0
  39. package/src/compliance/audit_db.py +215 -0
  40. package/src/compliance/audit_logger.py +148 -0
  41. package/src/compliance/retention_manager.py +289 -0
  42. package/src/compliance/retention_scheduler.py +186 -0
  43. package/src/compliance/tests/__init__.py +4 -0
  44. package/src/compliance/tests/test_abac_enforcement.py +95 -0
  45. package/src/compliance/tests/test_abac_engine.py +124 -0
  46. package/src/compliance/tests/test_abac_mcp_integration.py +118 -0
  47. package/src/compliance/tests/test_audit_db.py +123 -0
  48. package/src/compliance/tests/test_audit_logger.py +98 -0
  49. package/src/compliance/tests/test_mcp_audit.py +128 -0
  50. package/src/compliance/tests/test_mcp_retention_policy.py +125 -0
  51. package/src/compliance/tests/test_retention_manager.py +131 -0
  52. package/src/compliance/tests/test_retention_scheduler.py +99 -0
  53. package/src/db_connection_manager.py +2 -12
  54. package/src/embedding_engine.py +61 -669
  55. package/src/embeddings/__init__.py +47 -0
  56. package/src/embeddings/cache.py +70 -0
  57. package/src/embeddings/cli.py +113 -0
  58. package/src/embeddings/constants.py +47 -0
  59. package/src/embeddings/database.py +91 -0
  60. package/src/embeddings/engine.py +247 -0
  61. package/src/embeddings/model_loader.py +145 -0
  62. package/src/event_bus.py +3 -13
  63. package/src/graph/__init__.py +36 -0
  64. package/src/graph/build_helpers.py +74 -0
  65. package/src/graph/cli.py +87 -0
  66. package/src/graph/cluster_builder.py +188 -0
  67. package/src/graph/cluster_summary.py +148 -0
  68. package/src/graph/constants.py +47 -0
  69. package/src/graph/edge_builder.py +162 -0
  70. package/src/graph/entity_extractor.py +95 -0
  71. package/src/graph/graph_core.py +226 -0
  72. package/src/graph/graph_search.py +231 -0
  73. package/src/graph/hierarchical.py +207 -0
  74. package/src/graph/schema.py +99 -0
  75. package/src/graph_engine.py +45 -1451
  76. package/src/hnsw_index.py +3 -7
  77. package/src/hybrid_search.py +36 -683
  78. package/src/learning/__init__.py +27 -12
  79. package/src/learning/adaptive_ranker.py +50 -12
  80. package/src/learning/cross_project_aggregator.py +2 -12
  81. package/src/learning/engagement_tracker.py +2 -12
  82. package/src/learning/feature_extractor.py +175 -43
  83. package/src/learning/feedback_collector.py +7 -12
  84. package/src/learning/learning_db.py +180 -12
  85. package/src/learning/project_context_manager.py +2 -12
  86. package/src/learning/source_quality_scorer.py +2 -12
  87. package/src/learning/synthetic_bootstrap.py +2 -12
  88. package/src/learning/tests/__init__.py +2 -0
  89. package/src/learning/tests/test_adaptive_ranker.py +2 -6
  90. package/src/learning/tests/test_adaptive_ranker_v28.py +60 -0
  91. package/src/learning/tests/test_aggregator.py +2 -6
  92. package/src/learning/tests/test_auto_retrain_v28.py +35 -0
  93. package/src/learning/tests/test_e2e_ranking_v28.py +82 -0
  94. package/src/learning/tests/test_feature_extractor_v28.py +93 -0
  95. package/src/learning/tests/test_feedback_collector.py +2 -6
  96. package/src/learning/tests/test_learning_db.py +2 -6
  97. package/src/learning/tests/test_learning_db_v28.py +110 -0
  98. package/src/learning/tests/test_learning_init_v28.py +48 -0
  99. package/src/learning/tests/test_outcome_signals.py +48 -0
  100. package/src/learning/tests/test_project_context.py +2 -6
  101. package/src/learning/tests/test_schema_migration.py +319 -0
  102. package/src/learning/tests/test_signal_inference.py +11 -13
  103. package/src/learning/tests/test_source_quality.py +2 -6
  104. package/src/learning/tests/test_synthetic_bootstrap.py +3 -7
  105. package/src/learning/tests/test_workflow_miner.py +2 -6
  106. package/src/learning/workflow_pattern_miner.py +2 -12
  107. package/src/lifecycle/__init__.py +54 -0
  108. package/src/lifecycle/bounded_growth.py +239 -0
  109. package/src/lifecycle/compaction_engine.py +226 -0
  110. package/src/lifecycle/lifecycle_engine.py +302 -0
  111. package/src/lifecycle/lifecycle_evaluator.py +225 -0
  112. package/src/lifecycle/lifecycle_scheduler.py +130 -0
  113. package/src/lifecycle/retention_policy.py +285 -0
  114. package/src/lifecycle/tests/__init__.py +4 -0
  115. package/src/lifecycle/tests/test_bounded_growth.py +193 -0
  116. package/src/lifecycle/tests/test_compaction.py +179 -0
  117. package/src/lifecycle/tests/test_lifecycle_engine.py +137 -0
  118. package/src/lifecycle/tests/test_lifecycle_evaluation.py +177 -0
  119. package/src/lifecycle/tests/test_lifecycle_scheduler.py +127 -0
  120. package/src/lifecycle/tests/test_lifecycle_search.py +109 -0
  121. package/src/lifecycle/tests/test_mcp_compact.py +149 -0
  122. package/src/lifecycle/tests/test_mcp_lifecycle_status.py +114 -0
  123. package/src/lifecycle/tests/test_retention_policy.py +162 -0
  124. package/src/mcp_tools_v28.py +280 -0
  125. package/src/memory-profiles.py +2 -12
  126. package/src/memory-reset.py +2 -12
  127. package/src/memory_compression.py +2 -12
  128. package/src/memory_store_v2.py +76 -20
  129. package/src/migrate_v1_to_v2.py +2 -12
  130. package/src/pattern_learner.py +29 -975
  131. package/src/patterns/__init__.py +24 -0
  132. package/src/patterns/analyzers.py +247 -0
  133. package/src/patterns/learner.py +267 -0
  134. package/src/patterns/scoring.py +167 -0
  135. package/src/patterns/store.py +223 -0
  136. package/src/patterns/terminology.py +138 -0
  137. package/src/provenance_tracker.py +4 -14
  138. package/src/query_optimizer.py +4 -6
  139. package/src/rate_limiter.py +2 -6
  140. package/src/search/__init__.py +20 -0
  141. package/src/search/cli.py +77 -0
  142. package/src/search/constants.py +26 -0
  143. package/src/search/engine.py +239 -0
  144. package/src/search/fusion.py +122 -0
  145. package/src/search/index_loader.py +112 -0
  146. package/src/search/methods.py +162 -0
  147. package/src/search_engine_v2.py +4 -6
  148. package/src/setup_validator.py +7 -13
  149. package/src/subscription_manager.py +2 -12
  150. package/src/tree/__init__.py +59 -0
  151. package/src/tree/builder.py +183 -0
  152. package/src/tree/nodes.py +196 -0
  153. package/src/tree/queries.py +252 -0
  154. package/src/tree/schema.py +76 -0
  155. package/src/tree_manager.py +10 -711
  156. package/src/trust/__init__.py +45 -0
  157. package/src/trust/constants.py +66 -0
  158. package/src/trust/queries.py +157 -0
  159. package/src/trust/schema.py +95 -0
  160. package/src/trust/scorer.py +299 -0
  161. package/src/trust/signals.py +95 -0
  162. package/src/trust_scorer.py +39 -697
  163. package/src/webhook_dispatcher.py +2 -12
  164. package/ui/app.js +1 -1
  165. package/ui/index.html +3 -0
  166. package/ui/js/agents.js +1 -1
  167. package/ui/js/core.js +21 -5
  168. package/ui/js/profiles.js +29 -7
  169. package/ui_server.py +2 -14
  170. package/ATTRIBUTION.md +0 -140
  171. package/docs/ARCHITECTURE-V2.5.md +0 -190
  172. package/docs/GRAPH-ENGINE.md +0 -503
  173. package/docs/architecture-diagram.drawio +0 -405
  174. package/docs/plans/2026-02-13-benchmark-suite.md +0 -1349
@@ -0,0 +1,149 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Attribute-Based Access Control policy evaluation.
4
+
5
+ Evaluates access requests against JSON-defined policies using
6
+ subject, resource, and action attributes. Deny-first semantics
7
+ ensure any matching deny policy blocks access regardless of
8
+ allow policies. When no policies exist, all access is permitted
9
+ (backward compatible with v2.7 default-allow behavior).
10
+
11
+ Policy format:
12
+ {
13
+ "name": str, # Human-readable policy name
14
+ "effect": str, # "allow" or "deny"
15
+ "subjects": dict, # Attribute constraints on the requester
16
+ "resources": dict, # Attribute constraints on the resource
17
+ "actions": list[str] # Actions this policy applies to
18
+ }
19
+
20
+ Matching rules:
21
+ - "*" matches any value for that attribute
22
+ - Specific values require exact match
23
+ - All attributes in the policy must match for the policy to apply
24
+ """
25
+ import json
26
+ import logging
27
+ from pathlib import Path
28
+ from typing import Any, Dict, List, Optional
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class ABACEngine:
34
+ """Evaluates ABAC policies for memory access control.
35
+
36
+ Deny-first evaluation: if ANY deny policy matches the request,
37
+ access is denied. If no deny matches, access is allowed
38
+ (default-allow preserves v2.7 backward compatibility).
39
+ """
40
+
41
+ def __init__(self, config_path: Optional[str] = None) -> None:
42
+ self._config_path = config_path
43
+ self.policies: List[Dict[str, Any]] = []
44
+ if config_path:
45
+ self._load_policies(config_path)
46
+
47
+ def _load_policies(self, path: str) -> None:
48
+ """Load policies from a JSON file. Graceful on missing/invalid."""
49
+ try:
50
+ raw = Path(path).read_text(encoding="utf-8")
51
+ data = json.loads(raw)
52
+ if isinstance(data, list):
53
+ self.policies = data
54
+ logger.info("Loaded %d ABAC policies from %s", len(data), path)
55
+ else:
56
+ logger.warning("ABAC policy file is not a list: %s", path)
57
+ except FileNotFoundError:
58
+ logger.debug("No ABAC policy file at %s — default allow", path)
59
+ except (json.JSONDecodeError, OSError) as exc:
60
+ logger.warning("Failed to parse ABAC policies: %s", exc)
61
+
62
+ def evaluate(
63
+ self,
64
+ subject: Dict[str, Any],
65
+ resource: Dict[str, Any],
66
+ action: str,
67
+ ) -> Dict[str, Any]:
68
+ """Evaluate an access request against loaded policies.
69
+
70
+ Args:
71
+ subject: Attributes of the requester (e.g. agent_id).
72
+ resource: Attributes of the target resource.
73
+ action: The action being requested (read/write/delete).
74
+
75
+ Returns:
76
+ Dict with keys: allowed (bool), reason (str),
77
+ and policy_name (str) when a specific policy decided.
78
+ """
79
+ if not self.policies:
80
+ return {"allowed": True, "reason": "no_policies_loaded"}
81
+
82
+ # Phase 1: check all deny policies first
83
+ for policy in self.policies:
84
+ if policy.get("effect") != "deny":
85
+ continue
86
+ if self._matches(policy, subject, resource, action):
87
+ return {
88
+ "allowed": False,
89
+ "reason": "denied_by_policy",
90
+ "policy_name": policy.get("name", "unnamed"),
91
+ }
92
+
93
+ # Phase 2: check allow policies
94
+ for policy in self.policies:
95
+ if policy.get("effect") != "allow":
96
+ continue
97
+ if self._matches(policy, subject, resource, action):
98
+ return {
99
+ "allowed": True,
100
+ "reason": "allowed_by_policy",
101
+ "policy_name": policy.get("name", "unnamed"),
102
+ }
103
+
104
+ # Phase 3: no matching policy — default allow (backward compat)
105
+ return {"allowed": True, "reason": "no_matching_policy"}
106
+
107
+ # ------------------------------------------------------------------
108
+ # Internal matching helpers
109
+ # ------------------------------------------------------------------
110
+
111
+ def _matches(
112
+ self,
113
+ policy: Dict[str, Any],
114
+ subject: Dict[str, Any],
115
+ resource: Dict[str, Any],
116
+ action: str,
117
+ ) -> bool:
118
+ """Return True if policy matches the request."""
119
+ if not self._action_matches(policy.get("actions", []), action):
120
+ return False
121
+ if not self._attrs_match(policy.get("subjects", {}), subject):
122
+ return False
123
+ if not self._attrs_match(policy.get("resources", {}), resource):
124
+ return False
125
+ return True
126
+
127
+ @staticmethod
128
+ def _action_matches(policy_actions: List[str], action: str) -> bool:
129
+ """Check if the requested action is in the policy's action list."""
130
+ if "*" in policy_actions:
131
+ return True
132
+ return action in policy_actions
133
+
134
+ @staticmethod
135
+ def _attrs_match(
136
+ policy_attrs: Dict[str, Any],
137
+ request_attrs: Dict[str, Any],
138
+ ) -> bool:
139
+ """Check if all policy attribute constraints are satisfied.
140
+
141
+ Every key in policy_attrs must either be "*" (match anything)
142
+ or exactly equal the corresponding value in request_attrs.
143
+ """
144
+ for key, expected in policy_attrs.items():
145
+ if expected == "*":
146
+ continue
147
+ if request_attrs.get(key) != expected:
148
+ return False
149
+ return True
@@ -0,0 +1,116 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """ABAC middleware for MCP tool integration.
4
+
5
+ Provides a simple interface for MCP tools to check access before
6
+ executing memory operations. Delegates to ABACEngine for policy
7
+ evaluation.
8
+ """
9
+ import threading
10
+ from pathlib import Path
11
+ from typing import Any, Dict, Optional
12
+
13
+ from .abac_engine import ABACEngine
14
+
15
+
16
+ class ABACMiddleware:
17
+ """Thin middleware between MCP tools and ABAC policy engine.
18
+
19
+ Usage from MCP tools:
20
+ mw = ABACMiddleware(db_path)
21
+ result = mw.check_access(agent_id="agent_1", action="read",
22
+ resource={"access_level": "private"})
23
+ if not result["allowed"]:
24
+ return error_response(result["reason"])
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ db_path: Optional[str] = None,
30
+ policy_path: Optional[str] = None,
31
+ ) -> None:
32
+ if db_path is None:
33
+ db_path = str(Path.home() / ".claude-memory" / "memory.db")
34
+ self._db_path = str(db_path)
35
+
36
+ if policy_path is None:
37
+ policy_path = str(
38
+ Path(self._db_path).parent / "abac_policies.json"
39
+ )
40
+
41
+ self._lock = threading.Lock()
42
+ self.denied_count = 0
43
+ self.allowed_count = 0
44
+
45
+ try:
46
+ self._engine = ABACEngine(config_path=policy_path)
47
+ except Exception:
48
+ self._engine = None
49
+
50
+ def check_access(
51
+ self,
52
+ agent_id: str,
53
+ action: str,
54
+ resource: Optional[Dict[str, Any]] = None,
55
+ ) -> Dict[str, Any]:
56
+ """Check if an agent has access to perform an action.
57
+
58
+ Args:
59
+ agent_id: Identifier for the requesting agent.
60
+ action: The action being performed (read, write, delete).
61
+ resource: Resource attributes (access_level, project, tags).
62
+
63
+ Returns:
64
+ Dict with ``allowed`` (bool), ``reason`` (str), and
65
+ optionally ``policy_name``.
66
+ """
67
+ if self._engine is None:
68
+ return {
69
+ "allowed": True,
70
+ "reason": "ABAC engine unavailable — default allow",
71
+ }
72
+
73
+ subject = {"agent_id": agent_id}
74
+ result = self._engine.evaluate(
75
+ subject=subject,
76
+ resource=resource or {},
77
+ action=action,
78
+ )
79
+
80
+ with self._lock:
81
+ if result["allowed"]:
82
+ self.allowed_count += 1
83
+ else:
84
+ self.denied_count += 1
85
+
86
+ return result
87
+
88
+ def build_agent_context(
89
+ self,
90
+ agent_id: str = "user",
91
+ protocol: str = "mcp",
92
+ ) -> Dict[str, Any]:
93
+ """Build an agent context dict for passing to MemoryStoreV2.
94
+
95
+ Args:
96
+ agent_id: Agent identifier.
97
+ protocol: Access protocol (mcp, cli, dashboard).
98
+
99
+ Returns:
100
+ Dict suitable for ``MemoryStoreV2.search(agent_context=...)``.
101
+ """
102
+ return {
103
+ "agent_id": agent_id,
104
+ "protocol": protocol,
105
+ }
106
+
107
+ def get_status(self) -> Dict[str, Any]:
108
+ """Return middleware status."""
109
+ return {
110
+ "engine_available": self._engine is not None,
111
+ "policies_loaded": (
112
+ len(self._engine.policies) if self._engine else 0
113
+ ),
114
+ "allowed_count": self.allowed_count,
115
+ "denied_count": self.denied_count,
116
+ }
@@ -0,0 +1,215 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """Audit database management with hash chain tamper detection.
4
+
5
+ Provides a tamper-evident audit trail stored in a separate audit.db.
6
+ Each entry's hash incorporates the previous entry's hash, forming a
7
+ chain that can detect any modification to historical records.
8
+ """
9
+ import hashlib
10
+ import json
11
+ import sqlite3
12
+ import threading
13
+ from datetime import datetime, timezone
14
+ from typing import Any, Dict, List, Optional
15
+
16
+
17
+ _GENESIS = "genesis"
18
+
19
+ _SCHEMA = """
20
+ CREATE TABLE IF NOT EXISTS audit_events (
21
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ event_type TEXT NOT NULL,
23
+ actor TEXT NOT NULL,
24
+ resource_id INTEGER,
25
+ details TEXT DEFAULT '{}',
26
+ prev_hash TEXT NOT NULL,
27
+ entry_hash TEXT NOT NULL,
28
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
29
+ )
30
+ """
31
+
32
+
33
+ def _compute_hash(
34
+ event_type: str,
35
+ actor: str,
36
+ resource_id: Optional[int],
37
+ details: str,
38
+ prev_hash: str,
39
+ created_at: str,
40
+ ) -> str:
41
+ """Compute SHA-256 hash for an audit entry."""
42
+ payload = (
43
+ f"{event_type}{actor}{resource_id}{details}{prev_hash}{created_at}"
44
+ )
45
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
46
+
47
+
48
+ class AuditDB:
49
+ """Manages audit.db -- tamper-evident compliance audit trail.
50
+
51
+ The hash chain guarantees that any modification to a stored event
52
+ will be detected by verify_chain(). The first entry uses a fixed
53
+ genesis value as its previous hash.
54
+ """
55
+
56
+ def __init__(self, db_path: Optional[str] = None):
57
+ self._db_path = db_path
58
+ self._lock = threading.Lock()
59
+ if db_path:
60
+ self._init_db()
61
+
62
+ # ------------------------------------------------------------------
63
+ # Internal helpers
64
+ # ------------------------------------------------------------------
65
+
66
+ def _get_conn(self) -> sqlite3.Connection:
67
+ conn = sqlite3.connect(self._db_path)
68
+ conn.execute("PRAGMA journal_mode=WAL")
69
+ conn.execute("PRAGMA foreign_keys=ON")
70
+ conn.row_factory = sqlite3.Row
71
+ return conn
72
+
73
+ def _init_db(self) -> None:
74
+ conn = self._get_conn()
75
+ try:
76
+ conn.executescript(_SCHEMA)
77
+ conn.commit()
78
+ finally:
79
+ conn.close()
80
+
81
+ # ------------------------------------------------------------------
82
+ # Public API
83
+ # ------------------------------------------------------------------
84
+
85
+ def log_event(
86
+ self,
87
+ event_type: str,
88
+ actor: str = "system",
89
+ resource_id: Optional[int] = None,
90
+ details: Optional[Dict[str, Any]] = None,
91
+ ) -> int:
92
+ """Append an event to the audit trail and return its row id."""
93
+ details_str = json.dumps(details or {}, sort_keys=True)
94
+ created_at = datetime.now(timezone.utc).isoformat()
95
+
96
+ with self._lock:
97
+ conn = self._get_conn()
98
+ try:
99
+ # Fetch the hash of the most recent entry (or genesis)
100
+ row = conn.execute(
101
+ "SELECT entry_hash FROM audit_events "
102
+ "ORDER BY id DESC LIMIT 1"
103
+ ).fetchone()
104
+ prev_hash = row["entry_hash"] if row else _GENESIS
105
+
106
+ entry_hash = _compute_hash(
107
+ event_type, actor, resource_id,
108
+ details_str, prev_hash, created_at,
109
+ )
110
+
111
+ cursor = conn.execute(
112
+ "INSERT INTO audit_events "
113
+ "(event_type, actor, resource_id, details, "
114
+ " prev_hash, entry_hash, created_at) "
115
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
116
+ (
117
+ event_type, actor, resource_id,
118
+ details_str, prev_hash, entry_hash, created_at,
119
+ ),
120
+ )
121
+ conn.commit()
122
+ return cursor.lastrowid
123
+ finally:
124
+ conn.close()
125
+
126
+ def query_events(
127
+ self,
128
+ event_type: Optional[str] = None,
129
+ actor: Optional[str] = None,
130
+ resource_id: Optional[int] = None,
131
+ limit: int = 100,
132
+ ) -> List[Dict[str, Any]]:
133
+ """Query audit events with optional filters."""
134
+ clauses: List[str] = []
135
+ params: List[Any] = []
136
+
137
+ if event_type is not None:
138
+ clauses.append("event_type = ?")
139
+ params.append(event_type)
140
+ if actor is not None:
141
+ clauses.append("actor = ?")
142
+ params.append(actor)
143
+ if resource_id is not None:
144
+ clauses.append("resource_id = ?")
145
+ params.append(resource_id)
146
+
147
+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
148
+ sql = (
149
+ f"SELECT id, event_type, actor, resource_id, details, "
150
+ f"prev_hash, entry_hash, created_at "
151
+ f"FROM audit_events {where} "
152
+ f"ORDER BY id DESC LIMIT ?"
153
+ )
154
+ params.append(limit)
155
+
156
+ conn = self._get_conn()
157
+ try:
158
+ rows = conn.execute(sql, params).fetchall()
159
+ return [dict(r) for r in rows]
160
+ finally:
161
+ conn.close()
162
+
163
+ def verify_chain(self) -> Dict[str, Any]:
164
+ """Verify the integrity of the entire hash chain.
165
+
166
+ Returns a dict with:
167
+ valid -- bool, True if chain is intact
168
+ entries_checked -- int, number of entries verified
169
+ error -- str or None, description of first failure
170
+ """
171
+ conn = self._get_conn()
172
+ try:
173
+ rows = conn.execute(
174
+ "SELECT id, event_type, actor, resource_id, details, "
175
+ "prev_hash, entry_hash, created_at "
176
+ "FROM audit_events ORDER BY id"
177
+ ).fetchall()
178
+ finally:
179
+ conn.close()
180
+
181
+ if not rows:
182
+ return {"valid": True, "entries_checked": 0, "error": None}
183
+
184
+ expected_prev = _GENESIS
185
+ for row in rows:
186
+ row = dict(row)
187
+ # Check the prev_hash link
188
+ if row["prev_hash"] != expected_prev:
189
+ return {
190
+ "valid": False,
191
+ "entries_checked": row["id"],
192
+ "error": f"prev_hash mismatch at entry {row['id']}",
193
+ }
194
+ # Recompute the entry hash
195
+ computed = _compute_hash(
196
+ row["event_type"],
197
+ row["actor"],
198
+ row["resource_id"],
199
+ row["details"],
200
+ row["prev_hash"],
201
+ row["created_at"],
202
+ )
203
+ if computed != row["entry_hash"]:
204
+ return {
205
+ "valid": False,
206
+ "entries_checked": row["id"],
207
+ "error": f"entry_hash mismatch at entry {row['id']}",
208
+ }
209
+ expected_prev = row["entry_hash"]
210
+
211
+ return {
212
+ "valid": True,
213
+ "entries_checked": len(rows),
214
+ "error": None,
215
+ }
@@ -0,0 +1,148 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
3
+ """EventBus listener that writes all events to audit.db.
4
+
5
+ Bridges the EventBus (real-time event emission) with AuditDB (tamper-evident
6
+ audit trail). Every event that passes through the EventBus gets persisted
7
+ into audit.db with full hash-chain integrity.
8
+
9
+ Thread-safe: handle_event() runs on the emitter's thread and must be fast.
10
+ Graceful: malformed events are logged defensively, never crash the caller.
11
+ """
12
+ import json
13
+ import logging
14
+ import threading
15
+ from typing import Any, Dict, Optional
16
+
17
+ from .audit_db import AuditDB
18
+
19
+ logger = logging.getLogger("superlocalmemory.compliance.audit_logger")
20
+
21
+
22
+ class AuditLogger:
23
+ """Listens to EventBus events and writes them to audit.db.
24
+
25
+ Usage:
26
+ audit_logger = AuditLogger("/path/to/audit.db")
27
+ audit_logger.register_with_eventbus() # auto-subscribe
28
+
29
+ Or manually:
30
+ event_bus.add_listener(audit_logger.handle_event)
31
+ """
32
+
33
+ def __init__(self, audit_db_path: str):
34
+ self._audit_db = AuditDB(audit_db_path)
35
+ self._lock = threading.Lock()
36
+ self._events_logged: int = 0
37
+ self._errors: int = 0
38
+ self._registered: bool = False
39
+
40
+ # ------------------------------------------------------------------
41
+ # Public API
42
+ # ------------------------------------------------------------------
43
+
44
+ @property
45
+ def events_logged(self) -> int:
46
+ """Total number of events successfully written to audit.db."""
47
+ return self._events_logged
48
+
49
+ def handle_event(self, event: Dict[str, Any]) -> None:
50
+ """Process a single EventBus event and write it to audit.db.
51
+
52
+ Extracts event_type, source_agent (actor), memory_id (resource_id),
53
+ and payload (details) from the event dict, then delegates to
54
+ AuditDB.log_event().
55
+
56
+ This method MUST NOT raise — it runs on the emitter's thread.
57
+ Any failure is caught, logged, and counted in self._errors.
58
+
59
+ Args:
60
+ event: Dict emitted by EventBus. Expected keys:
61
+ event_type, source_agent, memory_id, payload, timestamp.
62
+ All keys are optional for graceful degradation.
63
+ """
64
+ try:
65
+ if not isinstance(event, dict):
66
+ logger.warning("AuditLogger received non-dict event: %s", type(event))
67
+ return
68
+
69
+ event_type = event.get("event_type", "unknown")
70
+ actor = event.get("source_agent", "system")
71
+ resource_id = event.get("memory_id")
72
+ payload = event.get("payload", {})
73
+
74
+ # Build details dict including any extra context
75
+ details = {}
76
+ if isinstance(payload, dict):
77
+ details.update(payload)
78
+ else:
79
+ details["raw_payload"] = str(payload)
80
+
81
+ # Include timestamp from event if present
82
+ ts = event.get("timestamp")
83
+ if ts:
84
+ details["event_timestamp"] = ts
85
+
86
+ with self._lock:
87
+ self._audit_db.log_event(
88
+ event_type=event_type,
89
+ actor=actor,
90
+ resource_id=resource_id,
91
+ details=details,
92
+ )
93
+ self._events_logged += 1
94
+
95
+ except Exception as exc:
96
+ self._errors += 1
97
+ logger.error(
98
+ "AuditLogger failed to log event: %s (event=%s)",
99
+ exc,
100
+ _safe_repr(event),
101
+ )
102
+
103
+ def register_with_eventbus(self) -> bool:
104
+ """Register this logger as an EventBus listener.
105
+
106
+ Attempts to find the EventBus singleton and subscribe
107
+ handle_event as a listener. Returns True on success,
108
+ False if EventBus is unavailable.
109
+
110
+ Graceful: never raises; returns False on any failure.
111
+ """
112
+ try:
113
+ from event_bus import EventBus as EB
114
+
115
+ bus = EB.get_instance()
116
+ bus.add_listener(self.handle_event)
117
+ self._registered = True
118
+ logger.info("AuditLogger registered with EventBus")
119
+ return True
120
+ except Exception as exc:
121
+ logger.warning("AuditLogger could not register with EventBus: %s", exc)
122
+ self._registered = False
123
+ return False
124
+
125
+ def get_status(self) -> Dict[str, Any]:
126
+ """Return diagnostic status of this audit logger.
127
+
128
+ Returns:
129
+ Dict with keys: events_logged, errors, registered.
130
+ """
131
+ return {
132
+ "events_logged": self._events_logged,
133
+ "errors": self._errors,
134
+ "registered": self._registered,
135
+ }
136
+
137
+
138
+ # ------------------------------------------------------------------
139
+ # Internal helpers
140
+ # ------------------------------------------------------------------
141
+
142
+ def _safe_repr(obj: Any, max_len: int = 200) -> str:
143
+ """Safe repr that truncates and never raises."""
144
+ try:
145
+ r = repr(obj)
146
+ return r[:max_len] + "..." if len(r) > max_len else r
147
+ except Exception:
148
+ return "<unrepresentable>"