forked from NSPG13/agent-bounties
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_claim_comment.py
More file actions
1446 lines (1349 loc) · 53.8 KB
/
Copy pathgithub_claim_comment.py
File metadata and controls
1446 lines (1349 loc) · 53.8 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
"""Plan and publish public claim-comment signals for GitHub bounty issues."""
from __future__ import annotations
import argparse
import io
import json
import os
import pathlib
import re
import subprocess
import sys
import urllib.parse
from typing import Dict, List, Mapping, Optional, TextIO, Tuple
from _shared.github_actions import (
append_step_summary as append_github_summary,
cargo_body_path,
find_executable,
json_field,
load_issue_comments,
publish_issue_comment,
read_event as read_github_event,
repo_root,
)
from reconcile_github_bounty_labels import (
LabelReconciliationError,
canonical_records,
default_http_request,
fetch_canonical_feeds,
normalize_api_base_url,
require_amount,
)
MARKER = "<!-- agent-bounties-claim-comment -->"
CLAIM_COMMAND_RE = re.compile(r"(?im)^\s*/(?:agent-bounty\s+)?(claim|attempt)\b")
COMMENT_ID_RE = re.compile(r"Claim comment id:\s*`?([0-9]+)`?")
RESERVATION_RE = re.compile(r"Reservation id:\s*`?([^\s`]+)`?")
CONTRIBUTOR_RE = re.compile(r"Contributor:\s*`?([^\s`]+)`?")
DEFAULT_API_BASE_URL = "https://api.agentbounties.app"
STATIC_EARN_PAGE_URL = "https://agentbounties.app/earn.html"
EVM_ADDRESS_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
EVM_ADDRESS_SEARCH_RE = re.compile(r"(?<![0-9A-Za-z])0x[0-9a-fA-F]{40}(?![0-9A-Za-z])")
class UserError(RuntimeError):
pass
def script_repo_root() -> pathlib.Path:
return repo_root(__file__)
def read_json_field(value: object, field: str) -> object:
return json_field(value, field, UserError, "claim planner output missing field: {field}")
def read_event(env: Mapping[str, str]) -> Dict[str, object]:
return read_github_event(env, UserError)
def write_issue_files(
env: Mapping[str, str], event: Mapping[str, object], tmp_dir: pathlib.Path
) -> Tuple[Dict[str, object], pathlib.Path]:
issue = event.get("issue") or {}
comment = event.get("comment") or {}
repository = event.get("repository") or {}
if not isinstance(issue, dict) or not isinstance(comment, dict):
raise UserError("issue_comment event is required")
body_file = tmp_dir / "paid-bounty-claim-issue-body.md"
body_file.write_text(str(issue.get("body") or ""), encoding="utf-8")
comment_user = comment.get("user") if isinstance(comment.get("user"), dict) else {}
labels = issue.get("labels") if isinstance(issue.get("labels"), list) else []
label_names = sorted(
{
str(label.get("name") or "").strip().lower()
for label in labels
if isinstance(label, dict) and str(label.get("name") or "").strip()
}
)
meta: Dict[str, object] = {
"repo": env.get("GITHUB_REPOSITORY") or repository.get("full_name") or "",
"number": issue.get("number"),
"title": issue.get("title") or "",
"url": issue.get("html_url") or "",
"comment_body": comment.get("body") or "",
"comment_id": str(comment.get("id") or ""),
"comment_url": comment.get("html_url") or "",
"contributor_login": comment_user.get("login") or "",
"labels": label_names,
"issue_body": issue.get("body") or "",
}
missing = [
key
for key, value in meta.items()
if key not in {"comment_url", "issue_body"} and value in ("", None)
]
if missing:
raise UserError(f"claim comment event missing required metadata: {', '.join(missing)}")
if not CLAIM_COMMAND_RE.search(str(meta["comment_body"])):
raise UserError("comment does not contain a /claim, /attempt, or /agent-bounty claim command")
return meta, body_file
def recovery_reserved_plan(meta: Mapping[str, object]) -> Dict[str, object]:
details = "\n".join(
[
f"Issue: {meta['url']}",
f"Contributor: {meta['contributor_login']}",
"Decision: RecoveryReserved",
"Settlement authority: false",
"",
"This issue is marked recovery-reserved after a platform incident.",
"Do not connect a wallet, sign a claim, or post a solver bond for this round.",
"The GitHub command is coordination evidence only and created no reservation or failed attempt.",
"Use a different canonical feed entry with status=claimable and verification_ready=true.",
]
)
return {
"ready": False,
"signal": {
"decision": "RecoveryReserved",
"reservation_id": "none",
},
"check": {
"conclusion": "ActionRequired",
"title": "Bounty is reserved for incident recovery",
"summary": "Do not sign a claim or post a bond for this recovery-reserved bounty.",
"text": details,
},
}
def load_canonical_claim_records(
env: Mapping[str, str], repository: str
) -> Tuple[Dict[str, Dict[str, object]], set[Tuple[str, str]]]:
fixture = env.get("AGENT_BOUNTIES_CLAIM_FEED_FILE")
if fixture:
payload = json.loads(pathlib.Path(fixture).read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise UserError("claim feed fixture must be an object")
full = payload.get("full_feed")
earning = payload.get("claimable_feed")
if not isinstance(full, list) or not isinstance(earning, list):
raise UserError("claim feed fixture requires full_feed and claimable_feed arrays")
if not all(isinstance(item, dict) for item in [*full, *earning]):
raise UserError("claim feed fixture entries must be objects")
else:
base_url = normalize_api_base_url(
env.get("AGENT_BOUNTIES_API_BASE_URL") or DEFAULT_API_BASE_URL
)
full, earning = fetch_canonical_feeds(
default_http_request, base_url, "base-mainnet"
)
records, earning_pairs = canonical_records(full, earning, repository)
return records, earning_pairs
def native_claim_request(
signal: Mapping[str, object], api_base_url: str, contract: str
) -> Dict[str, object]:
existing = (
signal.get("claim_plan_request")
if isinstance(signal.get("claim_plan_request"), dict)
else {}
)
existing_body = (
existing.get("body") if isinstance(existing.get("body"), dict) else {}
)
solver_wallet = str(
existing_body.get("solver_wallet") or "0xYOUR_PUBLIC_BASE_WALLET"
)
return {
"method": "POST",
"url": f"{api_base_url}/v1/base/autonomous-bounties/claims",
"body": {
"idempotency_key": str(
existing_body.get("idempotency_key")
or signal.get("reservation_id")
or "github-claim-comment"
),
"network": "base-mainnet",
"bounty_contract": contract,
"solver_wallet": solver_wallet,
"request_bond_sponsorship": True,
"source": "github",
},
"result": (
"The first response reserves an exclusive candidate or waitlist position and "
"returns the exact indexed bond plus wallet_request. Send wallet_request to the "
"solver wallet once, then copy its unchanged 65-byte result into "
"next_request.body.wallet_signature. Only confirmed canonical BountyClaimed owns "
"the round."
),
}
def load_native_claim_handoff(
env: Mapping[str, str], request: Mapping[str, object]
) -> Tuple[int, object]:
fixture = env.get("AGENT_BOUNTIES_CLAIM_HANDOFF_FILE")
if fixture:
payload = json.loads(pathlib.Path(fixture).read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise UserError("claim handoff fixture must be an object")
return int(payload.get("status") or 0), payload.get("body")
response = default_http_request(
str(request["method"]),
str(request["url"]),
request.get("body"),
{"Accept": "application/json"},
)
return response.status, response.body
def summarize_native_claim_handoff(
status: int,
payload: object,
*,
contract: str,
solver_wallet: str,
) -> Tuple[Optional[Dict[str, object]], Optional[Dict[str, object]]]:
if not isinstance(payload, dict):
return None, {
"http_status": status,
"error": "claim_handoff_unreadable",
"next_action": "Replay the machine claim request later; do not sign anything from this response.",
}
if status not in {200, 202}:
return None, {
"http_status": status,
"schema_version": payload.get("schema_version"),
"state": payload.get("state"),
"failed_transition": payload.get("failed_transition"),
"error": payload.get("error") or "claim_handoff_failed",
"next_action": payload.get("next_action")
or "Replay the same machine request after the reported condition is resolved.",
}
candidate = payload.get("candidate")
if not isinstance(candidate, dict):
raise UserError("hosted claim handoff omitted candidate state")
if str(candidate.get("bounty_contract") or "").lower() != contract.lower():
raise UserError("hosted claim handoff returned a different bounty contract")
if str(candidate.get("solver_wallet") or "").lower() != solver_wallet.lower():
raise UserError("hosted claim handoff returned a different solver wallet")
handoff = {
"http_status": status,
"schema_version": payload.get("schema_version"),
"candidate": {
"id": candidate.get("id"),
"status": candidate.get("status"),
"exclusive_until": candidate.get("exclusive_until"),
},
"waitlist_position": payload.get("waitlist_position"),
"claim_bond": payload.get("claim_bond"),
"sponsorship_requested": payload.get("sponsorship_requested"),
"sponsorship_available": payload.get("sponsorship_available"),
"sponsorship_protocol": payload.get("sponsorship_protocol"),
"sponsor_contract": payload.get("sponsor_contract"),
"wallet_request": payload.get("wallet_request"),
"next_request": payload.get("next_request"),
"next_action": payload.get("next_action"),
"evidence_boundary": payload.get("evidence_boundary"),
}
return handoff, None
def canonical_unavailable_plan(
meta: Mapping[str, object],
*,
status: str,
contract: Optional[str],
reason: str,
claim_recovery: Optional[Mapping[str, object]] = None,
) -> Dict[str, object]:
title_by_status = {
"claimed": "Bounty already has an on-chain solver",
"submitted": "Bounty is awaiting deterministic verification",
"paid": "Bounty is already settled",
"cancelled": "Bounty is cancelled",
"open": "Bounty is not yet fully funded",
"missing": "Canonical bounty is not indexed",
"ambiguous": "Canonical bounty mapping is ambiguous",
"unavailable": "Canonical bounty state is unavailable",
}
contract_line = (
f"Canonical contract: {contract}"
if contract
else "Canonical contract: unavailable"
)
details = "\n".join(
[
f"Issue: {meta['url']}",
f"Contributor: {meta['contributor_login']}",
"Decision: CanonicalStateUnavailable",
f"Canonical status: {status}",
contract_line,
f"Reason: {reason}",
"Settlement authority: false",
"",
"Do not connect a wallet, sign a claim, or post a solver bond for this round.",
"A future canonical state transition may make a new round claimable; rerun /claim then.",
"Only a confirmed BountySettled event proves payment.",
]
)
signal: Dict[str, object] = {
"decision": "CanonicalStateUnavailable",
"reservation_id": "none",
"bounty_contract": contract,
"canonical_status": status,
}
if claim_recovery is not None:
signal["claim_recovery"] = dict(claim_recovery)
return {
"ready": False,
"signal": signal,
"check": {
"conclusion": "ActionRequired",
"title": title_by_status.get(status, "Bounty is not currently claimable"),
"summary": "Do not sign a claim or post a bond for the current canonical state.",
"text": details,
},
}
def claim_recovery_descriptor(
meta: Mapping[str, object],
api_base_url: str,
records: Optional[Mapping[str, Mapping[str, object]]] = None,
earning_pairs: Optional[set[Tuple[str, str]]] = None,
) -> Dict[str, object]:
repository = str(meta["repo"])
issue_url = str(meta["url"])
query = "is:issue is:open label:ready-to-earn"
alternatives: List[Dict[str, object]] = []
for source_url, record in (records or {}).items():
contract = str(record.get("bounty_contract") or "").lower()
if source_url == issue_url or (source_url, contract) not in (earning_pairs or set()):
continue
source_issue_number = source_url.rsplit("/", 1)[-1]
solver_reward = require_amount(record, "solver_reward")
claim_bond = require_amount(record, "claim_bond")
alternatives.append(
{
"source_issue_number": int(source_issue_number),
"source_url": source_url,
"bounty_contract": contract,
"solver_reward_usdc_base_units": str(solver_reward),
"claim_bond_usdc_base_units": str(claim_bond),
"claim_command": (
f"/claim #{source_issue_number} wallet: 0xYOUR_PUBLIC_BASE_ADDRESS"
),
}
)
alternatives.sort(
key=lambda item: (
-int(str(item["solver_reward_usdc_base_units"])),
int(item["source_issue_number"]),
)
)
return {
"schema_version": "agent-bounties/claim-recovery-v1",
"failed_issue": issue_url,
"claimable_feed": (
f"{api_base_url}/v1/base/autonomous-bounties/feed"
"?network=base-mainnet&claimable_only=true"
),
"github_query": (
f"https://github.com/{repository}/issues?q="
f"{urllib.parse.quote(query, safe='')}"
),
"alternatives": alternatives[:3],
"next_action": (
"Choose one listed alternative or refresh claimable_feed. Then run its exact "
"claim_command with a public Base address. Do not work on the failed issue."
if alternatives
else "Refresh claimable_feed later. No canonical alternative is currently "
"available; do not work on the failed issue."
),
"evidence_boundary": (
"This recovery object cannot reserve or claim work. Only confirmed canonical "
"BountyClaimed owns a round; only BountySettled proves payment."
),
}
def open_competition_wrong_mode_plan(meta: Mapping[str, object]) -> Dict[str, object]:
body = str(meta.get("issue_body") or "")
match = re.search(
r"(?:bountyContract=|agent-bounties/open-competition-v1:)(0x[0-9a-fA-F]{40})",
body,
)
contract = match.group(1).lower() if match else None
query = {
"network": "base-mainnet",
"utm_source": "github",
"utm_medium": "issue-comment",
"utm_campaign": "wrong-mode-recovery-v1",
}
if contract:
query["bountyContract"] = contract
query["discovery_id"] = (
f"eip155:8453:agent-bounties/open-competition-v1:{contract}"
)
competition_url = f"https://agentbounties.app/competition.html?{urllib.parse.urlencode(query)}"
details = "\n".join(
[
f"Issue: {meta['url']}",
"Error: wrong_competition_mode",
"Competition mode: first_valid_submission",
"Correct action: enter_competition",
f"Competition URL: {competition_url}",
"",
"This bounty has no exclusive Claim action. Generate and save the private commitment recovery envelope, enter with only its commitment, wait at least one block, and reveal from the same wallet.",
"Only a confirmed canonical BountySettled event proves payment.",
]
)
return {
"ready": False,
"signal": {
"decision": "WrongCompetitionMode",
"error_code": "wrong_competition_mode",
"competition_mode": "first_valid_submission",
"correct_action": "enter_competition",
"competition_url": competition_url,
"bounty_contract": contract,
"settlement_authority": False,
},
"check": {
"conclusion": "ActionRequired",
"title": "Enter this Open Competition",
"summary": "Use Enter competition; an exclusive claim is not available.",
"text": details,
},
}
def apply_canonical_claim_state(
env: Mapping[str, str],
meta: Mapping[str, object],
plan: Dict[str, object],
) -> Dict[str, object]:
signal = plan.get("signal") if isinstance(plan.get("signal"), dict) else None
labels = {
str(label).strip().lower()
for label in meta.get("labels", [])
if str(label).strip()
}
if "open-competition" in labels:
return open_competition_wrong_mode_plan(meta)
expects_canonical = (
signal is not None
and signal.get("decision") == "OnChainClaimRequired"
) or bool(labels & {"claimable-live", "funded-live", "claimed-live"})
if not expects_canonical:
return plan
try:
api_base_url = normalize_api_base_url(
env.get("AGENT_BOUNTIES_API_BASE_URL") or DEFAULT_API_BASE_URL
)
records, earning_pairs = load_canonical_claim_records(
env, str(meta["repo"])
)
claim_recovery = claim_recovery_descriptor(
meta, api_base_url, records, earning_pairs
)
except (OSError, ValueError, UserError, LabelReconciliationError) as error:
return canonical_unavailable_plan(
meta,
status="unavailable",
contract=None,
reason=str(error),
claim_recovery=claim_recovery_descriptor(meta, DEFAULT_API_BASE_URL),
)
issue_url = str(meta["url"])
record = records.get(issue_url)
if record is None:
return canonical_unavailable_plan(
meta,
status="missing",
contract=None,
reason="the full canonical feed has no exact source_url match",
claim_recovery=claim_recovery,
)
if signal is None or signal.get("decision") != "OnChainClaimRequired":
comment_body = str(meta.get("comment_body") or "")
wallet_match = EVM_ADDRESS_SEARCH_RE.search(comment_body)
solver_wallet = (
wallet_match.group(0).lower()
if wallet_match
else "0xYOUR_PUBLIC_BASE_WALLET"
)
reservation_id = (
f"github-claim-comment:{meta['repo']}:{issue_url}:"
f"comment:{meta['comment_id']}"
)
command_match = CLAIM_COMMAND_RE.search(comment_body)
signal = {
"issue_url": issue_url,
"contributor_login": str(meta.get("contributor_login") or "") or None,
"command": command_match.group(1).lower() if command_match else "claim",
"decision": "OnChainClaimRequired",
"reservation_id": reservation_id,
"reservation_window_minutes": 0,
"progress_required_within_minutes": 0,
"progress_signal_count": 0,
"has_progress_signal": False,
"settlement_authority": False,
"bounty_contract": None,
"claim_handoff_url": None,
"claim_plan_request": {
"body": {
"idempotency_key": reservation_id,
"solver_wallet": solver_wallet,
}
},
"operator_note": (
"The exact canonical source record supersedes legacy GitHub issue-form "
"parsing. Canonical state still controls whether a wallet request is safe."
),
}
contract = str(record.get("bounty_contract") or "").lower()
status = str(record.get("status") or "unknown").lower()
executable = (
status == "claimable"
and record.get("terms_valid") is True
and record.get("verification_ready") is True
and (issue_url, contract) in earning_pairs
)
if not executable:
if status != "claimable":
reason = f"canonical status is {status}; only claimable permits a new solver"
elif record.get("terms_valid") is not True:
reason = "the canonical terms record is missing or invalid"
elif record.get("verification_ready") is not True:
reason = str(
record.get("verification_readiness_reason")
or "the committed verification path is not executable"
)
elif (issue_url, contract) not in earning_pairs:
reason = "the exact contract is absent from the executable earning feed"
else:
reason = "the canonical record is not executable"
return canonical_unavailable_plan(
meta,
status=status,
contract=contract,
reason=reason,
claim_recovery=claim_recovery,
)
request = native_claim_request(signal, api_base_url, contract)
request_body = request.get("body") if isinstance(request.get("body"), dict) else {}
solver_wallet = str(request_body.get("solver_wallet") or "")
solver_query = (
f"&solver={urllib.parse.quote(solver_wallet, safe='')}"
if EVM_ADDRESS_RE.fullmatch(solver_wallet)
else ""
)
claim_key = str(signal.get("reservation_id") or "github-claim-comment")
handoff = (
f"{STATIC_EARN_PAGE_URL}?bountyContract={urllib.parse.quote(contract, safe='')}"
f"&claimKey={urllib.parse.quote(claim_key, safe='')}"
f"&source=github-claim{solver_query}"
f"&issue={urllib.parse.quote(issue_url, safe='')}"
)
signal.update(
{
"bounty_contract": contract,
"claim_handoff_url": handoff,
"claim_plan_request": request,
"operator_note": (
f"Canonical contract: {contract}. The exact record is claimable, "
"terms-valid, verification-ready, and present in the earning feed. "
"A hosted candidate is coordination state; only canonical BountyClaimed "
"owns the round."
),
}
)
solver_wallet = str(request["body"]["solver_wallet"])
if EVM_ADDRESS_RE.fullmatch(solver_wallet):
try:
status_code, response_body = load_native_claim_handoff(env, request)
response, problem = summarize_native_claim_handoff(
status_code,
response_body,
contract=contract,
solver_wallet=solver_wallet,
)
if response is not None:
signal["claim_handoff_response"] = response
if problem is not None:
signal["claim_handoff_problem"] = problem
except (OSError, ValueError, UserError, LabelReconciliationError) as error:
signal["claim_handoff_problem"] = {
"error": "claim_handoff_unavailable",
"next_action": (
f"{error}. Replay the published machine request with the same "
"idempotency_key; do not sign an unverified payload."
),
}
plan["signal"] = signal
handoff_response = signal.get("claim_handoff_response")
wallet_request_ready = isinstance(handoff_response, dict) and isinstance(
handoff_response.get("wallet_request"), dict
)
plan["check"] = {
"conclusion": "ActionRequired",
"title": (
"Exact wallet signature requested"
if wallet_request_ready
else "Autonomous bounty requires an on-chain claim"
),
"summary": (
"Send the exact wallet_request to the payout wallet once, then replay its unchanged signature."
if wallet_request_ready
else "Provide a public Base payout wallet or run the published machine request."
),
"text": "\n".join(
[
f"Issue: {issue_url}",
f"Contributor: {meta['contributor_login']}",
"Decision: OnChainClaimRequired",
f"Canonical contract: {contract}",
"Canonical status: claimable",
"Verification ready: true",
"Settlement authority: false",
"",
"The wallet signature and confirmed contract event, not this comment, claim the round.",
"Only a confirmed BountySettled event proves payment.",
]
),
}
return plan
def load_existing_comments(env: Mapping[str, str], meta: Mapping[str, object]) -> List[Mapping[str, object]]:
return load_issue_comments(
env,
meta["repo"],
meta["number"],
"AGENT_BOUNTIES_CLAIM_COMMENTS_FILE",
"gh is required to inspect existing claim planner comments",
UserError,
)
def marker_field(pattern: re.Pattern[str], body: str) -> Optional[str]:
match = pattern.search(body)
return match.group(1) if match else None
def claim_comment_id(body: str) -> Optional[str]:
return marker_field(COMMENT_ID_RE, body)
def reservation_id(body: str) -> Optional[str]:
return marker_field(RESERVATION_RE, body)
def contributor_login(body: str) -> Optional[str]:
return marker_field(CONTRIBUTOR_RE, body)
def active_claim_login(existing_comments: List[Mapping[str, object]], current_comment_id: str) -> Optional[str]:
for comment in reversed(existing_comments):
body = str(comment.get("body") or "")
if MARKER not in body or claim_comment_id(body) == current_comment_id:
continue
if "Agent bounty claim reserved" in body:
contributor = contributor_login(body)
if contributor and contributor != "unknown":
return contributor
return None
def progress_signal_count(existing_comments: List[Mapping[str, object]], current_reservation_id: Optional[str]) -> int:
if not current_reservation_id:
return 0
count = 0
for comment in existing_comments:
body = str(comment.get("body") or "")
if MARKER in body and reservation_id(body) == current_reservation_id and "Has progress signal: true" in body:
count += 1
return count
def run_github_claim_plan(
env: Mapping[str, str],
workspace: pathlib.Path,
meta: Mapping[str, object],
body_file: pathlib.Path,
active_login: Optional[str],
prior_progress_count: int,
) -> str:
cargo_path = find_executable(["cargo", "cargo.exe"])
if not cargo_path:
raise UserError("cargo is required to plan a claim comment")
command = [
cargo_path,
"run",
"-p",
"cli",
"--",
"github-claim-comment-plan",
"--repository",
str(meta["repo"]),
"--issue-url",
str(meta["url"]),
"--title",
str(meta["title"]),
"--body-file",
cargo_body_path(body_file, cargo_path),
"--comment-body",
str(meta["comment_body"]),
"--contributor-login",
str(meta["contributor_login"]),
"--comment-id",
str(meta["comment_id"]),
"--claim-age-minutes",
"0",
"--progress-signal-count",
str(prior_progress_count),
]
if active_login:
command.extend(["--active-claim-login", active_login])
result = subprocess.run(
command,
cwd=workspace,
env=dict(env),
text=True,
stdout=subprocess.PIPE,
stderr=None,
check=False,
)
if result.returncode != 0:
raise UserError(f"github-claim-comment-plan failed with exit code {result.returncode}")
return result.stdout
def render_comment(meta: Mapping[str, object], plan: Mapping[str, object]) -> str:
conclusion = str(read_json_field(plan, "check.conclusion"))
title = str(read_json_field(plan, "check.title"))
summary = str(read_json_field(plan, "check.summary"))
details = str(read_json_field(plan, "check.text"))
ready = bool(plan.get("ready"))
signal = plan.get("signal") if isinstance(plan.get("signal"), dict) else {}
decision = str(signal.get("decision") or "")
reservation = str(signal.get("reservation_id") or "none")
contributor = str(meta.get("contributor_login") or "unknown")
comment_url = str(meta.get("comment_url") or "").strip()
comment_ref = comment_url or f"issue comment {meta['comment_id']}"
wallet_handoff = str(signal.get("claim_handoff_url") or "").strip()
machine_request = signal.get("claim_plan_request")
handoff_response = signal.get("claim_handoff_response")
handoff_problem = signal.get("claim_handoff_problem")
claim_recovery = signal.get("claim_recovery")
if decision == "RecoveryReserved":
status_line = (
"This issue is reserved for incident recovery. The claim command created no "
"on-chain reservation; do not connect a wallet, sign a claim, or post a bond."
)
elif decision == "CanonicalStateUnavailable":
status_line = (
"Canonical state does not permit a new claim. Do not connect a wallet, "
"sign a claim, or post a bond for this round."
)
elif decision == "OnChainClaimRequired":
if isinstance(handoff_response, dict) and isinstance(
handoff_response.get("wallet_request"), dict
):
status_line = (
"The hosted service reserved this candidate and returned the exact wallet "
"request. This is not yet an on-chain claim: sign once, replay the unchanged "
"65-byte result privately through next_request, and wait for confirmed "
"BountyClaimed."
)
elif isinstance(handoff_response, dict):
status_line = (
"The hosted service recorded the candidate state below but did not request a "
"signature. Follow next_action; do not sign while waitlisted or after a "
"terminal state."
)
elif isinstance(handoff_problem, dict):
status_line = (
"The hosted handoff did not reach signature-ready state. Follow the exact "
"failed transition below or replay the same machine request; do not invent or "
"post a signature."
)
else:
status_line = (
"GitHub recorded claim intent but no valid public payout wallet was supplied. "
"Add `wallet: 0xYOUR_PUBLIC_BASE_ADDRESS` to a new `/claim` comment; never post "
"a private key or seed phrase."
)
elif ready:
status_line = "This claim is a temporary coordination signal only; it never authorizes bounty acceptance, escrow release, or payout."
else:
status_line = "This claim comment needs a concrete progress signal before it should reserve attention."
claim_actions = []
if isinstance(machine_request, dict):
claim_actions.extend(
[
"**Machine claim request:**",
"",
"```json",
json.dumps(machine_request, indent=2, sort_keys=True),
"```",
"",
]
)
if isinstance(handoff_response, dict):
claim_actions.extend(
[
"**Hosted claim handoff:**",
"",
"```json",
json.dumps(handoff_response, indent=2, sort_keys=True),
"```",
"",
]
)
if isinstance(handoff_problem, dict):
claim_actions.extend(
[
"**Hosted handoff problem:**",
"",
"```json",
json.dumps(handoff_problem, indent=2, sort_keys=True),
"```",
"",
]
)
if wallet_handoff:
claim_actions.extend(
[
f"Optional browser fallback: {wallet_handoff}",
"",
]
)
if isinstance(claim_recovery, dict):
claim_actions.extend(
[
"**Recover into live earning inventory:**",
"",
"```json",
json.dumps(claim_recovery, indent=2, sort_keys=True),
"```",
"",
]
)
return "\n".join(
[
MARKER,
f"### {title}: {conclusion}",
"",
summary,
"",
status_line,
"",
*claim_actions,
"Feedback (never eligibility or payment authority): reply with `discovery_source`, "
"`participation_reason`, and `improvement_feedback`.",
"",
f"Claim comment id: `{meta['comment_id']}`",
f"Claim comment: {comment_ref}",
f"Contributor: `{contributor}`",
f"Reservation id: `{reservation}`",
"",
"<details><summary>Planner output</summary>",
"",
"```",
details,
"```",
"",
"</details>",
"",
]
)
def append_step_summary(env: Mapping[str, str], comment: str) -> None:
append_github_summary(env, "Agent bounty claim signal", comment)
def publish_comment(
env: Mapping[str, str],
meta: Mapping[str, object],
existing_comments: List[Mapping[str, object]],
comment: str,
) -> None:
publish_issue_comment(
env,
meta["repo"],
meta["number"],
MARKER,
comment,
"paid-bounty-claim-comment.md",
"gh is required to publish the claim planner comment",
UserError,
existing_comments,
lambda body: MARKER in body
and claim_comment_id(body) == str(meta["comment_id"]),
)
def run_from_env(env: Mapping[str, str], stdout: TextIO) -> int:
repo_root = script_repo_root()
workspace = pathlib.Path(env.get("GITHUB_WORKSPACE") or repo_root).resolve()
tmp_dir = pathlib.Path(env.get("RUNNER_TEMP") or workspace / "target" / "tmp").resolve()
tmp_dir.mkdir(parents=True, exist_ok=True)
event = read_event(env)
meta, body_file = write_issue_files(env, event, tmp_dir)
existing_comments = load_existing_comments(env, meta)
active_login = active_claim_login(existing_comments, str(meta["comment_id"]))
prior_progress_count = progress_signal_count(existing_comments, None)
labels = meta.get("labels") if isinstance(meta.get("labels"), list) else []
if "recovery-reserved" in labels:
plan = recovery_reserved_plan(meta)
plan_json = json.dumps(plan, indent=2, sort_keys=True) + "\n"
else:
plan_json = run_github_claim_plan(
env, workspace, meta, body_file, active_login, prior_progress_count
)
plan = json.loads(plan_json)
plan = apply_canonical_claim_state(env, meta, plan)
plan_json = json.dumps(plan, indent=2, sort_keys=True) + "\n"
comment = render_comment(meta, plan)
plan_file = tmp_dir / "paid-bounty-claim-plan.json"
plan_file.write_text(plan_json, encoding="utf-8")
comment_file = tmp_dir / "paid-bounty-claim-comment.md"
comment_file.write_text(comment, encoding="utf-8")
append_step_summary(env, comment)
if env.get("DRY_RUN") == "1":
stdout.write(plan_json)
if not plan_json.endswith("\n"):
stdout.write("\n")
stdout.write("\n")
stdout.write(comment)
return 0
publish_comment(env, meta, existing_comments, comment)
return 0
def run_self_test() -> int:
repo_root = script_repo_root()
tmp_dir = repo_root / "target" / "tmp"
tmp_dir.mkdir(parents=True, exist_ok=True)
issue_body = (repo_root / "examples" / "github-paid-bounty-issue.md").read_text(
encoding="utf-8"
)
event = {
"repository": {"full_name": "agent-bounties/agent-bounties"},
"issue": {
"number": 1,
"title": "[bounty]: Fix CI",
"html_url": "https://github.com/agent-bounties/agent-bounties/issues/1",
"body": issue_body,
"labels": [{"name": "bounty"}],
},
"comment": {
"id": 12346,
"html_url": "https://github.com/agent-bounties/agent-bounties/issues/1#issuecomment-12346",
"body": "/agent-bounty claim\nPlan: inspect CI logs and open a focused PR with local test output.",
"user": {"login": "example-agent"},
},
}
event_path = tmp_dir / "github-claim-event.json"
event_path.write_text(json.dumps(event), encoding="utf-8")
env = dict(os.environ)
env.update(
{
"GITHUB_EVENT_PATH": str(event_path),
"GITHUB_REPOSITORY": "agent-bounties/agent-bounties",
"GITHUB_WORKSPACE": str(repo_root),
"RUNNER_TEMP": str(tmp_dir),
"AGENT_BOUNTIES_CLAIM_COMMENTS_FILE": str(tmp_dir / "github-claim-existing-comments.json"),
"DRY_RUN": "1",
}
)