Lightweight coding agent that runs in your terminal
Rust
Remove repository-local Codex guidance, skills, and environment config (#49713)
Adam Perry @ OpenAI18131270fe82
diff --git a/.codex/environments/environment.toml b/.codex/environments/environment.tomldeleted file mode 100644index ae0bd24ca8..0000000000--- a/.codex/environments/environment.toml+++ /dev/null@@ -1,12 +0,0 @@-# THIS IS AUTOGENERATED. DO NOT EDIT MANUALLY-version = 1-name = "codex"--# TODO(anp) make it optional to specify this field-[setup]-script = ""--[[actions]]-name = "Run"-icon = "run"-command = "cargo +1.95.0 run --manifest-path=codex-rs/Cargo.toml --bin codex -- -c mcp_oauth_credentials_store=file"diff --git a/.codex/skills/babysit-pr/SKILL.md b/.codex/skills/babysit-pr/SKILL.mddeleted file mode 100644index 36c6bd093a..0000000000--- a/.codex/skills/babysit-pr/SKILL.md+++ /dev/null@@ -1,223 +0,0 @@-----name: babysit-pr-description: Babysit a GitHub pull request after creation by continuously polling review comments, CI checks/workflow runs, and mergeability state until the PR is merged/closed or user help is required. Diagnose failures, retry likely flaky failures up to 3 times, auto-fix/push branch-related issues when appropriate, and keep watching open PRs so fresh review feedback is surfaced promptly. Use when the user asks Codex to monitor a PR, watch CI, handle review comments, or keep an eye on failures and feedback on an open PR.------# PR Babysitter--## Objective-Babysit a PR persistently until one of these terminal outcomes occurs:--- The PR is merged or closed.-- A situation requires user help (for example CI infrastructure issues, repeated flaky failures after retry budget is exhausted, permission problems, or ambiguity that cannot be resolved safely).-- Optional handoff milestone: the PR is currently green + mergeable + review-clean. Treat this as a progress state, not a watcher stop, so late-arriving review comments are still surfaced promptly while the PR remains open.--Do not stop merely because a single snapshot returns `idle` while checks are still pending.--## Inputs-Accept any of the following:--- No PR argument: infer the PR from the current branch (`--pr auto`)-- PR number-- PR URL--## Core Workflow--1. When the user asks to "monitor"/"watch"/"babysit" a PR, start with the watcher's continuous mode (`--watch`) unless you are intentionally doing a one-shot diagnostic snapshot.-2. Run the watcher script to snapshot PR/review/CI state (or consume each streamed snapshot from `--watch`).-3. Inspect the `actions` list in the JSON response.-4. If `diagnose_ci_failure` is present, inspect failed run logs and classify the failure.-5. If the failure is likely caused by the current branch, patch code locally, commit, and push. Do not patch random flaky tests, CI infrastructure, dependency outages, runner issues, or other failures that are unrelated to the branch.-6. If `process_review_comment` is present, inspect surfaced published review items and decide whether to address them.-7. If a review item is actionable and correct, patch code locally, commit, push, and then resolve the associated review thread only when allowed by the GitHub state mutation policy below.-8. Do not post replies to human-authored review comments/threads unless the user explicitly confirms the exact response. If a human review item is non-actionable, already addressed, or not valid, surface the item and recommended response to the user instead of replying on GitHub.-9. If the failure is likely flaky/unrelated and `retry_failed_checks` is present, rerun failed jobs with `--retry-failed-now`.-10. If both actionable review feedback and `retry_failed_checks` are present, prioritize review feedback first; a new commit will retrigger CI, so avoid rerunning flaky checks on the old SHA unless you intentionally defer the review change.-11. On every loop, look for newly surfaced review feedback before acting on CI failures or mergeability state, then verify mergeability / merge-conflict status (for example via `gh pr view`) alongside CI.-12. After any push or rerun action, immediately return to step 1 and continue polling on the updated SHA/state.-13. If you had been using `--watch` before pausing to patch/commit/push, relaunch `--watch` yourself in the same turn immediately after the push (do not wait for the user to re-invoke the skill).-14. Repeat polling until `stop_pr_closed` appears or a user-help-required blocker is reached. A green + review-clean + mergeable PR is a progress milestone, not a reason to stop the watcher while the PR is still open.-15. Maintain terminal/session ownership: while babysitting is active, keep consuming watcher output in the same turn; do not leave a detached `--watch` process running and then end the turn as if monitoring were complete.--## Commands--### One-shot snapshot--```bash-python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --once-```--### Continuous watch (JSONL)--```bash-python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --watch-```--### Trigger flaky retry cycle (only when watcher indicates)--```bash-python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --retry-failed-now-```--### Explicit PR target--```bash-python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr <number-or-url> --once-```--## CI Failure Classification-Use `gh` commands to inspect failed runs before deciding to rerun.--- `gh run view <run-id> --json jobs,name,workflowName,conclusion,status,url,headSha`-- `gh api repos/<owner>/<repo>/actions/runs/<run-id>/jobs -X GET -f per_page=100`-- `gh api repos/<owner>/<repo>/actions/jobs/<job-id>/logs > /tmp/codex-gh-job-<job-id>-logs.zip`-- `gh run view <run-id> --log-failed` as a fallback after the overall workflow run is complete--`gh run view --log-failed` is workflow-run scoped and may not expose failed-job logs until the overall run finishes. For faster diagnosis, poll the run's jobs first and, as soon as a specific job has failed, fetch that job's logs directly from the Actions job logs endpoint. The watcher includes a `failed_jobs` list with each failed job's `job_id` and `logs_endpoint` when GitHub exposes one.--Prefer treating failures as branch-related when failed-job logs point to changed code (compile/test/lint/typecheck/snapshots/static analysis in touched areas).--Prefer treating failures as flaky/unrelated when logs show transient infra/external issues (timeouts, runner provisioning failures, registry/network outages, GitHub Actions infra errors).--Do not attempt to fix flaky/unrelated failures by changing tests, build scripts, CI configuration, dependency pins, or infrastructure-adjacent code unless the logs clearly connect the failure to the PR branch. For flaky/unrelated failures, rerun only when the watcher recommends `retry_failed_checks`; otherwise wait or stop for user help.--If classification is ambiguous, perform one manual diagnosis attempt before choosing rerun.--Read `.codex/skills/babysit-pr/references/heuristics.md` for a concise checklist.--## Review Comment Handling-The watcher surfaces review items from:--- PR issue comments-- Inline review comments-- Review submissions (COMMENT / APPROVED / CHANGES_REQUESTED)--Only act on published feedback. Ignore review submissions in GitHub's `PENDING` state and inline-comments attached to those pending reviews. Do not mark pending review feedback as seen; it should-be eligible to surface after the reviewer submits the review.--It intentionally surfaces Codex reviewer bot feedback (for example comments/reviews from `chatgpt-codex-connector[bot]`) in addition to human reviewer feedback. Most unrelated bot noise should still be ignored.-For safety, the watcher only auto-surfaces trusted human review authors (for example repo OWNER/MEMBER/COLLABORATOR, plus the authenticated operator) and approved review bots such as Codex.-On a fresh watcher state file, existing unaddressed published review feedback may be surfaced immediately (not only comments that arrive after monitoring starts). This is intentional so already-open review comments are not missed.--When you agree with a comment and it is actionable:--1. Patch code locally.-2. Commit with `codex: address PR review feedback (#<n>)`.-3. Push to the PR head branch.-4. After the push succeeds, resolve the associated GitHub review thread only when allowed by the GitHub state mutation policy below.-5. Resume watching on the new SHA immediately (do not stop after reporting the push).-6. If monitoring was running in `--watch` mode, restart `--watch` immediately after the push in the same turn; do not wait for the user to ask again.--Do not post replies to human-authored GitHub review comments/threads automatically. If you disagree with a human comment, believe it is non-actionable/already addressed, or need to answer a question, report the item to the user with a suggested response and wait for explicit confirmation before posting anything on GitHub. If the user approves a response, prefix it with `[codex]` so it is clear the response is automated and not from the human user.-If the watcher later surfaces your own approved reply because the authenticated operator is treated as a trusted review author, treat that self-authored item as already handled and do not reply again.-If a code review comment/thread is already marked as resolved in GitHub, treat it as non-actionable and safely ignore it unless new unresolved follow-up feedback appears.--## GitHub State Mutation Policy--You can read any PR state you need for monitoring. Writes must comply with this policy.--You can push PRs to update the code under review or to force CI re-runs as described above.--You can resolve review comment threads from the human who requested babysitting or from the Codex-review bot. When resolving, leave a comment prefixed with `[from Codex]: ` and explain what changes-you made and which commit includes them. Don't touch review threads if other humans other than the-user who requested babysitting have participated.--Before making any changes, fetch the PR state yourself instead of relying on the PR watcher script's-output.--Unless explicitly asked, do not:--* comment on other humans' review threads, communicate with the user in chat instead-* resolve review threads from humans other than the user-* interact with humans other than the user-* mark PRs as drafts or ready for review-* close or reopen PRs--In general, never act on GitHub in ways that would make it hard to tell whether you or the user did-something visible to other humans. When in doubt, ask the user for clarification in chat.--## Git Safety Rules--- Work only on the PR head branch.-- Avoid destructive git commands.-- Do not switch branches unless necessary to recover context.-- Before editing, check for unrelated uncommitted changes. If present, stop and ask the user.-- After each successful fix, commit and `git push`, then re-run the watcher.-- If you interrupted a live `--watch` session to make the fix, restart `--watch` immediately after the push in the same turn.-- Do not run multiple concurrent `--watch` processes for the same PR/state file; keep one watcher session active and reuse it until it stops or you intentionally restart it.-- A push is not a terminal outcome; continue the monitoring loop unless a strict stop condition is met.--Commit message defaults:--- `codex: fix CI failure on PR #<n>`-- `codex: address PR review feedback (#<n>)`--## Monitoring Loop Pattern-Use this loop in a live Codex session:--1. Run `--once`.-2. Read `actions`.-3. First check whether the PR is now merged or otherwise closed; if so, report that terminal state and stop polling immediately.-4. Check CI summary, new review items, and mergeability/conflict status.-5. Diagnose CI failures and classify branch-related vs flaky/unrelated. If the overall run is still pending but `failed_jobs` already includes a failed job, fetch that job's logs and diagnose immediately instead of waiting for the whole workflow run to finish. Patch only when the failure is branch-related.-6. For each surfaced review item from another author, patch/commit/push if it is actionable, then resolve it only when allowed by the GitHub state mutation policy above. If it is non-actionable, already addressed, or requires a written answer, surface it to the user with a suggested response instead of posting automatically. If a later snapshot surfaces your own approved reply, treat it as informational and continue without responding again.-7. Process actionable review comments before flaky reruns when both are present; if a review fix requires a commit, push it and skip rerunning failed checks on the old SHA.-8. Retry failed checks only when `retry_failed_checks` is present and you are not about to replace the current SHA with a review/CI fix commit. Do not make code changes for unrelated flakes or infrastructure failures just to get CI green.-9. If you pushed a commit, resolved an eligible review thread, or triggered a rerun, report the action briefly and continue polling (do not stop). If a human review comment needs a written GitHub response, stop and ask for confirmation before posting.-10. After a review-fix push, proactively restart continuous monitoring (`--watch`) in the same turn unless a strict stop condition has already been reached.-11. If everything is passing, mergeable, not blocked on required review approval, and there are no unaddressed review items, report that the PR is currently ready to merge but keep the watcher running so new review comments are surfaced quickly while the PR remains open.-12. If blocked on a user-help-required issue (infra outage, exhausted flaky retries, unclear reviewer request, permissions), report the blocker and stop.-13. Otherwise sleep according to the polling cadence below and repeat.--When the user explicitly asks to monitor/watch/babysit a PR, prefer `--watch` so polling continues autonomously in one command. Use repeated `--once` snapshots only for debugging, local testing, or when the user explicitly asks for a one-shot check.-Do not stop to ask the user whether to continue polling; continue autonomously until a strict stop condition is met or the user explicitly interrupts.-Do not hand control back to the user after a review-fix push just because a new SHA was created; restarting the watcher and re-entering the poll loop is part of the same babysitting task.-If a `--watch` process is still running and no strict stop condition has been reached, the babysitting task is still in progress; keep streaming/consuming watcher output instead of ending the turn.--## Polling Cadence-Keep review polling aggressive and continue monitoring even after CI turns green:--- While CI is not green (pending/running/queued or failing): poll every 1 minute.-- After CI turns green: keep polling at the base cadence while the PR remains open so newly posted review comments are surfaced promptly instead of waiting on a long green-state backoff.-- Reset the cadence immediately whenever anything changes (new commit/SHA, check status changes, new review comments, mergeability changes, review decision changes).-- If CI stops being green again (new commit, rerun, or regression): stay on the base polling cadence.-- If any poll shows the PR is merged or otherwise closed: stop polling immediately and report the terminal state.--## Stop Conditions (Strict)-Stop only when one of the following is true:--- PR merged or closed (stop as soon as a poll/snapshot confirms this).-- User intervention is required and Codex cannot safely proceed alone.--Keep polling when:--- `actions` contains only `idle` but checks are still pending.-- CI is still running/queued.-- Review state is quiet but CI is not terminal.-- CI is green but mergeability is unknown/pending.-- CI is green and mergeable, but the PR is still open and you are waiting for possible new review comments or merge-conflict changes.-- The PR is green but blocked on review approval (`REVIEW_REQUIRED` / similar); continue polling at the base cadence and surface any new review comments without asking for confirmation to keep watching.--## Output Expectations-Provide concise progress updates while monitoring and a final summary that includes:--- During long unchanged monitoring periods, avoid emitting a full update on every poll; summarize only status changes plus occasional heartbeat updates.-- Treat push confirmations, intermediate CI snapshots, ready-to-merge snapshots, and review-action updates as progress updates only; do not emit the final summary or end the babysitting session unless a strict stop condition is met.-- A user request to "monitor" is not satisfied by a couple of sample polls; remain in the loop until a strict stop condition or an explicit user interruption.-- A review-fix commit + push is not a completion event; immediately resume live monitoring (`--watch`) in the same turn and continue reporting progress updates.-- When CI first transitions to all green for the current SHA, emit a one-time celebratory progress update (do not repeat it on every green poll). Preferred style: `🚀 CI is all green! 33/33 passed. Still on watch for review approval.`-- Do not send the final summary while a watcher terminal is still running unless the watcher has emitted/confirmed a strict stop condition; otherwise continue with progress updates.--- Final PR SHA-- CI status summary-- Mergeability / conflict status-- Fixes pushed-- Flaky retry cycles used-- Remaining unresolved failures or review comments--## References--- Heuristics and decision tree: `.codex/skills/babysit-pr/references/heuristics.md`-- GitHub CLI/API details used by the watcher: `.codex/skills/babysit-pr/references/github-api-notes.md`diff --git a/.codex/skills/babysit-pr/agents/openai.yaml b/.codex/skills/babysit-pr/agents/openai.yamldeleted file mode 100644index e07637b903..0000000000--- a/.codex/skills/babysit-pr/agents/openai.yaml+++ /dev/null@@ -1,4 +0,0 @@-interface:- display_name: "PR Babysitter"- short_description: "Watch PR review comments, CI, and merge conflicts"- default_prompt: "Babysit the current PR: monitor published reviewer comments, CI, and merge-conflict status (prefer the watcher’s --watch mode for live monitoring); ignore unpublished comments in pending GitHub reviews; surface new published review feedback before acting on CI or mergeability work, fix valid issues, push updates, and rerun flaky failures up to 3 times. Do not post replies to human-authored review comments unless the user explicitly confirms the exact response. Do not patch unrelated flaky tests, CI infrastructure, dependency outages, runner issues, or other failures that are not caused by the branch. Keep exactly one watcher session active for the PR (do not leave duplicate --watch terminals running). If you pause monitoring to patch review/CI feedback, restart --watch yourself immediately after the push in the same turn. If a watcher is still running and no strict stop condition has been reached, the task is still in progress: keep consuming watcher output and sending progress updates instead of ending the turn. Do not treat a green + mergeable PR as a terminal stop while it is still open; continue polling autonomously after any push/rerun so newly posted review comments are surfaced until a strict terminal stop condition is reached or the user interrupts."diff --git a/.codex/skills/babysit-pr/references/github-api-notes.md b/.codex/skills/babysit-pr/references/github-api-notes.mddeleted file mode 100644index 645e7453c1..0000000000--- a/.codex/skills/babysit-pr/references/github-api-notes.md+++ /dev/null@@ -1,85 +0,0 @@-# GitHub CLI / API Notes For `babysit-pr`--## Primary commands used--### PR metadata--- `gh pr view --json number,url,state,mergedAt,closedAt,headRefName,headRefOid,headRepository,headRepositoryOwner`--Used to resolve PR number, URL, branch, head SHA, and closed/merged state.--### PR checks summary--- `gh pr checks --json name,state,bucket,link,workflow,event,startedAt,completedAt`--Used to compute pending/failed/passed counts and whether the current CI round is terminal.--### Workflow runs for head SHA--- `gh api repos/{owner}/{repo}/actions/runs -X GET -f head_sha=<sha> -f per_page=100`--Used to discover failed workflow runs and rerunnable run IDs.--### Failed log inspection--- `gh run view <run-id> --json jobs,name,workflowName,conclusion,status,url,headSha`-- `gh api repos/{owner}/{repo}/actions/runs/{run_id}/jobs -X GET -f per_page=100`-- `gh api repos/{owner}/{repo}/actions/jobs/{job_id}/logs > /tmp/codex-gh-job-{job_id}-logs.zip`-- `gh run view <run-id> --log-failed`--Used by Codex to classify branch-related vs flaky/unrelated failures. Prefer the direct job log endpoint as soon as a job has failed because `gh run view --log-failed` may not produce failed-job logs until the overall workflow run completes.--### Retry failed jobs only--- `gh run rerun <run-id> --failed`--Reruns only failed jobs (and dependencies) for a workflow run.--## Review-related endpoints--- Issue comments on PR:- - `gh api repos/{owner}/{repo}/issues/<pr_number>/comments?per_page=100`-- Inline PR review comments:- - `gh api repos/{owner}/{repo}/pulls/<pr_number>/comments?per_page=100`-- Review submissions:- - `gh api repos/{owner}/{repo}/pulls/<pr_number>/reviews?per_page=100`--Use each inline comment's `pull_request_review_id` to find its parent review. Ignore parent reviews-whose `state` is `PENDING`, along with their inline comments, until the review is submitted.--## JSON fields consumed by the watcher--### `gh pr view`--- `number`-- `url`-- `state`-- `mergedAt`-- `closedAt`-- `headRefName`-- `headRefOid`--### `gh pr checks`--- `bucket` (`pass`, `fail`, `pending`, `skipping`)-- `state`-- `name`-- `workflow`-- `link`--### Actions runs API (`workflow_runs[]`)--- `id`-- `name`-- `status`-- `conclusion`-- `html_url`-- `head_sha`--### Actions run jobs API (`jobs[]`)--- `id`-- `name`-- `status`-- `conclusion`-- `html_url`diff --git a/.codex/skills/babysit-pr/references/heuristics.md b/.codex/skills/babysit-pr/references/heuristics.mddeleted file mode 100644index ee44c4a194..0000000000--- a/.codex/skills/babysit-pr/references/heuristics.md+++ /dev/null@@ -1,66 +0,0 @@-# CI / Review Heuristics--## CI classification checklist--Treat as **branch-related** when logs clearly indicate a regression caused by the PR branch:--- Compile/typecheck/lint failures in files or modules touched by the branch-- Deterministic unit/integration test failures in changed areas-- Snapshot output changes caused by UI/text changes in the branch-- Static analysis violations introduced by the latest push-- Build script/config changes in the PR causing a deterministic failure--Treat as **likely flaky or unrelated** when evidence points to transient or external issues:--- DNS/network/registry timeout errors while fetching dependencies-- Runner image provisioning or startup failures-- GitHub Actions infrastructure/service outages-- Cloud/service rate limits or transient API outages-- Non-deterministic failures in unrelated integration tests with known flake patterns--Do not patch likely flaky/unrelated failures. Use the retry budget for rerunnable failures, wait for pending jobs, or stop and report the blocker when the failure is persistent or infrastructure-owned.--If uncertain, inspect failed logs once before choosing rerun.--## Decision tree (fix vs rerun vs stop)--1. If PR is merged/closed: stop.-2. If there are failed checks:- - Diagnose first.- - If checks are still pending but an individual job has already failed: fetch that job's logs and diagnose now.- - If branch-related: fix locally, commit, push.- - If likely flaky/unrelated and all checks for the current SHA are terminal: rerun failed jobs.- - If likely flaky/unrelated and not safely rerunnable: stop and report the blocker; do not edit unrelated tests, build scripts, CI configuration, dependency pins, or infrastructure code.- - If checks are still pending and no failed job is available yet: wait.-3. If flaky reruns for the same SHA reach the configured limit (default 3): stop and report persistent failure.-4. Independently, process any new human review comments.--## Review comment agreement criteria--Address the comment when:--- The comment is technically correct.-- The change is actionable in the current branch.-- The requested change does not conflict with the user’s intent or recent guidance.-- The change can be made safely without unrelated refactors.--Fix valid human review feedback in code when possible, but do not post a GitHub reply to a human-authored comment/thread unless the user explicitly confirms the exact response.--Do not auto-fix when:--- The comment is ambiguous and needs clarification.-- The request conflicts with explicit user instructions.-- The proposed change requires product/design decisions the user has not made.-- The codebase is in a dirty/unrelated state that makes safe editing uncertain.-- The comment only needs a written answer or disagreement response; propose the reply to the user instead of posting it automatically.--## Stop-and-ask conditions--Stop and ask the user instead of continuing automatically when:--- The local worktree has unrelated uncommitted changes.-- `gh` auth/permissions fail.-- The PR branch cannot be pushed.-- CI failures persist after the flaky retry budget.-- Reviewer feedback requires a product decision or cross-team coordination.-- A human review comment requires a written GitHub reply instead of a code change.diff --git a/.codex/skills/babysit-pr/scripts/gh_pr_watch.py b/.codex/skills/babysit-pr/scripts/gh_pr_watch.pydeleted file mode 100755index 1572133c92..0000000000--- a/.codex/skills/babysit-pr/scripts/gh_pr_watch.py+++ /dev/null@@ -1,951 +0,0 @@-#!/usr/bin/env python3-"""Watch GitHub PR CI and review activity for Codex PR babysitting workflows."""--import argparse-import json-import os-import re-import subprocess-import sys-import tempfile-import time-from pathlib import Path-from urllib.parse import urlparse--FAILED_RUN_CONCLUSIONS = {- "failure",- "timed_out",- "cancelled",- "action_required",- "startup_failure",- "stale",-}-PENDING_CHECK_STATES = {- "QUEUED",- "IN_PROGRESS",- "PENDING",- "WAITING",- "REQUESTED",-}-REVIEW_BOT_LOGIN_KEYWORDS = {- "codex",-}-TRUSTED_AUTHOR_ASSOCIATIONS = {- "OWNER",- "MEMBER",- "COLLABORATOR",-}-MERGE_BLOCKING_REVIEW_DECISIONS = {- "REVIEW_REQUIRED",- "CHANGES_REQUESTED",-}-MERGE_CONFLICT_OR_BLOCKING_STATES = {- "BLOCKED",- "DIRTY",- "DRAFT",- "UNKNOWN",-}---class GhCommandError(RuntimeError):- pass---def parse_args():- parser = argparse.ArgumentParser(- description=(- "Normalize PR/CI/review state for Codex PR babysitting and optionally "- "trigger flaky reruns."- )- )- parser.add_argument("--pr", default="auto", help="auto, PR number, or PR URL")- parser.add_argument("--repo", help="Optional OWNER/REPO override")- parser.add_argument(- "--poll-seconds", type=int, default=30, help="Watch poll interval"- )- parser.add_argument(- "--max-flaky-retries",- type=int,- default=3,- help="Max rerun cycles per head SHA before stop recommendation",- )- parser.add_argument("--state-file", help="Path to state JSON file")- parser.add_argument(- "--once", action="store_true", help="Emit one snapshot and exit"- )- parser.add_argument(- "--watch", action="store_true", help="Continuously emit JSONL snapshots"- )- parser.add_argument(- "--retry-failed-now",- action="store_true",- help="Rerun failed jobs for current failed workflow runs when policy allows",- )- parser.add_argument(- "--json",- action="store_true",- help="Emit machine-readable output (default behavior for --once and --retry-failed-now)",- )- args = parser.parse_args()-- if args.poll_seconds <= 0:- parser.error("--poll-seconds must be > 0")- if args.max_flaky_retries < 0:- parser.error("--max-flaky-retries must be >= 0")- if args.watch and args.retry_failed_now:- parser.error("--watch cannot be combined with --retry-failed-now")- if not args.once and not args.watch and not args.retry_failed_now:- args.once = True- return args---def _format_gh_error(cmd, err):- stdout = (err.stdout or "").strip()- stderr = (err.stderr or "").strip()- parts = [f"GitHub CLI command failed: {' '.join(cmd)}"]- if stdout:- parts.append(f"stdout: {stdout}")- if stderr:- parts.append(f"stderr: {stderr}")- return "\n".join(parts)---def gh_text(args, repo=None):- cmd = ["gh"]- # `gh api` does not accept `-R/--repo` on all gh versions. The watcher's- # API calls use explicit endpoints (e.g. repos/{owner}/{repo}/...), so the- # repo flag is unnecessary there.- if repo and (not args or args[0] != "api"):- cmd.extend(["-R", repo])- cmd.extend(args)- try:- proc = subprocess.run(cmd, check=True, capture_output=True, text=True)- except FileNotFoundError as err:- raise GhCommandError("`gh` command not found") from err- except subprocess.CalledProcessError as err:- raise GhCommandError(_format_gh_error(cmd, err)) from err- return proc.stdout---def gh_json(args, repo=None):- raw = gh_text(args, repo=repo).strip()- if not raw:- return None- try:- return json.loads(raw)- except json.JSONDecodeError as err:- raise GhCommandError(- f"Failed to parse JSON from gh output for {' '.join(args)}"- ) from err---def parse_pr_spec(pr_spec):- if pr_spec == "auto":- return {"mode": "auto", "value": None}- if re.fullmatch(r"\d+", pr_spec):- return {"mode": "number", "value": pr_spec}- parsed = urlparse(pr_spec)- if parsed.scheme and parsed.netloc and "/pull/" in parsed.path:- return {"mode": "url", "value": pr_spec}- raise ValueError("--pr must be 'auto', a PR number, or a PR URL")---def pr_view_fields():- return (- "number,url,state,mergedAt,closedAt,headRefName,headRefOid,"- "headRepository,headRepositoryOwner,mergeable,mergeStateStatus,reviewDecision"- )---def checks_fields():- return "name,state,bucket,link,workflow,event,startedAt,completedAt"---def resolve_pr(pr_spec, repo_override=None):- parsed = parse_pr_spec(pr_spec)- cmd = ["pr", "view"]- if parsed["value"] is not None:- cmd.append(parsed["value"])- cmd.extend(["--json", pr_view_fields()])- data = gh_json(cmd, repo=repo_override)- if not isinstance(data, dict):- raise GhCommandError("Unexpected PR payload from `gh pr view`")-- pr_url = str(data.get("url") or "")- repo = (- repo_override- or extract_repo_from_pr_url(pr_url)- or extract_repo_from_pr_view(data)- )- if not repo:- raise GhCommandError("Unable to determine OWNER/REPO for the PR")-- state = str(data.get("state") or "")- merged = bool(data.get("mergedAt"))- closed = bool(data.get("closedAt")) or state.upper() == "CLOSED"-- return {- "number": int(data["number"]),- "url": pr_url,- "repo": repo,- "head_sha": str(data.get("headRefOid") or ""),- "head_branch": str(data.get("headRefName") or ""),- "state": state,- "merged": merged,- "closed": closed,- "mergeable": str(data.get("mergeable") or ""),- "merge_state_status": str(data.get("mergeStateStatus") or ""),- "review_decision": str(data.get("reviewDecision") or ""),- }---def extract_repo_from_pr_view(data):- head_repo = data.get("headRepository")- head_owner = data.get("headRepositoryOwner")- owner = None- name = None- if isinstance(head_owner, dict):- owner = head_owner.get("login") or head_owner.get("name")- elif isinstance(head_owner, str):- owner = head_owner- if isinstance(head_repo, dict):- name = head_repo.get("name")- repo_owner = head_repo.get("owner")- if not owner and isinstance(repo_owner, dict):- owner = repo_owner.get("login") or repo_owner.get("name")- elif isinstance(head_repo, str):- name = head_repo- if owner and name:- return f"{owner}/{name}"- return None---def extract_repo_from_pr_url(pr_url):- parsed = urlparse(pr_url)- parts = [p for p in parsed.path.split("/") if p]- if len(parts) >= 4 and parts[2] == "pull":- return f"{parts[0]}/{parts[1]}"- return None---def load_state(path):- if path.exists():- try:- data = json.loads(path.read_text())- except json.JSONDecodeError as err:- raise RuntimeError(f"State file is not valid JSON: {path}") from err- if not isinstance(data, dict):- raise RuntimeError(f"State file must contain an object: {path}")- return data, False- return {- "pr": {},- "started_at": None,- "last_seen_head_sha": None,- "retries_by_sha": {},- "seen_issue_comment_ids": [],- "seen_review_comment_ids": [],- "seen_review_ids": [],- "last_snapshot_at": None,- }, True---def save_state(path, state):- path.parent.mkdir(parents=True, exist_ok=True)- payload = json.dumps(state, indent=2, sort_keys=True) + "\n"- fd, tmp_name = tempfile.mkstemp(- prefix=f"{path.name}.", suffix=".tmp", dir=path.parent- )- tmp_path = Path(tmp_name)- try:- with os.fdopen(fd, "w", encoding="utf-8") as tmp_file:- tmp_file.write(payload)- os.replace(tmp_path, path)- except Exception:- try:- tmp_path.unlink(missing_ok=True)- except OSError:- pass- raise---def default_state_file_for(pr):- repo_slug = pr["repo"].replace("/", "-")- return Path(f"/tmp/codex-babysit-pr-{repo_slug}-pr{pr['number']}.json")---def get_pr_checks(pr_spec, repo):- parsed = parse_pr_spec(pr_spec)- cmd = ["pr", "checks"]- if parsed["value"] is not None:- cmd.append(parsed["value"])- cmd.extend(["--json", checks_fields()])- data = gh_json(cmd, repo=repo)- if data is None:- return []- if not isinstance(data, list):- raise GhCommandError("Unexpected payload from `gh pr checks`")- return data---def is_pending_check(check):- bucket = str(check.get("bucket") or "").lower()- state = str(check.get("state") or "").upper()- return bucket == "pending" or state in PENDING_CHECK_STATES---def summarize_checks(checks):- pending_count = 0- failed_count = 0- passed_count = 0- for check in checks:- bucket = str(check.get("bucket") or "").lower()- if is_pending_check(check):- pending_count += 1- if bucket == "fail":- failed_count += 1- if bucket == "pass":- passed_count += 1- return {- "pending_count": pending_count,- "failed_count": failed_count,- "passed_count": passed_count,- "all_terminal": pending_count == 0,- }---def get_workflow_runs_for_sha(repo, head_sha):- endpoint = f"repos/{repo}/actions/runs"- data = gh_json(- [- "api",- endpoint,- "-X",- "GET",- "-f",- f"head_sha={head_sha}",- "-f",- "per_page=100",- ],- repo=repo,- )- if not isinstance(data, dict):- raise GhCommandError("Unexpected payload from actions runs API")- runs = data.get("workflow_runs") or []- if not isinstance(runs, list):- raise GhCommandError("Expected `workflow_runs` to be a list")- return runs---def failed_runs_from_workflow_runs(runs, head_sha):- failed_runs = []- for run in runs:- if not isinstance(run, dict):- continue- if str(run.get("head_sha") or "") != head_sha:- continue- conclusion = str(run.get("conclusion") or "")- if conclusion not in FAILED_RUN_CONCLUSIONS:- continue- failed_runs.append(- {- "run_id": run.get("id"),- "workflow_name": run.get("name") or run.get("display_title") or "",- "status": str(run.get("status") or ""),- "conclusion": conclusion,- "html_url": str(run.get("html_url") or ""),- }- )- failed_runs.sort(- key=lambda item: (- str(item.get("workflow_name") or ""),- str(item.get("run_id") or ""),- )- )- return failed_runs---def get_jobs_for_run(repo, run_id):- endpoint = f"repos/{repo}/actions/runs/{run_id}/jobs"- data = gh_json(["api", endpoint, "-X", "GET", "-f", "per_page=100"], repo=repo)- if not isinstance(data, dict):- raise GhCommandError("Unexpected payload from actions run jobs API")- jobs = data.get("jobs") or []- if not isinstance(jobs, list):- raise GhCommandError("Expected `jobs` to be a list")- return jobs---def failed_jobs_from_workflow_runs(repo, runs, head_sha):- failed_jobs = []- for run in runs:- if not isinstance(run, dict):- continue- if str(run.get("head_sha") or "") != head_sha:- continue- run_id = run.get("id")- if run_id in (None, ""):- continue- run_status = str(run.get("status") or "")- run_conclusion = str(run.get("conclusion") or "")- if (- run_status.lower() == "completed"- and run_conclusion not in FAILED_RUN_CONCLUSIONS- ):- continue- jobs = get_jobs_for_run(repo, run_id)- for job in jobs:- if not isinstance(job, dict):- continue- conclusion = str(job.get("conclusion") or "")- if conclusion not in FAILED_RUN_CONCLUSIONS:- continue- job_id = job.get("id")- logs_endpoint = None- if job_id not in (None, ""):- logs_endpoint = f"repos/{repo}/actions/jobs/{job_id}/logs"- failed_jobs.append(- {- "run_id": run_id,- "workflow_name": run.get("name") or run.get("display_title") or "",- "run_status": run_status,- "run_conclusion": run_conclusion,- "job_id": job_id,- "job_name": str(job.get("name") or ""),- "status": str(job.get("status") or ""),- "conclusion": conclusion,- "html_url": str(job.get("html_url") or ""),- "logs_endpoint": logs_endpoint,- }- )- failed_jobs.sort(- key=lambda item: (- str(item.get("workflow_name") or ""),- str(item.get("job_name") or ""),- str(item.get("job_id") or ""),- )- )- return failed_jobs---def get_authenticated_login():- data = gh_json(["api", "user"])- if not isinstance(data, dict) or not data.get("login"):- raise GhCommandError(- "Unable to determine authenticated GitHub login from `gh api user`"- )- return str(data["login"])---def comment_endpoints(repo, pr_number):- return {- "issue_comment": f"repos/{repo}/issues/{pr_number}/comments",- "review_comment": f"repos/{repo}/pulls/{pr_number}/comments",- "review": f"repos/{repo}/pulls/{pr_number}/reviews",- }---def gh_api_list_paginated(endpoint, repo=None, per_page=100):- items = []- page = 1- while True:- sep = "&" if "?" in endpoint else "?"- page_endpoint = f"{endpoint}{sep}per_page={per_page}&page={page}"- payload = gh_json(["api", page_endpoint], repo=repo)- if payload is None:- break- if not isinstance(payload, list):- raise GhCommandError(f"Unexpected paginated payload from gh api {endpoint}")- items.extend(payload)- if len(payload) < per_page:- break- page += 1- return items---def normalize_issue_comments(items):- out = []- for item in items:- if not isinstance(item, dict):- continue- out.append(- {- "kind": "issue_comment",- "id": str(item.get("id") or ""),- "author": extract_login(item.get("user")),- "author_association": str(item.get("author_association") or ""),- "created_at": str(item.get("created_at") or ""),- "body": str(item.get("body") or ""),- "path": None,- "line": None,- "url": str(item.get("html_url") or ""),- }- )- return out---def normalize_review_comments(items, review_states):- out = []- for item in items:- if not isinstance(item, dict):- continue- review_id = str(item.get("pull_request_review_id") or "")- if review_states.get(review_id) == "PENDING":- continue- line = item.get("line")- if line is None:- line = item.get("original_line")- out.append(- {- "kind": "review_comment",- "id": str(item.get("id") or ""),- "author": extract_login(item.get("user")),- "author_association": str(item.get("author_association") or ""),- "created_at": str(item.get("created_at") or ""),- "body": str(item.get("body") or ""),- "path": item.get("path"),- "line": line,- "url": str(item.get("html_url") or ""),- }- )- return out---def normalize_reviews(items):- out = []- for item in items:- if not isinstance(item, dict):- continue- if str(item.get("state") or "").upper() == "PENDING":- continue- out.append(- {- "kind": "review",- "id": str(item.get("id") or ""),- "author": extract_login(item.get("user")),- "author_association": str(item.get("author_association") or ""),- "created_at": str(- item.get("submitted_at") or item.get("created_at") or ""- ),- "body": str(item.get("body") or ""),- "path": None,- "line": None,- "url": str(item.get("html_url") or ""),- }- )- return out---def extract_login(user_obj):- if isinstance(user_obj, dict):- return str(user_obj.get("login") or "")- return ""---def is_bot_login(login):- return bool(login) and login.endswith("[bot]")---def is_actionable_review_bot_login(login):- if not is_bot_login(login):- return False- lower_login = login.lower()- return any(keyword in lower_login for keyword in REVIEW_BOT_LOGIN_KEYWORDS)---def is_trusted_human_review_author(item, authenticated_login):- author = str(item.get("author") or "")- if not author:- return False- if authenticated_login and author == authenticated_login:- return True- association = str(item.get("author_association") or "").upper()- return association in TRUSTED_AUTHOR_ASSOCIATIONS---def fetch_new_review_items(pr, state, fresh_state, authenticated_login=None):- repo = pr["repo"]- pr_number = pr["number"]- endpoints = comment_endpoints(repo, pr_number)-- issue_payload = gh_api_list_paginated(endpoints["issue_comment"], repo=repo)- review_comment_payload = gh_api_list_paginated(- endpoints["review_comment"], repo=repo- )- review_payload = gh_api_list_paginated(endpoints["review"], repo=repo)-- issue_items = normalize_issue_comments(issue_payload)- review_states = {- str(item.get("id")): str(item.get("state") or "").upper()- for item in review_payload- if isinstance(item, dict) and item.get("id") not in (None, "")- }- pending_review_ids = {- review_id- for review_id, review_state in review_states.items()- if review_state == "PENDING"- }- pending_review_comment_ids = {- str(item.get("id"))- for item in review_comment_payload- if isinstance(item, dict)- and item.get("id") not in (None, "")- and str(item.get("pull_request_review_id") or "") in pending_review_ids- }- review_comment_items = normalize_review_comments(- review_comment_payload, review_states- )- review_items = normalize_reviews(review_payload)- all_items = issue_items + review_comment_items + review_items-- seen_issue = {str(x) for x in state.get("seen_issue_comment_ids") or []}- seen_review_comment = {str(x) for x in state.get("seen_review_comment_ids") or []}- seen_review = {str(x) for x in state.get("seen_review_ids") or []}- seen_review_comment.difference_update(pending_review_comment_ids)- seen_review.difference_update(pending_review_ids)-- # On a brand-new state file, surface existing review activity instead of- # silently treating it as seen. This avoids missing already-published review- # feedback when monitoring starts after comments were posted.-- new_items = []- for item in all_items:- item_id = item.get("id")- if not item_id:- continue- author = item.get("author") or ""- if not author:- continue- if is_bot_login(author):- if not is_actionable_review_bot_login(author):- continue- elif not is_trusted_human_review_author(item, authenticated_login):- continue-- kind = item["kind"]- if kind == "issue_comment" and item_id in seen_issue:- continue- if kind == "review_comment" and item_id in seen_review_comment:- continue- if kind == "review" and item_id in seen_review:- continue-- new_items.append(item)- if kind == "issue_comment":- seen_issue.add(item_id)- elif kind == "review_comment":- seen_review_comment.add(item_id)- elif kind == "review":- seen_review.add(item_id)-- new_items.sort(- key=lambda item: (- item.get("created_at") or "",- item.get("kind") or "",- item.get("id") or "",- )- )- state["seen_issue_comment_ids"] = sorted(seen_issue)- state["seen_review_comment_ids"] = sorted(seen_review_comment)- state["seen_review_ids"] = sorted(seen_review)- return new_items---def current_retry_count(state, head_sha):- retries = state.get("retries_by_sha") or {}- value = retries.get(head_sha, 0)- try:- return int(value)- except (TypeError, ValueError):- return 0---def set_retry_count(state, head_sha, count):- retries = state.get("retries_by_sha")- if not isinstance(retries, dict):- retries = {}- retries[head_sha] = int(count)- state["retries_by_sha"] = retries---def unique_actions(actions):- out = []- seen = set()- for action in actions:- if action not in seen:- out.append(action)- seen.add(action)- return out---def is_pr_ready_to_merge(pr, checks_summary, new_review_items):- if pr["closed"] or pr["merged"]:- return False- if not checks_summary["all_terminal"]:- return False- if checks_summary["failed_count"] > 0 or checks_summary["pending_count"] > 0:- return False- if new_review_items:- return False- if str(pr.get("mergeable") or "") != "MERGEABLE":- return False- if str(pr.get("merge_state_status") or "") in MERGE_CONFLICT_OR_BLOCKING_STATES:- return False- if str(pr.get("review_decision") or "") in MERGE_BLOCKING_REVIEW_DECISIONS:- return False- return True---def recommend_actions(- pr,- checks_summary,- failed_runs,- failed_jobs,- new_review_items,- retries_used,- max_retries,-):- actions = []- if pr["closed"] or pr["merged"]:- if new_review_items:- actions.append("process_review_comment")- actions.append("stop_pr_closed")- return unique_actions(actions)-- if is_pr_ready_to_merge(pr, checks_summary, new_review_items):- actions.append("ready_to_merge")- return unique_actions(actions)-- if new_review_items:- actions.append("process_review_comment")-- has_failed_pr_checks = checks_summary["failed_count"] > 0 or bool(failed_jobs)- if has_failed_pr_checks:- if checks_summary["all_terminal"] and retries_used >= max_retries:- actions.append("stop_exhausted_retries")- else:- actions.append("diagnose_ci_failure")- if (- checks_summary["all_terminal"]- and failed_runs- and retries_used < max_retries- ):- actions.append("retry_failed_checks")-- if not actions:- actions.append("idle")- return unique_actions(actions)---def collect_snapshot(args):- pr = resolve_pr(args.pr, repo_override=args.repo)- state_path = (- Path(args.state_file) if args.state_file else default_state_file_for(pr)- )- state, fresh_state = load_state(state_path)-- if not state.get("started_at"):- state["started_at"] = int(time.time())-- authenticated_login = get_authenticated_login()- new_review_items = fetch_new_review_items(- pr,- state,- fresh_state=fresh_state,- authenticated_login=authenticated_login,- )- # Surface review feedback before drilling into CI and mergeability details.- # That keeps the babysitter responsive to new comments even when other- # actions are also available.- # `gh pr checks -R <repo>` requires an explicit PR/branch/url argument.- # After resolving `--pr auto`, reuse the concrete PR number.- checks = get_pr_checks(str(pr["number"]), repo=pr["repo"])- checks_summary = summarize_checks(checks)- workflow_runs = get_workflow_runs_for_sha(pr["repo"], pr["head_sha"])- failed_runs = failed_runs_from_workflow_runs(workflow_runs, pr["head_sha"])- failed_jobs = failed_jobs_from_workflow_runs(- pr["repo"], workflow_runs, pr["head_sha"]- )-- retries_used = current_retry_count(state, pr["head_sha"])- actions = recommend_actions(- pr,- checks_summary,- failed_runs,- failed_jobs,- new_review_items,- retries_used,- args.max_flaky_retries,- )-- state["pr"] = {"repo": pr["repo"], "number": pr["number"]}- state["last_seen_head_sha"] = pr["head_sha"]- state["last_snapshot_at"] = int(time.time())- save_state(state_path, state)-- snapshot = {- "pr": pr,- "checks": checks_summary,- "failed_runs": failed_runs,- "failed_jobs": failed_jobs,- "new_review_items": new_review_items,- "actions": actions,- "retry_state": {- "current_sha_retries_used": retries_used,- "max_flaky_retries": args.max_flaky_retries,- },- }- return snapshot, state_path---def retry_failed_now(args):- snapshot, state_path = collect_snapshot(args)- pr = snapshot["pr"]- checks_summary = snapshot["checks"]- failed_runs = snapshot["failed_runs"]- retries_used = snapshot["retry_state"]["current_sha_retries_used"]- max_retries = snapshot["retry_state"]["max_flaky_retries"]-- result = {- "snapshot": snapshot,- "state_file": str(state_path),- "rerun_attempted": False,- "rerun_count": 0,- "rerun_run_ids": [],- "reason": None,- }-- if pr["closed"] or pr["merged"]:- result["reason"] = "pr_closed"- return result- if checks_summary["failed_count"] <= 0:- result["reason"] = "no_failed_pr_checks"- return result- if not failed_runs:- result["reason"] = "no_failed_runs"- return result- if not checks_summary["all_terminal"]:- result["reason"] = "checks_still_pending"- return result- if retries_used >= max_retries:- result["reason"] = "retry_budget_exhausted"- return result-- for run in failed_runs:- run_id = run.get("run_id")- if run_id in (None, ""):- continue- gh_text(["run", "rerun", str(run_id), "--failed"], repo=pr["repo"])- result["rerun_run_ids"].append(run_id)-- if result["rerun_run_ids"]:- state, _ = load_state(state_path)- new_count = current_retry_count(state, pr["head_sha"]) + 1- set_retry_count(state, pr["head_sha"], new_count)- state["last_snapshot_at"] = int(time.time())- save_state(state_path, state)- result["rerun_attempted"] = True- result["rerun_count"] = len(result["rerun_run_ids"])- result["reason"] = "rerun_triggered"- else:- result["reason"] = "failed_runs_missing_ids"-- return result---def print_json(obj):- sys.stdout.write(json.dumps(obj, sort_keys=True) + "\n")- sys.stdout.flush()---def print_event(event, payload):- print_json({"event": event, "payload": payload})---def is_ci_green(snapshot):- checks = snapshot.get("checks") or {}- return (- bool(checks.get("all_terminal"))- and int(checks.get("failed_count") or 0) == 0- and int(checks.get("pending_count") or 0) == 0- )---def snapshot_change_key(snapshot):- pr = snapshot.get("pr") or {}- checks = snapshot.get("checks") or {}- review_items = snapshot.get("new_review_items") or []- return (- str(pr.get("head_sha") or ""),- str(pr.get("state") or ""),- str(pr.get("mergeable") or ""),- str(pr.get("merge_state_status") or ""),- str(pr.get("review_decision") or ""),- int(checks.get("passed_count") or 0),- int(checks.get("failed_count") or 0),- int(checks.get("pending_count") or 0),- tuple(- (str(item.get("kind") or ""), str(item.get("id") or ""))- for item in review_items- if isinstance(item, dict)- ),- tuple(snapshot.get("actions") or []),- )---def run_watch(args):- poll_seconds = args.poll_seconds- last_change_key = None- while True:- snapshot, state_path = collect_snapshot(args)- print_event(- "snapshot",- {- "snapshot": snapshot,- "state_file": str(state_path),- "next_poll_seconds": poll_seconds,- },- )- actions = set(snapshot.get("actions") or [])- if "stop_pr_closed" in actions or "stop_exhausted_retries" in actions:- print_event(- "stop", {"actions": snapshot.get("actions"), "pr": snapshot.get("pr")}- )- return 0-- current_change_key = snapshot_change_key(snapshot)- changed = current_change_key != last_change_key- green = is_ci_green(snapshot)- pr = snapshot.get("pr") or {}- pr_open = not bool(pr.get("closed")) and not bool(pr.get("merged"))-- if not green or pr_open:- poll_seconds = args.poll_seconds- elif changed or last_change_key is None:- poll_seconds = args.poll_seconds-- last_change_key = current_change_key- time.sleep(poll_seconds)---def main():- args = parse_args()- try:- if args.retry_failed_now:- print_json(retry_failed_now(args))- return 0- if args.watch:- return run_watch(args)- snapshot, state_path = collect_snapshot(args)- snapshot["state_file"] = str(state_path)- print_json(snapshot)- return 0- except (GhCommandError, RuntimeError, ValueError) as err:- sys.stderr.write(f"gh_pr_watch.py error: {err}\n")- return 1- except KeyboardInterrupt:- sys.stderr.write("gh_pr_watch.py interrupted\n")- return 130---if __name__ == "__main__":- raise SystemExit(main())diff --git a/.codex/skills/babysit-pr/scripts/test_gh_pr_watch.py b/.codex/skills/babysit-pr/scripts/test_gh_pr_watch.pydeleted file mode 100644index 76293b56f8..0000000000--- a/.codex/skills/babysit-pr/scripts/test_gh_pr_watch.py+++ /dev/null@@ -1,285 +0,0 @@-import argparse-import importlib.util-from pathlib import Path--import pytest---MODULE_PATH = Path(__file__).with_name("gh_pr_watch.py")-MODULE_SPEC = importlib.util.spec_from_file_location("gh_pr_watch", MODULE_PATH)-gh_pr_watch = importlib.util.module_from_spec(MODULE_SPEC)-assert MODULE_SPEC.loader is not None-MODULE_SPEC.loader.exec_module(gh_pr_watch)---def sample_pr():- return {- "number": 123,- "url": "https://github.com/openai/codex/pull/123",- "repo": "openai/codex",- "head_sha": "abc123",- "head_branch": "feature",- "state": "OPEN",- "merged": False,- "closed": False,- "mergeable": "MERGEABLE",- "merge_state_status": "CLEAN",- "review_decision": "",- }---def sample_checks(**overrides):- checks = {- "pending_count": 0,- "failed_count": 0,- "passed_count": 12,- "all_terminal": True,- }- checks.update(overrides)- return checks---def test_collect_snapshot_fetches_review_items_before_ci(monkeypatch, tmp_path):- call_order = []- pr = sample_pr()-- monkeypatch.setattr(gh_pr_watch, "resolve_pr", lambda *args, **kwargs: pr)- monkeypatch.setattr(gh_pr_watch, "load_state", lambda path: ({}, True))- monkeypatch.setattr(- gh_pr_watch,- "get_authenticated_login",- lambda: call_order.append("auth") or "octocat",- )- monkeypatch.setattr(- gh_pr_watch,- "fetch_new_review_items",- lambda *args, **kwargs: call_order.append("review") or [],- )- monkeypatch.setattr(- gh_pr_watch,- "get_pr_checks",- lambda *args, **kwargs: call_order.append("checks") or [],- )- monkeypatch.setattr(- gh_pr_watch,- "summarize_checks",- lambda checks: call_order.append("summarize") or sample_checks(),- )- monkeypatch.setattr(- gh_pr_watch,- "get_workflow_runs_for_sha",- lambda *args, **kwargs: call_order.append("workflow") or [],- )- monkeypatch.setattr(- gh_pr_watch,- "failed_runs_from_workflow_runs",- lambda *args, **kwargs: call_order.append("failed_runs") or [],- )- monkeypatch.setattr(- gh_pr_watch,- "failed_jobs_from_workflow_runs",- lambda *args, **kwargs: call_order.append("failed_jobs") or [],- )- monkeypatch.setattr(- gh_pr_watch,- "recommend_actions",- lambda *args, **kwargs: call_order.append("recommend") or ["idle"],- )- monkeypatch.setattr(gh_pr_watch, "save_state", lambda *args, **kwargs: None)-- args = argparse.Namespace(- pr="123",- repo=None,- state_file=str(tmp_path / "watcher-state.json"),- max_flaky_retries=3,- )-- gh_pr_watch.collect_snapshot(args)-- assert call_order.index("review") < call_order.index("checks")- assert call_order.index("review") < call_order.index("workflow")---def test_recommend_actions_prioritizes_review_comments():- actions = gh_pr_watch.recommend_actions(- sample_pr(),- sample_checks(failed_count=1),- [{"run_id": 99}],- [],- [{"kind": "review_comment", "id": "1"}],- 0,- 3,- )-- assert actions == [- "process_review_comment",- "diagnose_ci_failure",- "retry_failed_checks",- ]---def test_pending_review_feedback_surfaces_only_after_publication(monkeypatch):- state = {- "seen_review_comment_ids": ["20"],- "seen_review_ids": ["10"],- }- review = {- "id": 10,- "user": {"login": "octocat"},- "author_association": "MEMBER",- "state": "PENDING",- "body": "Please rename this.",- "created_at": "2026-06-08T10:00:00Z",- "submitted_at": None,- "html_url": "https://github.com/openai/codex/pull/123#pullrequestreview-10",- }- review_comment = {- "id": 20,- "pull_request_review_id": 10,- "user": {"login": "octocat"},- "author_association": "MEMBER",- "body": "Please rename this.",- "created_at": "2026-06-08T10:00:00Z",- "path": "src/example.rs",- "line": 7,- "html_url": "https://github.com/openai/codex/pull/123#discussion_r20",- }-- def fake_list(endpoint, **kwargs):- if endpoint.endswith("/issues/123/comments"):- return []- if endpoint.endswith("/pulls/123/comments"):- return [review_comment]- if endpoint.endswith("/pulls/123/reviews"):- return [review]- raise AssertionError(f"unexpected endpoint: {endpoint}")-- monkeypatch.setattr(gh_pr_watch, "gh_api_list_paginated", fake_list)-- assert (- gh_pr_watch.fetch_new_review_items(- sample_pr(),- state,- fresh_state=True,- authenticated_login="octocat",- )- == []- )- assert state["seen_review_comment_ids"] == []- assert state["seen_review_ids"] == []-- review["state"] = "COMMENTED"- review["submitted_at"] = "2026-06-08T10:05:00Z"-- published_items = gh_pr_watch.fetch_new_review_items(- sample_pr(),- state,- fresh_state=False,- authenticated_login="octocat",- )-- assert {(item["kind"], item["id"]) for item in published_items} == {- ("review", "10"),- ("review_comment", "20"),- }- assert state["seen_review_comment_ids"] == ["20"]- assert state["seen_review_ids"] == ["10"]---def test_run_watch_keeps_polling_open_ready_to_merge_pr(monkeypatch):- sleeps = []- events = []- snapshot = {- "pr": sample_pr(),- "checks": sample_checks(),- "failed_runs": [],- "failed_jobs": [],- "new_review_items": [],- "actions": ["ready_to_merge"],- "retry_state": {- "current_sha_retries_used": 0,- "max_flaky_retries": 3,- },- }-- monkeypatch.setattr(- gh_pr_watch,- "collect_snapshot",- lambda args: (snapshot, Path("/tmp/codex-babysit-pr-state.json")),- )- monkeypatch.setattr(- gh_pr_watch,- "print_event",- lambda event, payload: events.append((event, payload)),- )-- class StopWatch(Exception):- pass-- def fake_sleep(seconds):- sleeps.append(seconds)- if len(sleeps) >= 2:- raise StopWatch-- monkeypatch.setattr(gh_pr_watch.time, "sleep", fake_sleep)-- with pytest.raises(StopWatch):- gh_pr_watch.run_watch(argparse.Namespace(poll_seconds=30))-- assert sleeps == [30, 30]- assert [event for event, _ in events] == ["snapshot", "snapshot"]---def test_failed_jobs_include_direct_logs_endpoint(monkeypatch):- jobs_by_run = {- 99: [- {- "id": 555,- "name": "unit tests",- "status": "completed",- "conclusion": "failure",- "html_url": "https://github.com/openai/codex/actions/runs/99/job/555",- },- {- "id": 556,- "name": "lint",- "status": "completed",- "conclusion": "success",- },- ]- }-- monkeypatch.setattr(- gh_pr_watch,- "get_jobs_for_run",- lambda repo, run_id: jobs_by_run[run_id],- )-- failed_jobs = gh_pr_watch.failed_jobs_from_workflow_runs(- "openai/codex",- [- {- "id": 99,- "name": "CI",- "status": "in_progress",- "conclusion": "",- "head_sha": "abc123",- }- ],- "abc123",- )-- assert failed_jobs == [- {- "run_id": 99,- "workflow_name": "CI",- "run_status": "in_progress",- "run_conclusion": "",- "job_id": 555,- "job_name": "unit tests",- "status": "completed",- "conclusion": "failure",- "html_url": "https://github.com/openai/codex/actions/runs/99/job/555",- "logs_endpoint": "repos/openai/codex/actions/jobs/555/logs",- }- ]diff --git a/.codex/skills/code-review-breaking-changes/SKILL.md b/.codex/skills/code-review-breaking-changes/SKILL.mddeleted file mode 100644index d0bddf281e..0000000000--- a/.codex/skills/code-review-breaking-changes/SKILL.md+++ /dev/null@@ -1,12 +0,0 @@-----name: code-breaking-changes-description: Breaking changes------Search for breaking changes in external integration surfaces:-- app-server APIs-- CLI parameters-- configuration loading-- resuming sessions from existing rollouts--Do not stop after finding one issue; analyze all possible ways breaking changes can happen.diff --git a/.codex/skills/code-review-change-size/SKILL.md b/.codex/skills/code-review-change-size/SKILL.mddeleted file mode 100644index 4e8048dcd4..0000000000--- a/.codex/skills/code-review-change-size/SKILL.md+++ /dev/null@@ -1,11 +0,0 @@-----name: code-review-change-size-description: Change size guidance (800 lines)------Unless the change is mechanical the total number of changed lines should not exceed 800 lines.-For complex logic changes the size should be under 500 lines.--If the change is larger, explain whether it can be split into reviewable stages and identify the smallest coherent stage to land first.-Base the staging suggestion on the actual diff, dependencies, and affected call sites.-diff --git a/.codex/skills/code-review-context/SKILL.md b/.codex/skills/code-review-context/SKILL.mddeleted file mode 100644index 7faf3d7cd2..0000000000--- a/.codex/skills/code-review-context/SKILL.md+++ /dev/null@@ -1,13 +0,0 @@-----name: code-review-context-description: Model visible context------Codex maintains a context (history of messages) that is sent to the model in inference requests.--1. No history rewrite - the context must be built up incrementally.-2. Avoid frequent changes to context that cause cache misses.-3. No unbounded items - everything injected in the model context must have a bounded size and a hard cap.-4. No items larger than 10K tokens.-5. Highlight new individual items that can cross >1k tokens as P0. These need an additional manual review.-6. All injected fragments must be defined as structs in `core/context` and implement ContextualUserFragment trait\ No newline at end of filediff --git a/.codex/skills/code-review-testing/SKILL.md b/.codex/skills/code-review-testing/SKILL.mddeleted file mode 100644index c8d99e13cd..0000000000--- a/.codex/skills/code-review-testing/SKILL.md+++ /dev/null@@ -1,14 +0,0 @@-----name: code-review-testing-description: Test authoring guidance------For agent changes prefer integration tests over unit tests. Integration tests are under `core/suite` and use `test_codex` to set up a test instance of codex.--Features that change the agent logic MUST add an integration test:-- Provide a list of major logic changes and user-facing behaviors that need to be tested.--If unit tests are needed, put them in a dedicated test file (*_tests.rs).-Avoid test-only functions in the main implementation.--Check whether there are existing helpers to make tests more streamlined and readable.diff --git a/.codex/skills/code-review/SKILL.md b/.codex/skills/code-review/SKILL.mddeleted file mode 100644index ccd37a9868..0000000000--- a/.codex/skills/code-review/SKILL.md+++ /dev/null@@ -1,14 +0,0 @@-----name: code-review-description: Run a final code review on a pull request------Use subagents to review code using all code-review-* skills other than this orchestrator. One subagent per skill. Pass full skill path to subagents. Use xhigh reasoning.--You must return every single issue from every subagent. You can return an unlimited number of findings.-Use raw Markdown to report findings.-Number findings for ease of reference.-Each finding must include a specific file path and line number.--If the GitHub user running the review is the owner of the pull request add a `code-reviewed` label.-Do not leave GitHub comments unless explicitly asked.diff --git a/.codex/skills/codex-pr-body/SKILL.md b/.codex/skills/codex-pr-body/SKILL.mddeleted file mode 100644index 332ba0a268..0000000000--- a/.codex/skills/codex-pr-body/SKILL.md+++ /dev/null@@ -1,61 +0,0 @@-----name: codex-pr-body-description: Update the title and body of one or more pull requests.------## Determining the PR(s)--When this skill is invoked, the PR(s) to update may be specified explicitly, but in the common case, the PR(s) to update will be inferred from the branch / commit that the user is currently working on. For ordinary Git usage (i.e., not Sapling as discussed below), you may have to use a combination of `git branch` and `gh pr view <branch> --repo openai/codex --json number --jq '.number'` to determine the PR associated with the current branch / commit.--## PR Body Contents--When invoked, use `gh` to edit the pull request body and title to reflect the contents of the specified PR. Make sure to check the existing pull request body to see if there is key information that should be preserved. For example, NEVER remove an image in the existing pull request body, as the author may have no way to recover it if you remove it.--It is critically important to explain _why_ the change is being made. If the current conversation in which this skill is invoked has discussed the motivation, be sure to capture this in the pull request body.--The body should also explain _what_ changed, but this should appear after the _why_.--Limit discussion to the _net change_ of the commit. It is generally frowned upon to discuss changes that were attempted but later undone in the course of the development of the pull request. When rewriting the pull request body, you may need to eliminate details such as these when they are no longer appropriate / of interest to future readers.--Avoid references to absolute paths on my local disk. When talking about a path that is within the repository, simply use the repo-relative path.--Avoid references to confidential information including but not limited to codenames or OpenAI-internal URLs.--It is generally helpful to discuss how the change was verified. That said, it is unnecessary to mention things that CI checks automatically, e.g., do not include "ran `just fmt`" as part of the test plan. Though identifying the new tests that were purposely introduced to verify the new behavior introduced by the pull request is often appropriate.--Make use of Markdown to format the pull request professionally. Ensure "code things" appear in single backticks when referenced inline. Fenced code blocks are useful when referencing code or showing a shell transcript. Also, make use of GitHub permalinks when citing existing pieces of code that are relevant to the change.--Make sure to reference any relevant pull requests or issues, though there should be no need to reference the pull request in its own PR body.--If there is documentation that should be updated on https://developers.openai.com/codex as a result of this change, please note that in a separate section near the end of the pull request. Omit this section if there is no documentation that needs to be updated.--## Working with Stacks--Sometimes a pull request is composed of a stack of commits that build on one another. In these cases, the PR body should reflect the _net_ change introduced by the stack as a whole, rather than the individual commits that make up the stack.--Similarly, sometimes a user may be using a tool like Sapling to leverage _stacked pull requests_, in which case the `base` of the PR may be the a branch that is the `head` of another PR in the stack rather than `main`. In this case, be sure to discuss only the net change between the `base` and `head` of the PR that is being opened against that stacked base, rather than the changes relative to `main`.--## Sapling--If `.git/sl/store` is present, then this Git repository is governed by Sapling SCM (https://sapling-scm.com).--In Sapling, run the following to see if there is a GitHub pull request associated with the current revision:--```shell-sl log --template '{github_pull_request_url}' -r .-```--Alternatively, you can run `sl sl` to see the current development branch and whether there is a GitHub pull request associated with the current commit. For example, if the output were:--```- @ cb032b31cf 72 minutes ago mbolin #11412-╭─╯ tui: show non-file layer content in /debug-config-│-o fdd0cd1de9 Today at 20:09 origin/main-│-~-```--- `@` indicates the current commit is `cb032b31cf`-- it is a development branch containing a single commit branched off of `origin/main`-- it is associated with GitHub pull request #11412diff --git a/.codex/skills/path-types/SKILL.md b/.codex/skills/path-types/SKILL.mddeleted file mode 100644index 87be423d58..0000000000--- a/.codex/skills/path-types/SKILL.md+++ /dev/null@@ -1,43 +0,0 @@-----name: path-types-description: Choose Rust types for operating system paths across the Codex repository. Use when defining new path-bearing types or explicitly migrating existing ones.------# Path Types--Apply this guidance when defining new types. Change existing code only when explicitly requested,-and keep edits minimal and proportional. Treat these rules as the target state of an ongoing-migration; if compliance is difficult, ask the user how to proceed.--- In app-server protocol types, use `LegacyAppPathString` for backwards compatibility during the URI- migration. At the protocol boundary, convert it to `PathUri` and use `PathUri` internally. For- host-local logic, such as some config values, use `AbsolutePathBuf` or `PathBuf` instead.-- In exec-server protocol types, use `PathUri`. Internally, use `PathUri` or `AbsolutePathBuf` as- appropriate.-- In dependencies shared by both servers, use `PathUri` or separate APIs that decouple their use- cases.-- Tool call arguments that the model is expected to generate should be deserialized as regular- `String`s with feature-specific path handling code.--## Migration requirements--Keep these requirements in mind while migrating code to conform with the above guidelines:--* existing app-server clients keep sending and receiving legacy native-path strings-* app-server can retain and manipulate foreign-platform path URIs-* exec-server APIs use file:// URIs-* local-only operation must not change model-visible text-* model tool arguments may contain raw relative or absolute paths for any OS-* path reasoning must work before the related environment has come online-* URIs cannot explicitly encode the executor’s path convention or operating system-* users must not configure the environment’s OS/path convention explicitly-* URIs should not yet be stored in rollouts, databases, or other persistent storage-* path conversion errors: fail-closed for security-relevant paths, fail-open for UI/diagnostics-* prefer small focused methods on `PathUri` or `LegacyAppPathString` over local helpers-* represent `PathUri` values as URIs in diagnostics--It is OK if the conversion between paths and URIs is somewhat lossy as long as it will do the right-thing for real users.--Migrating to URIs should not add significant new failure modes. We will need to surface errors in-some places that were previously infallible but it should be kept to a minimum.diff --git a/.codex/skills/remote-tests/SKILL.md b/.codex/skills/remote-tests/SKILL.mddeleted file mode 100644index 9a5fcdff34..0000000000--- a/.codex/skills/remote-tests/SKILL.md+++ /dev/null@@ -1,106 +0,0 @@-----name: remote-tests-description: Testing against remote executors in integration tests.------Remote executor tests exercise the app-server/exec-server split to ensure that agent features work-in both local and remote execution environments.--Remote executor tests currently require an x86_64 Linux host machine. There are two flavors:--1. Docker (Linux exec-server)-2. Wine (Windows exec-server)--## Test Fixtures--Individual test cases must opt-in to being run against a remote executor.--### codex_core--Use `TestCodexBuilder::build_with_auto_env()` to opt-in to remote execution in core integration-tests unless the test needs more precise control over its executor.--### app-server--Start the server with `TestAppServer::new_with_auto_env()` unless the test defines its own-`$CODEX_HOME/environments.toml` or will define custom environments at runtime.--Start threads with `TestAppServer::send_thread_start_request_with_auto_env()` if you've created the-server with the `auto_env` approach. Omit `ThreadStartParams.environments` (leave it as `None`) when-doing so.--## Test Skips--If a test doesn't pass in a particular remote executor configuration you can skip it in just that-configuration. Include a string reason for future readers when the selected skip macro supports-one.--Choose the skip macro by what causes the test to fail:--- `skip_if_target_windows!`: Windows target behavior.-- `skip_if_wine_exec!`: Wine-exec runner constraints.-- `skip_if_host_windows!`: Windows host constraints.-- `skip_if_remote!`: Local-only test behavior.-- `skip_if_no_remote_env!`: Remote-only test behavior.--Prefer defining tests that run in all host/target configurations by default. See the `$path-types`-skill for the most common changes required to make tests compatible.--## Docker--Docker container is built and initialized via ./scripts/test-remote-env.sh. Sourcing this script-in bash also provides the `codex_remote_env_cleanup` function to use after testing.--To run core integration tests against a Docker remote executor:--```bash-bash -c '- set -euo pipefail- unset CODEX_TEST_REMOTE_EXEC_SERVER_URL- source scripts/test-remote-env.sh- trap codex_remote_env_cleanup EXIT-- cd codex-rs- just test -p codex-core --test all-'-```--To run app-server integration tests against a Docker remote executor:--```bash-bash -c '- set -euo pipefail- unset CODEX_TEST_REMOTE_EXEC_SERVER_URL- source scripts/test-remote-env.sh- trap codex_remote_env_cleanup EXIT-- cd codex-rs- just test -p codex-app-server --test all-'-```--## Wine--These tests build an exec-server for Windows and run it under Wine, with the app-server staying on-the Linux host. The cross-platform build dependency means they only run in Bazel.--For core integration tests:--```sh-bazel test //codex-rs/core:core-all-wine-exec-test-```--For app-server integration tests:--```sh-bazel test //codex-rs/app-server:app-server-all-wine-exec-test-```--## Devboxes--You can use a devbox to run these tests if you are running on a macOS machine.--You can list devboxes via `applied_devbox ls`, pick the one with `codex` in the name.-Connect to devbox via `ssh <devbox_name>`.-Reuse the same checkout of codex in `~/code/codex`. Reset files if needed. Multiple checkouts take longer to build and take up more space.-Check whether the SHA and modified files are in sync between remote and local.diff --git a/.codex/skills/test-tui/SKILL.md b/.codex/skills/test-tui/SKILL.mddeleted file mode 100644index e58e67730e..0000000000--- a/.codex/skills/test-tui/SKILL.md+++ /dev/null@@ -1,14 +0,0 @@-----name: test-tui-description: Guide for testing Codex TUI interactively------You can start and use Codex TUI to verify changes.--Important notes:--Start interactively.-Always set RUST_LOG="trace" when starting the process.-Pass `-c log_dir=<some_temp_dir>` argument to have logs written to a specific directory to help with debugging.-When sending a test message programmatically, send text first, then send Enter in a separate write (do not send text + Enter in one burst).-Use `just codex` target to run - `just codex -c ...`diff --git a/.codex/skills/update-v8-version/SKILL.md b/.codex/skills/update-v8-version/SKILL.mddeleted file mode 100644index 512cc0d5a7..0000000000--- a/.codex/skills/update-v8-version/SKILL.md+++ /dev/null@@ -1,72 +0,0 @@-----name: update-v8-version-description: Update Codex's pinned `v8` / `rusty_v8` versions, validate the release-candidate path, and investigate failed V8 canary or artifact builds. Use when asked to bump V8, update `rusty_v8` artifacts, prepare or validate a V8 release candidate, check `v8-canary`, or diagnose why a V8 version update no longer builds.------# Update V8 Version--## Core Workflow--1. Read `third_party/v8/README.md` and follow its version-bump sequence. Treat- that document as the release-process source of truth.-2. Inspect and update the concrete repo surfaces that carry the pin:- - `codex-rs/Cargo.toml`- - `codex-rs/Cargo.lock`- - `MODULE.bazel`- - `third_party/v8/BUILD.bazel`- - `third_party/v8/README.md`- - the matching `third_party/v8/rusty_v8_<version>.sha256` manifest when the- remaining prebuilt inputs change-3. Keep the existing checksum helpers in the loop:-- ```bash- python3 .github/scripts/rusty_v8_bazel.py update-module-bazel- python3 .github/scripts/rusty_v8_bazel.py check-module-bazel- python3 -m unittest discover -s .github/scripts -p test_rusty_v8_bazel.py- ```--4. Validate the release-candidate path before broadening the work:- - Prefer checking the `v8-canary` CI result for the candidate branch or PR- when one exists, using GitHub check tooling or `gh` as appropriate.- - If CI is unavailable or the user asked for a local-only check, run the- closest local validation that is practical for the changed surface and say- explicitly that it is a local substitute, not the full hosted canary.-5. If the canary path passes, stop there. Summarize the result and encourage the- user to commit the candidate changes or proceed with the release flow they- requested. Do not publish tags, releases, or pushes unless the user asked.--## Failure Path--Enter this path only when the canary or local build path fails.--1. Capture the failing target, workflow job, and first actionable error.-2. Compare the currently pinned version with the target version at the relevant- upstream tag or SHA. Inspect both:- - `denoland/rusty_v8`- - upstream V8 source at the target Bazel-pinned version-3. Track build-relevant deltas rather than broad source churn:- - generated binding layout changes- - archive or asset naming changes- - GN/Bazel target changes- - custom libc++ / libc++abi / llvm-libc inputs- - sandbox or pointer-compression feature relationships- - patch hunks in `patches/` that no longer apply or no longer match upstream-4. Trace each failing delta back into Codex's build graph:- - `MODULE.bazel`- - `third_party/v8/BUILD.bazel`- - `.github/scripts/rusty_v8_bazel.py`- - `.github/workflows/v8-canary.yml`- - `.github/workflows/rusty-v8-release.yml`-5. Update only the pieces required to restore the target version's build and- artifact contract. Keep patch explanations and doc changes close to the- affected files.-6. Re-run the focused validation. If it becomes green, return to the normal- workflow and stop with a concise summary plus the remaining release step.--## Reporting--- Say whether validation came from hosted `v8-canary` or from a local- substitute.-- Distinguish "version bump complete" from "release published".-- When blocked, report the upstream delta that matters, the Codex file it hits,- and the next concrete fix to try.diff --git a/.codex/skills/update-v8-version/agents/openai.yaml b/.codex/skills/update-v8-version/agents/openai.yamldeleted file mode 100644index 36e7af80d8..0000000000--- a/.codex/skills/update-v8-version/agents/openai.yaml+++ /dev/null@@ -1,4 +0,0 @@-interface:- display_name: "Update V8 Version"- short_description: "Guide V8 bumps and release validation"- default_prompt: "Use $update-v8-version to update Codex to a new v8 release and validate the release-candidate path."diff --git a/AGENTS.md b/AGENTS.mddeleted file mode 100644index fd0b9ed9e7..0000000000--- a/AGENTS.md+++ /dev/null@@ -1,320 +0,0 @@-# Rust/codex-rs--In the codex-rs folder where the rust code lives:--- Crate names are prefixed with `codex-`. For example, the `core` folder's crate is named `codex-core`-- When using format! and you can inline variables into {}, always do that.-- Install any commands the repo relies on (for example `just`, `rg`, or `cargo-insta`) if they aren't already available before running instructions here.-- Never add or modify any code related to `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` or `CODEX_SANDBOX_ENV_VAR`.- - You operate in a sandbox where `CODEX_SANDBOX_NETWORK_DISABLED=1` will be set whenever you use the `shell` tool. Any existing code that uses `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` was authored with this fact in mind. It is often used to early exit out of tests that the author knew you would not be able to run given your sandbox limitations.- - Similarly, when you spawn a process using Seatbelt (`/usr/bin/sandbox-exec`), `CODEX_SANDBOX=seatbelt` will be set on the child process. Integration tests that want to run Seatbelt themselves cannot be run under Seatbelt, so checks for `CODEX_SANDBOX=seatbelt` are also often used to early exit out of tests, as appropriate.-- Always collapse if statements per https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if-- Always inline format! args when possible per https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args-- Use method references over closures when possible per https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_for_method_calls-- Avoid bool or ambiguous `Option` parameters that force callers to write hard-to-read code such as `foo(false)` or `bar(None)`. Prefer enums, named methods, newtypes, or other idiomatic Rust API shapes when they keep the callsite self-documenting.-- When you cannot make that API change and still need a small positional-literal callsite in Rust, follow the `argument_comment_lint` convention:- - Use an exact `/*param_name*/` comment before opaque literal arguments such as `None`, booleans, and numeric literals when passing them by position.- - A method's sole non-self argument is exempt when the method and parameter names match, such as `.enabled(false)` for `fn enabled(&self, enabled: bool)`.- - Do not add these comments for string or char literals unless the comment adds real clarity; those literals are intentionally exempt from the lint.- - The parameter name in the comment must exactly match the callee signature.- - You can run `just argument-comment-lint` to run the lint check locally. This is powered by Bazel, so running it the first time can be slow if Bazel is not warmed up, though incremental invocations should take <15s. Most of the time, it is best to update the PR and let CI take responsibility for checking this (or run it asynchronously in the background after submitting the PR). Note CI checks all three platforms, which the local run does not.-- When possible, make `match` statements exhaustive and avoid wildcard arms.-- Newly added traits should include doc comments that explain their role and how implementations are expected to use them.-- Discourage both `#[async_trait]` and `#[allow(async_fn_in_trait)]` in Rust traits.- - Prefer native RPITIT trait methods with explicit `Send` bounds on the returned future, as in `3c7f013f9735` / `#16630`.- - Preferred trait shape:- `fn foo(&self, ...) -> impl std::future::Future<Output = T> + Send;`- - Implementations may still use `async fn foo(&self, ...) -> T` when they satisfy that contract.- - Do not use `#[allow(async_fn_in_trait)]` as a shortcut around spelling the future contract explicitly.-- When writing tests, prefer comparing the equality of entire objects over fields one by one.-- Do not add tests for values that are statically defined.-- Do not add negative tests for logic that was removed.-- Do not add general product or user-facing documentation to the `docs/` folder. The official Codex documentation lives elsewhere. The exception is app-server API documentation, which is covered by the app-server guidance below.-- Prefer private modules and explicitly exported public crate API.-- If you change `ConfigToml` or nested config types, run `just write-config-schema` to update `codex-rs/core/config.schema.json`.-- When working with MCP tool calls, prefer using `codex-rs/codex-mcp/src/mcp_connection_manager.rs` to handle mutation of tools and tool calls. Aim to minimize the footprint of changes and leverage existing abstractions rather than plumbing code through multiple levels of function calls.-- Do not call `reset_client_session` unnecessarily; let the incremental check logic decide whether to reuse the previous request.-- If you change Rust dependencies (`Cargo.toml` or `Cargo.lock`), run `just bazel-lock-update` from the- repo root to refresh `MODULE.bazel.lock`, and include that lockfile update in the same change. CI- verifies lockfile drift.-- Bazel does not automatically make source-tree files available to compile-time Rust file access. If- you add `include_str!`, `include_bytes!`, `sqlx::migrate!`, or similar build-time file or- directory reads, update the crate's `BUILD.bazel` (`compile_data`, `build_script_data`, or test- data) or Bazel may fail even when Cargo passes.-- Do not create small helper methods that are referenced only once.-- For tracing async work, instrument the function or method definition with- `#[tracing::instrument(...)]` instead of attaching spans to futures with- `.instrument(...)` at call sites. Before adding instrumentation, check whether the callee—or- the implementation method it immediately delegates to—is already instrumented.-- Avoid large modules:- - Prefer adding new modules instead of growing existing ones.- - Target Rust modules under 500 LoC, excluding tests.- - If a file exceeds roughly 800 LoC, add new functionality in a new module instead of extending- the existing file unless there is a strong documented reason not to.- - This rule applies especially to high-touch files that already attract unrelated changes, such- as `codex-rs/tui/src/app.rs`, `codex-rs/tui/src/bottom_pane/chat_composer.rs`,- `codex-rs/tui/src/bottom_pane/footer.rs`, `codex-rs/tui/src/chatwidget.rs`,- `codex-rs/tui/src/bottom_pane/mod.rs`, and similarly central orchestration modules.- - When extracting code from a large module, move the related tests and module/type docs toward- the new implementation so the invariants stay close to the code that owns them.- - Avoid adding new standalone methods to `codex-rs/tui/src/chatwidget.rs` unless the change is- trivial; prefer new modules/files and keep `chatwidget.rs` focused on orchestration.-- When running Rust commands (e.g. `just fix` or `just test`) be patient with the command and never try to kill them using the PID. Rust lock can make the execution slow, this is expected.--Run `just fmt` (in the `codex-rs` directory) automatically after you have finished making code changes anywhere in this repository; do not ask for approval to run it. Additionally, run the tests:--1. Do not run `cargo test` directly. Use `just test` so test execution follows the repo defaults.-2. Run the test for the specific project that was changed. For example, if changes were made in `codex-rs/tui`, run `just test -p codex-tui`.-3. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `just test`. Avoid `--all-features` for routine local runs because it expands the build matrix and can significantly increase `target/` disk usage; use it only when you specifically need full feature coverage. project-specific or individual tests can be run without asking the user, but do ask the user before running the complete test suite.--Before finalizing a large change to `codex-rs`, run `just fix -p <project>` (in `codex-rs` directory) to fix any linter issues in the code. Prefer scoping with `-p` to avoid slow workspace‑wide Clippy builds; only run `just fix` without `-p` if you changed shared crates. Do not re-run tests after running `fix` or `fmt`.--## The `codex-core` crate--Over time, the `codex-core` crate (defined in `codex-rs/core/`) has become bloated because it is the largest crate, so it is often easier to add something new to `codex-core` rather than refactor out the library code you need so your new code neither takes a dependency on, nor contributes to the size of, `codex-core`.--To that end: **resist adding code to codex-core**!--Particularly when introducing a new concept/feature/API, before adding to `codex-core`, consider whether:--- There is an existing crate other than `codex-core` that is an appropriate place for your new code to live.-- It is time to introduce a new crate to the Cargo workspace for your new functionality. Refactor existing code as necessary to make this happen.--Likewise, when reviewing code, do not hesitate to push back on PRs that would unnecessarily add code to `codex-core`.--## Code Review Rules--### Crate API surface--Keep crate API surfaces as small as possible. Avoid proliferating test-only helpers.--### Model visible context--Codex maintains a context (history of messages) that is sent to the model in inference requests.--1. No history rewrite - the context must be built up incrementally.-2. Avoid frequent changes to context that cause cache misses.-3. No unbounded items - everything injected in the model context must have a bounded size and a hard cap.-4. No items larger than 10K tokens.-5. Highlight new individual items that can cross >1k tokens as P0. These need an additional manual review.-6. All injected fragments must be defined as structs in `core/context` and implement ContextualUserFragment trait--### Breaking changes--Search for breaking changes in external integration surfaces:--- app-server APIs-- raw response item events (`rawResponseItem/*`), even while experimental-- CLI parameters-- configuration loading-- resuming sessions from existing rollouts--### Test authoring guidance--For agent changes prefer integration tests over unit tests. Integration tests are under `core/suite` and use `test_codex` to set up a test instance of codex.--Features that change the agent logic MUST add an integration test:--- Provide a list of major logic changes and user-facing behaviors that need to be tested.--If unit tests are needed, put them in a dedicated test file (\*\_tests.rs).-Avoid test-only functions in the main implementation.--Check whether there are existing helpers to make tests more streamlined and readable.--### Change size guidance (800 lines)--Unless the change is mechanical the total number of changed lines should not exceed 800 lines.-For complex logic changes the size should be under 500 lines.--If the change is larger, explore whether it can be split into reviewable stages and identify the smallest coherent stage to land first.-Base the staging suggestion on the actual diff, dependencies, and affected call sites.--## TUI style conventions--See `codex-rs/tui/styles.md`.--## TUI code conventions--- Use concise styling helpers from ratatui’s Stylize trait.- - Basic spans: use "text".into()- - Styled spans: use "text".red(), "text".green(), "text".magenta(), "text".dim(), etc.- - Prefer these over constructing styles with `Span::styled` and `Style` directly.- - Example: patch summary file lines- - Desired: vec![" └ ".into(), "M".red(), " ".dim(), "tui/src/app.rs".dim()]--### TUI Styling (ratatui)--- Prefer Stylize helpers: use "text".dim(), .bold(), .cyan(), .italic(), .underlined() instead of manual Style where possible.-- Prefer simple conversions: use "text".into() for spans and vec![…].into() for lines; when inference is ambiguous (e.g., Paragraph::new/Cell::from), use Line::from(spans) or Span::from(text).-- Computed styles: if the Style is computed at runtime, using `Span::styled` is OK (`Span::from(text).set_style(style)` is also acceptable).-- Avoid hardcoded white: do not use `.white()`; prefer the default foreground (no color).-- Chaining: combine helpers by chaining for readability (e.g., url.cyan().underlined()).-- Single items: prefer "text".into(); use Line::from(text) or Span::from(text) only when the target type isn’t obvious from context, or when using .into() would require extra type annotations.-- Building lines: use vec![…].into() to construct a Line when the target type is obvious and no extra type annotations are needed; otherwise use Line::from(vec![…]).-- Avoid churn: don’t refactor between equivalent forms (Span::styled ↔ set_style, Line::from ↔ .into()) without a clear readability or functional gain; follow file‑local conventions and do not introduce type annotations solely to satisfy .into().-- Compactness: prefer the form that stays on one line after rustfmt; if only one of Line::from(vec![…]) or vec![…].into() avoids wrapping, choose that. If both wrap, pick the one with fewer wrapped lines.--### Text wrapping--- Always use textwrap::wrap to wrap plain strings.-- If you have a ratatui Line and you want to wrap it, use the helpers in tui/src/wrapping.rs, e.g. word_wrap_lines / word_wrap_line.-- If you need to indent wrapped lines, use the initial_indent / subsequent_indent options from RtOptions if you can, rather than writing custom logic.-- If you have a list of lines and you need to prefix them all with some prefix (optionally different on the first vs subsequent lines), use the `prefix_lines` helper from line_utils.--## Tests--### Test module organization--- When adding a new test module, define its contents in a separate sibling file rather than inline in the implementation file.-- Use an explicit `#[path = "..._tests.rs"]` attribute so the test filename is descriptive and easy to locate:-- ```rust- #[cfg(test)]- #[path = "parser_tests.rs"]- mod tests;- ```--- This applies only when introducing a new test module. Do not move or rewrite existing inline `#[cfg(test)] mod tests { ... }` modules solely to follow this convention.--### Snapshot tests--This repo uses snapshot tests (via `insta`), especially in `codex-rs/tui`, to validate rendered output.--**Requirement:** any change that affects user-visible UI (including adding new UI) must include-corresponding `insta` snapshot coverage (add a new snapshot test if one doesn't exist yet, or-update the existing snapshot). Review and accept snapshot updates as part of the PR so UI impact-is easy to review and future diffs stay visual.--When UI or text output changes intentionally, update the snapshots as follows:--- Run tests to generate any updated snapshots:- - `just test -p codex-tui`-- Check what’s pending:- - `cargo insta pending-snapshots -p codex-tui`-- Review changes by reading the generated `*.snap.new` files directly in the repo, or preview a specific file:- - `cargo insta show -p codex-tui path/to/file.snap.new`-- Only if you intend to accept all new snapshots in this crate, run:- - `cargo insta accept -p codex-tui`--If you don’t have the tool:--- `cargo install --locked cargo-insta`--### Benchmarks--cargo benchmarks can be run with `just bench`, use the divan crate to write new ones.--Use `just bench-smoke` to dry-run the benchmark for a single iteration to ensure it works.--### Test assertions--- Tests should use pretty_assertions::assert_eq for clearer diffs. Import this at the top of the test module if it isn't already.-- Prefer deep equals comparisons whenever possible. Perform `assert_eq!()` on entire objects, rather than individual fields.-- Avoid mutating process environment in tests; prefer passing environment-derived flags or dependencies from above.--### Spawning workspace binaries in tests (Cargo vs Bazel)--- Prefer `codex_utils_cargo_bin::cargo_bin("...")` over `assert_cmd::Command::cargo_bin(...)` or `escargot` when tests need to spawn first-party binaries.- - Under Bazel, binaries and resources may live under runfiles; use `codex_utils_cargo_bin::cargo_bin` to resolve absolute paths that remain stable after `chdir`.-- When locating fixture files or test resources under Bazel, avoid `env!("CARGO_MANIFEST_DIR")`. Prefer `codex_utils_cargo_bin::find_resource!` so paths resolve correctly under both Cargo and Bazel runfiles.--### Integration tests--#### codex_core integration testing--- Prefer the utilities in `core_test_support::responses` when writing end-to-end Codex tests.-- Use `TestCodexBuilder::build_with_auto_env()` by default to ensure that new tests work with- foreign app/exec OSes. See $remote-tests for details.-- All `mount_sse*` helpers return a `ResponseMock`; hold onto it so you can assert against outbound `/responses` POST bodies.-- Use `ResponseMock::single_request()` when a test should only issue one POST, or `ResponseMock::requests()` to inspect every captured `ResponsesRequest`.-- `ResponsesRequest` exposes helpers (`body_json`, `input`, `function_call_output`, `custom_tool_call_output`, `call_output`, `header`, `path`, `query_param`) so assertions can target structured payloads instead of manual JSON digging.-- Build SSE payloads with the provided `ev_*` constructors and the `sse(...)`.-- Prefer `wait_for_event` over `wait_for_event_with_timeout`.-- Prefer `mount_sse_once` over `mount_sse_once_match` or `mount_sse_sequence`--- Typical pattern:-- ```rust- let mock = responses::mount_sse_once(&server, responses::sse(vec![- responses::ev_response_created("resp-1"),- responses::ev_function_call(call_id, "shell", &serde_json::to_string(&args)?),- responses::ev_completed("resp-1"),- ])).await;-- codex.submit(Op::UserTurn { ... }).await?;-- // Assert request body if needed.- let request = mock.single_request();- // assert using request.function_call_output(call_id) or request.json_body() or other helpers.- ```--#### app-server integration testing--- Tests should exercise app-server's public JSON-RPC API.-- Use similar server mocking as for core integration tests.-- Use `TestAppServer::builder().build()` and `TestAppServer::send_thread_start_request_with_auto_env()`- by default to ensure that new tests work with foreign app/exec OSes. See `$remote-tests` for- details.--## App-server API Development Best Practices--These guidelines apply to app-server protocol work in `codex-rs`, especially:--- `app-server-protocol/src/protocol/common.rs`-- `app-server-protocol/src/protocol/v2.rs`--### Core Rules--- All active API development should happen in app-server v2. Do not add new API surface area to v1.-- Follow payload naming consistently:- `*Params` for request payloads, `*Response` for responses, and `*Notification` for notifications.-- Expose RPC methods as `<resource>/<method>` and keep `<resource>` singular (for example, `thread/read`, `app/list`).-- Always expose fields as camelCase on the wire with `#[serde(rename_all = "camelCase")]` unless a tagged union or explicit compatibility requirement needs a targeted rename.-- Always expose string enum values as camelCase on the wire with matching serde and TS `rename_all = "camelCase"` annotations unless an explicit compatibility requirement needs targeted renames.-- Exception: config RPC payloads are expected to use snake_case to mirror config.toml keys (see the config read/write/list APIs in `app-server-protocol/src/protocol/v2.rs`).-- Always set `#[ts(export_to = "v2/")]` on v2 request/response/notification types so generated TypeScript lands in the correct namespace.-- Never use `#[serde(skip_serializing_if = "Option::is_none")]` for v2 API payload fields.- Exception: client->server requests that intentionally have no params may use:- `params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>`.-- Keep Rust and TS wire renames aligned. If a field or variant uses `#[serde(rename = "...")]`, add matching `#[ts(rename = "...")]`.-- For discriminated unions, use explicit tagging in both serializers:- `#[serde(tag = "type", ...)]` and `#[ts(tag = "type", ...)]`.-- Prefer plain `String` IDs at the API boundary (do UUID parsing/conversion internally if needed).-- Timestamps should be integer Unix seconds (`i64`) and named `*_at` (for example, `created_at`, `updated_at`, `resets_at`).-- For experimental API surface area:- use `#[experimental("method/or/field")]`, derive `ExperimentalApi` when field-level gating is needed, and use `inspect_params: true` in `common.rs` when only some fields of a method are experimental.--### Client->server request payloads (`*Params`)--- Every optional field must be annotated with `#[ts(optional = nullable)]`. Do not use `#[ts(optional = nullable)]` outside client->server request payloads (`*Params`).-- Optional collection fields (for example `Vec`, `HashMap`) must use `Option<...>` + `#[ts(optional = nullable)]`. Do not use `#[serde(default)]` to model optional collections, and do not use `skip_serializing_if` on v2 payload fields.-- When you want omission to mean `false` for boolean fields, use `#[serde(default, skip_serializing_if = "std::ops::Not::not")] pub field: bool` over `Option<bool>`.-- For new list methods, implement cursor pagination by default:- request fields `pub cursor: Option<String>` and `pub limit: Option<u32>`,- response fields `pub data: Vec<...>` and `pub next_cursor: Option<String>`.--### Development Workflow--- Regenerate schema fixtures when API shapes change:- `just write-app-server-schema`- (and `just write-app-server-schema --experimental` when experimental API fixtures are affected).-- Validate with `just test -p codex-app-server-protocol`.-- Avoid boilerplate tests that only assert experimental field markers for individual- request fields in `common.rs`; rely on schema generation/tests and behavioral coverage instead.--## Python Development Best Practices--### Ignore Python 2 compatibility--This project uses Python 3+. You should not use the `__future__` module.--If you need to worry about feature compatibility between different 3.xx point releases, check the-closest `pyproject.toml`'s `requires-python` field to see what minimum runtime version is supported.--## Platform Support--Tests and features must support Linux, macOS and Windows unless feature is explicitly OS-specific.--Codex supports running connected app-server and exec-server on different operating systems. See the-`$remote-tests` skill for details about integration testing these configurations.