-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
1044 lines (939 loc) · 53 KB
/
Copy pathcore.py
File metadata and controls
1044 lines (939 loc) · 53 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
"""Shared register/attest/verify logic — ONE implementation behind both surfaces.
The MCP tools (tools/*.py, used by MCP/SSE clients) and the REST routes
(server.py /v1/register|attest|verify, used by the mint-attest Python SDK and any
HTTP client) both call these functions, so the two surfaces can never drift.
`api_key` is the per-request Forge key. Over MCP it's None → the server's service
key is used. Over REST it's the SDK developer's fnet_ key, passed through to Forge
so the actor + its attestations belong to THEIR account (Forge's /v1/attest
ownership check requires register + attest to use the same key).
"""
from __future__ import annotations
import hashlib
import json
import logging
import uuid
from datetime import datetime, timedelta, timezone
from typing import Optional
import actor_registry
import config
import forge_client
import merkle_batch
import ml_scorer
import okf_reliability
import payment_gate
import supa
import trust
import trust_engine
logger = logging.getLogger("mint.core")
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _data_hash(payload: dict) -> str:
"""sha256 over canonical JSON (sorted keys, no whitespace) — the reproducible
off-chain commitment. Same canonicalization Forge /v1/attest uses, so a hash
can be recomputed and checked independently."""
return hashlib.sha256(
json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
.encode("utf-8")).hexdigest()
async def _resolve_rater(api_key: Optional[str], claimed: Optional[str]) -> dict:
"""Bind a rater/recommender to a mint_id their fnet_ key actually owns.
Returns {"mint_id": …} on success or {"error": …} otherwise. Anti-spam: only
a real Forge account can rate, and only as an actor it controls. `claimed`
(if given) must be among the key's owned mint_ids; otherwise we auto-pick when
the key owns exactly one actor, and ask for disambiguation when it owns many.
"""
if not api_key:
return {"error": "not_configured",
"detail": "An fnet_ API key is required to identify the rater "
"(pass Authorization: Bearer for REST, or set FORGE_API_KEY)."}
who = await forge_client.whoami(api_key)
if "error" in who:
return who
user_id = who.get("user_id")
if not user_id:
return {"error": "http_401", "detail": "Key did not resolve to an account."}
owned = await supa.owner_mint_ids(user_id)
if claimed:
if claimed not in owned:
return {"error": "forbidden",
"detail": f"{claimed} is not owned by this API key. You can only "
f"rate/recommend as an actor your key controls."}
return {"mint_id": claimed}
if len(owned) == 1:
return {"mint_id": owned[0]}
if not owned:
return {"error": "bad_request",
"detail": "This key owns no registered actor. Register one first "
"(mint_register) so your rating is attributable."}
return {"error": "bad_request",
"detail": f"This key owns {len(owned)} actors; pass rater_mint_id / "
f"recommender_mint_id to say which one is rating."}
# ── register ──────────────────────────────────────────────────────────────────
VALID_ACTOR_TYPES = {"ai_agent", "machine", "iot_device", "service"}
_SERIAL_NS = uuid.UUID("4d494e54-0000-4000-8000-000000000001") # "MINT"
def derive_serial(actor_type: str, name: str, operator: Optional[str]) -> str:
"""Stable, idempotent serial for one logical actor; distinct per operator."""
seed = f"{actor_type}|{name}|{operator or ''}".lower()
return uuid.uuid5(_SERIAL_NS, seed).hex
async def do_register(actor_type: str, name: str,
capabilities: Optional[list] = None,
operator: Optional[str] = None,
metadata: Optional[dict] = None,
mcp_endpoint: Optional[str] = None,
description: Optional[str] = None,
api_key: Optional[str] = None) -> dict:
atype = (actor_type or "").strip().lower()
if atype not in VALID_ACTOR_TYPES:
return {"error": "bad_request",
"detail": f"actor_type must be one of {sorted(VALID_ACTOR_TYPES)}, got {actor_type!r}"}
if not (name or "").strip():
return {"error": "bad_request", "detail": "name is required"}
# Autonomous self-registration: the caller passed NO fnet_ key, so provision
# a fresh MINT identity AND a scoped fnet_ key in one call — no human, no
# signup. (A caller WITH a key registers under their own account, below.)
if api_key is None:
return await _autonomous_register(atype, name, capabilities, operator,
metadata, mcp_endpoint, description)
if not forge_client.configured(api_key):
return {"error": "not_configured",
"detail": "No Forge API key available (pass an fnet_ key or set FORGE_API_KEY)."}
serial = derive_serial(atype, name, operator)
meta = dict(metadata or {})
meta.update({"mint_actor_type": atype, "mint_actor_name": name,
"mint_capabilities": capabilities or []})
if operator:
meta["mint_operator"] = operator
resp = await forge_client.identify(oem=atype, model=name, serial=serial,
site=operator, metadata=meta, api_key=api_key)
if "error" in resp:
return resp
mint_id = resp.get("mint_id")
machine = resp.get("machine") or {}
if mint_id:
actor_registry.remember(mint_id, actor_type=atype, name=name,
capabilities=capabilities, operator=operator)
await _add_to_directory(mint_id, atype, name, capabilities, operator,
mcp_endpoint, description)
return {
"mint_id": mint_id, "actor_type": atype, "name": name,
"capabilities": capabilities or [], "operator": operator,
"mcp_endpoint": mcp_endpoint, "description": description,
"registered": True, "newly_registered": bool(resp.get("created")),
"first_seen": resp.get("first_seen"),
"wallet_address": machine.get("wallet_address"),
"status": machine.get("status", "active"), "trust_score": 50,
"discoverable": supa.configured(),
"note": ("Identity is persistent and on-chain. Use this mint_id for "
"attest (prove work), rate/recommend (build trust), and verify "
"or discover (query trust). New actors start at trust 50."),
}
async def _add_to_directory(mint_id: str, actor_type: str, name: str,
capabilities: Optional[list], operator: Optional[str],
mcp_endpoint: Optional[str], description: Optional[str]) -> None:
"""Best-effort: make the actor discoverable + seed a neutral trust score.
Never fails registration — identity already succeeded on Forge."""
if not supa.configured():
return
await supa.upsert_actor(mint_id, name=name, actor_type=actor_type,
capabilities=capabilities, operator=operator,
mcp_endpoint=mcp_endpoint, description=description)
if await supa.get_trust(mint_id) is None:
await supa.upsert_trust(mint_id, {"trust_score": 50})
# Trust-engine state (ported on-chain MachineState): create the agent's row so
# mint_attest can quality-score against it. Idempotent + best-effort — a repeat
# register no-ops, and a failure here never fails registration.
await supa.create_agent(mint_id)
async def _autonomous_register(actor_type: str, name: str,
capabilities: Optional[list], operator: Optional[str],
metadata: Optional[dict],
mcp_endpoint: Optional[str] = None,
description: Optional[str] = None) -> dict:
"""No-key path: Forge mints a fresh identity AND a scoped fnet_ key in one
anonymous call. The agent gets everything it needs to attest — no human."""
resp = await forge_client.autonomous_register(
actor_type=actor_type, name=name, capabilities=capabilities,
operator=operator, metadata=metadata)
if "error" in resp:
return resp
mint_id = resp.get("mint_id")
if mint_id:
actor_registry.remember(mint_id, actor_type=actor_type, name=name,
capabilities=capabilities, operator=operator)
await _add_to_directory(mint_id, actor_type, name, capabilities, operator,
mcp_endpoint, description)
return {
"mint_id": mint_id,
"api_key": resp.get("api_key"), # one-shot — the agent MUST persist it
"actor_type": actor_type, "name": name,
"capabilities": capabilities or [], "operator": operator,
"mcp_endpoint": mcp_endpoint, "description": description,
"registered": True, "autonomous": True, "trust_score": 50,
"discoverable": supa.configured(),
"wallet_address": resp.get("wallet_address"),
"daily_attest_limit": resp.get("daily_attest_limit"),
"note": ("Identity + key provisioned with no human in the loop. PERSIST "
"api_key — it is shown once, is scoped to this mint_id, and is "
"required to attest. Register is free; attest is metered (free up "
"to the daily cap, then pay via x402 or a metered key)."),
}
# ── attest ────────────────────────────────────────────────────────────────────
VALID_WORK_TYPES = {"code_review", "normalization", "research", "generation",
"analysis", "delivery", "manufacturing", "custom"}
_WORK_COMPLEXITY = {"code_review": 1500, "analysis": 1400, "research": 1300,
"manufacturing": 1200, "generation": 1100, "normalization": 1000,
"custom": 1000, "delivery": 700}
async def do_attest(mint_id: str, work_type: str, duration_seconds,
summary: str = "", input_hash: Optional[str] = None,
output_hash: Optional[str] = None, metadata: Optional[dict] = None,
payment_tx: Optional[str] = None, api_key: Optional[str] = None) -> dict:
if not (mint_id or "").startswith("MINT-"):
return {"error": "bad_request",
"detail": f"mint_id must look like 'MINT-xxxxxx', got {mint_id!r}. Register first."}
wtype = (work_type or "").strip().lower()
if wtype not in VALID_WORK_TYPES:
return {"error": "bad_request",
"detail": f"work_type must be one of {sorted(VALID_WORK_TYPES)}, got {work_type!r}"}
try:
duration_seconds = int(duration_seconds)
except (TypeError, ValueError):
return {"error": "bad_request", "detail": "duration_seconds must be an integer"}
if duration_seconds <= 0:
return {"error": "bad_request", "detail": "duration_seconds must be > 0"}
if not forge_client.configured(api_key):
return {"error": "not_configured",
"detail": "No Forge API key available (pass an fnet_ key or set FORGE_API_KEY)."}
# ── Trust-engine ban gate (ported on-chain MachineBanned) ──
# Reject a banned agent UP FRONT with a clear error — before the payment gate,
# so a banned agent is never shown a 402 (per the task constraint). Only the
# merkle-batch path runs the engine; the legacy per-PDA path keeps its on-chain
# ban check. agent_state is reused below to avoid a second fetch.
agent_state: Optional[dict] = None
if config.MERKLE_ANCHOR_ENABLED and supa.configured():
agent_state = await supa.get_or_create_agent(mint_id)
if agent_state.get("is_banned"):
return {"error": "agent_banned",
"detail": (f"{mint_id} is banned (repeat zero-trust) and can no longer "
"attest. This status is terminal for the identity."),
"mint_id": mint_id, "is_banned": True,
"trust_score": agent_state.get("trust_score", 0)}
# Pay-per-attest gate (2¢ USDC on Solana). Inert unless armed; an fnet_ key or
# a live retry credit bypasses it. A "blocked" decision returns the 402 body
# verbatim — the REST layer maps error=payment_required to HTTP 402, and an MCP
# client reads the {"status": 402, "payment_required": {…}} dict directly.
intent = payment_gate.intent_id(mint_id, wtype, duration_seconds, summary,
input_hash, output_hash, metadata)
decision = await payment_gate.precheck(mint_id, intent, payment_tx, api_key)
if decision["gate"] == "blocked":
return decision["body"]
# NEW — merkle batch flow (default): record the attestation off-chain and queue
# it for batch anchoring, returning immediately. ONE on-chain tx anchors the
# merkle root of a whole batch (merkle_batch.py), replacing the per-attestation
# recordJob/settleJob/updateTrust that cost ~0.002 SOL each. The kill switch
# MERKLE_ANCHOR_ENABLED=false drops to the per-attestation Forge path below.
if config.MERKLE_ANCHOR_ENABLED:
return await _attest_batched(mint_id, wtype, duration_seconds, summary,
input_hash, output_hash, metadata, decision,
agent_state=agent_state)
complexity = _WORK_COMPLEXITY.get(wtype, 1000)
receipt = await forge_client.attest(
mint_id, duration_seconds, complexity=complexity, work_type=wtype,
input_hash=input_hash, output_hash=output_hash, summary=summary,
metadata=metadata, api_key=api_key)
if "error" in receipt:
# Attestation failed AFTER payment cleared — settle() grants a 24h retry
# credit so the agent isn't out the 2¢, then we surface the failure.
await payment_gate.settle(decision, mint_id, attestation_id=None, ok=False)
out = {"error": "attest_failed", "detail": receipt,
"hint": "On-chain anchor failed; nothing was minted. Retry."}
if decision["gate"] in ("paid", "credit"):
out["payment_status"] = "credited"
out["hint"] = ("On-chain anchor failed; nothing was minted. Your payment "
"is preserved as a one-time retry credit (valid 24h) — "
"retry the SAME request with no new payment.")
return out
actor_registry.record_work(mint_id, wtype)
attestation_id = receipt.get("attestation_id")
# Attestation succeeded — finalize the revenue ledger row against the real
# attestation_id (no-op for the api_key/open paths).
await payment_gate.settle(decision, mint_id, attestation_id=attestation_id, ok=True)
tx = receipt.get("tx_signature")
verify_url = receipt.get("verify_url") or (
f"{config.SOLSCAN_TX_BASE}/{tx}" if tx else None)
out = {
"attestation_id": attestation_id, "mint_id": mint_id,
"work_type": wtype, "data_hash": receipt.get("data_hash"),
"tx_signature": tx, "verify_url": verify_url,
"trust_score": receipt.get("trust_score"), "reward": receipt.get("reward"),
"settled": bool(receipt.get("settled", bool(tx))),
"note": ("On-chain anchor is real; verify_url is a live Solscan link, and "
"this attestation permanently accrues to the actor's mint_id."),
}
if decision["gate"] == "paid":
out["payment"] = {"method": "x402", "paid_usdc": decision.get("amount_usdc"),
"payment_tx": decision.get("payment_tx"), "payer": decision.get("payer")}
elif decision["gate"] == "credit":
out["payment"] = {"method": "retry_credit"}
return out
async def _attest_batched(mint_id: str, wtype: str, duration_seconds: int,
summary: str, input_hash: Optional[str],
output_hash: Optional[str], metadata: Optional[dict],
decision: dict, agent_state: Optional[dict] = None) -> dict:
"""Quality-score the attestation server-side (ported on-chain trust engine + ML
scorer), record it WITH the scores, apply the trust delta to the agent, advance
the rolling network window, and queue it for the next merkle batch anchor —
returning immediately. No on-chain calls.
Scoring is deterministic and fail-open: the model is sub-ms, and any scorer
error defaults to (ml_confidence=500, trust_delta=0) so an attestation is never
blocked on the scorer. State persistence is best-effort — the paid attestation
is the durable artifact; a trust-state write blip is logged, not surfaced."""
now_iso = _now_iso()
# ── 1. Score (ported on-chain engine + ML). Pure + deterministic; compute <1ms. ──
if agent_state is None: # REST callers / merkle-off ban-skip
agent_state = await supa.get_or_create_agent(mint_id)
network_state = await supa.get_network_state() if supa.configured() else {}
# complexity is derived from work_type (the SDK doesn't pass one), clamped to the
# on-chain protocol range — same convention as the legacy per-PDA path.
complexity_claimed = trust_engine.clamp_complexity(_WORK_COMPLEXITY.get(wtype, 1000))
job_count = int(agent_state.get("job_count") or 0)
# network_avg + warmup use the PRE-update window/job_count, exactly like record_job.
net_avg = trust_engine.network_avg_complexity(
int(network_state.get("window_complexity_sum") or 0),
int(network_state.get("window_jobs") or 0))
normalized_complexity = trust_engine.normalize_complexity(complexity_claimed, net_avg)
warmup = trust_engine.warmup_multiplier(job_count)
base_score = trust_engine.compute_base_score(duration_seconds, normalized_complexity, warmup)
# Rolling 1h attestation count for the scorer's rate-anomaly feature (one cheap
# COUNT; excludes this in-flight attestation, which isn't recorded yet).
jobs_last_hour = await supa.jobs_in_last_hour(mint_id) if supa.configured() else 0
ml_confidence, trust_delta = ml_scorer.score_attestation(
{"work_type": wtype, "duration_seconds": duration_seconds,
"complexity_claimed": complexity_claimed, "input_hash": input_hash,
"output_hash": output_hash, "summary": summary, "metadata": metadata,
"jobs_last_hour_machine": jobs_last_hour},
agent_state, network_state)
delta_res = trust_engine.apply_trust_delta(
int(agent_state.get("trust_score") if agent_state.get("trust_score") is not None
else trust_engine.TRUST_START),
trust_delta,
was_on_probation=bool(agent_state.get("on_probation")),
probation_count=int(agent_state.get("probation_count") or 0),
now_iso=now_iso)
new_trust = delta_res["new_trust"]
on_probation = delta_res["on_probation"]
is_banned = delta_res["is_banned"]
trust_weighted = trust_engine.trust_weighted_score(base_score, new_trust, on_probation=on_probation)
scores = {
"ml_confidence": ml_confidence, "trust_delta": trust_delta,
"base_score": base_score, "trust_weighted_score": trust_weighted,
"complexity_claimed": complexity_claimed,
"normalized_complexity": normalized_complexity,
}
# ── 2. Record the attestation WITH its scores. The scores are merged AFTER the
# attestation_hash is computed (in record_attestation), so the merkle leaf stays
# reproducible from the canonical work payload alone. ──
rec = await merkle_batch.record_attestation(
mint_id=mint_id, work_type=wtype, duration_seconds=duration_seconds,
summary=summary, input_hash=input_hash, output_hash=output_hash,
metadata=metadata, payment_tx=decision.get("payment_tx"), scores=scores)
if "error" in rec:
# Recording failed AFTER payment cleared — make the agent whole with a
# one-shot 24h retry credit, exactly like the old on-chain-failure path.
await payment_gate.settle(decision, mint_id, attestation_id=None, ok=False)
out = {"error": "attest_failed", "detail": rec.get("detail"),
"hint": "Could not record the attestation; nothing accrued. Retry."}
if decision["gate"] in ("paid", "credit"):
out["payment_status"] = "credited"
out["hint"] = ("Could not record the attestation; your payment is preserved "
"as a one-time retry credit (valid 24h) — retry the SAME "
"request with no new payment.")
return out
attestation_id = rec["attestation_id"]
actor_registry.record_work(mint_id, wtype)
# The attestation IS recorded and valid; anchoring is a later durability step
# that never re-charges the agent. So payment settles successfully now.
await payment_gate.settle(decision, mint_id, attestation_id=attestation_id, ok=True)
# ── 3. Persist updated agent + network state (best-effort; never blocks). ──
await _persist_engine_state(mint_id, duration_seconds, complexity_claimed,
agent_state, network_state, delta_res, now_iso)
# ── 4. Keep the social/directory trust fresh (volume axis) — best-effort. This
# is the existing reputation score served by verify/discover; the engine
# trust_score (new_trust) is separate and is what the receipt reports. ──
if supa.configured():
try:
await trust.recompute(mint_id)
except Exception:
pass
out = {
"attestation_id": attestation_id, "mint_id": mint_id, "work_type": wtype,
"data_hash": rec["data_hash"], "attestation_hash": rec["attestation_hash"],
"ml_confidence": ml_confidence,
"trust_score": new_trust,
"trust_delta": trust_delta,
"base_score": base_score,
"trust_weighted_score": trust_weighted,
"complexity_claimed": complexity_claimed,
"normalized_complexity": normalized_complexity,
"on_probation": on_probation,
"status": "attested", "anchored": False, "pending_anchor": True,
"anchor_eta": merkle_batch.next_anchor_eta(),
"scorer": ml_scorer.model_info().get("scorer"),
"note": ("Attestation scored, recorded and paid. trust_score + trust_delta come "
"from the server-side trust engine (ported on-chain scoring); "
"ml_confidence is the model's read on whether the work is genuine. It "
"anchors in the next merkle batch — ONE Solana tx covers the batch. "
"Verify with this attestation_hash for the on-chain proof once anchored."),
}
if on_probation:
out["note"] = ("Attestation recorded, but the agent's trust is at zero "
"(probation): it accrues no trust-weighted score until trust "
"recovers. " + out["note"])
if is_banned:
out["is_banned"] = True
out["note"] = ("Attestation recorded, but this delta drove trust to zero a "
"second time — the agent is now BANNED and cannot attest again.")
if decision["gate"] == "paid":
out["payment"] = {"method": "x402", "paid_usdc": decision.get("amount_usdc"),
"payment_tx": decision.get("payment_tx"), "payer": decision.get("payer")}
elif decision["gate"] == "credit":
out["payment"] = {"method": "retry_credit"}
return out
async def _persist_engine_state(mint_id: str, duration_seconds: int, complexity_claimed: int,
agent_state: dict, network_state: dict, delta_res: dict,
now_iso: str) -> None:
"""Write the post-attestation agent + network state (mirrors record_job's counter
bumps + update_trust's trust write). Best-effort: a Supabase blip is logged, not
raised — the attestation is already recorded and paid."""
if not supa.configured():
return
try:
agent_update = {
"trust_score": delta_res["new_trust"],
"job_count": int(agent_state.get("job_count") or 0) + 1,
"total_duration": int(agent_state.get("total_duration") or 0) + int(duration_seconds),
"complexity_sum": int(agent_state.get("complexity_sum") or 0) + int(complexity_claimed),
"is_banned": delta_res["is_banned"],
"on_probation": delta_res["on_probation"],
"probation_count": delta_res["probation_count"],
"last_job_at": now_iso,
}
pstarted = delta_res["probation_started_at"]
if pstarted is None: # recovered → clear the stamp
agent_update["probation_started_at"] = None
elif pstarted != "__keep__": # entered probation → set the stamp
agent_update["probation_started_at"] = pstarted
# (pstarted == "__keep__" → leave the column untouched)
await supa.update_agent(mint_id, agent_update)
# Network rolling window (maybe_rotate_window + the post-job increments).
if trust_engine.should_rotate_window(network_state.get("window_start")):
wj = wd = wc = 0
wstart = now_iso
else:
wj = int(network_state.get("window_jobs") or 0)
wd = int(network_state.get("window_duration") or 0)
wc = int(network_state.get("window_complexity_sum") or 0)
wstart = network_state.get("window_start") or now_iso
await supa.update_network_state({
"total_jobs": int(network_state.get("total_jobs") or 0) + 1,
"total_duration": int(network_state.get("total_duration") or 0) + int(duration_seconds),
"total_complexity_sum": int(network_state.get("total_complexity_sum") or 0) + int(complexity_claimed),
"window_jobs": wj + 1,
"window_duration": wd + int(duration_seconds),
"window_complexity_sum": wc + int(complexity_claimed),
"window_start": wstart,
})
except Exception as e:
logger.warning(f"trust-engine state persist failed for {mint_id}: {e}")
# ── verify ────────────────────────────────────────────────────────────────────
_PENDING_NOTE = (
"Trust score + on-chain attestation history are served by Forge's trust-read "
"endpoint, which is rolling out next. Attestations are already permanent "
"on-chain and will surface here once the read endpoint is wired.")
async def _engine_summary(mint_id: str) -> dict:
"""The trust-engine view of an actor: its mint_agents state plus quality
aggregates (avg trust-weighted score / ML confidence) over its scored
attestations. Used by verify/rate/recommend so consumers see QUALITY, not just
attestation count. Returns {} when Supabase is unconfigured."""
if not supa.configured():
return {}
agent = await supa.get_agent(mint_id) or {}
rows = await supa.attestations_for_mint(mint_id, limit=200)
tw = [int(r["trust_weighted_score"]) for r in rows
if r.get("trust_weighted_score") is not None]
mlc = [int(r["ml_confidence"]) for r in rows if r.get("ml_confidence") is not None]
return {
"trust_score": agent.get("trust_score"),
"job_count": agent.get("job_count"),
"on_probation": agent.get("on_probation"),
"is_banned": agent.get("is_banned"),
"probation_count": agent.get("probation_count"),
"last_job_at": agent.get("last_job_at"),
"avg_trust_weighted_score": round(sum(tw) / len(tw), 2) if tw else None,
"avg_ml_confidence": round(sum(mlc) / len(mlc), 1) if mlc else None,
"scored_attestations": len(tw),
}
async def _verify_attestation(attestation_hash: str) -> dict:
"""Verify ONE attestation by its hash: where it sits in the anchoring pipeline
and (once anchored) the merkle proof that lets anyone confirm its inclusion
under the on-chain root without trusting FoundryNet."""
row = await merkle_batch.get_attestation(attestation_hash)
if not row:
return {"error": "not_found",
"detail": f"No attestation with attestation_hash={attestation_hash!r} "
"is known on this instance.", "verifiable": True}
base = {
"attestation_id": row.get("id"), "mint_id": row.get("mint_id"),
"work_type": row.get("work_type"), "data_hash": row.get("data_hash"),
"attestation_hash": row.get("attestation_hash"),
"duration_seconds": row.get("duration_seconds"), "summary": row.get("summary"),
"payment_tx": row.get("payment_tx"), "created_at": row.get("created_at"),
# trust-engine scores stored with the attestation (None for pre-engine rows)
"ml_confidence": row.get("ml_confidence"), "trust_delta": row.get("trust_delta"),
"base_score": row.get("base_score"),
"trust_weighted_score": row.get("trust_weighted_score"),
"complexity_claimed": row.get("complexity_claimed"),
"normalized_complexity": row.get("normalized_complexity"),
}
if row.get("status") == "anchored":
root, proof, tx = row.get("merkle_root"), row.get("merkle_proof") or [], row.get("anchor_tx")
return {
**base, "status": "anchored", "anchored": True,
"merkle_root": root, "merkle_proof": proof, "anchor_tx": tx,
"batch_id": row.get("batch_id"), "anchored_at": row.get("anchored_at"),
"verify_url": f"{config.SOLSCAN_TX_BASE}/{tx}" if tx else None,
"proof_valid": merkle_batch.verify_proof(row.get("attestation_hash"), proof, root),
"verification": "merkle-inclusion", "verifiable": True,
"note": ("Independently verifiable: fold merkle_proof into "
"sha256(0x00 || attestation_hash) and confirm the result equals "
"merkle_root, which is written in the SPL-memo of anchor_tx on "
"Solana. No trust in FoundryNet required."),
}
return {
**base, "status": "attested", "anchored": False, "pending_anchor": True,
"anchor_eta": merkle_batch.next_anchor_eta(),
"verification": "recorded", "verifiable": True,
"note": ("Recorded and paid for, not yet anchored on-chain. It will be "
"included in the next merkle batch (one tx anchors the whole batch). "
"Re-verify with this attestation_hash to get the proof once anchored."),
}
async def do_verify(mint_id: Optional[str] = None, actor_name: Optional[str] = None,
actor_type: Optional[str] = None,
attestation_hash: Optional[str] = None) -> dict:
# Attestation-level verification: prove a specific unit of work is anchored.
if attestation_hash:
return await _verify_attestation(attestation_hash)
local: Optional[dict] = None
if mint_id:
local = actor_registry.lookup(mint_id)
elif actor_name:
found = actor_registry.find_by_name(actor_name, actor_type)
if found:
mint_id, local = found
else:
return {"error": "bad_request", "detail": "Provide either mint_id or actor_name."}
if not mint_id:
return {"error": "not_found",
"detail": f"No mint_id known on this instance for actor_name={actor_name!r}. "
"Pass the mint_id directly.", "verifiable": True}
if not mint_id.startswith("MINT-"):
return {"error": "bad_request",
"detail": f"mint_id must look like 'MINT-xxxxxx', got {mint_id!r}"}
# Trust layer live: serve the real profile (trust score, ratings,
# recommendations, work-type breakdown) from Supabase, enriched with the
# actor's recent attestations and their on-chain anchor status. Falls back to
# the identity-only "pending" shape only if the trust store isn't configured.
if supa.configured():
prof = await trust.profile(mint_id, local)
try:
atts = await merkle_batch.attestations_for_mint(mint_id, limit=10)
if atts:
prof["recent_attestations"] = [
{"attestation_hash": a.get("attestation_hash"),
"work_type": a.get("work_type"), "status": a.get("status"),
"anchored": a.get("status") == "anchored",
"anchor_tx": a.get("anchor_tx"), "merkle_root": a.get("merkle_root"),
# trust-engine scores recorded with each attestation
"ml_confidence": a.get("ml_confidence"),
"trust_delta": a.get("trust_delta"),
"base_score": a.get("base_score"),
"trust_weighted_score": a.get("trust_weighted_score"),
"at": a.get("created_at")}
for a in atts]
prof["unanchored_attestations"] = sum(
1 for a in atts if a.get("status") != "anchored")
except Exception:
pass
# Trust-engine view (ported on-chain MachineState + quality aggregates).
# Distinct from the reputation `trust_score` above (ratings/recs-driven):
# this is the ML-scored quality trust that starts at 100 and moves per attest.
try:
prof["trust_engine"] = await _engine_summary(mint_id)
except Exception:
pass
return prof
return {
"mint_id": mint_id, "registered": local is not None,
"actor_type": (local or {}).get("actor_type"), "name": (local or {}).get("name"),
"capabilities": (local or {}).get("capabilities", []),
"operator": (local or {}).get("operator"),
"trust_score": "pending", "total_attestations": "pending",
"work_types": (local or {}).get("work_types", {}),
"recent_attestations": [], "verification": "on-chain", "verifiable": True,
"trust_read_status": "pending_forge_endpoint", "note": _PENDING_NOTE,
}
# ── rate ──────────────────────────────────────────────────────────────────────
async def do_rate(attestation_id: str, rated_mint_id: str, score,
rater_mint_id: Optional[str] = None, accuracy: bool = True,
would_use_again: bool = True, tags: Optional[list] = None,
comment: Optional[str] = None, api_key: Optional[str] = None) -> dict:
"""Record a 1–5 rating of a completed attestation and recompute the rated
actor's trust. FREE.
Enforced today: score range, no self-rating, one rating per (attestation,
rater), and that the rater is bound to an identity their fnet_ key owns
(anti-spam). NOTE: Forge attestations don't yet record a separate paying
party, so the "rater must be the buyer of THIS attestation" check is not
cryptographically enforced — the rater is bound to a real owned actor
instead. The hook is here for when Forge records counterparties.
"""
if not (attestation_id or "").strip():
return {"error": "bad_request", "detail": "attestation_id is required"}
if not (rated_mint_id or "").startswith("MINT-"):
return {"error": "bad_request",
"detail": f"rated_mint_id must look like 'MINT-xxxxxx', got {rated_mint_id!r}"}
try:
score = int(score)
except (TypeError, ValueError):
return {"error": "bad_request", "detail": "score must be an integer 1–5"}
if not 1 <= score <= 5:
return {"error": "bad_request", "detail": "score must be between 1 and 5"}
if not supa.configured():
return {"error": "not_configured", "detail": "Trust store (Supabase) is not configured."}
resolved = await _resolve_rater(api_key, rater_mint_id)
if "error" in resolved:
return resolved
rater = resolved["mint_id"]
if rater == rated_mint_id:
return {"error": "bad_request", "detail": "You can't rate yourself."}
if await supa.rating_exists(attestation_id, rater):
return {"error": "conflict",
"detail": f"{rater} already rated attestation {attestation_id}."}
tags = [str(t) for t in (tags or [])]
payload = {"attestation_id": attestation_id, "rater_mint_id": rater,
"rated_mint_id": rated_mint_id, "score": score, "accuracy": bool(accuracy),
"would_use_again": bool(would_use_again), "tags": tags, "comment": comment or ""}
data_hash = _data_hash(payload)
row = {**payload, "data_hash": data_hash}
res = await supa.insert_rating(row)
if "error" in res:
# unique-violation ⇒ raced with another rating
if str(res.get("error")).endswith("409") or "duplicate" in str(res).lower():
return {"error": "conflict",
"detail": f"{rater} already rated attestation {attestation_id}."}
return {"error": "rate_failed", "detail": res}
rating_id = (res.get("data") or [{}])[0].get("id")
updated = await trust.recompute(rated_mint_id)
engine = await _engine_summary(rated_mint_id)
return {
"rating_id": rating_id, "attestation_id": attestation_id,
"rated_mint_id": rated_mint_id, "rater_mint_id": rater, "score": score,
"tags": tags, "data_hash": data_hash,
"trust_score_updated": updated.get("trust_score"), # reputation score (ratings/recs)
# Trust-engine state of the rated actor (ported on-chain MachineState):
"trust_score": engine.get("trust_score"),
"job_count": engine.get("job_count"),
"on_probation": engine.get("on_probation"),
"is_banned": engine.get("is_banned"),
"agent_state": engine,
"status": "recorded",
"note": ("Rating recorded and the rated actor's trust recomputed. trust_score + "
"job_count + probation come from the trust engine; trust_score_updated "
"is the ratings/recommendations reputation score. data_hash is the "
"reproducible off-chain commitment."),
}
# ── recommend ─────────────────────────────────────────────────────────────────
async def do_recommend(recommended_mint_id: str, context: str, score,
note: Optional[str] = None, recommender_mint_id: Optional[str] = None,
attestation_id: Optional[str] = None,
api_key: Optional[str] = None) -> dict:
"""Record a peer recommendation (1–5) for an actor in a named context and
recompute that actor's trust. FREE.
Enforced today: score range, no self-recommendation, one recommendation per
(recommender, recommended, context), and recommender bound to a key-owned
identity. NOTE: "must have worked with the actor" requires a cross-actor
transaction record Forge doesn't expose yet, so it's not enforced here —
documented rather than faked.
"""
if not (recommended_mint_id or "").startswith("MINT-"):
return {"error": "bad_request",
"detail": f"recommended_mint_id must look like 'MINT-xxxxxx', got {recommended_mint_id!r}"}
if not (context or "").strip():
return {"error": "bad_request", "detail": "context is required"}
try:
score = int(score)
except (TypeError, ValueError):
return {"error": "bad_request", "detail": "score must be an integer 1–5"}
if not 1 <= score <= 5:
return {"error": "bad_request", "detail": "score must be between 1 and 5"}
if not supa.configured():
return {"error": "not_configured", "detail": "Trust store (Supabase) is not configured."}
resolved = await _resolve_rater(api_key, recommender_mint_id)
if "error" in resolved:
return resolved
recommender = resolved["mint_id"]
if recommender == recommended_mint_id:
return {"error": "bad_request", "detail": "You can't recommend yourself."}
context = context.strip()
payload = {"recommender_mint_id": recommender, "recommended_mint_id": recommended_mint_id,
"context": context, "score": score, "note": note or "",
"attestation_id": attestation_id}
data_hash = _data_hash(payload)
row = {**payload, "data_hash": data_hash}
res = await supa.insert_recommendation(row)
if "error" in res:
if str(res.get("error")).endswith("409") or "duplicate" in str(res).lower():
return {"error": "conflict",
"detail": (f"{recommender} already recommended {recommended_mint_id} "
f"for context {context!r}.")}
return {"error": "recommend_failed", "detail": res}
recommendation_id = (res.get("data") or [{}])[0].get("id")
updated = await trust.recompute(recommended_mint_id)
engine = await _engine_summary(recommended_mint_id)
return {
"recommendation_id": recommendation_id,
"recommended_mint_id": recommended_mint_id,
"recommender_mint_id": recommender, "context": context, "score": score,
"data_hash": data_hash, "trust_score_updated": updated.get("trust_score"),
# Quality context for the endorsed actor — trust-weighted-score average (not
# just attestation count), so an endorsement is weighed against real quality.
"trust_score": engine.get("trust_score"),
"avg_trust_weighted_score": engine.get("avg_trust_weighted_score"),
"scored_attestations": engine.get("scored_attestations"),
"agent_state": engine,
"status": "recorded",
"note": ("Recommendation recorded and the recommended actor's trust recomputed. "
"avg_trust_weighted_score reflects the engine's quality-weighted score "
"across its scored attestations, not just attestation volume."),
}
# ── discover ──────────────────────────────────────────────────────────────────
_SORTS = {"trust_score", "recommendations", "recent"}
def _cap_match(actor: dict, q: str) -> bool:
"""Loose capability/text match: normalize spaces↔underscores, case-fold, and
substring-match against capabilities, name, and description."""
norm = q.lower().replace(" ", "_")
hay = "_".join([
*(str(c).lower() for c in (actor.get("capabilities") or [])),
str(actor.get("name") or "").lower().replace(" ", "_"),
str(actor.get("description") or "").lower().replace(" ", "_"),
])
return norm in hay or q.lower() in (actor.get("description") or "").lower()
async def do_discover(capability: Optional[str] = None, actor_type: Optional[str] = None,
min_trust_score: float = 0, min_recommendations: int = 0,
sort_by: str = "trust_score", limit: int = 10) -> dict:
"""Trust-ranked search of the actor directory. FREE, no auth."""
if not supa.configured():
return {"error": "not_configured", "detail": "Discovery store (Supabase) is not configured."}
sort_by = sort_by if sort_by in _SORTS else "trust_score"
try:
limit = max(1, min(50, int(limit)))
except (TypeError, ValueError):
limit = 10
try:
min_trust_score = float(min_trust_score or 0)
except (TypeError, ValueError):
min_trust_score = 0.0
try:
min_recommendations = int(min_recommendations or 0)
except (TypeError, ValueError):
min_recommendations = 0
pool = await supa.actor_pool(actor_type)
if capability:
pool = [a for a in pool if _cap_match(a, capability)]
ids = [a["mint_id"] for a in pool if a.get("mint_id")]
trust_by_id = await supa.trust_for_ids(ids)
recs_by_id = await supa.recommendations_for_ids(ids)
results = []
for a in pool:
mid = a.get("mint_id")
t = trust_by_id.get(mid) or {}
recs = recs_by_id.get(mid) or []
tscore = float(t.get("trust_score") or 50)
n_recs = len(recs)
if tscore < min_trust_score or n_recs < min_recommendations:
continue
results.append({
"mint_id": mid, "name": a.get("name"), "actor_type": a.get("actor_type"),
"trust_score": tscore,
"total_attestations": t.get("total_attestations", 0),
"avg_rating": t.get("avg_rating", 0),
"total_ratings": t.get("total_ratings", 0),
"recommendations": n_recs,
"capabilities": a.get("capabilities") or [],
"mcp_endpoint": a.get("mcp_endpoint"),
"description": a.get("description"),
"last_active": t.get("last_active") or a.get("last_active"),
"registered_at": a.get("registered_at"),
"top_recommendations": [
{"from": r.get("recommender_mint_id"), "context": r.get("context"),
"score": r.get("score"), "note": r.get("note")}
for r in recs[:3]
],
})
if sort_by == "recommendations":
results.sort(key=lambda r: (r["recommendations"], r["trust_score"]), reverse=True)
elif sort_by == "recent":
results.sort(key=lambda r: (r.get("last_active") or r.get("registered_at") or ""), reverse=True)
else:
results.sort(key=lambda r: r["trust_score"], reverse=True)
total = len(results)
return {
"results": results[:limit], "total_matches": total,
"query": {"capability": capability, "actor_type": actor_type,
"min_trust_score": min_trust_score, "min_recommendations": min_recommendations,
"sort_by": sort_by, "limit": limit},
}
# ── Paid trust reads (read_gate.py gates these — $0.01 / $0.25 / $0.05) ────────
# The 2026-06-30 pivot: reading the trust graph is the product. These build on the
# SAME trust engine as mint_verify (trust.recompute / merkle_batch), not a naive
# column read, so the numbers match the full profile exactly.
async def do_trust_score(mint_id: str) -> dict:
"""Compact agent reputation lookup: the trust score + headline counts for one
MINT identity, freshly recomputed from every signal (attestations, ratings,
recommendations, recency). $0.01."""
if not (mint_id or "").startswith("MINT-"):
return {"error": "bad_request",
"detail": f"mint_id must look like 'MINT-xxxxxx', got {mint_id!r}."}
if not supa.configured():
return {"error": "not_configured", "detail": "Trust store (Supabase) is not configured."}
row = await supa.get_trust(mint_id)
if row is None:
row = await trust.recompute(mint_id)
last_hash = None
try:
atts = await merkle_batch.attestations_for_mint(mint_id, limit=1)
if atts:
last_hash = atts[0].get("attestation_hash")
except Exception:
pass
return {
"agent_id": mint_id,
"mint_id": mint_id,
"trust_score": row.get("trust_score"),
"total_attestations": row.get("total_attestations", 0),
"avg_rating": row.get("avg_rating", 0),
"total_ratings": row.get("total_ratings", 0),
"recommendations": row.get("total_recommendations_received", 0),
"work_types": row.get("work_types", {}),
"last_active": row.get("last_active"),
"computed_at": row.get("computed_at") or _now_iso(),
"reliability": okf_reliability.for_attested_analysis(
attestation_hash=last_hash, as_of=row.get("last_active"),
score=row.get("trust_score")),
}
async def do_trust_history(mint_id: str, days: int = 30) -> dict:
"""Full attestation audit trail for an agent over the last `days` — every
anchored/queued attestation with its work type, scores, and on-chain anchor
status. $0.25."""
if not (mint_id or "").startswith("MINT-"):
return {"error": "bad_request",
"detail": f"mint_id must look like 'MINT-xxxxxx', got {mint_id!r}."}
if not supa.configured():
return {"error": "not_configured", "detail": "Trust store (Supabase) is not configured."}
try:
days = max(1, min(365, int(days)))
except (TypeError, ValueError):
days = 30
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
try:
atts = await merkle_batch.attestations_for_mint(mint_id, limit=1000)
except Exception as e:
return {"error": "not_found", "detail": f"Could not read attestation history: {e}"}
entries = [a for a in atts if (a.get("created_at") or "") >= cutoff]
last_hash = entries[0].get("attestation_hash") if entries else None
return {
"agent_id": mint_id,
"mint_id": mint_id,
"period_days": days,
"since": cutoff,
"attestations": len(entries),
"anchored": sum(1 for a in entries if a.get("status") == "anchored"),
"entries": [
{"attestation_hash": a.get("attestation_hash"),
"work_type": a.get("work_type"),
"status": a.get("status"),
"anchored": a.get("status") == "anchored",
"anchor_tx": a.get("anchor_tx"),
"merkle_root": a.get("merkle_root"),
"ml_confidence": a.get("ml_confidence"),
"trust_delta": a.get("trust_delta"),
"base_score": a.get("base_score"),
"trust_weighted_score": a.get("trust_weighted_score"),
"summary": a.get("summary"),
"at": a.get("created_at")}
for a in entries
],
"reliability": okf_reliability.for_attested_analysis(attestation_hash=last_hash),
}
async def do_trust_compare(agent_ids: list) -> dict:
"""Rank multiple agents by trust score — a head-to-head leaderboard built from
each agent's full trust profile. $0.05."""
if not isinstance(agent_ids, list) or not agent_ids:
return {"error": "bad_request",
"detail": "agent_ids must be a non-empty list of MINT ids."}
if len(agent_ids) > 25:
return {"error": "bad_request", "detail": "Compare at most 25 agents per call."}
if not supa.configured():
return {"error": "not_configured", "detail": "Trust store (Supabase) is not configured."}
results = []
for aid in agent_ids:
s = await do_trust_score(aid)
if "error" in s:
results.append({"agent_id": aid, "error": s["error"], "detail": s.get("detail")})
else:
results.append({k: s[k] for k in
("agent_id", "mint_id", "trust_score", "total_attestations",
"avg_rating", "recommendations", "last_active")})
ranked = sorted(results, key=lambda x: (x.get("trust_score") or 0), reverse=True)
return {
"comparison": ranked,
"ranked_count": sum(1 for r in ranked if "error" not in r),
"reliability": okf_reliability.for_attested_analysis(attestation_hash=None),
}
# ── Free discovery: live network feed (read_gate does NOT gate this) ──────────