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.
- package/CHANGELOG.md +120 -155
- package/README.md +115 -89
- package/api_server.py +2 -12
- package/docs/PATTERN-LEARNING.md +64 -199
- package/docs/example_graph_usage.py +4 -6
- package/install.sh +59 -0
- package/mcp_server.py +83 -7
- package/package.json +1 -8
- package/scripts/generate-thumbnails.py +3 -5
- package/skills/slm-build-graph/SKILL.md +1 -1
- package/skills/slm-list-recent/SKILL.md +1 -1
- package/skills/slm-recall/SKILL.md +1 -1
- package/skills/slm-remember/SKILL.md +1 -1
- package/skills/slm-show-patterns/SKILL.md +1 -1
- package/skills/slm-status/SKILL.md +1 -1
- package/skills/slm-switch-profile/SKILL.md +1 -1
- package/src/agent_registry.py +7 -18
- package/src/auth_middleware.py +3 -5
- package/src/auto_backup.py +3 -7
- package/src/behavioral/__init__.py +49 -0
- package/src/behavioral/behavioral_listener.py +203 -0
- package/src/behavioral/behavioral_patterns.py +275 -0
- package/src/behavioral/cross_project_transfer.py +206 -0
- package/src/behavioral/outcome_inference.py +194 -0
- package/src/behavioral/outcome_tracker.py +193 -0
- package/src/behavioral/tests/__init__.py +4 -0
- package/src/behavioral/tests/test_behavioral_integration.py +108 -0
- package/src/behavioral/tests/test_behavioral_patterns.py +150 -0
- package/src/behavioral/tests/test_cross_project_transfer.py +142 -0
- package/src/behavioral/tests/test_mcp_behavioral.py +139 -0
- package/src/behavioral/tests/test_mcp_report_outcome.py +117 -0
- package/src/behavioral/tests/test_outcome_inference.py +107 -0
- package/src/behavioral/tests/test_outcome_tracker.py +96 -0
- package/src/cache_manager.py +4 -6
- package/src/compliance/__init__.py +48 -0
- package/src/compliance/abac_engine.py +149 -0
- package/src/compliance/abac_middleware.py +116 -0
- package/src/compliance/audit_db.py +215 -0
- package/src/compliance/audit_logger.py +148 -0
- package/src/compliance/retention_manager.py +289 -0
- package/src/compliance/retention_scheduler.py +186 -0
- package/src/compliance/tests/__init__.py +4 -0
- package/src/compliance/tests/test_abac_enforcement.py +95 -0
- package/src/compliance/tests/test_abac_engine.py +124 -0
- package/src/compliance/tests/test_abac_mcp_integration.py +118 -0
- package/src/compliance/tests/test_audit_db.py +123 -0
- package/src/compliance/tests/test_audit_logger.py +98 -0
- package/src/compliance/tests/test_mcp_audit.py +128 -0
- package/src/compliance/tests/test_mcp_retention_policy.py +125 -0
- package/src/compliance/tests/test_retention_manager.py +131 -0
- package/src/compliance/tests/test_retention_scheduler.py +99 -0
- package/src/db_connection_manager.py +2 -12
- package/src/embedding_engine.py +61 -669
- package/src/embeddings/__init__.py +47 -0
- package/src/embeddings/cache.py +70 -0
- package/src/embeddings/cli.py +113 -0
- package/src/embeddings/constants.py +47 -0
- package/src/embeddings/database.py +91 -0
- package/src/embeddings/engine.py +247 -0
- package/src/embeddings/model_loader.py +145 -0
- package/src/event_bus.py +3 -13
- package/src/graph/__init__.py +36 -0
- package/src/graph/build_helpers.py +74 -0
- package/src/graph/cli.py +87 -0
- package/src/graph/cluster_builder.py +188 -0
- package/src/graph/cluster_summary.py +148 -0
- package/src/graph/constants.py +47 -0
- package/src/graph/edge_builder.py +162 -0
- package/src/graph/entity_extractor.py +95 -0
- package/src/graph/graph_core.py +226 -0
- package/src/graph/graph_search.py +231 -0
- package/src/graph/hierarchical.py +207 -0
- package/src/graph/schema.py +99 -0
- package/src/graph_engine.py +45 -1451
- package/src/hnsw_index.py +3 -7
- package/src/hybrid_search.py +36 -683
- package/src/learning/__init__.py +27 -12
- package/src/learning/adaptive_ranker.py +50 -12
- package/src/learning/cross_project_aggregator.py +2 -12
- package/src/learning/engagement_tracker.py +2 -12
- package/src/learning/feature_extractor.py +175 -43
- package/src/learning/feedback_collector.py +7 -12
- package/src/learning/learning_db.py +180 -12
- package/src/learning/project_context_manager.py +2 -12
- package/src/learning/source_quality_scorer.py +2 -12
- package/src/learning/synthetic_bootstrap.py +2 -12
- package/src/learning/tests/__init__.py +2 -0
- package/src/learning/tests/test_adaptive_ranker.py +2 -6
- package/src/learning/tests/test_adaptive_ranker_v28.py +60 -0
- package/src/learning/tests/test_aggregator.py +2 -6
- package/src/learning/tests/test_auto_retrain_v28.py +35 -0
- package/src/learning/tests/test_e2e_ranking_v28.py +82 -0
- package/src/learning/tests/test_feature_extractor_v28.py +93 -0
- package/src/learning/tests/test_feedback_collector.py +2 -6
- package/src/learning/tests/test_learning_db.py +2 -6
- package/src/learning/tests/test_learning_db_v28.py +110 -0
- package/src/learning/tests/test_learning_init_v28.py +48 -0
- package/src/learning/tests/test_outcome_signals.py +48 -0
- package/src/learning/tests/test_project_context.py +2 -6
- package/src/learning/tests/test_schema_migration.py +319 -0
- package/src/learning/tests/test_signal_inference.py +11 -13
- package/src/learning/tests/test_source_quality.py +2 -6
- package/src/learning/tests/test_synthetic_bootstrap.py +3 -7
- package/src/learning/tests/test_workflow_miner.py +2 -6
- package/src/learning/workflow_pattern_miner.py +2 -12
- package/src/lifecycle/__init__.py +54 -0
- package/src/lifecycle/bounded_growth.py +239 -0
- package/src/lifecycle/compaction_engine.py +226 -0
- package/src/lifecycle/lifecycle_engine.py +302 -0
- package/src/lifecycle/lifecycle_evaluator.py +225 -0
- package/src/lifecycle/lifecycle_scheduler.py +130 -0
- package/src/lifecycle/retention_policy.py +285 -0
- package/src/lifecycle/tests/__init__.py +4 -0
- package/src/lifecycle/tests/test_bounded_growth.py +193 -0
- package/src/lifecycle/tests/test_compaction.py +179 -0
- package/src/lifecycle/tests/test_lifecycle_engine.py +137 -0
- package/src/lifecycle/tests/test_lifecycle_evaluation.py +177 -0
- package/src/lifecycle/tests/test_lifecycle_scheduler.py +127 -0
- package/src/lifecycle/tests/test_lifecycle_search.py +109 -0
- package/src/lifecycle/tests/test_mcp_compact.py +149 -0
- package/src/lifecycle/tests/test_mcp_lifecycle_status.py +114 -0
- package/src/lifecycle/tests/test_retention_policy.py +162 -0
- package/src/mcp_tools_v28.py +280 -0
- package/src/memory-profiles.py +2 -12
- package/src/memory-reset.py +2 -12
- package/src/memory_compression.py +2 -12
- package/src/memory_store_v2.py +76 -20
- package/src/migrate_v1_to_v2.py +2 -12
- package/src/pattern_learner.py +29 -975
- package/src/patterns/__init__.py +24 -0
- package/src/patterns/analyzers.py +247 -0
- package/src/patterns/learner.py +267 -0
- package/src/patterns/scoring.py +167 -0
- package/src/patterns/store.py +223 -0
- package/src/patterns/terminology.py +138 -0
- package/src/provenance_tracker.py +4 -14
- package/src/query_optimizer.py +4 -6
- package/src/rate_limiter.py +2 -6
- package/src/search/__init__.py +20 -0
- package/src/search/cli.py +77 -0
- package/src/search/constants.py +26 -0
- package/src/search/engine.py +239 -0
- package/src/search/fusion.py +122 -0
- package/src/search/index_loader.py +112 -0
- package/src/search/methods.py +162 -0
- package/src/search_engine_v2.py +4 -6
- package/src/setup_validator.py +7 -13
- package/src/subscription_manager.py +2 -12
- package/src/tree/__init__.py +59 -0
- package/src/tree/builder.py +183 -0
- package/src/tree/nodes.py +196 -0
- package/src/tree/queries.py +252 -0
- package/src/tree/schema.py +76 -0
- package/src/tree_manager.py +10 -711
- package/src/trust/__init__.py +45 -0
- package/src/trust/constants.py +66 -0
- package/src/trust/queries.py +157 -0
- package/src/trust/schema.py +95 -0
- package/src/trust/scorer.py +299 -0
- package/src/trust/signals.py +95 -0
- package/src/trust_scorer.py +39 -697
- package/src/webhook_dispatcher.py +2 -12
- package/ui/app.js +1 -1
- package/ui/js/agents.js +1 -1
- package/ui_server.py +2 -14
- package/ATTRIBUTION.md +0 -140
- package/docs/ARCHITECTURE-V2.5.md +0 -190
- package/docs/GRAPH-ENGINE.md +0 -503
- package/docs/architecture-diagram.drawio +0 -405
- package/docs/plans/2026-02-13-benchmark-suite.md +0 -1349
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
|
|
4
|
+
"""
|
|
5
|
+
Trust scoring package -- Bayesian Beta-Binomial trust for AI agents.
|
|
6
|
+
|
|
7
|
+
Re-exports all public symbols for backward compatibility.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .constants import (
|
|
11
|
+
SIGNAL_WEIGHTS,
|
|
12
|
+
SIGNAL_DELTAS,
|
|
13
|
+
INITIAL_ALPHA,
|
|
14
|
+
INITIAL_BETA,
|
|
15
|
+
DECAY_FACTOR,
|
|
16
|
+
DECAY_INTERVAL,
|
|
17
|
+
ALPHA_FLOOR,
|
|
18
|
+
BETA_FLOOR,
|
|
19
|
+
QUICK_DELETE_HOURS,
|
|
20
|
+
BURST_THRESHOLD,
|
|
21
|
+
BURST_WINDOW_MINUTES,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from .schema import init_trust_schema
|
|
25
|
+
|
|
26
|
+
from .scorer import TrustScorer
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
# Class
|
|
30
|
+
"TrustScorer",
|
|
31
|
+
# Constants
|
|
32
|
+
"SIGNAL_WEIGHTS",
|
|
33
|
+
"SIGNAL_DELTAS",
|
|
34
|
+
"INITIAL_ALPHA",
|
|
35
|
+
"INITIAL_BETA",
|
|
36
|
+
"DECAY_FACTOR",
|
|
37
|
+
"DECAY_INTERVAL",
|
|
38
|
+
"ALPHA_FLOOR",
|
|
39
|
+
"BETA_FLOOR",
|
|
40
|
+
"QUICK_DELETE_HOURS",
|
|
41
|
+
"BURST_THRESHOLD",
|
|
42
|
+
"BURST_WINDOW_MINUTES",
|
|
43
|
+
# Schema
|
|
44
|
+
"init_trust_schema",
|
|
45
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
|
|
4
|
+
"""
|
|
5
|
+
Beta-Binomial signal weights and trust scoring constants.
|
|
6
|
+
|
|
7
|
+
Extracted from trust_scorer.py for modularity.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
# ---------------------------------------------------------------------------
|
|
11
|
+
# Beta-Binomial signal weights
|
|
12
|
+
# ---------------------------------------------------------------------------
|
|
13
|
+
# Positive signals increment alpha (building trust).
|
|
14
|
+
# Negative signals increment beta (eroding trust).
|
|
15
|
+
# Neutral signals give a tiny alpha nudge to reward normal activity.
|
|
16
|
+
#
|
|
17
|
+
# Asymmetry: negative weights are larger than positive weights.
|
|
18
|
+
# This means it's harder to build trust than to lose it -- the system
|
|
19
|
+
# is intentionally skeptical. One poisoning event takes many good
|
|
20
|
+
# actions to recover from.
|
|
21
|
+
# ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
SIGNAL_WEIGHTS = {
|
|
24
|
+
# Positive signals -> alpha += weight
|
|
25
|
+
"memory_recalled_by_others": ("positive", 0.30), # cross-agent validation
|
|
26
|
+
"memory_updated": ("positive", 0.15), # ongoing relevance
|
|
27
|
+
"high_importance_write": ("positive", 0.20), # valuable content (importance >= 7)
|
|
28
|
+
"consistent_pattern": ("positive", 0.15), # stable write behavior
|
|
29
|
+
|
|
30
|
+
# Negative signals -> beta += weight
|
|
31
|
+
"quick_delete": ("negative", 0.50), # deleted within 1 hour
|
|
32
|
+
"high_volume_burst": ("negative", 0.40), # >20 writes in 5 minutes
|
|
33
|
+
"content_overwritten_by_user": ("negative", 0.25), # user had to fix output
|
|
34
|
+
|
|
35
|
+
# Neutral signals -> tiny alpha nudge
|
|
36
|
+
"normal_write": ("neutral", 0.01),
|
|
37
|
+
"normal_recall": ("neutral", 0.01),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
# Backward-compatible: expose SIGNAL_DELTAS as a derived dict so that
|
|
41
|
+
# bm6_trust.py (which imports SIGNAL_DELTAS) and any other consumer
|
|
42
|
+
# continues to work. The values represent the *direction* and *magnitude*
|
|
43
|
+
# of each signal: positive for alpha, negative for beta, zero for neutral.
|
|
44
|
+
SIGNAL_DELTAS = {}
|
|
45
|
+
for _sig, (_direction, _weight) in SIGNAL_WEIGHTS.items():
|
|
46
|
+
if _direction == "positive":
|
|
47
|
+
SIGNAL_DELTAS[_sig] = +_weight
|
|
48
|
+
elif _direction == "negative":
|
|
49
|
+
SIGNAL_DELTAS[_sig] = -_weight
|
|
50
|
+
else:
|
|
51
|
+
SIGNAL_DELTAS[_sig] = 0.0
|
|
52
|
+
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
# Beta prior and decay parameters
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
INITIAL_ALPHA = 2.0 # Slight positive prior
|
|
57
|
+
INITIAL_BETA = 1.0 # -> initial trust = 2/(2+1) = 0.667
|
|
58
|
+
DECAY_FACTOR = 0.995 # Multiply alpha & beta every DECAY_INTERVAL signals
|
|
59
|
+
DECAY_INTERVAL = 50 # Apply decay every N signals per agent
|
|
60
|
+
ALPHA_FLOOR = 1.0 # Never decay alpha below this
|
|
61
|
+
BETA_FLOOR = 0.5 # Never decay beta below this
|
|
62
|
+
|
|
63
|
+
# Thresholds
|
|
64
|
+
QUICK_DELETE_HOURS = 1 # Delete within 1 hour = negative signal
|
|
65
|
+
BURST_THRESHOLD = 20 # >20 writes in burst window = negative
|
|
66
|
+
BURST_WINDOW_MINUTES = 5 # Burst detection window
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
|
|
4
|
+
"""
|
|
5
|
+
Trust query and enforcement mixin for TrustScorer.
|
|
6
|
+
|
|
7
|
+
Contains: get_trust_score, get_beta_params, check_trust, get_signals, get_trust_stats.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Dict, List
|
|
13
|
+
|
|
14
|
+
from .constants import INITIAL_ALPHA, INITIAL_BETA
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("superlocalmemory.trust")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TrustQueryMixin:
|
|
20
|
+
"""Mixin providing trust query, enforcement, and stats methods."""
|
|
21
|
+
|
|
22
|
+
def get_trust_score(self, agent_id: str) -> float:
|
|
23
|
+
"""
|
|
24
|
+
Get current trust score for an agent.
|
|
25
|
+
|
|
26
|
+
Computes alpha/(alpha+beta) from cached or stored Beta params.
|
|
27
|
+
Returns INITIAL_ALPHA/(INITIAL_ALPHA+INITIAL_BETA) = 0.667 for
|
|
28
|
+
unknown agents.
|
|
29
|
+
"""
|
|
30
|
+
alpha, beta = self._get_beta_params(agent_id)
|
|
31
|
+
if (alpha + beta) > 0:
|
|
32
|
+
return alpha / (alpha + beta)
|
|
33
|
+
return INITIAL_ALPHA / (INITIAL_ALPHA + INITIAL_BETA)
|
|
34
|
+
|
|
35
|
+
def get_beta_params(self, agent_id: str) -> Dict[str, float]:
|
|
36
|
+
"""
|
|
37
|
+
Get the Beta distribution parameters for an agent.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
{"alpha": float, "beta": float, "trust_score": float}
|
|
41
|
+
"""
|
|
42
|
+
alpha, beta = self._get_beta_params(agent_id)
|
|
43
|
+
score = alpha / (alpha + beta) if (alpha + beta) > 0 else 0.0
|
|
44
|
+
return {
|
|
45
|
+
"alpha": round(alpha, 4),
|
|
46
|
+
"beta": round(beta, 4),
|
|
47
|
+
"trust_score": round(score, 4),
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
def check_trust(self, agent_id: str, operation: str = "write") -> bool:
|
|
51
|
+
"""
|
|
52
|
+
Check if agent is trusted enough for the given operation.
|
|
53
|
+
|
|
54
|
+
v2.6 enforcement: blocks write/delete for agents with trust < 0.3.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
agent_id: The agent identifier
|
|
58
|
+
operation: One of "read", "write", "delete"
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
True if operation is allowed, False if blocked
|
|
62
|
+
"""
|
|
63
|
+
if operation == "read":
|
|
64
|
+
return True # Reads are always allowed
|
|
65
|
+
|
|
66
|
+
score = self.get_trust_score(agent_id)
|
|
67
|
+
|
|
68
|
+
threshold = 0.3 # Block write/delete below this
|
|
69
|
+
if score < threshold:
|
|
70
|
+
logger.warning(
|
|
71
|
+
"Trust enforcement: agent '%s' blocked from '%s' (trust=%.4f < %.2f)",
|
|
72
|
+
agent_id, operation, score, threshold
|
|
73
|
+
)
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
def get_signals(self, agent_id: str, limit: int = 50) -> List[dict]:
|
|
79
|
+
"""Get recent trust signals for an agent."""
|
|
80
|
+
try:
|
|
81
|
+
from db_connection_manager import DbConnectionManager
|
|
82
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
83
|
+
|
|
84
|
+
with mgr.read_connection() as conn:
|
|
85
|
+
cursor = conn.cursor()
|
|
86
|
+
cursor.execute("""
|
|
87
|
+
SELECT signal_type, delta, old_score, new_score, context, created_at
|
|
88
|
+
FROM trust_signals
|
|
89
|
+
WHERE agent_id = ?
|
|
90
|
+
ORDER BY created_at DESC
|
|
91
|
+
LIMIT ?
|
|
92
|
+
""", (agent_id, limit))
|
|
93
|
+
|
|
94
|
+
signals = []
|
|
95
|
+
for row in cursor.fetchall():
|
|
96
|
+
ctx = {}
|
|
97
|
+
try:
|
|
98
|
+
ctx = json.loads(row[4]) if row[4] else {}
|
|
99
|
+
except (json.JSONDecodeError, TypeError):
|
|
100
|
+
pass
|
|
101
|
+
signals.append({
|
|
102
|
+
"signal_type": row[0],
|
|
103
|
+
"delta": row[1],
|
|
104
|
+
"old_score": row[2],
|
|
105
|
+
"new_score": row[3],
|
|
106
|
+
"context": ctx,
|
|
107
|
+
"created_at": row[5],
|
|
108
|
+
})
|
|
109
|
+
return signals
|
|
110
|
+
|
|
111
|
+
except Exception as e:
|
|
112
|
+
logger.error("Failed to get trust signals: %s", e)
|
|
113
|
+
return []
|
|
114
|
+
|
|
115
|
+
def get_trust_stats(self) -> dict:
|
|
116
|
+
"""Get trust system statistics."""
|
|
117
|
+
try:
|
|
118
|
+
from db_connection_manager import DbConnectionManager
|
|
119
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
120
|
+
|
|
121
|
+
with mgr.read_connection() as conn:
|
|
122
|
+
cursor = conn.cursor()
|
|
123
|
+
|
|
124
|
+
cursor.execute("SELECT COUNT(*) FROM trust_signals")
|
|
125
|
+
total_signals = cursor.fetchone()[0]
|
|
126
|
+
|
|
127
|
+
cursor.execute("""
|
|
128
|
+
SELECT signal_type, COUNT(*) FROM trust_signals
|
|
129
|
+
GROUP BY signal_type ORDER BY COUNT(*) DESC
|
|
130
|
+
""")
|
|
131
|
+
by_type = dict(cursor.fetchall())
|
|
132
|
+
|
|
133
|
+
cursor.execute("""
|
|
134
|
+
SELECT agent_id, COUNT(*) FROM trust_signals
|
|
135
|
+
GROUP BY agent_id ORDER BY COUNT(*) DESC LIMIT 10
|
|
136
|
+
""")
|
|
137
|
+
by_agent = dict(cursor.fetchall())
|
|
138
|
+
|
|
139
|
+
cursor.execute("""
|
|
140
|
+
SELECT AVG(trust_score) FROM agent_registry
|
|
141
|
+
WHERE trust_score IS NOT NULL
|
|
142
|
+
""")
|
|
143
|
+
avg = cursor.fetchone()[0]
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
"total_signals": total_signals,
|
|
147
|
+
"by_signal_type": by_type,
|
|
148
|
+
"by_agent": by_agent,
|
|
149
|
+
"avg_trust_score": round(avg, 4) if avg else INITIAL_ALPHA / (INITIAL_ALPHA + INITIAL_BETA),
|
|
150
|
+
"scoring_model": "Beta-Binomial",
|
|
151
|
+
"prior": f"Beta({INITIAL_ALPHA}, {INITIAL_BETA})",
|
|
152
|
+
"enforcement": "enabled (v2.6 -- write/delete blocked below 0.3 trust)",
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
except Exception as e:
|
|
156
|
+
logger.error("Failed to get trust stats: %s", e)
|
|
157
|
+
return {"total_signals": 0, "error": str(e)}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
|
|
4
|
+
"""
|
|
5
|
+
Database schema initialization for the trust scoring system.
|
|
6
|
+
|
|
7
|
+
Creates trust_signals table and adds alpha/beta columns to agent_registry.
|
|
8
|
+
Extracted from TrustScorer._init_schema for modularity.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .constants import INITIAL_ALPHA, INITIAL_BETA
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def init_trust_schema(db_path: Path):
|
|
17
|
+
"""
|
|
18
|
+
Create trust_signals table and add alpha/beta columns to agent_registry.
|
|
19
|
+
|
|
20
|
+
Handles both DbConnectionManager (preferred) and direct sqlite3 fallback.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
db_path: Path to the SQLite database file.
|
|
24
|
+
"""
|
|
25
|
+
try:
|
|
26
|
+
from db_connection_manager import DbConnectionManager
|
|
27
|
+
mgr = DbConnectionManager.get_instance(db_path)
|
|
28
|
+
|
|
29
|
+
def _create(conn):
|
|
30
|
+
# Trust signals audit trail
|
|
31
|
+
conn.execute('''
|
|
32
|
+
CREATE TABLE IF NOT EXISTS trust_signals (
|
|
33
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
34
|
+
agent_id TEXT NOT NULL,
|
|
35
|
+
signal_type TEXT NOT NULL,
|
|
36
|
+
delta REAL NOT NULL,
|
|
37
|
+
old_score REAL,
|
|
38
|
+
new_score REAL,
|
|
39
|
+
context TEXT DEFAULT '{}',
|
|
40
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
41
|
+
)
|
|
42
|
+
''')
|
|
43
|
+
conn.execute('''
|
|
44
|
+
CREATE INDEX IF NOT EXISTS idx_trust_agent
|
|
45
|
+
ON trust_signals(agent_id)
|
|
46
|
+
''')
|
|
47
|
+
conn.execute('''
|
|
48
|
+
CREATE INDEX IF NOT EXISTS idx_trust_created
|
|
49
|
+
ON trust_signals(created_at)
|
|
50
|
+
''')
|
|
51
|
+
|
|
52
|
+
# Add trust_alpha and trust_beta columns to agent_registry
|
|
53
|
+
# (backward compatible -- old databases get these columns added)
|
|
54
|
+
for col_name, col_default in [("trust_alpha", INITIAL_ALPHA),
|
|
55
|
+
("trust_beta", INITIAL_BETA)]:
|
|
56
|
+
try:
|
|
57
|
+
conn.execute(
|
|
58
|
+
f'ALTER TABLE agent_registry ADD COLUMN {col_name} REAL DEFAULT {col_default}'
|
|
59
|
+
)
|
|
60
|
+
except Exception:
|
|
61
|
+
pass # Column already exists
|
|
62
|
+
|
|
63
|
+
conn.commit()
|
|
64
|
+
|
|
65
|
+
mgr.execute_write(_create)
|
|
66
|
+
except ImportError:
|
|
67
|
+
import sqlite3
|
|
68
|
+
conn = sqlite3.connect(str(db_path))
|
|
69
|
+
conn.execute('''
|
|
70
|
+
CREATE TABLE IF NOT EXISTS trust_signals (
|
|
71
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
72
|
+
agent_id TEXT NOT NULL,
|
|
73
|
+
signal_type TEXT NOT NULL,
|
|
74
|
+
delta REAL NOT NULL,
|
|
75
|
+
old_score REAL,
|
|
76
|
+
new_score REAL,
|
|
77
|
+
context TEXT DEFAULT '{}',
|
|
78
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
79
|
+
)
|
|
80
|
+
''')
|
|
81
|
+
conn.execute('CREATE INDEX IF NOT EXISTS idx_trust_agent ON trust_signals(agent_id)')
|
|
82
|
+
conn.execute('CREATE INDEX IF NOT EXISTS idx_trust_created ON trust_signals(created_at)')
|
|
83
|
+
|
|
84
|
+
# Add trust_alpha and trust_beta columns (backward compatible)
|
|
85
|
+
for col_name, col_default in [("trust_alpha", INITIAL_ALPHA),
|
|
86
|
+
("trust_beta", INITIAL_BETA)]:
|
|
87
|
+
try:
|
|
88
|
+
conn.execute(
|
|
89
|
+
f'ALTER TABLE agent_registry ADD COLUMN {col_name} REAL DEFAULT {col_default}'
|
|
90
|
+
)
|
|
91
|
+
except sqlite3.OperationalError:
|
|
92
|
+
pass # Column already exists
|
|
93
|
+
|
|
94
|
+
conn.commit()
|
|
95
|
+
conn.close()
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# Copyright (c) 2026 SuperLocalMemory (superlocalmemory.com)
|
|
4
|
+
"""SuperLocalMemory V2 - Trust Scorer (core class)
|
|
5
|
+
. MIT License.
|
|
6
|
+
|
|
7
|
+
Bayesian Beta-Binomial trust scoring for AI agents.
|
|
8
|
+
Core class with Beta parameter management and signal recording.
|
|
9
|
+
Query/stats via TrustQueryMixin; signal helpers via TrustSignalsMixin.
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import threading
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Optional, Dict
|
|
16
|
+
|
|
17
|
+
from .constants import (
|
|
18
|
+
SIGNAL_WEIGHTS,
|
|
19
|
+
INITIAL_ALPHA,
|
|
20
|
+
INITIAL_BETA,
|
|
21
|
+
DECAY_FACTOR,
|
|
22
|
+
DECAY_INTERVAL,
|
|
23
|
+
ALPHA_FLOOR,
|
|
24
|
+
BETA_FLOOR,
|
|
25
|
+
)
|
|
26
|
+
from .schema import init_trust_schema
|
|
27
|
+
from .signals import TrustSignalsMixin
|
|
28
|
+
from .queries import TrustQueryMixin
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("superlocalmemory.trust")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TrustScorer(TrustSignalsMixin, TrustQueryMixin):
|
|
34
|
+
"""
|
|
35
|
+
Bayesian Beta-Binomial trust scorer for AI agents.
|
|
36
|
+
|
|
37
|
+
Each agent is modeled as Beta(alpha, beta). Positive signals
|
|
38
|
+
increment alpha, negative signals increment beta. The trust
|
|
39
|
+
score is the posterior mean: alpha / (alpha + beta).
|
|
40
|
+
|
|
41
|
+
Thread-safe singleton per database path.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
_instances: Dict[str, "TrustScorer"] = {}
|
|
45
|
+
_instances_lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def get_instance(cls, db_path: Optional[Path] = None) -> "TrustScorer":
|
|
49
|
+
"""Get or create the singleton TrustScorer."""
|
|
50
|
+
if db_path is None:
|
|
51
|
+
db_path = Path.home() / ".claude-memory" / "memory.db"
|
|
52
|
+
key = str(db_path)
|
|
53
|
+
with cls._instances_lock:
|
|
54
|
+
if key not in cls._instances:
|
|
55
|
+
cls._instances[key] = cls(db_path)
|
|
56
|
+
return cls._instances[key]
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def reset_instance(cls, db_path: Optional[Path] = None):
|
|
60
|
+
"""Remove singleton. Used for testing."""
|
|
61
|
+
with cls._instances_lock:
|
|
62
|
+
if db_path is None:
|
|
63
|
+
cls._instances.clear()
|
|
64
|
+
else:
|
|
65
|
+
key = str(db_path)
|
|
66
|
+
if key in cls._instances:
|
|
67
|
+
del cls._instances[key]
|
|
68
|
+
|
|
69
|
+
def __init__(self, db_path: Path):
|
|
70
|
+
self.db_path = Path(db_path)
|
|
71
|
+
|
|
72
|
+
# In-memory signal log for burst detection (agent_id -> list of timestamps)
|
|
73
|
+
self._write_timestamps: Dict[str, list] = {}
|
|
74
|
+
self._timestamps_lock = threading.Lock()
|
|
75
|
+
|
|
76
|
+
# Signal count per agent (for decay interval tracking)
|
|
77
|
+
self._signal_counts: Dict[str, int] = {}
|
|
78
|
+
|
|
79
|
+
# In-memory cache of Beta parameters per agent
|
|
80
|
+
# Key: agent_id, Value: (alpha, beta)
|
|
81
|
+
self._beta_params: Dict[str, tuple] = {}
|
|
82
|
+
self._beta_lock = threading.Lock()
|
|
83
|
+
|
|
84
|
+
self._init_schema()
|
|
85
|
+
logger.info("TrustScorer initialized (Beta-Binomial -- alpha=%.1f, beta=%.1f prior)",
|
|
86
|
+
INITIAL_ALPHA, INITIAL_BETA)
|
|
87
|
+
|
|
88
|
+
def _init_schema(self):
|
|
89
|
+
"""Create trust_signals table and add alpha/beta columns to agent_registry."""
|
|
90
|
+
init_trust_schema(self.db_path)
|
|
91
|
+
|
|
92
|
+
# =========================================================================
|
|
93
|
+
# Beta Parameter Management
|
|
94
|
+
# =========================================================================
|
|
95
|
+
|
|
96
|
+
def _get_beta_params(self, agent_id: str) -> tuple:
|
|
97
|
+
"""
|
|
98
|
+
Get (alpha, beta) for an agent. Checks in-memory cache first,
|
|
99
|
+
then database, then falls back to prior defaults.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
(alpha, beta) tuple
|
|
103
|
+
"""
|
|
104
|
+
with self._beta_lock:
|
|
105
|
+
if agent_id in self._beta_params:
|
|
106
|
+
return self._beta_params[agent_id]
|
|
107
|
+
|
|
108
|
+
# Not in cache -- read from database
|
|
109
|
+
alpha, beta = None, None
|
|
110
|
+
try:
|
|
111
|
+
from db_connection_manager import DbConnectionManager
|
|
112
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
113
|
+
|
|
114
|
+
with mgr.read_connection() as conn:
|
|
115
|
+
cursor = conn.cursor()
|
|
116
|
+
cursor.execute(
|
|
117
|
+
"SELECT trust_alpha, trust_beta FROM agent_registry WHERE agent_id = ?",
|
|
118
|
+
(agent_id,)
|
|
119
|
+
)
|
|
120
|
+
row = cursor.fetchone()
|
|
121
|
+
if row:
|
|
122
|
+
alpha = row[0]
|
|
123
|
+
beta = row[1]
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
# Fall back to defaults if NULL or missing
|
|
128
|
+
if alpha is None or beta is None:
|
|
129
|
+
alpha = INITIAL_ALPHA
|
|
130
|
+
beta = INITIAL_BETA
|
|
131
|
+
|
|
132
|
+
with self._beta_lock:
|
|
133
|
+
self._beta_params[agent_id] = (alpha, beta)
|
|
134
|
+
|
|
135
|
+
return (alpha, beta)
|
|
136
|
+
|
|
137
|
+
def _set_beta_params(self, agent_id: str, alpha: float, beta: float):
|
|
138
|
+
"""
|
|
139
|
+
Update (alpha, beta) in cache and persist to agent_registry.
|
|
140
|
+
Also computes and stores the derived trust_score = alpha/(alpha+beta).
|
|
141
|
+
"""
|
|
142
|
+
trust_score = alpha / (alpha + beta) if (alpha + beta) > 0 else 0.0
|
|
143
|
+
|
|
144
|
+
with self._beta_lock:
|
|
145
|
+
self._beta_params[agent_id] = (alpha, beta)
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
from db_connection_manager import DbConnectionManager
|
|
149
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
150
|
+
|
|
151
|
+
def _update(conn):
|
|
152
|
+
conn.execute(
|
|
153
|
+
"""UPDATE agent_registry
|
|
154
|
+
SET trust_score = ?, trust_alpha = ?, trust_beta = ?
|
|
155
|
+
WHERE agent_id = ?""",
|
|
156
|
+
(round(trust_score, 4), round(alpha, 4), round(beta, 4), agent_id)
|
|
157
|
+
)
|
|
158
|
+
conn.commit()
|
|
159
|
+
|
|
160
|
+
mgr.execute_write(_update)
|
|
161
|
+
except Exception as e:
|
|
162
|
+
logger.error("Failed to persist Beta params for %s: %s", agent_id, e)
|
|
163
|
+
|
|
164
|
+
def _apply_decay(self, agent_id: str, alpha: float, beta: float) -> tuple:
|
|
165
|
+
"""
|
|
166
|
+
Apply periodic decay to alpha and beta to forget very old signals.
|
|
167
|
+
|
|
168
|
+
Called every DECAY_INTERVAL signals per agent.
|
|
169
|
+
Multiplies both by DECAY_FACTOR with floor constraints.
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
(decayed_alpha, decayed_beta)
|
|
173
|
+
"""
|
|
174
|
+
new_alpha = max(ALPHA_FLOOR, alpha * DECAY_FACTOR)
|
|
175
|
+
new_beta = max(BETA_FLOOR, beta * DECAY_FACTOR)
|
|
176
|
+
return (new_alpha, new_beta)
|
|
177
|
+
|
|
178
|
+
# =========================================================================
|
|
179
|
+
# Signal Recording (Beta-Binomial Update)
|
|
180
|
+
# =========================================================================
|
|
181
|
+
|
|
182
|
+
def record_signal(
|
|
183
|
+
self,
|
|
184
|
+
agent_id: str,
|
|
185
|
+
signal_type: str,
|
|
186
|
+
context: Optional[dict] = None,
|
|
187
|
+
) -> bool:
|
|
188
|
+
"""
|
|
189
|
+
Record a trust signal for an agent using Beta-Binomial update.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
agent_id: Agent that generated the signal
|
|
193
|
+
signal_type: One of SIGNAL_WEIGHTS keys
|
|
194
|
+
context: Additional context (memory_id, etc.)
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
True if signal was recorded successfully
|
|
198
|
+
"""
|
|
199
|
+
if signal_type not in SIGNAL_WEIGHTS:
|
|
200
|
+
logger.warning("Unknown trust signal: %s", signal_type)
|
|
201
|
+
return False
|
|
202
|
+
|
|
203
|
+
direction, weight = SIGNAL_WEIGHTS[signal_type]
|
|
204
|
+
|
|
205
|
+
# Get current Beta parameters
|
|
206
|
+
alpha, beta = self._get_beta_params(agent_id)
|
|
207
|
+
old_score = alpha / (alpha + beta) if (alpha + beta) > 0 else 0.0
|
|
208
|
+
|
|
209
|
+
# Apply Beta-Binomial update
|
|
210
|
+
if direction == "positive":
|
|
211
|
+
alpha += weight
|
|
212
|
+
elif direction == "negative":
|
|
213
|
+
beta += weight
|
|
214
|
+
else: # neutral -- tiny alpha nudge
|
|
215
|
+
alpha += weight
|
|
216
|
+
|
|
217
|
+
# Apply periodic decay
|
|
218
|
+
count = self._signal_counts.get(agent_id, 0) + 1
|
|
219
|
+
self._signal_counts[agent_id] = count
|
|
220
|
+
|
|
221
|
+
if count % DECAY_INTERVAL == 0:
|
|
222
|
+
alpha, beta = self._apply_decay(agent_id, alpha, beta)
|
|
223
|
+
|
|
224
|
+
# Compute new trust score (posterior mean)
|
|
225
|
+
new_score = alpha / (alpha + beta) if (alpha + beta) > 0 else 0.0
|
|
226
|
+
|
|
227
|
+
# Compute delta for audit trail
|
|
228
|
+
delta = new_score - old_score
|
|
229
|
+
|
|
230
|
+
# Persist signal to audit trail
|
|
231
|
+
self._persist_signal(agent_id, signal_type, delta, old_score, new_score, context)
|
|
232
|
+
|
|
233
|
+
# Persist updated Beta parameters and derived trust_score
|
|
234
|
+
self._set_beta_params(agent_id, alpha, beta)
|
|
235
|
+
|
|
236
|
+
logger.debug(
|
|
237
|
+
"Trust signal: agent=%s, type=%s (%s, w=%.2f), "
|
|
238
|
+
"alpha=%.2f, beta=%.2f, score=%.4f->%.4f",
|
|
239
|
+
agent_id, signal_type, direction, weight,
|
|
240
|
+
alpha, beta, old_score, new_score
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
return True
|
|
244
|
+
|
|
245
|
+
def _persist_signal(self, agent_id, signal_type, delta, old_score, new_score, context):
|
|
246
|
+
"""Save signal to trust_signals table."""
|
|
247
|
+
try:
|
|
248
|
+
from db_connection_manager import DbConnectionManager
|
|
249
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
250
|
+
|
|
251
|
+
def _insert(conn):
|
|
252
|
+
conn.execute('''
|
|
253
|
+
INSERT INTO trust_signals (agent_id, signal_type, delta, old_score, new_score, context)
|
|
254
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
255
|
+
''', (agent_id, signal_type, delta, old_score, new_score, json.dumps(context or {})))
|
|
256
|
+
conn.commit()
|
|
257
|
+
|
|
258
|
+
mgr.execute_write(_insert)
|
|
259
|
+
except Exception as e:
|
|
260
|
+
logger.error("Failed to persist trust signal: %s", e)
|
|
261
|
+
|
|
262
|
+
def _get_agent_trust(self, agent_id: str) -> Optional[float]:
|
|
263
|
+
"""Get current trust score from agent_registry."""
|
|
264
|
+
try:
|
|
265
|
+
from db_connection_manager import DbConnectionManager
|
|
266
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
267
|
+
|
|
268
|
+
with mgr.read_connection() as conn:
|
|
269
|
+
cursor = conn.cursor()
|
|
270
|
+
cursor.execute(
|
|
271
|
+
"SELECT trust_score FROM agent_registry WHERE agent_id = ?",
|
|
272
|
+
(agent_id,)
|
|
273
|
+
)
|
|
274
|
+
row = cursor.fetchone()
|
|
275
|
+
return row[0] if row else None
|
|
276
|
+
except Exception:
|
|
277
|
+
return None
|
|
278
|
+
|
|
279
|
+
def _update_agent_trust(self, agent_id: str, new_score: float):
|
|
280
|
+
"""
|
|
281
|
+
Update trust score in agent_registry (legacy compatibility method).
|
|
282
|
+
|
|
283
|
+
In Beta-Binomial mode, _set_beta_params already updates trust_score
|
|
284
|
+
alongside alpha and beta. Kept for backward compatibility.
|
|
285
|
+
"""
|
|
286
|
+
try:
|
|
287
|
+
from db_connection_manager import DbConnectionManager
|
|
288
|
+
mgr = DbConnectionManager.get_instance(self.db_path)
|
|
289
|
+
|
|
290
|
+
def _update(conn):
|
|
291
|
+
conn.execute(
|
|
292
|
+
"UPDATE agent_registry SET trust_score = ? WHERE agent_id = ?",
|
|
293
|
+
(round(new_score, 4), agent_id)
|
|
294
|
+
)
|
|
295
|
+
conn.commit()
|
|
296
|
+
|
|
297
|
+
mgr.execute_write(_update)
|
|
298
|
+
except Exception as e:
|
|
299
|
+
logger.error("Failed to update agent trust: %s", e)
|