forked from NSPG13/agent-bounties
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreconcile_github_bounty_labels.py
More file actions
1407 lines (1285 loc) · 60.9 KB
/
Copy pathreconcile_github_bounty_labels.py
File metadata and controls
1407 lines (1285 loc) · 60.9 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
#!/usr/bin/env python3
"""Publish the canonical public bounty inventory as a GitHub issue mirror.
Dry-run is the default. The writer is intentionally non-authoritative: it can
create or update GitHub issues, but it cannot fund, claim, verify, settle, or
otherwise call a bounty contract.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import asdict, dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Mapping
USER_AGENT = "agent-bounties-github-discovery/1"
PROJECTION_SCHEMA = "agent-bounties/github-bounty-discovery-v1"
POLICY_SCHEMA = "agent-bounties/github-bounty-discovery-policy-v1"
SUPPORTED_PROTOCOLS = frozenset(
{
"agent-bounties/autonomous-v1",
"agent-bounties/open-competition-v1",
}
)
LIFECYCLE_STATES = frozenset(
{
"funding_needed",
"ready_to_earn",
"in_progress",
"verification_pending",
"unavailable",
"expired",
"settled",
"cancelled",
}
)
KNOWN_AUTONOMOUS_STATUSES = frozenset(
{"open", "claimable", "claimed", "submitted", "paid", "cancelled"}
)
NONTERMINAL_STATES = frozenset(
{"funding_needed", "ready_to_earn", "in_progress", "verification_pending", "unavailable"}
)
ADDRESS = re.compile(r"^0x[0-9a-f]{40}$")
TX_HASH = re.compile(r"^0x[0-9a-f]{64}$")
DISCOVERY_ID = re.compile(r"^eip155:[0-9]+:agent-bounties/[a-z0-9-]+:0x[0-9a-f]{40}$")
MANAGED_START = "<!-- agent-bounties/github-discovery-v1:start -->"
MANAGED_END = "<!-- agent-bounties/github-discovery-v1:end -->"
IDENTITY_MARKER_RE = re.compile(
r"<!-- agent-bounties/github-discovery-v1 (\{[^\r\n]*\}) -->"
)
SETTLEMENT_RECEIPT_MARKER = "<!-- agent-bounties-canonical-settlement -->"
COMMON_LABELS = frozenset({"bounty", "ai-agent-welcome", "payments"})
MANAGED_LABELS = frozenset(
{
*COMMON_LABELS,
"funding-needed",
"funded-live",
"ready-to-earn",
"claimable-live",
"open-competition",
"verifier",
"claimed-live",
"in-progress",
"verification-pending",
"verification-unavailable",
"refund-available",
"expired",
"cancelled",
"settled-paid",
"good-first-agent-bounty",
}
)
LABEL_DEFINITIONS = {
"bounty": ("0e8a16", "Work with an explicit outcome or reward"),
"ai-agent-welcome": ("7057ff", "AI agents are welcome to participate"),
"payments": ("1d76db", "Payment or escrow related"),
"funding-needed": ("d4c5f9", "Canonical bounty still needs funding"),
"funded-live": ("0e8a16", "Canonical bounty is fully funded"),
"ready-to-earn": ("a2eeef", "Public funded work accepting an eligible agent action"),
"claimable-live": ("2da44e", "Compatibility discovery label for live earning work"),
"open-competition": ("5319e7", "First valid confirmed reveal wins"),
"verifier": ("006b75", "Uses an explicitly identified verifier"),
"claimed-live": ("fbca04", "Exclusive claim is in progress"),
"in-progress": ("fbca04", "Work or reveal recovery is in progress"),
"verification-pending": ("f9d0c4", "Canonical submission awaits verification"),
"verification-unavailable": ("b60205", "Approved verification is unavailable"),
"refund-available": ("c5def5", "A wallet-scoped pull recovery action remains"),
"expired": ("ededed", "The canonical participation window expired"),
"cancelled": ("ededed", "The canonical bounty was cancelled"),
"settled-paid": ("0e8a16", "Canonical BountySettled payment evidence exists"),
"good-first-agent-bounty": ("bfdadc", "Explicitly graded as suitable introductory agent work"),
}
BOUNDARIES = (
"GitHub is a discovery mirror, not a funding, verification, or settlement authority.",
"A missing record never authorizes label removal or issue closure.",
"Only confirmed canonical BountySettled settlement_evidence proves payment.",
)
class LabelReconciliationError(RuntimeError):
pass
@dataclass(frozen=True)
class HttpResult:
status: int
body: Any
headers: Mapping[str, str]
@dataclass(frozen=True)
class SettlementReceipt:
fingerprint: str
body: str
@dataclass(frozen=True)
class IssuePlan:
discovery_id: str
protocol_version: str
lifecycle_state: str
competition_mode: str
issue_number: int | None
issue_url: str | None
mapping_action: str
create_eligible: bool
title: str
original_body: str
desired_body: str
current_managed_labels: list[str]
desired_managed_labels: list[str]
add_labels: list[str]
remove_labels: list[str]
desired_state: str
desired_state_reason: str | None
current_state: str | None
current_state_reason: str | None
settlement_receipt: SettlementReceipt | None
receipt_action: str
receipt_comment_id: int | None
publication_lag_seconds: int | None
HttpRequest = Callable[[str, str, Any | None, Mapping[str, str] | None], HttpResult]
def normalize_api_base_url(value: str) -> str:
parsed = urllib.parse.urlsplit(value.strip())
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise LabelReconciliationError("API base URL must be an absolute http(s) URL")
if parsed.query or parsed.fragment or parsed.username or parsed.password:
raise LabelReconciliationError("API base URL cannot contain credentials, query, or fragment")
host = (parsed.hostname or "").lower()
if parsed.scheme != "https" and host not in {"localhost", "127.0.0.1", "::1"}:
raise LabelReconciliationError("non-local API execution requires https")
return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""))
def validate_repository(value: str) -> str:
owner, separator, repo = value.strip().partition("/")
if (
not separator
or not owner
or not repo
or "/" in repo
or not re.fullmatch(r"[A-Za-z0-9_.-]+", owner)
or not re.fullmatch(r"[A-Za-z0-9_.-]+", repo)
):
raise LabelReconciliationError(f"invalid repository: {value!r}")
return f"{owner}/{repo}"
def decode_response(raw: str, content_type: str) -> Any:
if "json" in content_type.lower() or raw.lstrip().startswith(("{", "[")):
try:
return json.loads(raw)
except json.JSONDecodeError:
pass
return raw
def default_http_request(
method: str,
url: str,
body: Any | None,
headers: Mapping[str, str] | None,
) -> HttpResult:
request_headers = {
"Accept": "application/vnd.github+json, application/json",
"User-Agent": USER_AGENT,
}
if headers:
request_headers.update(headers)
data = None
if body is not None:
data = json.dumps(body, separators=(",", ":")).encode("utf-8")
request_headers["Content-Type"] = "application/json"
request = urllib.request.Request(url, data=data, headers=request_headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
raw = response.read().decode("utf-8")
return HttpResult(
response.status,
decode_response(raw, response.headers.get("Content-Type", "")),
dict(response.headers.items()),
)
except urllib.error.HTTPError as error:
raw = error.read().decode("utf-8", errors="replace")
return HttpResult(
error.code,
decode_response(raw, error.headers.get("Content-Type", "")),
dict(error.headers.items()),
)
except urllib.error.URLError as error:
raise LabelReconciliationError(f"request failed for {url}: {error.reason}") from error
def request_with_retry(
request: HttpRequest,
method: str,
url: str,
body: Any | None = None,
headers: Mapping[str, str] | None = None,
*,
sleep: Callable[[float], None] = time.sleep,
) -> HttpResult:
result: HttpResult | None = None
for attempt in range(3):
result = request(method, url, body, headers)
if result.status not in {429, 500, 502, 503, 504}:
return result
if attempt < 2:
retry_after = next(
(value for key, value in result.headers.items() if key.lower() == "retry-after"),
None,
)
delay = min(5.0, float(retry_after)) if str(retry_after or "").isdigit() else float(2**attempt)
sleep(delay)
assert result is not None
return result
def github_headers(token: str | None) -> dict[str, str]:
headers = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
if token:
headers["Authorization"] = f"Bearer {token}"
return headers
def parse_instant(value: Any, field: str) -> datetime:
if not isinstance(value, str):
raise LabelReconciliationError(f"{field} must be an RFC3339 string")
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as error:
raise LabelReconciliationError(f"{field} must be RFC3339") from error
if parsed.tzinfo is None:
raise LabelReconciliationError(f"{field} must include a timezone")
return parsed.astimezone(timezone.utc)
def require_unsigned(value: Any, field: str) -> int:
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
return value
if isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]*", value):
return int(value)
raise LabelReconciliationError(f"invalid unsigned field {field}")
def load_policy(path: Path, repository: str, network: str) -> dict[str, Any]:
try:
policy = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise LabelReconciliationError(f"cannot load activation policy: {error}") from error
if not isinstance(policy, dict) or policy.get("schema_version") != POLICY_SCHEMA:
raise LabelReconciliationError("activation policy schema is not supported")
if policy.get("repository") != repository or policy.get("network") != network:
raise LabelReconciliationError("activation policy repository or network mismatch")
if require_unsigned(policy.get("chain_id"), "policy.chain_id") <= 0:
raise LabelReconciliationError("activation policy chain id must be positive")
activation = policy.get("activation")
if not isinstance(activation, dict):
raise LabelReconciliationError("activation policy lacks activation evidence")
parse_instant(activation.get("timestamp"), "policy.activation.timestamp")
if require_unsigned(activation.get("safe_block"), "policy.activation.safe_block") <= 0:
raise LabelReconciliationError("activation block must be positive")
if not TX_HASH.fullmatch(str(activation.get("safe_block_hash") or "").lower()):
raise LabelReconciliationError("activation safe block hash is invalid")
required = policy.get("required_backfill_discovery_ids")
if not isinstance(required, list) or not all(isinstance(value, str) for value in required):
raise LabelReconciliationError("required backfill identities are malformed")
if len(required) != len(set(required)):
raise LabelReconciliationError("required backfill identities are duplicated")
trial = policy.get("open_competition_compatibility_trial")
if not isinstance(trial, dict):
raise LabelReconciliationError("compatibility trial policy is missing")
if parse_instant(trial.get("ends_at"), "trial.ends_at") <= parse_instant(
trial.get("starts_at"), "trial.starts_at"
):
raise LabelReconciliationError("compatibility trial interval is invalid")
return policy
def validate_projection(payload: Any, network: str, policy: Mapping[str, Any]) -> list[dict[str, Any]]:
if not isinstance(payload, dict) or payload.get("schema_version") != PROJECTION_SCHEMA:
raise LabelReconciliationError("discovery projection schema is not supported")
if payload.get("network") != network or payload.get("chain_id") != policy.get("chain_id"):
raise LabelReconciliationError("discovery projection network or chain mismatch")
safe = payload.get("safe_block")
if (
payload.get("degraded") is not False
or not isinstance(safe, dict)
or safe.get("fresh") is not True
or require_unsigned(safe.get("number"), "safe_block.number") <= 0
or not TX_HASH.fullmatch(str(safe.get("hash") or "").lower())
):
raise LabelReconciliationError("discovery projection is degraded or stale")
sources = payload.get("source_statuses")
if not isinstance(sources, list) or {
source.get("protocol_version") for source in sources if isinstance(source, dict)
} != SUPPORTED_PROTOCOLS:
raise LabelReconciliationError("discovery projection protocol adapters are incomplete")
if any(
not isinstance(source, dict)
or source.get("available") is not True
or source.get("fresh") is not True
for source in sources
):
raise LabelReconciliationError("a canonical projection source is degraded")
items = payload.get("items")
if not isinstance(items, list) or not all(isinstance(item, dict) for item in items):
raise LabelReconciliationError("discovery projection items are malformed")
seen: set[str] = set()
for item in items:
identity = str(item.get("discovery_id") or "")
protocol = str(item.get("protocol_version") or "")
contract = str(item.get("bounty_contract") or "").lower()
lifecycle = str(item.get("lifecycle_state") or "")
mode = str(item.get("competition_mode") or "")
if (
not DISCOVERY_ID.fullmatch(identity)
or identity in seen
or protocol not in SUPPORTED_PROTOCOLS
or lifecycle not in LIFECYCLE_STATES
or mode not in {"exclusive_claim", "first_valid_submission"}
or not ADDRESS.fullmatch(contract)
or item.get("network") != network
or item.get("chain_id") != policy.get("chain_id")
or not isinstance(item.get("title"), str)
or not str(item.get("title")).strip()
or not isinstance(item.get("summary"), str)
or not isinstance(item.get("categories"), list)
or not isinstance(item.get("skills"), list)
):
raise LabelReconciliationError(f"malformed discovery record: {identity or '<missing>'}")
if item.get("visibility") != "public":
raise LabelReconciliationError(f"private record reached public projection: {identity}")
require_public_https_url(item.get("public_url"), f"{identity}.public_url")
if item.get("source_url") is not None:
require_public_https_url(item.get("source_url"), f"{identity}.source_url")
action = item.get("next_action")
if not isinstance(action, dict):
raise LabelReconciliationError(f"next action is malformed: {identity}")
require_public_https_url(action.get("url"), f"{identity}.next_action.url")
if protocol == "agent-bounties/open-competition-v1" and mode != "first_valid_submission":
raise LabelReconciliationError(f"Open Competition mode mismatch: {identity}")
if protocol == "agent-bounties/autonomous-v1" and mode != "exclusive_claim":
raise LabelReconciliationError(f"autonomous-v1 mode mismatch: {identity}")
for field in (
"reward_usdc_base_units",
"verifier_reward_usdc_base_units",
"bond_usdc_base_units",
"funded_usdc_base_units",
"funding_target_usdc_base_units",
):
require_unsigned(item.get(field), f"{identity}.{field}")
parse_instant(item.get("created_at"), f"{identity}.created_at")
parse_instant(item.get("updated_at"), f"{identity}.updated_at")
require_unsigned(item.get("created_block"), f"{identity}.created_block")
if lifecycle == "settled":
validate_settlement(item)
elif item.get("settlement_evidence") is not None:
raise LabelReconciliationError(f"non-settled record exposes payment evidence: {identity}")
if item.get("ready_to_earn") is True and (
lifecycle != "ready_to_earn"
or item.get("funded") is not True
or item.get("verification_ready") is not True
):
raise LabelReconciliationError(f"unsafe ready-to-earn record: {identity}")
seen.add(identity)
for source in sources:
protocol = str(source["protocol_version"])
actual = sum(item.get("protocol_version") == protocol for item in items)
if require_unsigned(source.get("item_count"), f"{protocol}.item_count") != actual:
raise LabelReconciliationError(f"projection source count mismatch: {protocol}")
required = set(policy["required_backfill_discovery_ids"])
missing_required = required - seen
if missing_required:
raise LabelReconciliationError(
"required backfill identities are missing: " + ", ".join(sorted(missing_required))
)
return items
def validate_settlement(item: Mapping[str, Any]) -> Mapping[str, Any]:
identity = str(item.get("discovery_id") or "")
evidence = item.get("settlement_evidence")
if not isinstance(evidence, dict):
raise LabelReconciliationError(f"settled record lacks evidence: {identity}")
if evidence.get("event_name") != "BountySettled" or evidence.get("confirmed_canonical") is not True:
raise LabelReconciliationError(f"settlement is not canonical: {identity}")
if (
str(evidence.get("bounty_contract") or "").lower()
!= str(item.get("bounty_contract") or "").lower()
or not TX_HASH.fullmatch(str(evidence.get("transaction_hash") or "").lower())
or not ADDRESS.fullmatch(str(evidence.get("solver_wallet") or "").lower())
):
raise LabelReconciliationError(f"settlement identity is malformed: {identity}")
solver_reward = require_unsigned(evidence.get("solver_reward"), "settlement.solver_reward")
returned_bond = require_unsigned(evidence.get("returned_bond"), "settlement.returned_bond")
bonus = require_unsigned(evidence.get("completion_bonus"), "settlement.completion_bonus")
payout = require_unsigned(evidence.get("solver_payout"), "settlement.solver_payout")
require_unsigned(evidence.get("verifier_reward"), "settlement.verifier_reward")
if payout != solver_reward + returned_bond + bonus:
raise LabelReconciliationError(f"settlement payout is inconsistent: {identity}")
return evidence
def fetch_projection(request: HttpRequest, api_base_url: str, network: str) -> dict[str, Any]:
health = request_with_retry(request, "GET", f"{api_base_url}/health")
if health.status != 200 or str(health.body).strip() != "ok":
raise LabelReconciliationError("hosted API health is not confirmed")
query = urllib.parse.urlencode({"network": network})
result = request_with_retry(
request, "GET", f"{api_base_url}/v1/github/bounty-discovery-v1?{query}"
)
if result.status != 200 or not isinstance(result.body, dict):
raise LabelReconciliationError(f"discovery projection returned HTTP {result.status}")
return result.body
# The claim-comment workflow still consumes the autonomous-v1 full and earning
# feeds for its exclusive-claim handoff. Keep this compatibility reader here so
# both automations share the same strict transport and identity checks while the
# GitHub publisher itself uses only the lifecycle-complete projection above.
def fetch_canonical_feeds(
request: HttpRequest, api_base_url: str, network: str
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
health = request_with_retry(request, "GET", f"{api_base_url}/health")
if health.status != 200 or str(health.body).strip() != "ok":
raise LabelReconciliationError("hosted API health is not confirmed")
full_query = urllib.parse.urlencode({"network": network})
earning_query = urllib.parse.urlencode({"network": network, "claimable_only": "true"})
results: list[list[dict[str, Any]]] = []
for url in (
f"{api_base_url}/v1/base/autonomous-bounties/feed?{full_query}",
f"{api_base_url}/v1/base/autonomous-bounties/feed?{earning_query}",
):
result = request_with_retry(request, "GET", url)
if result.status != 200 or not isinstance(result.body, list) or not all(
isinstance(record, dict) for record in result.body
):
raise LabelReconciliationError(f"canonical feed returned HTTP {result.status}")
results.append(result.body)
return results[0], results[1]
def require_amount(item: Mapping[str, Any], field: str) -> int:
try:
return require_unsigned(item.get(field), field)
except LabelReconciliationError as error:
raise LabelReconciliationError(f"canonical item has invalid {field}") from error
def source_issue_url(item: Mapping[str, Any], repository: str) -> str | None:
terms = item.get("terms")
document = terms.get("document") if isinstance(terms, dict) else None
source = document.get("source_url") if isinstance(document, dict) else None
number = parse_same_repository_issue(source, repository)
return f"https://github.com/{repository}/issues/{number}" if number else None
def validate_autonomous_state_evidence(
item: Mapping[str, Any], status: str, contract: str
) -> None:
expected = {
"claimed": {"bounty_claimed"},
"submitted": {"bounty_claimed", "submission_added"},
"paid": {"bounty_settled"},
}.get(status)
if expected is None:
return
events = item.get("events")
if not isinstance(events, list):
raise LabelReconciliationError(f"canonical {status} item lacks an event list: {contract}")
observed = {
str(event.get("kind"))
for event in events
if isinstance(event, dict)
and str(event.get("contract_address") or "").lower() == contract
and TX_HASH.fullmatch(str(event.get("tx_hash") or "").lower())
}
if not expected.issubset(observed):
raise LabelReconciliationError(f"canonical {status} item lacks confirmed event evidence")
def canonical_records(
full_feed: list[dict[str, Any]],
claimable_feed: list[dict[str, Any]],
repository: str,
) -> tuple[dict[str, dict[str, Any]], set[tuple[str, str]]]:
by_contract: dict[str, dict[str, Any]] = {}
candidates: dict[str, list[dict[str, Any]]] = {}
for item in full_feed:
contract = str(item.get("bounty_contract") or "").lower()
status = str(item.get("status") or "").lower()
if not ADDRESS.fullmatch(contract) or status not in KNOWN_AUTONOMOUS_STATUSES:
raise LabelReconciliationError("canonical full feed has an invalid contract or status")
if contract in by_contract:
raise LabelReconciliationError(f"duplicate canonical contract: {contract}")
target = require_amount(item, "target_amount")
funded = require_amount(item, "funded_amount")
if target <= 0 or funded > target:
raise LabelReconciliationError(f"invalid canonical economics: {contract}")
if status in {"claimable", "claimed", "submitted", "paid"} and funded != target:
raise LabelReconciliationError(f"canonical {status} item is not fully funded: {contract}")
validate_autonomous_state_evidence(item, status, contract)
source = source_issue_url(item, repository)
normalized = dict(item)
normalized.update(
{"bounty_contract": contract, "status": status, "_source_issue_url": source}
)
by_contract[contract] = normalized
if source:
candidates.setdefault(source, []).append(normalized)
by_issue: dict[str, dict[str, Any]] = {}
for source, records in candidates.items():
if len(records) == 1:
by_issue[source] = records[0]
continue
ready = [
record
for record in records
if record["status"] in {"claimable", "claimed", "submitted", "paid"}
and record.get("terms_valid") is True
and record.get("verification_ready") is True
]
if len(ready) != 1:
raise LabelReconciliationError(
f"multiple canonical contracts reference {source} without one unique ready record"
)
by_issue[source] = ready[0]
earning: set[tuple[str, str]] = set()
for item in claimable_feed:
contract = str(item.get("bounty_contract") or "").lower()
source = source_issue_url(item, repository)
counterpart = by_contract.get(contract)
pair = (source or "", contract)
if counterpart is None or not (
source == counterpart["_source_issue_url"]
and counterpart["status"] == "claimable"
and counterpart.get("terms_valid") is True
and counterpart.get("verification_ready") is True
and str(item.get("status") or "").lower() == "claimable"
and item.get("terms_valid") is True
and item.get("verification_ready") is True
):
raise LabelReconciliationError(
f"earning feed item is not an exact executable full-feed record: {contract}"
)
if pair in earning:
raise LabelReconciliationError(f"duplicate earning feed item: {contract}")
earning.add(pair)
return by_issue, earning
def next_page(headers: Mapping[str, str]) -> str | None:
link = next((value for key, value in headers.items() if key.lower() == "link"), "")
for part in link.split(","):
match = re.match(r'\s*<([^>]+)>;\s*rel="next"', part)
if match:
return match.group(1)
return None
def fetch_paginated(
request: HttpRequest,
url: str,
token: str | None,
resource: str,
) -> list[dict[str, Any]]:
records: list[dict[str, Any]] = []
seen_urls: set[str] = set()
while url:
if url in seen_urls:
raise LabelReconciliationError(f"GitHub {resource} pagination looped")
seen_urls.add(url)
result = request_with_retry(request, "GET", url, headers=github_headers(token))
if result.status != 200 or not isinstance(result.body, list):
raise LabelReconciliationError(f"GitHub {resource} returned HTTP {result.status}")
records.extend(record for record in result.body if isinstance(record, dict))
url = next_page(result.headers)
return records
def fetch_github_issues(request: HttpRequest, repository: str, token: str | None) -> list[dict[str, Any]]:
# Listing every issue also recovers a managed issue whose `bounty` label was
# manually removed, preventing a duplicate mirror on the next run.
query = urllib.parse.urlencode({"state": "all", "per_page": "100"})
return fetch_paginated(
request,
f"https://api.github.com/repos/{repository}/issues?{query}",
token,
"bounty issue listing",
)
def parse_same_repository_issue(source_url: Any, repository: str) -> int | None:
if source_url is None:
return None
try:
parsed = urllib.parse.urlsplit(str(source_url))
except ValueError as error:
raise LabelReconciliationError("source URL is malformed") from error
if parsed.scheme != "https" or parsed.hostname != "github.com":
return None
if parsed.username or parsed.password or parsed.query or parsed.fragment:
raise LabelReconciliationError("GitHub source URL must be exact and credential-free")
match = re.fullmatch(rf"/{re.escape(repository)}/issues/([1-9][0-9]*)/?", parsed.path)
return int(match.group(1)) if match else None
def fetch_linked_source_issues(
request: HttpRequest,
repository: str,
token: str | None,
items: list[dict[str, Any]],
listed: list[dict[str, Any]],
) -> list[dict[str, Any]]:
by_number = {
issue.get("number"): issue
for issue in listed
if isinstance(issue.get("number"), int) and "pull_request" not in issue
}
for number in sorted(
{
number
for item in items
if (number := parse_same_repository_issue(item.get("source_url"), repository))
}
):
if number in by_number:
continue
result = request_with_retry(
request,
"GET",
f"https://api.github.com/repos/{repository}/issues/{number}",
headers=github_headers(token),
)
if result.status != 200 or not isinstance(result.body, dict) or "pull_request" in result.body:
raise LabelReconciliationError(f"linked source issue #{number} is unavailable")
by_number[number] = result.body
return list(by_number.values())
def fetch_issue_comments(
request: HttpRequest, repository: str, issue_number: int, token: str | None
) -> list[dict[str, Any]]:
query = urllib.parse.urlencode({"per_page": "100"})
return fetch_paginated(
request,
f"https://api.github.com/repos/{repository}/issues/{issue_number}/comments?{query}",
token,
f"comments for issue #{issue_number}",
)
def label_names(issue: Mapping[str, Any]) -> set[str]:
names: set[str] = set()
for label in issue.get("labels") or []:
if isinstance(label, str):
names.add(label.lower())
elif isinstance(label, dict) and label.get("name"):
names.add(str(label["name"]).lower())
return names
def issue_marker(issue: Mapping[str, Any]) -> str | None:
body = str(issue.get("body") or "")
starts = body.count(MANAGED_START)
ends = body.count(MANAGED_END)
markers = IDENTITY_MARKER_RE.findall(body)
if starts != ends or starts > 1 or ends > 1 or len(markers) > 1:
raise LabelReconciliationError(f"issue #{issue.get('number')} has malformed managed markers")
if starts == 1 and len(markers) != 1:
raise LabelReconciliationError(f"issue #{issue.get('number')} lacks one discovery identity")
if markers and starts != 1:
raise LabelReconciliationError(f"issue #{issue.get('number')} has an unmanaged discovery identity")
if not markers:
return None
try:
payload = json.loads(markers[0])
except json.JSONDecodeError as error:
raise LabelReconciliationError(f"issue #{issue.get('number')} marker is invalid JSON") from error
identity = payload.get("discovery_id") if isinstance(payload, dict) else None
if not isinstance(identity, str) or not DISCOVERY_ID.fullmatch(identity):
raise LabelReconciliationError(f"issue #{issue.get('number')} marker identity is invalid")
return identity
def add_attribution(url: str, discovery_id: str) -> str:
parsed = urllib.parse.urlsplit(url)
if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password:
raise LabelReconciliationError(f"public discovery URL is invalid: {discovery_id}")
query = dict(urllib.parse.parse_qsl(parsed.query, keep_blank_values=True))
query.update(
{
"utm_source": "github",
"utm_medium": "issue",
"utm_campaign": "bounty-discovery-v1",
"discovery_id": discovery_id,
}
)
return urllib.parse.urlunsplit(
(parsed.scheme, parsed.netloc, parsed.path, urllib.parse.urlencode(query), parsed.fragment)
)
def require_public_https_url(value: Any, field: str) -> str:
try:
parsed = urllib.parse.urlsplit(str(value or ""))
except ValueError as error:
raise LabelReconciliationError(f"{field} is malformed") from error
if (
parsed.scheme != "https"
or not parsed.netloc
or parsed.username
or parsed.password
or any(character in str(value) for character in ("\n", "\r"))
):
raise LabelReconciliationError(f"{field} must be a public credential-free HTTPS URL")
return str(value)
def format_usdc(amount: Any) -> str:
value = require_unsigned(amount, "USDC amount")
whole, fraction = divmod(value, 1_000_000)
decimals = f"{fraction:06d}".rstrip("0")
return f"{whole}.{decimals.ljust(2, '0')}" if decimals else f"{whole}.00"
def render_managed_block(item: Mapping[str, Any]) -> str:
identity = str(item["discovery_id"])
marker = json.dumps({"discovery_id": identity}, separators=(",", ":"), sort_keys=True)
public_url = add_attribution(str(item["public_url"]), identity)
next_action = item.get("next_action")
if not isinstance(next_action, dict) or not isinstance(next_action.get("label"), str):
raise LabelReconciliationError(f"next action is malformed: {identity}")
action_url = add_attribution(str(next_action.get("url")), identity)
lines = [
MANAGED_START,
f"<!-- agent-bounties/github-discovery-v1 {marker} -->",
"## Canonical bounty discovery",
"",
str(item["summary"]).strip(),
"",
f"- **Mode:** {'Open competition' if item['competition_mode'] == 'first_valid_submission' else 'Exclusive claim'}",
f"- **Lifecycle:** `{item['lifecycle_state']}`",
f"- **Solver reward:** {format_usdc(item['reward_usdc_base_units'])} USDC",
f"- **Entry/claim bond:** {format_usdc(item['bond_usdc_base_units'])} USDC",
f"- **Funding:** {format_usdc(item['funded_usdc_base_units'])} / {format_usdc(item['funding_target_usdc_base_units'])} USDC",
]
verifier = item.get("verifier")
if isinstance(verifier, dict):
lines.append(
f"- **Verifier:** {verifier.get('display_name', 'Unspecified')} "
f"(`{verifier.get('method', 'unknown')}`; ready: `{str(verifier.get('ready') is True).lower()}`)"
)
if item.get("entry_count") is not None or item.get("max_entries") is not None:
lines.append(f"- **Capacity:** {item.get('entry_count', 0)} / {item.get('max_entries', '?')} entries")
if item.get("deadline"):
lines.append(f"- **{str(item.get('deadline_kind') or 'Deadline').replace('_', ' ').title()}:** `{item['deadline']}`")
if item["competition_mode"] == "first_valid_submission":
lines.extend(
[
"",
"### Open Competition rules",
"",
"First valid confirmed reveal wins. Each wallet may enter once; an entry does not prove one independent person. Save the local commitment recovery envelope because the API never stores its plaintext salt.",
]
)
lines.extend(
[
"",
"### Next action",
"",
f"**[{next_action['label']}]({action_url})** — {next_action.get('instructions', '')}",
"",
f"[Open the public bounty page]({public_url})",
]
)
if item.get("source_url"):
lines.append(f"[Original source]({item['source_url']})")
lines.extend(
[
"",
"> GitHub mirrors canonical public state and cannot fund, claim, verify, settle, or prove payment. Only a confirmed canonical `BountySettled` receipt below proves solver payment.",
MANAGED_END,
]
)
return "\n".join(lines)
def replace_managed_block(body: str, managed: str) -> str:
starts = body.count(MANAGED_START)
ends = body.count(MANAGED_END)
if starts != ends or starts > 1:
raise LabelReconciliationError("cannot update malformed managed issue body")
if starts == 0:
return f"{body.rstrip()}\n\n{managed}\n" if body.strip() else f"{managed}\n"
start = body.index(MANAGED_START)
end = body.index(MANAGED_END, start) + len(MANAGED_END)
return f"{body[:start]}{managed}{body[end:]}"
def trial_claimable_enabled(policy: Mapping[str, Any], generated_at: datetime) -> bool:
trial = policy["open_competition_compatibility_trial"]
ends_at = parse_instant(trial["ends_at"], "trial.ends_at")
return generated_at <= ends_at or trial.get("post_trial_action") == "hold_for_day_30_decision"
def desired_labels(item: Mapping[str, Any], policy: Mapping[str, Any], generated_at: datetime) -> set[str]:
labels = set(COMMON_LABELS)
state = str(item["lifecycle_state"])
mode = str(item["competition_mode"])
if state == "funding_needed":
labels.add("funding-needed")
elif state == "ready_to_earn":
labels.update({"funded-live", "ready-to-earn", "claimable-live"})
if mode == "first_valid_submission":
labels.update({"open-competition", "verifier"})
if not trial_claimable_enabled(policy, generated_at):
labels.discard("claimable-live")
elif state == "in_progress":
labels.add("funded-live")
labels.add("claimed-live" if mode == "exclusive_claim" else "in-progress")
if mode == "first_valid_submission":
labels.add("open-competition")
elif state == "verification_pending":
labels.update({"funded-live", "verification-pending"})
if mode == "first_valid_submission":
labels.add("open-competition")
elif state == "unavailable":
if item.get("funded") is True:
labels.add("funded-live")
if item.get("verification_ready") is not True:
labels.add("verification-unavailable")
else:
labels.add("in-progress")
if mode == "first_valid_submission":
labels.add("open-competition")
elif state in {"cancelled", "expired"}:
labels.add(state)
if item.get("recovery_action_available") is True:
labels.add("refund-available")
elif state == "settled":
labels.add("settled-paid")
difficulty = item.get("difficulty")
if isinstance(difficulty, str) and difficulty.strip():
labels.add("good-first-agent-bounty")
return labels
def settlement_transaction_url(network: str, tx_hash: str) -> str:
origins = {"base-mainnet": "https://basescan.org", "base-sepolia": "https://sepolia.basescan.org"}
try:
return f"{origins[network]}/tx/{tx_hash}"
except KeyError as error:
raise LabelReconciliationError(f"unsupported settlement network: {network}") from error
def build_settlement_receipt(item: Mapping[str, Any]) -> SettlementReceipt:
evidence = validate_settlement(item)
tx_hash = str(evidence["transaction_hash"]).lower()
fingerprint = hashlib.sha256(
json.dumps(evidence, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
body = "\n".join(
[
SETTLEMENT_RECEIPT_MARKER,
"## Canonical payout confirmed",
"",
f"- Bounty ID: `{evidence['bounty_id']}`",
f"- Contract: `{evidence['bounty_contract']}`",
f"- Settlement: [`{tx_hash}`]({settlement_transaction_url(str(item['network']), tx_hash)})",
f"- Solver wallet: `{evidence['solver_wallet']}`",
f"- Solver reward: **{format_usdc(evidence['solver_reward'])} USDC**",
f"- Returned bond: **{format_usdc(evidence['returned_bond'])} USDC**",
f"- Completion bonus: **{format_usdc(evidence['completion_bonus'])} USDC**",
f"- Total solver transfer: **{format_usdc(evidence['solver_payout'])} USDC**",
f"- Verifier reward: **{format_usdc(evidence['verifier_reward'])} USDC**",
f"- Receipt fingerprint: `{fingerprint}`",
"",
"Only this confirmed canonical `BountySettled` event proves solver payment. This GitHub comment reports the event; it did not authorize or execute settlement.",
]
)
return SettlementReceipt(fingerprint=fingerprint, body=body)
def create_allowed(item: Mapping[str, Any], policy: Mapping[str, Any]) -> tuple[bool, str]:
identity = str(item["discovery_id"])
if identity in policy["required_backfill_discovery_ids"]:
return True, "required_backfill"
state = str(item["lifecycle_state"])
if state in NONTERMINAL_STATES or item.get("recovery_action_available") is True:
return True, "current_nonterminal_backfill"
activation = policy["activation"]
created_after = require_unsigned(item["created_block"], "created_block") >= require_unsigned(
activation["safe_block"], "activation.safe_block"
) and parse_instant(item["created_at"], "created_at") >= parse_instant(
activation["timestamp"], "activation.timestamp"
)
if created_after:
return True, "post_activation_record"
return False, "historical_terminal_without_existing_issue"
def mapping_rank(item: Mapping[str, Any]) -> tuple[int, int, str]:
state = str(item["lifecycle_state"])
priority = 0 if state == "ready_to_earn" else 1 if state in NONTERMINAL_STATES else 2
return (priority, -require_unsigned(item["created_block"], "created_block"), str(item["discovery_id"]))
def build_plans(
projection: Mapping[str, Any],
issues: list[dict[str, Any]],
policy: Mapping[str, Any],
repository: str,
comments_by_issue: Mapping[int, list[dict[str, Any]]] | None = None,
) -> list[IssuePlan]:
items = validate_projection(projection, str(policy["network"]), policy)
generated_at = parse_instant(projection["generated_at"], "projection.generated_at")
issue_by_number: dict[int, dict[str, Any]] = {}
marker_to_issue: dict[str, dict[str, Any]] = {}
for issue in issues:
if "pull_request" in issue:
continue
number = issue.get("number")
if not isinstance(number, int) or number <= 0 or number in issue_by_number:
raise LabelReconciliationError("GitHub issue listing has an invalid or duplicate number")
issue_by_number[number] = issue
marker = issue_marker(issue)
if marker:
if marker in marker_to_issue:
raise LabelReconciliationError(f"duplicate discovery_id mapping: {marker}")
marker_to_issue[marker] = issue
known_ids = {str(item["discovery_id"]) for item in items}
for marker in marker_to_issue:
if marker not in known_ids:
continue # Preserve disappeared records exactly as they are.
source_candidates: dict[int, list[dict[str, Any]]] = {}
for item in items:
identity = str(item["discovery_id"])
if identity in marker_to_issue:
continue
number = parse_same_repository_issue(item.get("source_url"), repository)
if number is not None:
source_candidates.setdefault(number, []).append(item)
source_winners = {
number: sorted(candidates, key=mapping_rank)[0]["discovery_id"]
for number, candidates in source_candidates.items()
if number in issue_by_number and issue_marker(issue_by_number[number]) is None
}
used_issues: set[int] = set()
plans: list[IssuePlan] = []
for item in sorted(items, key=lambda value: str(value["discovery_id"])):
identity = str(item["discovery_id"])
issue = marker_to_issue.get(identity)
mapping_action = "reuse_marker" if issue else "create_mirror"
if issue is None:
source_number = parse_same_repository_issue(item.get("source_url"), repository)