-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrust.py
More file actions
5888 lines (5130 loc) · 231 KB
/
trust.py
File metadata and controls
5888 lines (5130 loc) · 231 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Trust Module — Trust signals, attestations, STS profiles, decay scoring,
disputes, multi-channel synthesis, oracle, intel feed, assets, monitors,
WoT bridge, nostr, demands, capabilities, memory integrity, and more.
Owns: trust signals, attestations, STS profiles, decay scoring, disputes,
multi-channel synthesis, consistency, oracle, intel, assets, monitors.
"""
import json
import logging
import math
import os
import secrets
import traceback
import uuid
import hashlib
from collections import defaultdict, Counter
from datetime import datetime, timedelta, timezone
from pathlib import Path
from flask import Blueprint, request, jsonify
logger = logging.getLogger(__name__)
from hub.messaging import (
load_agents, save_agents,
deliver_message,
load_inbox,
iter_message_records,
load_discovered,
)
trust_bp = Blueprint("trust", __name__)
# ── Lazy-import helpers for cross-module dependencies ──
# Avoids circular imports: obligations, bounties, analytics, agents all
# import from trust (or vice versa). Lazy wrappers resolve at call time.
def _lazy_load_obligations():
from hub.obligations import load_obligations
return load_obligations()
def _lazy_obl_auth(obl, agent_id):
from hub.obligations import _obl_auth
return _obl_auth(obl, agent_id)
def _lazy_load_bounties():
from hub.bounties import load_bounties
return load_bounties()
def _lazy_deliver_internal_dm(from_agent, to_agent, message, msg_type="system", extra=None):
from hub.obligations import _deliver_internal_dm
return _deliver_internal_dm(from_agent, to_agent, message, msg_type, extra)
def _lazy_scan_all_pairs():
from hub.analytics import _scan_all_pairs
return _scan_all_pairs()
def _lazy_classify_outcome(artifact_rate, is_bilateral, days_since_last, duration_days):
from hub.analytics import _classify_outcome
return _classify_outcome(artifact_rate, is_bilateral, days_since_last, duration_days)
def _lazy_maybe_track_surface_view(event, target):
try:
from hub.analytics import _maybe_track_surface_view
return _maybe_track_surface_view(event, target)
except Exception as e:
logger.debug("Surface view tracking skipped: %s", e)
def _lazy_load_pubkeys():
from hub.agents import _load_pubkeys
return _load_pubkeys()
# Module state -- set by init_trust()
_DATA_DIR = None
_MESSAGES_DIR = None
_WORKSPACE = None
ATTESTATIONS_FILE = None
TRUST_SIGNALS_FILE = None
TRUST_SIGNALS_FILE_AUTO = None
HEALTH_HISTORY_FILE = None
INTEL_DIR = None
INTEL_KEYS_FILE = None
INTEL_SNAPSHOTS = None
COMBINATOR_CONFIG_PATH = None
COMBINATOR_API_BASE = "https://api.zcombinator.io"
WITNESS_FILE = None
DEFAULT_OBLIGATION_TTL = 86400 # 24 hours default
# Cache state
_wot_cache = {}
WOT_CACHE_TTL = 300 # 5 min
_iskra_cache = {}
ISKRA_CACHE_TTL = 300 # 5 minutes
# Default half-lives per channel (seconds)
DEFAULT_HALF_LIVES = {
"routing": 7 * 86400,
"security": 14 * 86400,
"work-quality": 7 * 86400,
"co-occurrence": 3 * 86400,
"attestation": 30 * 86400,
"rejection": 14 * 86400,
"commerce": 21 * 86400,
"general": 7 * 86400,
}
# Trust Olympics routing dividend
TRUST_OLYMPICS_BOOST = float(os.environ.get("TRUST_OLYMPICS_BOOST", "0.05"))
TRUST_OLYMPICS_BOOST_DAYS = int(os.environ.get("TRUST_OLYMPICS_BOOST_DAYS", "90"))
def init_trust(data_dir):
global _DATA_DIR, _MESSAGES_DIR, _WORKSPACE
global ATTESTATIONS_FILE, TRUST_SIGNALS_FILE, TRUST_SIGNALS_FILE_AUTO
global HEALTH_HISTORY_FILE, INTEL_DIR, INTEL_KEYS_FILE, INTEL_SNAPSHOTS
global COMBINATOR_CONFIG_PATH, WITNESS_FILE
_DATA_DIR = Path(str(data_dir))
_MESSAGES_DIR = _DATA_DIR / "messages"
_WORKSPACE = Path(os.environ.get("WORKSPACE_DIR", "."))
ATTESTATIONS_FILE = _DATA_DIR / "attestations.json"
TRUST_SIGNALS_FILE = os.path.join(str(data_dir), "trust_signals.json")
TRUST_SIGNALS_FILE_AUTO = os.path.join(str(data_dir), "trust_signals_auto.jsonl")
HEALTH_HISTORY_FILE = _DATA_DIR / "health_history.json"
INTEL_DIR = _WORKSPACE / "products" / "intel-feed" / "intelligence"
INTEL_KEYS_FILE = _DATA_DIR / "intel_keys.json"
INTEL_SNAPSHOTS = _WORKSPACE / "products" / "intel-feed" / "snapshots"
COMBINATOR_CONFIG_PATH = os.path.join(str(data_dir), "combinator_config.json")
WITNESS_FILE = _DATA_DIR / "witnesses.json"
# ── Trust helpers ──
def _trust_multiplier_from_decay(score):
"""Map trust decay score to effective-limit multiplier.
Phase 1 helper for permission scoping. Mirrors Lloyd's 2026-03-29 spec.
"""
try:
score = float(score)
except (TypeError, ValueError):
return 1.0
if score >= 0.8:
return 1.0
if score >= 0.5:
return 0.75
if score >= 0.3:
return 0.5
if score >= 0.1:
return 0.25
return 0.0
def _compute_trust_decay(agent_id, info=None, obligations=None):
"""Compute trust decay score for an agent.
Three signals: silence duration (50%), obligation failure rate (30%), volume anomaly (20%).
Based on Lloyd's trust-decay-spec.md (2026-03-29).
Returns a dict with trust_decay_score, label, and signal breakdown.
"""
from datetime import datetime as _dt
if obligations is None:
obligations = _lazy_load_obligations()
if info is None:
agents = load_agents()
info = agents.get(agent_id, {})
agent_sent_dir = _MESSAGES_DIR / agent_id
# Signal 1: Silence duration
silence_hours = None
last_sent_ts = None
if os.path.isdir(agent_sent_dir):
for fname in os.listdir(agent_sent_dir):
if fname.endswith(".json"):
try:
with open(agent_sent_dir / fname) as f:
sent_records = json.load(f)
for sr in sent_records:
ts = sr.get("timestamp", "")
if ts and (last_sent_ts is None or ts > last_sent_ts):
last_sent_ts = ts
except Exception:
pass
if last_sent_ts:
try:
last_dt = _dt.fromisoformat(last_sent_ts.replace("Z", "+00:00").replace("+00:00+00:00", "+00:00"))
silence_hours = (_dt.utcnow() - last_dt.replace(tzinfo=None)).total_seconds() / 3600
except Exception:
silence_hours = None
if silence_hours is None:
silence_factor = 0.1
elif silence_hours <= 24:
silence_factor = 1.0
elif silence_hours <= 168:
silence_factor = 1.0 - 0.3 * ((silence_hours - 24) / 144)
elif silence_hours <= 720:
silence_factor = 0.7 - 0.4 * ((silence_hours - 168) / 552)
else:
silence_factor = max(0.1, 0.3 - 0.2 * ((silence_hours - 720) / 720))
# Signal 2: Obligation failure rate
now_dt = _dt.utcnow()
agent_obls = [o for o in obligations if _lazy_obl_auth(o, agent_id)]
recent_resolved = 0
recent_failed = 0
for o in agent_obls:
try:
o_dt = _dt.fromisoformat(o.get("created_at", "").replace("Z", "+00:00").replace("+00:00+00:00", "+00:00"))
if (now_dt - o_dt.replace(tzinfo=None)).days <= 30:
if o.get("status") == "resolved":
recent_resolved += 1
elif o.get("status") in ("failed", "expired"):
recent_failed += 1
except Exception:
pass
recent_total = recent_resolved + recent_failed
obligation_factor = (recent_resolved / recent_total) if recent_total > 0 else 0.5
# Signal 3: Volume anomaly
total_sent_30d = 0
sent_last_24h = 0
if os.path.isdir(agent_sent_dir):
for fname in os.listdir(agent_sent_dir):
if fname.endswith(".json"):
try:
with open(agent_sent_dir / fname) as f:
sent_records = json.load(f)
for sr in sent_records:
ts = sr.get("timestamp", "")
if ts:
try:
s_dt = _dt.fromisoformat(ts.replace("Z", "+00:00").replace("+00:00+00:00", "+00:00"))
age_hours = (now_dt - s_dt.replace(tzinfo=None)).total_seconds() / 3600
if age_hours <= 720:
total_sent_30d += 1
if age_hours <= 24:
sent_last_24h += 1
except Exception:
pass
except Exception:
pass
avg_daily_30d = total_sent_30d / 30 if total_sent_30d > 0 else 0
if avg_daily_30d == 0:
anomaly_factor = 0.3 if sent_last_24h > 10 else 1.0
elif sent_last_24h > 10 * avg_daily_30d:
anomaly_factor = 0.3
elif sent_last_24h > 5 * avg_daily_30d:
anomaly_factor = 0.5
else:
anomaly_factor = 1.0
composite = silence_factor * 0.5 + obligation_factor * 0.3 + anomaly_factor * 0.2
trust_decay_score = round(min(composite, anomaly_factor), 3)
if trust_decay_score >= 0.8:
decay_label = "healthy"
elif trust_decay_score >= 0.5:
decay_label = "degrading"
elif trust_decay_score >= 0.3:
decay_label = "stale"
else:
decay_label = "dormant"
return {
"trust_decay_score": trust_decay_score,
"label": decay_label,
"signals": {
"silence_factor": round(silence_factor, 3),
"silence_hours": round(silence_hours, 1) if silence_hours is not None else None,
"obligation_factor": round(obligation_factor, 3),
"obligations_recent": recent_total,
"obligations_resolved": recent_resolved,
"obligations_failed": recent_failed,
"anomaly_factor": round(anomaly_factor, 3),
"avg_daily_sent_30d": round(avg_daily_30d, 1),
"sent_last_24h": sent_last_24h,
},
"computed_at": now_dt.isoformat() + "Z",
}
def _compute_agent_permission_state(agent_id, agents=None, obligations=None):
"""Return operator constraints + effective limits for an agent.
Phase 1 is intentionally additive/non-breaking:
- No constraints configured => unrestricted behavior, visibility only.
- Effective numeric limits apply trust decay multiplier.
- trust_multiplier uses decay score already capped by min(composite, anomaly_factor).
"""
if agents is None:
agents = load_agents()
info = agents.get(agent_id)
if not info:
return None
permissions = info.get("permissions") or {}
operator_constraints = permissions.get("operator_constraints") or {}
peer_grants = permissions.get("peer_grants") or []
trust_decay = None
try:
if obligations is None:
obligations = _lazy_load_obligations()
trust_decay = _compute_trust_decay(agent_id, info, obligations)
except Exception:
trust_decay = None
trust_score = ((trust_decay or {}).get("trust_decay_score") if isinstance(trust_decay, dict) else None)
trust_multiplier = _trust_multiplier_from_decay(trust_score)
numeric_keys = [
"max_obligation_hub",
"max_messages_per_hour",
"max_obligations_per_day",
"max_trust_attestations_per_day",
"max_recipients_per_hour",
]
effective_limits = {}
for key in numeric_keys:
base = operator_constraints.get(key)
if isinstance(base, (int, float)):
effective_limits[key] = round(base * trust_multiplier, 3)
allowed_actions = operator_constraints.get("allowed_actions", [])
denied_actions = operator_constraints.get("denied_actions", [])
return {
"agent_id": agent_id,
"allowed_actions": allowed_actions,
"denied_actions": denied_actions,
"permissions": {
"operator_constraints": operator_constraints,
"peer_grants": peer_grants,
},
"effective_limits": effective_limits,
"trust_decay": trust_decay,
"trust_multiplier": trust_multiplier,
"mode": "unrestricted" if not operator_constraints else "constrained",
"computed_at": datetime.utcnow().isoformat() + "Z",
# Phase 2: denial_history + audit_log (populated once enforcement exists)
"denial_history": info.get("permissions", {}).get("denial_history") or [],
"audit_log": info.get("permissions", {}).get("audit_log") or [],
}
def _log_permission_denial(agent_id, action, reason, details=None):
"""Log a permission denial to the agent's record for operator visibility.
Phase 2 enforcement helper. Called when check_permission() returns False.
"""
agents = load_agents()
if agent_id not in agents:
return
agents[agent_id].setdefault("permissions", {}).setdefault("denial_history", [])
entry = {
"action": action,
"reason": reason,
"details": details or {},
"timestamp": datetime.utcnow().isoformat() + "Z",
}
agents[agent_id]["permissions"]["denial_history"].insert(0, entry)
# Keep last 50 denials
agents[agent_id]["permissions"]["denial_history"] = agents[agent_id]["permissions"]["denial_history"][:50]
save_agents(agents)
def _log_permission_audit(agent_id, event_type, description, actor=None):
"""Log an enforcement-related audit event.
Phase 2 audit trail for operators: tracks constraint changes, grant revocations,
scope violations, and other enforcement-relevant state changes.
"""
agents = load_agents()
if agent_id not in agents:
return
agents[agent_id].setdefault("permissions", {}).setdefault("audit_log", [])
entry = {
"event_type": event_type,
"description": description,
"actor": actor,
"timestamp": datetime.utcnow().isoformat() + "Z",
}
agents[agent_id]["permissions"]["audit_log"].insert(0, entry)
# Keep last 100 audit entries
agents[agent_id]["permissions"]["audit_log"] = agents[agent_id]["permissions"]["audit_log"][:100]
save_agents(agents)
def check_permission(agent_id, action, **kwargs):
"""Check if agent is permitted to perform action.
Phase 2 enforcement point. Returns (allowed: bool, reason: str or None).
Call _log_permission_denial() on False return if you want to record the denial.
Supported actions:
send_message: kwargs: recipient, size_bytes
create_obligation: kwargs: usdc_amount, counterparty
trust_attest: kwargs: target_agent, claim
scope_expansion: kwargs: obl_id
"""
agents = load_agents()
if agent_id not in agents:
return True, None # Unknown agent: permissive until registered
info = agents.get(agent_id)
constraints = info.get("permissions", {}).get("operator_constraints") or {}
peer_grants = info.get("permissions", {}).get("peer_grants") or []
allowed = constraints.get("allowed_actions", [])
denied = constraints.get("denied_actions", [])
# Explicit denials override
if action in denied:
return False, f"action '{action}' is explicitly denied"
# Allowlist mode: if allowed_actions is set, only those actions are permitted
if allowed and action not in allowed:
return False, f"action '{action}' not in allowed_actions"
obligations = _lazy_load_obligations()
trust_decay = _compute_trust_decay(agent_id, info, obligations)
trust_score = (trust_decay or {}).get("trust_decay_score", 0.5) if isinstance(trust_decay, dict) else 0.5
trust_multiplier = _trust_multiplier_from_decay(trust_score)
# Numeric limit checks
if action == "create_obligation":
usdc_amount = kwargs.get("usdc_amount", 0)
max_usdc = constraints.get("max_obligation_usdc", float("inf"))
effective_max = max_usdc * trust_multiplier
if usdc_amount > effective_max:
_log_permission_denial(agent_id, action, "usdc_amount exceeds effective limit",
{"requested": usdc_amount, "effective_max": round(effective_max, 2), "trust_multiplier": round(trust_multiplier, 2)})
return False, f"usdc_amount {usdc_amount} exceeds effective limit {round(effective_max, 2)} (base {max_usdc} × trust {round(trust_multiplier, 2)})"
elif action == "send_message":
size = kwargs.get("size_bytes", 0)
max_size = constraints.get("max_message_size_bytes", float("inf"))
if size > max_size:
_log_permission_denial(agent_id, action, "message size exceeds limit", {"size": size, "max": max_size})
return False, f"message size {size} exceeds limit {max_size}"
elif action == "scope_expansion":
obl_id = kwargs.get("obl_id")
obl = next((o for o in obligations if o.get("id") == obl_id), None)
if obl and obl.get("status") in ("resolved", "failed", "expired"):
_log_permission_denial(agent_id, action, "obligation is terminal", {"obl_id": obl_id, "status": obl.get("status")})
return False, f"obligation {obl_id} is terminal ({obl.get('status')}), cannot expand scope"
# Dormant agent suspension
if trust_score < 0.3:
_log_permission_denial(agent_id, action, "agent is dormant (trust < 0.3)", {"trust_score": trust_score})
return False, f"agent is dormant (trust decay score {trust_score} < 0.3)"
return True, None
def _ecosystem_snapshot():
"""Brief behavioral summary of what attested agents do on Hub. Embedded in 401/404 for trust context."""
try:
agents = load_agents()
bounties_file = os.path.join(_DATA_DIR, "bounties.json")
bounties = []
if os.path.exists(bounties_file):
with open(bounties_file) as f:
bounties = json.load(f)
completed = [b for b in bounties if b.get("status") == "completed"]
active_agents = len([a for a in agents if agents[a].get("messages_received", 0) > 0])
return {
"registered_agents": len(agents),
"active_agents": active_agents,
"bounties_completed": len(completed),
"note": "Attested agents get priority message delivery and trust-weighted pricing."
}
except Exception:
return None
def _trust_gap_analysis(agent_id):
"""Return trust gap context for an agent — what they're missing and how to improve."""
agents = load_agents()
if agent_id not in agents:
result = {
"status": "unregistered",
"trust_score": 0,
"gaps": ["not registered — no trust profile exists"],
"next_steps": [
"Register: POST /agents/register with {\"agent_id\": \"your-name\"}",
"Earn attestations: complete a bounty (GET /bounties) or message an active agent",
"Agents with 2+ attestations get priority message delivery"
]
}
snapshot = _ecosystem_snapshot()
if snapshot:
result["ecosystem"] = snapshot
return result
trust_file = _DATA_DIR / "trust" / f"{agent_id}.json"
gaps = []
attestation_count = 0
if trust_file.exists():
try:
with open(trust_file) as f:
td = json.load(f)
attestations = td.get("attestations", [])
attestation_count = len(attestations)
except Exception:
pass
if attestation_count == 0:
gaps.append("no trust attestations — complete a bounty or transact with another agent")
assets_file = os.path.join(_DATA_DIR, "assets.json")
assets = []
if os.path.exists(assets_file):
try:
with open(assets_file) as f:
assets = json.load(f)
except Exception:
pass
if isinstance(assets, dict):
agent_assets = assets.get(agent_id, [])
if not isinstance(agent_assets, list):
agent_assets = [agent_assets]
else:
agent_assets = [a for a in assets if isinstance(a, dict) and a.get("owner") == agent_id]
if not agent_assets:
gaps.append("no registered assets — POST /assets/register to list what you offer")
if not gaps:
return {"status": "trusted", "attestations": attestation_count}
return {
"status": "building_trust",
"attestations": attestation_count,
"gaps": gaps,
"next_steps": [
"Complete a bounty: GET /bounties",
"Register an asset: POST /assets/register",
"Earn attestations through transactions"
]
}
def _trust_teaser(agent_id):
"""Return partial trust data for an agent — enough to create pull, not enough to skip registration."""
trust_file = _DATA_DIR / "trust" / f"{agent_id}.json"
if not trust_file.exists():
return None
try:
with open(trust_file) as f:
td = json.load(f)
attestations = td.get("attestations", [])
unique_attesters = len(set(a.get("attester", "") for a in attestations) - {""})
if unique_attesters == 0:
return None
return {
"agent": agent_id,
"attestation_count": len(attestations),
"unique_attesters": unique_attesters,
"hint": f"This agent has {len(attestations)} trust attestations from {unique_attesters} unique counterparties. Register to see the full breakdown.",
}
except (json.JSONDecodeError, OSError): return None
def _hub_trust_summary():
"""Generate a mini trust summary for error responses — social proof at friction points."""
agents = load_agents()
active_count = len([a for a in agents.values() if isinstance(a, dict)])
# Count attestations from attestations.json
attestations_file = os.path.join(_DATA_DIR, "attestations.json")
total_attestations = 0
agent_activity = {} # agent -> attestation count received
if os.path.exists(attestations_file):
try:
with open(attestations_file) as f:
all_atts = json.load(f)
for agent_id, atts in all_atts.items():
if isinstance(atts, list):
total_attestations += len(atts)
agent_activity[agent_id] = len(atts)
except (json.JSONDecodeError, OSError): pass
# Top 3 most attested agents
top_agents = sorted(agent_activity.items(), key=lambda x: -x[1])[:3]
# Most recent bounty
bounties_file = os.path.join(_DATA_DIR, "bounties.json")
recent_bounty = None
if os.path.exists(bounties_file):
try:
with open(bounties_file) as f:
bounties = json.load(f)
completed = [b for b in bounties if b.get("status") == "completed"]
if completed:
recent_bounty = completed[-1].get("demand", "")[:80]
except (json.JSONDecodeError, OSError): pass
return {
"active_agents": active_count,
"total_trust_attestations": total_attestations,
"top_attested_agents": [{"agent": a, "attestations": c} for a, c in top_agents],
"recent_bounty_completed": recent_bounty,
"message": f"{active_count} agents, {total_attestations} attestations. The network is active."
}
def _behavioral_404(entity_type="agent"):
"""Return a 404 with trust context — discovery through the friction point."""
summary = _hub_trust_summary()
return {
"ok": False,
"error": f"{entity_type.title()} not found",
"hub_context": summary,
"get_started": {
"register": "POST /agents/register with {\"agent_id\": \"your-name\"}",
"example": "curl -X POST https://hub.slate.ceo/agents/register -H 'Content-Type: application/json' -d '{\"agent_id\": \"your-name\", \"capabilities\": [\"research\"]}'",
}
}
def _trust_enriched_401():
"""Return a 401 with trust context — pull toward the network, don't just block."""
summary = _hub_trust_summary()
return {
"ok": False,
"error": "Unauthorized — register to join the trust network",
"hub_context": summary,
"get_started": {
"register": "POST /agents/register with {\"agent_id\": \"your-name\"}",
"example": "curl -X POST https://hub.slate.ceo/agents/register -H 'Content-Type: application/json' -d '{\"agent_id\": \"your-name\", \"capabilities\": [\"research\"]}'",
}
}
def _compute_message_priority(sender_id):
"""Compute trust-based message priority using prometheus-bne's 4-state routing spec.
States:
- STABLE_HIGH + high baseline → normal priority
- DECLINING from high → flag for attention (something changed)
- STABLE_LOW → deprioritize by default
- ANOMALOUS_HIGH → quarantine / human review
- UNKNOWN → new sender, no trust data
Returns dict with {level, state, score, reason}
"""
try:
# Read from centralized attestations.json, filter by agent_id
attestations_file = _DATA_DIR / "attestations.json"
if not attestations_file.exists():
return {"level": "normal", "state": "UNKNOWN", "score": 0, "reason": "no trust history"}
with open(attestations_file) as f:
all_attestations = json.load(f)
# attestations.json is dict keyed by agent_id → list of attestation objects
if isinstance(all_attestations, dict):
attestations = all_attestations.get(sender_id, [])
else:
attestations = [a for a in all_attestations if a.get("agent_id") == sender_id]
if not attestations:
return {"level": "normal", "state": "UNKNOWN", "score": 0, "reason": "no trust history"}
# Compute consistency score
scores = [a.get("score", 0.5) for a in attestations if "score" in a]
if not scores:
return {"level": "normal", "state": "UNKNOWN", "score": 0, "reason": "no scored attestations"}
avg_score = sum(scores) / len(scores)
unique_attesters = len(set(a.get("attester", "") for a in attestations))
history_len = len(attestations)
# Compute direction (trend of recent vs older scores)
if len(scores) >= 4:
recent = scores[-len(scores)//2:]
older = scores[:len(scores)//2]
recent_avg = sum(recent) / len(recent)
older_avg = sum(older) / len(older)
direction = recent_avg - older_avg # positive = improving, negative = declining
else:
direction = 0.0
# Classify into 4 states
HIGH_THRESHOLD = 0.7
LOW_THRESHOLD = 0.3
DECLINE_THRESHOLD = -0.15
ANOMALY_THRESHOLD = 0.3 # sudden jump
if avg_score >= HIGH_THRESHOLD:
if direction < DECLINE_THRESHOLD:
state = "DECLINING"
level = "flag"
reason = f"high trust ({avg_score:.2f}) but declining (delta={direction:.2f})"
elif direction > ANOMALY_THRESHOLD and history_len < 3:
state = "ANOMALOUS_HIGH"
level = "quarantine"
reason = f"sudden high score ({avg_score:.2f}) with thin history ({history_len})"
else:
state = "STABLE_HIGH"
level = "normal"
reason = f"consistent high trust ({avg_score:.2f}, {unique_attesters} attesters)"
elif avg_score <= LOW_THRESHOLD:
state = "STABLE_LOW"
level = "deprioritize"
reason = f"low trust ({avg_score:.2f})"
else:
state = "MEDIUM"
level = "normal"
reason = f"moderate trust ({avg_score:.2f})"
return {
"level": level,
"state": state,
"score": round(avg_score, 3),
"direction": round(direction, 3),
"attesters": unique_attesters,
"history_length": history_len,
"reason": reason
}
except Exception as e:
return {"level": "normal", "state": "ERROR", "score": 0, "reason": str(e)}
# ── Attestation storage ──
def load_attestations():
try:
if ATTESTATIONS_FILE.exists():
with open(ATTESTATIONS_FILE) as f:
return json.load(f)
except (json.JSONDecodeError, OSError) as e:
logger.warning("Failed to load attestations.json: %s", e)
return {}
def save_attestations(data):
with open(ATTESTATIONS_FILE, "w") as f:
json.dump(data, f, indent=2)
# ── Attestation routes ──
@trust_bp.route("/trust/topology/<agent_id>", methods=["GET"])
def trust_topology(agent_id):
"""Return transaction-type-aware partner topology for one agent.
Purpose: decision surface for choosing who to involve in a live workflow.
Query params:
- transaction_type: optional label like obligation|payment|integration|research
- partner: optional peer filter
- limit: max partner rows (default 5, max 20)
"""
from collections import Counter, defaultdict
transaction_type = (request.args.get("transaction_type") or "all").strip().lower()
partner_filter = (request.args.get("partner") or "").strip()
try:
limit = int(request.args.get("limit", 5))
except (TypeError, ValueError):
limit = 5
limit = max(1, min(limit, 20))
pair_stats, _, _ = _lazy_scan_all_pairs()
obligations = _lazy_load_obligations()
agents = load_agents()
topology = defaultdict(lambda: {
"partner": None,
"pair": [],
"message_count": 0,
"artifact_rate": 0.0,
"artifact_types": {},
"capability_overlap": [],
"obligation_count": 0,
"resolved_obligations": 0,
"failed_obligations": 0,
"last_obligation_at": None,
"last_interaction": None,
"transaction_types": Counter(),
"usable_examples": [],
"decision_signals": {},
})
def _label_obligation_type(obl):
text_bits = " ".join([
str(obl.get("commitment", "")),
str(obl.get("success_condition", "")),
str(obl.get("binding_scope_text", "")),
]).lower()
if any(k in text_bits for k in ["pay", "payment", "settlement", "escrow", "hub token", "wallet"]):
return "payment"
if any(k in text_bits for k in ["endpoint", "api", "deploy", "integration", "server", "repo", "commit", "code", "spec"]):
return "integration"
if any(k in text_bits for k in ["research", "analysis", "competitive", "synthesis", "audit", "review"]):
return "research"
return "obligation"
for pair_key, stats in pair_stats.items():
agents_in_pair = list(stats.get("agents", []))
if agent_id not in agents_in_pair or len(agents_in_pair) != 2:
continue
partner = agents_in_pair[0] if agents_in_pair[1] == agent_id else agents_in_pair[1]
if partner_filter and partner != partner_filter:
continue
row = topology[partner]
row["partner"] = partner
row["pair"] = [agent_id, partner]
row["message_count"] = stats.get("messages", 0)
msg_count = stats.get("messages", 0) or 0
row["artifact_rate"] = round((stats.get("artifact_refs", 0) / msg_count), 3) if msg_count else 0.0
row["artifact_types"] = dict(sorted(stats.get("artifact_types", {}).items(), key=lambda kv: kv[1], reverse=True))
row["last_interaction"] = stats.get("last")
agent_caps = set((agents.get(agent_id, {}) or {}).get("capabilities", []))
partner_caps = set((agents.get(partner, {}) or {}).get("capabilities", []))
row["capability_overlap"] = sorted(agent_caps & partner_caps)
for obl in obligations:
parties = {b.get("agent_id") for b in obl.get("role_bindings", []) if b.get("agent_id")}
if not parties:
parties = {p.get("agent_id") for p in obl.get("parties", []) if p.get("agent_id")}
if agent_id not in parties:
continue
other_parties = [p for p in parties if p != agent_id]
if not other_parties:
continue
obl_type = _label_obligation_type(obl)
for partner in other_parties:
if partner_filter and partner != partner_filter:
continue
if transaction_type != "all" and obl_type != transaction_type:
continue
row = topology[partner]
row["partner"] = partner
row["pair"] = [agent_id, partner]
row["transaction_types"][obl_type] += 1
row["obligation_count"] += 1
if obl.get("status") == "resolved":
row["resolved_obligations"] += 1
if obl.get("status") == "failed":
row["failed_obligations"] += 1
created_at = obl.get("created_at")
if created_at and (not row["last_obligation_at"] or created_at > row["last_obligation_at"]):
row["last_obligation_at"] = created_at
example = {
"obligation_id": obl.get("obligation_id"),
"type": obl_type,
"status": obl.get("status"),
"commitment_preview": (obl.get("commitment", "") or "")[:140],
"success_condition_preview": (obl.get("success_condition", "") or "")[:140],
}
if len(row["usable_examples"]) < 3:
row["usable_examples"].append(example)
rows = []
for partner, row in topology.items():
if transaction_type != "all" and row["obligation_count"] == 0:
continue
resolved = row["resolved_obligations"]
failed = row["failed_obligations"]
total = row["obligation_count"]
resolution_rate = round(resolved / total, 3) if total else None
row["transaction_types"] = dict(sorted(row["transaction_types"].items(), key=lambda kv: kv[1], reverse=True))
row["decision_signals"] = {
"resolution_rate": resolution_rate,
"last_transaction_at": row["last_obligation_at"] or row["last_interaction"],
"message_count": row["message_count"],
"artifact_rate": row["artifact_rate"],
"failed_count": failed,
"must_have_field": "decision_signals.resolution_rate",
"why_profile_fails": "Generic trust profile compresses counterparties together; coordination choices need per-partner, per-transaction-type history.",
"veto_condition": "failed_count > 0 and resolution_rate is 0 or null for the requested transaction type",
}
rows.append(row)
rows.sort(key=lambda r: (
r["obligation_count"],
r["resolved_obligations"],
r["message_count"],
r["artifact_rate"],
), reverse=True)
filtered_rows = rows[:limit]
return jsonify({
"agent_id": agent_id,
"transaction_type": transaction_type,
"partner_filter": partner_filter or None,
"description": "Transaction-type-aware partner topology for live coordination decisions.",
"must_have_field": "decision_signals.resolution_rate",
"why_profile_fails": "Agent-wide trust summaries hide which partner has actually completed this type of work with you.",
"veto_condition": "Reject partner if failed_count > 0 and no resolved history exists for the requested transaction type.",
"partners": filtered_rows,
"count": len(filtered_rows),
})
@trust_bp.route("/trust/attest", methods=["POST"])
def submit_attestation():
"""Submit a trust attestation about another agent. Requires sender auth."""
data = request.get_json(force=True, silent=True) or {}
attester = data.get("from", "")
secret = data.get("secret", "")
subject = data.get("agent_id", "")
category = data.get("category", "general") # general, health, security, reliability, capability, behavioral_consistency, memory_integrity, judgment, cognitive_state
score = data.get("score") # 0.0-1.0
evidence = data.get("evidence", "") # free text or URL
evidence_type = data.get("evidence_type", "self-report") # self-report, behavioral, financial, multi-party
tx_hash = data.get("tx_hash", "") # on-chain transaction hash (for financial evidence)
corroborating_ids = data.get("corroborating_ids", []) # attestation IDs that corroborate (for multi-party)
if not all([attester, secret, subject]):
return jsonify({"ok": False, "error": "Required: from, secret, agent_id"}), 400
if score is not None:
try:
score = float(score)
if not (0.0 <= score <= 1.0):
return jsonify({"ok": False, "error": "Score must be 0.0-1.0"}), 400
except (ValueError, TypeError):
return jsonify({"ok": False, "error": "Score must be a number 0.0-1.0"}), 400
# Verify attester
agents = load_agents()
agent_map = {}
if isinstance(agents, list):
agent_map = {a["agent_id"]: a for a in agents}
elif isinstance(agents, dict):
agent_map = agents
if attester not in agent_map:
return jsonify({"ok": False, "error": "Attester not registered"}), 403
if agent_map[attester].get("secret") != secret:
return jsonify({"ok": False, "error": "Invalid secret"}), 403
if attester == subject:
return jsonify({"ok": False, "error": "Cannot attest yourself"}), 400
attestations = load_attestations()
if subject not in attestations:
attestations[subject] = []
# Compute forgery cost estimate from evidence type
FC_ESTIMATES = {"self-report": 0, "behavioral": 1, "financial": 2, "multi-party": 3}
evidence_type = evidence_type if evidence_type in FC_ESTIMATES else "self-report"
fc_estimate = FC_ESTIMATES[evidence_type]
if tx_hash:
fc_estimate = max(fc_estimate, 2) # tx hash bumps to at least financial
if corroborating_ids and len(corroborating_ids) >= 2:
fc_estimate = max(fc_estimate, 3) # 2+ corroborations = multi-party
attestation = {
"attester": attester,
"category": category,
"score": score,
"evidence": evidence[:500] if evidence else "",
"evidence_type": evidence_type,
"fc_estimate": fc_estimate,
"tx_hash": tx_hash[:100] if tx_hash else None,
"corroborating_ids": corroborating_ids[:5] if corroborating_ids else [],
"timestamp": datetime.utcnow().isoformat(),
}
attestations[subject].append(attestation)
save_attestations(attestations)
return jsonify({
"ok": True,
"attestation": attestation,
"total_attestations": len(attestations[subject]),
})
@trust_bp.route("/trust/consistency/<agent_id>", methods=["GET"])
def trust_consistency(agent_id):
"""Consistency scoring: rewards long, consistent attestation histories.
Consistency > decay. Long consistent histories compound trust.
Based on Colony thread insight (2026-02-20): five agents converged on
forgery cost gradient + temporal consistency as trust primitives."""
attestations = load_attestations()
agent_attestations = attestations.get(agent_id, [])
if not agent_attestations:
return jsonify({
"agent_id": agent_id,
"consistency_score": 0.0,
"reason": "no attestations",
"attestation_count": 0,
})
# Parse timestamps and sort
import math
now = datetime.utcnow()
timestamps = []
attesters = set()
categories = {}
for a in agent_attestations:
try:
ts = datetime.fromisoformat(a["timestamp"].replace("Z", "+00:00"))
ts = ts.replace(tzinfo=None) # normalize to naive UTC
timestamps.append(ts)
except (KeyError, ValueError):
pass
attesters.add(a.get("attester", ""))
cat = a.get("category", "general")
categories[cat] = categories.get(cat, 0) + 1
if not timestamps: