-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathentrypoint.py
More file actions
2091 lines (1842 loc) · 80.1 KB
/
entrypoint.py
File metadata and controls
2091 lines (1842 loc) · 80.1 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
"""Background Agent entrypoint.
Mirrors the durable function orchestration flow from the PRD (Section 6).
Supports two modes:
- Local batch mode: `python entrypoint.py` (reads config from env vars)
- AgentCore server mode: imported by server.py via `run_task()`
Flow:
1. Build configuration
2. Context hydration: fetch GitHub issue, assemble prompt
3. Setup: clone repo, create branch, mise install, initial build
4. Invoke Claude Agent SDK (one-shot, unattended)
5. Post-hooks: safety-net commit, verify build, verify lint, ensure PR
6. Collect and return metrics
"""
import asyncio
import glob
import hashlib
import json
import os
import re
import subprocess
import sys
import time
import uuid
from urllib.parse import quote
import requests
import memory as agent_memory
import task_state
from observability import task_span
from prompts import get_system_prompt
from system_prompt import SYSTEM_PROMPT
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
AGENT_WORKSPACE = os.environ.get("AGENT_WORKSPACE", "/workspace")
# Task types that operate on an existing pull request.
PR_TASK_TYPES = frozenset(("pr_iteration", "pr_review"))
def resolve_github_token() -> str:
"""Resolve GitHub token from Secrets Manager or environment variable.
In deployed mode, GITHUB_TOKEN_SECRET_ARN is set and the token is fetched
from Secrets Manager on first call, then cached in os.environ.
For local development, falls back to GITHUB_TOKEN.
"""
# Return cached value if already resolved
cached = os.environ.get("GITHUB_TOKEN", "")
if cached:
return cached
secret_arn = os.environ.get("GITHUB_TOKEN_SECRET_ARN")
if secret_arn:
import boto3
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
client = boto3.client("secretsmanager", region_name=region)
resp = client.get_secret_value(SecretId=secret_arn)
token = resp["SecretString"]
# Cache in env so downstream tools (git, gh CLI) work unchanged
os.environ["GITHUB_TOKEN"] = token
return token
return ""
def build_config(
repo_url: str,
task_description: str = "",
issue_number: str = "",
github_token: str = "",
anthropic_model: str = "",
max_turns: int = 10,
max_budget_usd: float | None = None,
aws_region: str = "",
dry_run: bool = False,
task_id: str = "",
system_prompt_overrides: str = "",
task_type: str = "new_task",
branch_name: str = "",
pr_number: str = "",
) -> dict:
"""Build and validate configuration from explicit parameters.
Parameters fall back to environment variables if empty.
"""
config = {
"repo_url": repo_url or os.environ.get("REPO_URL", ""),
"issue_number": issue_number or os.environ.get("ISSUE_NUMBER", ""),
"task_description": task_description or os.environ.get("TASK_DESCRIPTION", ""),
"github_token": github_token or resolve_github_token(),
"aws_region": aws_region or os.environ.get("AWS_REGION", ""),
"anthropic_model": anthropic_model
or os.environ.get("ANTHROPIC_MODEL", "us.anthropic.claude-sonnet-4-6"),
"dry_run": dry_run,
"max_turns": max_turns,
"max_budget_usd": max_budget_usd,
"system_prompt_overrides": system_prompt_overrides,
"task_type": task_type,
"branch_name": branch_name,
"pr_number": pr_number,
}
errors = []
if not config["repo_url"]:
errors.append("repo_url is required (e.g., 'owner/repo')")
if not config["github_token"]:
errors.append("github_token is required")
if not config["aws_region"]:
errors.append("aws_region is required for Bedrock")
if config["task_type"] in PR_TASK_TYPES:
if not config["pr_number"]:
errors.append("pr_number is required for pr_iteration/pr_review task type")
elif not config["issue_number"] and not config["task_description"]:
errors.append("Either issue_number or task_description is required")
if errors:
raise ValueError("; ".join(errors))
config["task_id"] = task_id or uuid.uuid4().hex[:12]
return config
def get_config() -> dict:
"""Parse configuration from environment variables (local batch mode)."""
try:
return build_config(
repo_url=os.environ.get("REPO_URL", ""),
task_description=os.environ.get("TASK_DESCRIPTION", ""),
issue_number=os.environ.get("ISSUE_NUMBER", ""),
github_token=os.environ.get("GITHUB_TOKEN", ""),
anthropic_model=os.environ.get("ANTHROPIC_MODEL", ""),
max_turns=int(os.environ.get("MAX_TURNS", "100")),
max_budget_usd=float(os.environ.get("MAX_BUDGET_USD", "0")) or None,
aws_region=os.environ.get("AWS_REGION", ""),
dry_run=os.environ.get("DRY_RUN", "").lower() in ("1", "true", "yes"),
)
except ValueError as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
# ---------------------------------------------------------------------------
# Context hydration
# ---------------------------------------------------------------------------
def fetch_github_issue(repo_url: str, issue_number: str, token: str) -> dict:
"""Fetch a GitHub issue's title, body, and comments."""
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json",
}
# Fetch issue
issue_resp = requests.get(
f"https://api.github.com/repos/{repo_url}/issues/{issue_number}",
headers=headers,
timeout=30,
)
issue_resp.raise_for_status()
issue = issue_resp.json()
# Fetch comments
comments = []
if issue.get("comments", 0) > 0:
comments_resp = requests.get(
f"https://api.github.com/repos/{repo_url}/issues/{issue_number}/comments",
headers=headers,
timeout=30,
)
comments_resp.raise_for_status()
comments = [{"author": c["user"]["login"], "body": c["body"]} for c in comments_resp.json()]
return {
"title": issue["title"],
"body": issue.get("body", ""),
"number": issue["number"],
"comments": comments,
}
def assemble_prompt(config: dict) -> str:
"""Assemble the user prompt from issue context and task description.
.. deprecated::
In production (AgentCore server mode), the orchestrator's
``assembleUserPrompt()`` in ``context-hydration.ts`` is the sole prompt
assembler. The hydrated prompt arrives via ``hydrated_context["user_prompt"]``.
This Python implementation is retained only for **local batch mode**
(``python entrypoint.py``) and **dry-run mode** (``DRY_RUN=1``).
"""
parts = []
parts.append(f"Task ID: {config['task_id']}")
parts.append(f"Repository: {config['repo_url']}")
if config.get("issue"):
issue = config["issue"]
parts.append(f"\n## GitHub Issue #{issue['number']}: {issue['title']}\n")
parts.append(issue["body"] or "(no description)")
if issue["comments"]:
parts.append("\n### Comments\n")
for c in issue["comments"]:
parts.append(f"**@{c['author']}**: {c['body']}\n")
if config["task_description"]:
parts.append(f"\n## Task\n\n{config['task_description']}")
elif config.get("issue"):
parts.append(
"\n## Task\n\nResolve the GitHub issue described above. "
"Follow the workflow in your system instructions."
)
return "\n".join(parts)
# ---------------------------------------------------------------------------
# Repository setup (deterministic pre-hooks)
# ---------------------------------------------------------------------------
def slugify(text: str, max_len: int = 40) -> str:
"""Convert text to a URL-safe slug for branch names."""
text = text.lower().strip()
text = re.sub(r"[^a-z0-9\s-]", "", text)
text = re.sub(r"[\s-]+", "-", text)
text = text.strip("-")
if len(text) > max_len:
text = text[:max_len].rstrip("-")
return text or "task"
def redact_secrets(text: str) -> str:
"""Redact tokens and secrets from log output."""
# GitHub and generic token-like values.
text = re.sub(r"(ghp_|github_pat_|gho_|ghs_|ghr_)[A-Za-z0-9_]+", r"\1***", text)
text = re.sub(r"(x-access-token:)[^\s@]+", r"\1***", text)
text = re.sub(r"(authorization:\s*(?:bearer|token)\s+)[^\s]+", r"\1***", text, flags=re.I)
text = re.sub(
r"([?&](?:token|access_token|api_key|apikey|password)=)[^&\s]+",
r"\1***",
text,
flags=re.I,
)
text = re.sub(r"(gh[opusr]_[A-Za-z0-9_]+)", "***", text)
return text
def _clean_env() -> dict[str, str]:
"""Return a copy of os.environ with OTEL auto-instrumentation vars removed.
The ``opentelemetry-instrument`` wrapper injects PYTHONPATH and OTEL_*
env vars that would cause child Python processes (e.g. mise run build →
semgrep in the target repo) to attempt OTEL auto-instrumentation and fail
because the target repo's Python environment doesn't have the OTEL
packages installed. Stripping these vars isolates target-repo commands
from the agent's own instrumentation.
"""
env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_")}
# Strip only OTEL-injected PYTHONPATH components (the sitecustomize.py
# directory), preserving any entries the target repo's toolchain may need.
pythonpath = env.get("PYTHONPATH", "")
if pythonpath:
cleaned = os.pathsep.join(
p for p in pythonpath.split(os.pathsep) if "opentelemetry" not in p
)
if cleaned:
env["PYTHONPATH"] = cleaned
else:
env.pop("PYTHONPATH", None)
return env
def run_cmd(
cmd: list[str],
label: str,
cwd: str | None = None,
timeout: int = 600,
check: bool = True,
) -> subprocess.CompletedProcess:
"""Run a command with logging."""
log("CMD", redact_secrets(f"{label}: {' '.join(cmd)}"))
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
env=_clean_env(),
)
if result.returncode != 0:
log("CMD", f"{label}: FAILED (exit {result.returncode})")
if result.stderr:
for line in result.stderr.strip().splitlines()[:20]:
log("CMD", f" {line}")
if check:
stderr_snippet = redact_secrets(result.stderr.strip()[:500]) if result.stderr else ""
raise RuntimeError(f"{label} failed (exit {result.returncode}): {stderr_snippet}")
else:
log("CMD", f"{label}: OK")
return result
def setup_repo(config: dict) -> dict:
"""Clone repo, create branch, configure git auth, run mise install.
Returns a dict with keys: repo_dir, branch, notes, build_before,
lint_before, and default_branch.
"""
repo_dir = f"{AGENT_WORKSPACE}/{config['task_id']}"
setup: dict[str, str | list[str] | bool] = {"repo_dir": repo_dir, "notes": []}
if config.get("task_type") in PR_TASK_TYPES and config.get("branch_name"):
branch = config["branch_name"]
setup["branch"] = branch
else:
# Derive branch slug from issue title or task description
title = ""
if config.get("issue"):
title = config["issue"]["title"]
if not title:
title = config["task_description"]
slug = slugify(title)
branch = f"bgagent/{config['task_id']}/{slug}"
setup["branch"] = branch
# Mark the repo directory as safe for git. On persistent session storage
# the mount may be owned by a different UID than the container user,
# triggering git's "dubious ownership" check on clone/resume.
run_cmd(
["git", "config", "--global", "--add", "safe.directory", repo_dir],
label="safe-directory",
)
# Clone
log("SETUP", f"Cloning {config['repo_url']}...")
run_cmd(
["gh", "repo", "clone", config["repo_url"], repo_dir],
label="clone",
)
# Configure remote URL with embedded token so git push works without
# credential helpers or extra auth setup inside the agent.
token = config["github_token"]
run_cmd(
[
"git",
"remote",
"set-url",
"origin",
f"https://x-access-token:{token}@github.com/{config['repo_url']}.git",
],
label="set-remote-url",
cwd=repo_dir,
)
# Branch setup
if config.get("task_type") in PR_TASK_TYPES and config.get("branch_name"):
log("SETUP", f"Checking out existing PR branch: {branch}")
run_cmd(
["git", "fetch", "origin", branch],
label="fetch-pr-branch",
cwd=repo_dir,
)
run_cmd(
["git", "checkout", "-b", branch, f"origin/{branch}"],
label="checkout-pr-branch",
cwd=repo_dir,
)
else:
log("SETUP", f"Creating branch: {branch}")
run_cmd(["git", "checkout", "-b", branch], label="create-branch", cwd=repo_dir)
# Trust mise config files in the cloned repo (required before mise install)
run_cmd(
["mise", "trust", repo_dir],
label="mise-trust",
cwd=repo_dir,
check=False,
)
# mise install (deterministic — not left to the LLM)
log("SETUP", "Running mise install...")
result = run_cmd(
["mise", "install"],
label="mise-install",
cwd=repo_dir,
check=False,
)
if result.returncode != 0:
note = f"mise install failed (exit {result.returncode})"
setup["notes"].append(note)
else:
setup["notes"].append("mise install: OK")
# Initial build (record whether the project builds before agent changes)
log("SETUP", "Running initial build (mise run build)...")
result = run_cmd(
["mise", "run", "build"],
label="mise-run-build-pre",
cwd=repo_dir,
check=False,
)
if result.returncode != 0:
note = "Initial build (mise run build) FAILED before agent changes"
setup["notes"].append(note)
setup["build_before"] = False
else:
setup["notes"].append("Initial build (mise run build): OK")
setup["build_before"] = True
# Initial lint baseline (record whether lint passes before agent changes)
log("SETUP", "Running initial lint (mise run lint)...")
result = run_cmd(
["mise", "run", "lint"],
label="mise-run-lint-pre",
cwd=repo_dir,
check=False,
)
if result.returncode != 0:
note = "Initial lint (mise run lint) FAILED before agent changes"
setup["notes"].append(note)
setup["lint_before"] = False
else:
setup["notes"].append("Initial lint (mise run lint): OK")
setup["lint_before"] = True
# Detect default branch
# For PR tasks (pr_iteration, pr_review): use base_branch from orchestrator if available
if config.get("task_type") in PR_TASK_TYPES and config.get("base_branch"):
setup["default_branch"] = config["base_branch"]
else:
setup["default_branch"] = detect_default_branch(config["repo_url"], repo_dir)
# Install prepare-commit-msg hook for code attribution
_install_commit_hook(repo_dir)
return setup
def _install_commit_hook(repo_dir: str) -> None:
"""Install the prepare-commit-msg git hook for Task-Id/Prompt-Version trailers."""
try:
hooks_dir = os.path.join(repo_dir, ".git", "hooks")
os.makedirs(hooks_dir, exist_ok=True)
hook_src = os.path.join(os.path.dirname(__file__), "prepare-commit-msg.sh")
hook_dst = os.path.join(hooks_dir, "prepare-commit-msg")
if not os.path.isfile(hook_src):
log("ERROR", f"Hook not found at {hook_src}")
return
import shutil
import stat
shutil.copy2(hook_src, hook_dst)
current = os.stat(hook_dst).st_mode
exec_bits = stat.S_IXUSR | stat.S_IXGRP
os.chmod(hook_dst, current | exec_bits) # nosemgrep
log("SETUP", "Installed prepare-commit-msg hook")
except Exception as e:
log("WARN", f"Commit hook install failed: {type(e).__name__}: {e}")
def detect_default_branch(repo_url: str, repo_dir: str) -> str:
"""Detect the repository's default branch via gh CLI.
Falls back to 'main' if detection fails (timeout, auth error, etc.).
"""
try:
result = subprocess.run(
[
"gh",
"repo",
"view",
repo_url,
"--json",
"defaultBranchRef",
"-q",
".defaultBranchRef.name",
],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=30,
)
except subprocess.TimeoutExpired:
log("WARN", "Default branch detection timed out — defaulting to 'main'")
return "main"
if result.returncode == 0 and result.stdout.strip():
branch = result.stdout.strip()
log("SETUP", f"Detected default branch: {branch}")
return branch
stderr = result.stderr.strip()[:200] if result.stderr else "(no stderr)"
log(
"WARN",
f"Could not detect default branch (exit {result.returncode}): "
f"{stderr} — defaulting to 'main'",
)
return "main"
def verify_build(repo_dir: str) -> bool:
"""Run mise run build after agent completion to verify the build."""
log("POST", "Running post-agent build verification (mise run build)...")
try:
result = run_cmd(
["mise", "run", "build"],
label="mise-run-build-post",
cwd=repo_dir,
check=False,
)
except subprocess.TimeoutExpired:
log("WARN", "Post-agent build timed out — treating as failed")
return False
if result.returncode != 0:
log("POST", "Post-agent build FAILED")
return False
log("POST", "Post-agent build: OK")
return True
def verify_lint(repo_dir: str) -> bool:
"""Run mise run lint after agent completion to verify lint passes."""
log("POST", "Running post-agent lint verification (mise run lint)...")
try:
result = run_cmd(
["mise", "run", "lint"],
label="mise-run-lint-post",
cwd=repo_dir,
check=False,
)
except subprocess.TimeoutExpired:
log("WARN", "Post-agent lint timed out — treating as failed")
return False
if result.returncode != 0:
log("POST", "Post-agent lint FAILED")
return False
log("POST", "Post-agent lint: OK")
return True
def ensure_committed(repo_dir: str) -> bool:
"""Safety net: commit any uncommitted tracked changes before finalization.
This catches work the agent wrote but forgot to commit (e.g. due to turn
limit or timeout). Only stages tracked-but-modified files (git add -u) to
avoid accidentally committing temp files or build artifacts.
Returns True if a safety-net commit was created, False if nothing to commit
or if git operations fail.
"""
try:
result = subprocess.run(
["git", "status", "--porcelain"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
except subprocess.TimeoutExpired:
log("WARN", "git status timed out in safety-net commit")
return False
if result.returncode != 0:
stderr = result.stderr.strip()[:200] if result.stderr else ""
log("WARN", f"git status failed (exit {result.returncode}): {stderr}")
return False
if not result.stdout.strip():
return False
log("POST", "Uncommitted changes detected — creating safety-net commit")
# Stage tracked-but-modified files only (not untracked files)
try:
add_result = subprocess.run(
["git", "add", "-u"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
except subprocess.TimeoutExpired:
log("WARN", "git add -u timed out in safety-net commit")
return False
if add_result.returncode != 0:
stderr = add_result.stderr.strip()[:200] if add_result.stderr else ""
log("WARN", f"git add -u failed (exit {add_result.returncode}): {stderr}")
return False
# Check if there's anything staged after add -u
staged = subprocess.run(
["git", "diff", "--cached", "--quiet"],
cwd=repo_dir,
capture_output=True,
timeout=30,
)
if staged.returncode == 0:
# Nothing staged (changes were only untracked files) — skip
log("POST", "No tracked file changes to commit")
return False
commit_result = subprocess.run(
["git", "commit", "-m", "chore(agent): save uncommitted work from session end"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
if commit_result.returncode == 0:
log("POST", "Safety-net commit created")
return True
log("POST", f"Safety-net commit failed: {commit_result.stderr.strip()[:200]}")
return False
def ensure_pushed(repo_dir: str, branch: str) -> bool:
"""Push the branch if there are unpushed commits."""
result = subprocess.run(
["git", "log", f"origin/{branch}..HEAD", "--oneline"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
# If the remote branch doesn't exist or there are unpushed commits
if result.returncode != 0 or result.stdout.strip():
log("POST", "Pushing unpushed commits...")
push_result = run_cmd(
["git", "push", "-u", "origin", branch],
label="push",
cwd=repo_dir,
check=False,
)
return push_result.returncode == 0
return True
def ensure_pr(
config: dict,
setup: dict,
build_passed: bool,
lint_passed: bool,
agent_result: dict | None = None,
) -> str | None:
"""Check if a PR exists for the branch; if not, create one.
For ``new_task``: creates a new PR if needed.
For ``pr_iteration``: pushes commits, then resolves the existing PR URL.
For ``pr_review``: resolves the existing PR URL without pushing (read-only).
Returns the PR URL, or None if there are no commits beyond the default
branch or PR creation failed. ``build_passed`` and ``lint_passed`` control
the verification status shown in the PR body.
"""
repo_dir = setup["repo_dir"]
branch = setup["branch"]
default_branch = setup.get("default_branch", "main")
# PR iteration/review: skip PR creation — just resolve existing PR URL
if config.get("task_type") in PR_TASK_TYPES:
if config.get("task_type") == "pr_iteration":
if not ensure_pushed(repo_dir, branch):
log("WARN", "Failed to push commits before resolving PR URL")
else:
log("POST", "pr_review task — skipping push (read-only)")
log("POST", f"{config.get('task_type')} — returning existing PR URL")
result = subprocess.run(
[
"gh",
"pr",
"view",
branch,
"--repo",
config["repo_url"],
"--json",
"url",
"-q",
".url",
],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
if result.returncode == 0 and result.stdout.strip():
pr_url = result.stdout.strip()
log("POST", f"Existing PR: {pr_url}")
return pr_url
stderr_msg = result.stderr.strip() if result.stderr else "(no stderr)"
log("WARN", f"Could not resolve existing PR URL (rc={result.returncode}): {stderr_msg}")
return None
# Check if the agent already created a PR for this branch
log("POST", "Checking for existing PR...")
result = subprocess.run(
[
"gh",
"pr",
"view",
branch,
"--repo",
config["repo_url"],
"--json",
"url",
"-q",
".url",
],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
if result.returncode == 0 and result.stdout.strip():
pr_url = result.stdout.strip()
log("POST", f"PR already exists: {pr_url}")
return pr_url
# Check if there are any commits on this branch beyond the default branch
diff_result = subprocess.run(
["git", "log", f"origin/{default_branch}..HEAD", "--oneline"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
if diff_result.returncode != 0 or not diff_result.stdout.strip():
log("POST", "No commits to create PR from — skipping PR creation")
return None
# Ensure all commits are pushed
ensure_pushed(repo_dir, branch)
# Collect commit messages for the PR body
log_result = subprocess.run(
["git", "log", f"origin/{default_branch}..HEAD", "--pretty=format:%s%n%b---"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
commits = log_result.stdout.strip() if log_result.returncode == 0 else ""
# Derive PR title from first commit message
first_commit = subprocess.run(
["git", "log", f"origin/{default_branch}..HEAD", "--pretty=format:%s", "--reverse"],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=60,
)
pr_title = (
first_commit.stdout.strip().split("\n")[0]
if first_commit.stdout.strip()
else f"chore: bgagent/{config['task_id']}"
)
# Build PR body
task_source = ""
if config["issue_number"]:
task_source = f"Resolves #{config['issue_number']}\n\n"
elif config["task_description"]:
task_source = f"**Task:** {config['task_description']}\n\n"
build_status = "PASS" if build_passed else "FAIL"
lint_status = "PASS" if lint_passed else "FAIL"
cost_line = ""
if agent_result and agent_result.get("cost_usd") is not None:
cost_line = f"- Agent cost: **${agent_result['cost_usd']:.4f}**\n"
pr_body = (
f"## Summary\n\n"
f"{task_source}"
f"### Commits\n\n"
f"```\n{commits}\n```\n\n"
f"## Verification\n\n"
f"- `mise run build` (post-agent): **{build_status}**\n"
f"- `mise run lint` (post-agent): **{lint_status}**\n"
f"{cost_line}\n"
f"---\n\n"
f"By submitting this pull request, I confirm that you can use, modify, copy, "
f"and redistribute this contribution, under the terms of the [project license](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/LICENSE)."
)
log("POST", f"Creating PR: {pr_title}")
pr_result = run_cmd(
[
"gh",
"pr",
"create",
"--repo",
config["repo_url"],
"--head",
branch,
"--base",
default_branch,
"--title",
pr_title,
"--body",
pr_body,
],
label="create-pr",
cwd=repo_dir,
check=False,
)
if pr_result.returncode == 0:
pr_url = pr_result.stdout.strip()
log("POST", f"PR created: {pr_url}")
return pr_url
else:
log("POST", "Failed to create PR")
return None
# ---------------------------------------------------------------------------
# Self-feedback extraction
# ---------------------------------------------------------------------------
def _extract_agent_notes(repo_dir: str, branch: str, config: dict) -> str | None:
"""Extract the "## Agent notes" section from the PR body.
Checks the existing PR body via `gh pr view`. Returns the text content
of the "## Agent notes" section, or None if not found.
"""
try:
result = subprocess.run(
[
"gh",
"pr",
"view",
branch,
"--repo",
config["repo_url"],
"--json",
"body",
"-q",
".body",
],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0 or not result.stdout.strip():
return None
body = result.stdout.strip()
# Find "## Agent notes" section
match = re.search(
r"##\s*Agent\s*notes\s*\n(.*?)(?=\n##\s|\Z)",
body,
re.DOTALL | re.IGNORECASE,
)
if match:
notes = match.group(1).strip()
return notes if notes else None
return None
except Exception as e:
log("WARN", f"Failed to extract agent notes from PR body: {type(e).__name__}: {e}")
return None
# ---------------------------------------------------------------------------
# Metrics
# ---------------------------------------------------------------------------
def get_disk_usage(path: str = AGENT_WORKSPACE) -> float:
"""Return disk usage in bytes for the given path."""
try:
result = subprocess.run(
["du", "-sb", path],
capture_output=True,
text=True,
timeout=30,
)
return int(result.stdout.split()[0]) if result.returncode == 0 else 0
except (subprocess.TimeoutExpired, ValueError, IndexError):
return 0
def format_bytes(size: float) -> str:
"""Human-readable byte size."""
for unit in ("B", "KB", "MB", "GB"):
if abs(size) < 1024:
return f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} TB"
def _emit_metrics_to_cloudwatch(json_payload: dict) -> None:
"""Write the METRICS_REPORT JSON event directly to CloudWatch Logs.
Writes the log event directly to the APPLICATION_LOGS log group using the
CloudWatch Logs API, ensuring metrics are reliably available for dashboard
Logs Insights queries regardless of container stdout routing.
"""
log_group = os.environ.get("LOG_GROUP_NAME")
if not log_group:
return
try:
import contextlib
import boto3
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
client = boto3.client("logs", region_name=region)
task_id = json_payload.get("task_id", "unknown")
log_stream = f"metrics/{task_id}"
# Create the log stream (ignore if it already exists)
with contextlib.suppress(client.exceptions.ResourceAlreadyExistsException):
client.create_log_stream(logGroupName=log_group, logStreamName=log_stream)
client.put_log_events(
logGroupName=log_group,
logStreamName=log_stream,
logEvents=[
{
"timestamp": int(time.time() * 1000),
"message": json.dumps(json_payload),
}
],
)
except ImportError:
print("[metrics] boto3 not available — skipping CloudWatch write", flush=True)
except Exception as e:
exc_type = type(e).__name__
print(f"[metrics] CloudWatch Logs write failed (best-effort): {exc_type}: {e}", flush=True)
if "Credential" in exc_type or "Endpoint" in exc_type or "AccessDenied" in str(e):
print(
"[metrics] WARNING: This may indicate a deployment misconfiguration "
"(IAM role, VPC endpoint, or credentials). Dashboard data will be missing.",
flush=True,
)
class _TrajectoryWriter:
"""Write per-turn trajectory events to CloudWatch Logs.
Follows the same pattern as ``_emit_metrics_to_cloudwatch()``: lazy boto3
import, best-effort error handling, ``contextlib.suppress`` for idempotent
stream creation. Log stream: ``trajectory/{task_id}`` (parallel to the
existing ``metrics/{task_id}`` stream).
Events are progressively truncated to stay under the CloudWatch Logs 262 KB
event-size limit: large fields (thinking, tool result content) are truncated
first, then a hard byte-level safety-net truncation is applied.
"""
_CW_MAX_EVENT_BYTES = 262_144 # CloudWatch limit per event
_MAX_FAILURES = 3
def __init__(self, task_id: str) -> None:
self._task_id = task_id
self._log_group = os.environ.get("LOG_GROUP_NAME")
self._client = None
self._disabled = False
self._failure_count = 0
def _ensure_client(self):
"""Lazily create the CloudWatch Logs client and log stream."""
if self._client is not None:
return
if not self._log_group:
self._disabled = True
return
import contextlib
import boto3
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
self._client = boto3.client("logs", region_name=region)
log_stream = f"trajectory/{self._task_id}"
with contextlib.suppress(self._client.exceptions.ResourceAlreadyExistsException):
self._client.create_log_stream(logGroupName=self._log_group, logStreamName=log_stream)
def _put_event(self, payload: dict) -> None:
"""Serialize *payload* to JSON, truncate if needed, and write."""
if not self._log_group or self._disabled:
return
try:
self._ensure_client()
if self._client is None: