forked from OpenCoven/coven-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoven_github_adapter.py
More file actions
1682 lines (1457 loc) · 61.3 KB
/
Copy pathcoven_github_adapter.py
File metadata and controls
1682 lines (1457 loc) · 61.3 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
import base64
import hashlib
import hmac
import json
import os
import re
import subprocess
import tempfile
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
ROOT_DIR = Path(__file__).resolve().parent
STATE_DIR = Path(os.environ.get("COVEN_GITHUB_STATE_DIR", ROOT_DIR / "coven-github-state"))
DELIVERIES_DIR = STATE_DIR / "deliveries"
TASKS_DIR = STATE_DIR / "tasks"
WORKSPACES_DIR = STATE_DIR / "workspaces"
ATTEMPTS_DIR = STATE_DIR / "attempts"
POLICY_PATH = Path(os.environ.get("COVEN_GITHUB_POLICY_PATH", ROOT_DIR / "coven-github-policy.json"))
PRIVATE_KEY_PATH = Path(
os.environ.get("GITHUB_APP_PRIVATE_KEY_PATH", ROOT_DIR / ".coven-github-private-key.pem")
)
APP_ID = os.environ.get("GITHUB_APP_ID", "").strip()
COVEN_CODE_BIN = os.environ.get("COVEN_CODE_BIN", "coven-code").strip() or "coven-code"
COVEN_CODE_MODEL = os.environ.get("COVEN_CODE_MODEL", "gpt-5.5").strip()
WEBHOOK_SECRET = os.environ.get("GITHUB_WEBHOOK_SECRET", "").strip()
def env_int(name, default, minimum=0, maximum=10):
raw = os.environ.get(name, "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError:
return default
return max(minimum, min(maximum, value))
MAX_REVIEW_FIX_LOOPS = env_int("COVEN_REVIEW_FIX_LOOPS", 0, minimum=0, maximum=5)
TERMINAL_RESULT_EXIT_CODES = {0, 1, 3}
RESULT_STATUSES = {"success", "failure", "partial", "needs_input"}
REVIEW_MODES = {"none", "pull_request", "review_comment"}
REVIEW_EVIDENCE_STATUSES = {"not_applicable", "complete", "partial", "missing"}
RESULT_FIELDS = {
"contract_version",
"status",
"branch",
"commits",
"files_changed",
"summary",
"pr_body",
"review",
"exit_reason",
}
COMMIT_FIELDS = {"sha", "message"}
REVIEW_FIELDS = {
"mode",
"evidence_status",
"reviewed_files",
"supporting_files",
"findings",
"tests_run",
"no_findings_reason",
"limitations",
}
FINDING_FIELDS = {"severity", "file", "line", "title", "body", "recommendation"}
TEST_RUN_FIELDS = {"command", "status", "output_summary"}
def account_home():
try:
import pwd
return Path(pwd.getpwuid(os.getuid()).pw_dir)
except Exception:
return Path.home()
def configured_codex_tokens_path():
configured = os.environ.get("COVEN_CODE_CODEX_TOKENS_PATH", "").strip()
if configured:
return Path(configured).expanduser()
return account_home() / ".coven-code" / "codex_tokens.json"
CODEX_TOKENS_PATH = configured_codex_tokens_path()
for directory in (DELIVERIES_DIR, TASKS_DIR, WORKSPACES_DIR, ATTEMPTS_DIR):
directory.mkdir(parents=True, exist_ok=True)
DEFAULT_FAMILIAR = {
"id": "cody",
"display_name": "Cody",
"model": None,
"skills": ["code-review"],
}
DEFAULT_POLICY = {
"version": 1,
"installations": {},
}
def utc_now():
return datetime.now(timezone.utc).isoformat()
def read_json(path, default):
try:
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
except FileNotFoundError:
return default
def write_json_atomic(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=str(path.parent))
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(value, handle, sort_keys=True, indent=2)
handle.write("\n")
os.replace(tmp_name, str(path))
finally:
if os.path.exists(tmp_name):
os.unlink(tmp_name)
def b64url(raw):
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def sign_rs256(message):
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
key_data = PRIVATE_KEY_PATH.read_bytes()
private_key = serialization.load_pem_private_key(key_data, password=None)
return private_key.sign(message, padding.PKCS1v15(), hashes.SHA256())
def github_app_jwt():
if not APP_ID:
raise RuntimeError("GITHUB_APP_ID is required")
now = int(time.time())
header = {"alg": "RS256", "typ": "JWT"}
payload = {"iat": now - 60, "exp": now + 540, "iss": APP_ID}
signing_input = (
b64url(json.dumps(header, separators=(",", ":")).encode("utf-8"))
+ "."
+ b64url(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
).encode("ascii")
return signing_input.decode("ascii") + "." + b64url(sign_rs256(signing_input))
def github_request(method, url, token, body=None):
headers = {
"Accept": "application/vnd.github+json",
"Authorization": "Bearer " + token,
"User-Agent": "coven-github-hosted-prototype",
"X-GitHub-Api-Version": "2022-11-28",
}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = Request(url, data=data, headers=headers, method=method)
try:
with urlopen(request, timeout=30) as response:
raw = response.read().decode("utf-8")
return json.loads(raw) if raw else {}
except HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
raise RuntimeError("GitHub API {} {} failed: {}".format(method, url, raw))
def installation_token(installation_id):
app_token = github_app_jwt()
response = github_request(
"POST",
"https://api.github.com/app/installations/{}/access_tokens".format(installation_id),
app_token,
{},
)
token = response.get("token")
if not token:
raise RuntimeError("GitHub installation token response did not include token")
return token
def load_policy():
if not POLICY_PATH.exists():
write_json_atomic(POLICY_PATH, DEFAULT_POLICY)
return read_json(POLICY_PATH, DEFAULT_POLICY)
def repo_policy(payload):
policy = load_policy()
installation_id = str((payload.get("installation") or {}).get("id") or "")
repository = payload.get("repository") or {}
repo_id = str(repository.get("id") or "")
installation = (policy.get("installations") or {}).get(installation_id) or {}
repo = (installation.get("repositories") or {}).get(repo_id)
return installation_id, repo_id, repo
def delivery_path(delivery_id):
return DELIVERIES_DIR / (delivery_id + ".json")
def task_path(task_id):
return TASKS_DIR / (task_id + ".json")
def payload_hash(payload):
raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(raw).hexdigest()
def delivery_record(delivery_id, event_name, payload):
repository = payload.get("repository") or {}
installation = payload.get("installation") or {}
return {
"delivery_id": delivery_id,
"event": event_name,
"action": payload.get("action"),
"installation_id": installation.get("id"),
"repository_id": repository.get("id"),
"repository": repository.get("full_name"),
"payload_hash": payload_hash(payload),
"received_at": utc_now(),
"state": "received",
"issue_refs": ["OpenCoven/coven-github#2"],
}
def mentioned(text, policy):
normalized = text or ""
for username in policy.get("bot_usernames") or []:
login = str(username).strip()
if not login:
continue
pattern = r"(?<![A-Za-z0-9_.+-])@{}(?![A-Za-z0-9_/-])".format(
re.escape(login)
)
if re.search(pattern, normalized, flags=re.IGNORECASE):
return True
return False
def labels_include_trigger(labels, policy):
wanted = set((policy.get("trigger_labels") or []))
for label in labels or []:
name = (label.get("name") if isinstance(label, dict) else str(label)).strip()
if name in wanted:
return True
return False
def issue_assigned_to_bot(issue, policy):
wanted = {str(username).lower() for username in (policy.get("bot_usernames") or [])}
if not wanted:
return False
candidates = []
assignee = issue.get("assignee")
if assignee:
candidates.append(assignee)
candidates.extend(issue.get("assignees") or [])
for candidate in candidates:
login = candidate.get("login") if isinstance(candidate, dict) else str(candidate)
if str(login).lower() in wanted:
return True
return False
def trigger_enabled(policy, trigger):
enabled = policy.get("enabled_triggers")
if enabled is None:
return True
return trigger in set(enabled or [])
def event_trigger_key(event_name, payload):
action = str(payload.get("action") or "").strip()
return "{}.{}".format(event_name, action) if action else event_name
def build_task_from_event(event_name, delivery_id, payload, policy):
repository = payload.get("repository") or {}
installation = payload.get("installation") or {}
familiar = policy.get("familiar") or DEFAULT_FAMILIAR
base = {
"task_id": delivery_id,
"delivery_id": delivery_id,
"created_at": utc_now(),
"updated_at": utc_now(),
"state": "queued",
"attempts": 0,
"installation_id": installation.get("id"),
"repository_id": repository.get("id"),
"repository": repository.get("full_name"),
"clone_url": repository.get("clone_url")
or "https://github.com/{}.git".format(repository.get("full_name")),
"default_branch": repository.get("default_branch") or policy.get("default_branch") or "main",
"familiar": familiar,
"publication": policy.get("publication") or {"mode": "record_only"},
"issue_refs": ["OpenCoven/coven-github#2", "OpenCoven/coven-github#7"],
}
if event_name == "issue_comment":
issue = payload.get("issue") or {}
comment = payload.get("comment") or {}
if payload.get("action") != "created":
return ignored(base, "unsupported_issue_comment_action")
if not mentioned(comment.get("body"), policy):
return ignored(base, "issue_comment_without_mention")
if not trigger_enabled(policy, "issue_comment.created"):
return ignored(base, "issue_comment_not_enabled")
if issue.get("pull_request"):
base.update(
{
"trigger": "issue_mention",
"target": {
"kind": "pull_request",
"pr_number": int(issue.get("number") or 0),
},
"task": {
"kind": "respond_to_mention",
"issue_number": int(issue.get("number") or 0),
"comment_body": comment.get("body") or "",
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#4"],
}
)
return base
base.update(
{
"trigger": "issue_mention",
"task": {
"kind": "respond_to_mention",
"issue_number": int(issue.get("number") or 0),
"comment_body": comment.get("body") or "",
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#4"],
}
)
return base
if event_name == "pull_request_review_comment":
comment = payload.get("comment") or {}
pull_request = payload.get("pull_request") or {}
if payload.get("action") != "created":
return ignored(base, "unsupported_pr_review_comment_action")
if not mentioned(comment.get("body"), policy):
return ignored(base, "pr_review_comment_without_mention")
if not trigger_enabled(policy, "pull_request_review_comment.created"):
return ignored(base, "pr_review_comment_not_enabled")
base.update(
{
"trigger": "pr_review_comment",
"task": {
"kind": "address_review_comment",
"pr_number": int(pull_request.get("number") or 0),
"comment_body": comment.get("body") or "",
"diff_hunk": comment.get("diff_hunk"),
"path": comment.get("path"),
"line": comment.get("line"),
"side": comment.get("side"),
"commit_id": comment.get("commit_id"),
"html_url": comment.get("html_url"),
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#4"],
}
)
return base
if event_name == "issues":
issue = payload.get("issue") or {}
action = payload.get("action")
if action not in ("assigned", "labeled"):
return ignored(base, "unsupported_issue_action")
if action == "assigned" and not trigger_enabled(policy, "issues.assigned"):
return ignored(base, "issue_assigned_not_enabled")
if action == "assigned" and not issue_assigned_to_bot(issue, policy):
return ignored(base, "issue_assigned_to_unmanaged_user")
if action == "labeled" and not labels_include_trigger(issue.get("labels"), policy):
return ignored(base, "issue_label_not_enabled")
if action == "labeled" and not trigger_enabled(policy, "issues.labeled"):
return ignored(base, "issue_label_not_enabled")
base.update(
{
"trigger": "issue_assigned",
"task": {
"kind": "fix_issue",
"issue_number": int(issue.get("number") or 0),
"issue_title": issue.get("title") or "",
"issue_body": issue.get("body") or "",
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#4"],
}
)
return base
if event_name == "pull_request":
pull_request = payload.get("pull_request") or {}
if not trigger_enabled(policy, "pull_request"):
return ignored(base, "pull_request_not_enabled")
base.update(
{
"state": "ignored",
"ignored_reason": "pull_request_review_task_not_in_headless_contract_v2",
"trigger": "pull_request",
"target": {
"action": payload.get("action"),
"number": pull_request.get("number"),
"head_sha": (pull_request.get("head") or {}).get("sha"),
"head_ref": (pull_request.get("head") or {}).get("ref"),
"base_ref": (pull_request.get("base") or {}).get("ref"),
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#10"],
}
)
return base
if event_name == "push":
if not trigger_enabled(policy, "push"):
return ignored(base, "push_not_enabled")
base.update(
{
"state": "ignored",
"ignored_reason": "push_review_task_not_in_headless_contract_v2",
"trigger": "push",
"target": {
"ref": payload.get("ref"),
"before": payload.get("before"),
"after": payload.get("after"),
"commit_count": len(payload.get("commits") or []),
},
"issue_refs": base["issue_refs"] + ["OpenCoven/coven-github#10"],
}
)
return base
return ignored(base, "unsupported_event")
def ignored(base, reason):
base["state"] = "ignored"
base["ignored_reason"] = reason
return base
def header_value(headers, name):
wanted = name.lower()
for key, value in (headers or {}).items():
if str(key).lower() == wanted:
return value
return None
def verify_webhook_signature(secret, body, signature):
if not secret:
raise RuntimeError("GITHUB_WEBHOOK_SECRET is required")
if not signature or not str(signature).startswith("sha256="):
return False
expected = "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, str(signature))
def route_signed_delivery(headers, body, debug, webhook_secret=None):
raw_body = body.encode("utf-8") if isinstance(body, str) else body
if raw_body is None:
raw_body = b""
signature = header_value(headers, "x-hub-signature-256")
try:
signature_valid = verify_webhook_signature(
webhook_secret or WEBHOOK_SECRET, raw_body, signature
)
except RuntimeError as exc:
return {"ok": False, "status": 500, "error": str(exc)}
if not signature_valid:
return {"ok": False, "status": 401, "error": "invalid signature"}
event_name = header_value(headers, "x-github-event")
if not event_name:
return {"ok": False, "status": 400, "error": "missing event type"}
delivery_id = header_value(headers, "x-github-delivery")
if not delivery_id:
return {"ok": False, "status": 400, "error": "missing delivery id"}
try:
payload = json.loads(raw_body.decode("utf-8"))
except json.JSONDecodeError:
return {"ok": False, "status": 400, "error": "invalid json"}
if event_name == "ping":
return {"ok": True, "status": 200, "pong": True, "delivery_id": delivery_id}
result = route_delivery(str(event_name), str(delivery_id), payload, debug)
result["status"] = 200
return result
def route_delivery(event_name, delivery_id, payload, debug):
delivery_file = delivery_path(delivery_id)
if delivery_file.exists():
existing = read_json(delivery_file, {})
return {
"ok": True,
"action": "duplicate_ignored",
"delivery_id": delivery_id,
"task_id": existing.get("task_id"),
"state": existing.get("state"),
}
delivery = delivery_record(delivery_id, event_name, payload)
installation_id, repo_id, policy = repo_policy(payload)
if not policy:
delivery["state"] = "ignored"
delivery["routing_result"] = "no_policy_for_installation_repo"
delivery["installation_id"] = installation_id or delivery.get("installation_id")
delivery["repository_id"] = repo_id or delivery.get("repository_id")
write_json_atomic(delivery_file, delivery)
return {
"ok": True,
"action": "ignored",
"delivery_id": delivery_id,
"reason": "no_policy_for_installation_repo",
}
trigger = event_trigger_key(event_name, payload)
if not trigger_enabled(policy, trigger):
delivery["state"] = "ignored"
delivery["routing_result"] = "trigger_not_enabled"
delivery["installation_id"] = installation_id or delivery.get("installation_id")
delivery["repository_id"] = repo_id or delivery.get("repository_id")
write_json_atomic(delivery_file, delivery)
return {
"ok": True,
"action": "ignored",
"delivery_id": delivery_id,
"reason": "trigger_not_enabled",
"trigger": trigger,
}
task = build_task_from_event(event_name, delivery_id, payload, policy)
task["policy_snapshot"] = {
"enabled_triggers": policy.get("enabled_triggers") or [],
"publication": policy.get("publication") or {"mode": "record_only"},
}
write_json_atomic(task_path(task["task_id"]), task)
delivery["task_id"] = task["task_id"]
delivery["state"] = task["state"]
delivery["routing_result"] = task.get("ignored_reason") or "queued"
write_json_atomic(delivery_file, delivery)
if task["state"] == "queued":
try:
run_task(task["task_id"], debug)
except Exception:
debug("COVEN GITHUB TASK RUN FAIL task_id={} {}".format(task["task_id"], traceback.format_exc()))
return {
"ok": True,
"action": "accepted" if task["state"] != "ignored" else "ignored",
"delivery_id": delivery_id,
"task_id": task["task_id"],
"state": read_json(task_path(task["task_id"]), task).get("state"),
"reason": task.get("ignored_reason"),
"queued": task["state"] == "queued",
}
def run_command(args, cwd=None, env=None, timeout=300):
proc = subprocess.run(
args,
cwd=cwd,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
text=True,
)
return {
"args": args,
"returncode": proc.returncode,
"stdout": proc.stdout[-8000:],
"stderr": proc.stderr[-8000:],
}
def write_askpass(work_dir):
script = work_dir / "git-askpass.sh"
script.write_text("#!/bin/sh\nprintf '%s\\n' \"$COVEN_GIT_TOKEN\"\n", encoding="utf-8")
script.chmod(0o700)
return script
def require_string(value, path):
if not isinstance(value, str):
raise ValueError("{} must be a string".format(path))
def require_optional_string(value, path):
if value is not None and not isinstance(value, str):
raise ValueError("{} must be a string or null".format(path))
def validate_object_fields(value, allowed, path):
extra = set(value.keys()) - allowed
if extra:
raise ValueError("{} has unsupported field {}".format(path, sorted(extra)[0]))
def validate_string_array(values, path):
if not isinstance(values, list):
raise ValueError("{} must be an array".format(path))
for index, item in enumerate(values):
require_string(item, "{}[{}]".format(path, index))
def validate_commits(commits):
if not isinstance(commits, list):
raise ValueError("result.commits must be an array")
for index, commit in enumerate(commits):
if not isinstance(commit, dict):
raise ValueError("result.commits[{}] must be an object".format(index))
validate_object_fields(commit, COMMIT_FIELDS, "result.commits[{}]".format(index))
for field in COMMIT_FIELDS:
if field not in commit:
raise ValueError(
"result.commits[{}] missing required field {}".format(index, field)
)
require_string(commit.get(field), "result.commits[{}].{}".format(index, field))
def validate_findings(findings):
if not isinstance(findings, list):
raise ValueError("result.review.findings must be an array")
severities = {"info", "low", "medium", "high", "critical"}
for index, finding in enumerate(findings):
if not isinstance(finding, dict):
raise ValueError("result.review.findings[{}] must be an object".format(index))
validate_object_fields(finding, FINDING_FIELDS, "result.review.findings[{}]".format(index))
for field in FINDING_FIELDS:
if field not in finding:
raise ValueError(
"result.review.findings[{}] missing required field {}".format(index, field)
)
severity = finding.get("severity")
if severity not in severities:
raise ValueError("unsupported review finding severity {}".format(severity))
require_string(finding.get("file"), "result.review.findings[{}].file".format(index))
line = finding.get("line")
if line is not None and (isinstance(line, bool) or not isinstance(line, int) or line < 1):
raise ValueError(
"result.review.findings[{}].line must be an integer >= 1 or null".format(
index
)
)
require_string(finding.get("title"), "result.review.findings[{}].title".format(index))
require_string(finding.get("body"), "result.review.findings[{}].body".format(index))
require_optional_string(
finding.get("recommendation"),
"result.review.findings[{}].recommendation".format(index),
)
def validate_tests_run(tests_run):
if not isinstance(tests_run, list):
raise ValueError("result.review.tests_run must be an array")
statuses = {"passed", "failed", "not_run", "unknown"}
for index, test in enumerate(tests_run):
if not isinstance(test, dict):
raise ValueError("result.review.tests_run[{}] must be an object".format(index))
validate_object_fields(test, TEST_RUN_FIELDS, "result.review.tests_run[{}]".format(index))
for field in TEST_RUN_FIELDS:
if field not in test:
raise ValueError(
"result.review.tests_run[{}] missing required field {}".format(index, field)
)
require_string(test.get("command"), "result.review.tests_run[{}].command".format(index))
status = test.get("status")
if status not in statuses:
raise ValueError("unsupported review test status {}".format(status))
require_optional_string(
test.get("output_summary"),
"result.review.tests_run[{}].output_summary".format(index),
)
def validate_result_contract(result):
if not isinstance(result, dict):
raise ValueError("result.json must be a JSON object")
validate_object_fields(result, RESULT_FIELDS, "result.json")
for field in ("contract_version", "status", "commits", "files_changed", "summary", "pr_body", "review"):
if field not in result:
raise ValueError("result.json missing required field {}".format(field))
if result.get("contract_version") != "2":
raise ValueError("unsupported result contract_version {}".format(result.get("contract_version")))
if result.get("status") not in RESULT_STATUSES:
raise ValueError("unsupported result status {}".format(result.get("status")))
status = result.get("status")
validate_commits(result.get("commits"))
validate_string_array(result.get("files_changed"), "result.files_changed")
if not isinstance(result.get("summary"), str):
raise ValueError("result.summary must be a string")
if not isinstance(result.get("pr_body"), str):
raise ValueError("result.pr_body must be a string")
if result.get("branch") is not None and not isinstance(result.get("branch"), str):
raise ValueError("result.branch must be a string or null")
if result.get("exit_reason") not in (
"test_failure",
"ambiguous_spec",
"git_conflict",
"infra_error",
None,
):
raise ValueError("unsupported result exit_reason {}".format(result.get("exit_reason")))
if status == "success" and result.get("exit_reason") is not None:
raise ValueError("result.exit_reason must be null when status is success")
if status != "success" and result.get("exit_reason") is None:
raise ValueError("result.exit_reason is required when status is {}".format(status))
review = result.get("review")
if not isinstance(review, dict):
raise ValueError("result.review must be an object")
validate_object_fields(review, REVIEW_FIELDS, "result.review")
for field in REVIEW_FIELDS:
if field not in review:
raise ValueError("result.review missing required field {}".format(field))
mode = review.get("mode")
evidence_status = review.get("evidence_status")
if mode not in REVIEW_MODES:
raise ValueError("unsupported review mode {}".format(mode))
if evidence_status not in REVIEW_EVIDENCE_STATUSES:
raise ValueError("unsupported review evidence_status {}".format(evidence_status))
validate_string_array(review.get("reviewed_files"), "result.review.reviewed_files")
validate_string_array(review.get("supporting_files"), "result.review.supporting_files")
validate_findings(review.get("findings"))
validate_tests_run(review.get("tests_run"))
require_optional_string(review.get("no_findings_reason"), "result.review.no_findings_reason")
validate_string_array(review.get("limitations"), "result.review.limitations")
if mode in ("pull_request", "review_comment"):
if evidence_status == "not_applicable":
raise ValueError("review evidence_status not_applicable is invalid for {}".format(mode))
if evidence_status != "missing" and not review.get("reviewed_files"):
raise ValueError("reviewed_files is required for review mode {}".format(mode))
no_findings_reason = review.get("no_findings_reason")
if not review.get("findings") and not (
isinstance(no_findings_reason, str) and no_findings_reason.strip()
):
raise ValueError("no_findings_reason is required when review findings are empty")
if mode == "none" and evidence_status != "not_applicable":
raise ValueError("review evidence_status {} is invalid for none mode".format(evidence_status))
def session_brief(task, workspace, review_context=None, extra_audit_instruction=None):
owner, name = (task["repository"] or "/").split("/", 1)
brief = {
"contract_version": "2",
"trigger": task["trigger"],
"repo": {
"owner": owner,
"name": name,
"clone_url": task["clone_url"],
"default_branch": task["default_branch"],
},
"task": task["task"],
"familiar": task["familiar"],
"workspace": {"root": str(workspace)},
}
if review_context:
brief["review_context"] = review_context
instruction = (
"This run is evidence-backed. Review the supplied PR metadata and "
"changed-file patches in review_context before responding. Cite the "
"specific changed files you inspected in the result summary."
)
if extra_audit_instruction:
instruction = instruction + "\n\n" + extra_audit_instruction
brief["audit_instruction"] = instruction
return brief
def run_coven_code_cycle(
task,
workspace,
review_context,
attempt_dir,
env,
cycle,
extra_audit_instruction=None,
):
suffix = "" if cycle == 0 else "-repair-{}".format(cycle)
brief_path = attempt_dir / "session-brief{}.json".format(suffix)
result_path = attempt_dir / "result{}.json".format(suffix)
run_path = attempt_dir / "run{}.json".format(suffix)
write_json_atomic(
brief_path,
session_brief(task, workspace, review_context, extra_audit_instruction),
)
run = run_command(
[
COVEN_CODE_BIN,
"--headless",
"--hosted-review",
"--provider",
"codex",
"--model",
COVEN_CODE_MODEL,
"--context",
str(brief_path),
"--output",
str(result_path),
],
cwd=str(workspace),
env=env,
timeout=1800,
)
write_json_atomic(run_path, redacted_command_result(run))
result = None
result_error = None
if result_path.exists():
try:
result = read_json(result_path, None)
validate_result_contract(result)
except Exception as exc:
result_error = str(exc)
result = None
return {
"cycle": cycle,
"brief_path": brief_path,
"result_path": result_path,
"run_path": run_path,
"run": run,
"result": result,
"result_error": result_error,
}
def review_findings(result):
if not result:
return []
review = result.get("review") or {}
mode = review.get("mode")
if mode not in ("pull_request", "review_comment"):
return []
return review.get("findings") or []
def review_fix_instruction(findings, iteration, max_iterations):
lines = [
"Autofix review loop iteration {}/{}.".format(iteration, max_iterations),
"The previous hosted review returned structured findings. Fix the findings below, run the relevant checks you can run safely, then perform another bounded review of the updated code using the required review sections.",
"If a finding cannot be fixed safely, leave a clear limitation and explain the remaining blocker. Do not merely restate the findings.",
"",
"Findings to fix:",
]
for index, finding in enumerate(findings[:10], start=1):
location = finding.get("file") or "unknown file"
if finding.get("line") is not None:
location = "{}:{}".format(location, finding.get("line"))
lines.append(
"{}. [{}] `{}` {}".format(
index,
finding.get("severity") or "unknown",
location,
finding.get("title") or "Untitled finding",
)
)
body = (finding.get("body") or "").strip()
if body:
lines.append(" Body: {}".format(body[:1200]))
recommendation = (finding.get("recommendation") or "").strip()
if recommendation:
lines.append(" Recommendation: {}".format(recommendation[:1200]))
if len(findings) > 10:
lines.append("Only the first 10 findings are listed; inspect the prior result for the full set.")
return "\n".join(lines)
def task_with_repair_request(task, instruction):
copy = json.loads(json.dumps(task))
task_data = copy.get("task") or {}
explicit_request = (
"\n\nPlease fix the review findings from the previous hosted review cycle. "
"After fixing them, rerun relevant checks and produce another structured review.\n\n"
+ instruction
)
if "comment_body" in task_data:
task_data["comment_body"] = (task_data.get("comment_body") or "") + explicit_request
elif "issue_body" in task_data:
task_data["issue_body"] = (task_data.get("issue_body") or "") + explicit_request
copy["task"] = task_data
return copy
def run_task(task_id, debug):
path = task_path(task_id)
task = read_json(path, {})
if task.get("state") != "queued":
return task
task["state"] = "running"
task["attempts"] = int(task.get("attempts") or 0) + 1
task["updated_at"] = utc_now()
write_json_atomic(path, task)
attempt_dir = ATTEMPTS_DIR / task_id / str(task["attempts"])
attempt_dir.mkdir(parents=True, exist_ok=True)
workspace = WORKSPACES_DIR / task_id / "repo"
try:
token = installation_token(task["installation_id"])
askpass = write_askpass(attempt_dir)
env = os.environ.copy()
env["GIT_ASKPASS"] = str(askpass)
env["GIT_TERMINAL_PROMPT"] = "0"
env["COVEN_GIT_TOKEN"] = token
env["COVEN_CODE_PROVIDER"] = "codex"
env["COVEN_CODE_HOSTED_REVIEW"] = "1"
env["HOME"] = str(account_home())
codex_access_token = load_codex_access_token()
if not codex_access_token:
return fail_task(
path,
task,
"codex_auth_missing",
"Missing Codex access token at {}".format(CODEX_TOKENS_PATH),
)
env["OPENAI_API_KEY"] = codex_access_token
if not workspace.exists():
clone = run_command(
[
"git",
"clone",
"--depth",
"1",
"--branch",
task["default_branch"],
task["clone_url"],
str(workspace),
],
env=env,
timeout=180,
)
write_json_atomic(attempt_dir / "clone.json", redacted_command_result(clone))
if clone["returncode"] != 0:
return fail_task(path, task, "clone_failed", clone["stderr"])
review_context = prepare_review_context(task, workspace, token, env, attempt_dir)
if review_context:
review_context_path = attempt_dir / "review-context.json"
write_json_atomic(review_context_path, review_context)
task["review_context_path"] = str(review_context_path)
task["review_context_sha256"] = file_sha256(review_context_path)
task["review_evidence"] = review_evidence(review_context, review_context_path, task)
write_json_atomic(path, task)
if not command_exists(COVEN_CODE_BIN):
return fail_task(
path,
task,
"runtime_missing",
"COVEN_CODE_BIN is not available on the host: {}".format(COVEN_CODE_BIN),
)
cycle_result = run_coven_code_cycle(task, workspace, review_context, attempt_dir, env, 0)
brief_path = cycle_result["brief_path"]
result_path = cycle_result["result_path"]
run = cycle_result["run"]
task["session_brief_path"] = str(brief_path)
task["session_brief_sha256"] = file_sha256(brief_path)
task["runtime_exit_code"] = run["returncode"]
task["result_path"] = str(result_path)
write_json_atomic(path, task)
if run["returncode"] not in TERMINAL_RESULT_EXIT_CODES: