Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

claude/agent done gate (#745)

Ruben Lütke902deded7ef0
diff --git a/.claude/settings.json b/.claude/settings.json
new file mode 100644
index 0000000000..81fc3dae00
--- /dev/null
+++ b/.claude/settings.json
@@ -0,0 +1,28 @@
+{
+ "$schema": "https://json.schemastore.org/claude-code-settings.json",
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "PY=\"$(command -v python 2>/dev/null || command -v python3 2>/dev/null)\"; [ -n \"$PY\" ] && \"$PY\" \"${CLAUDE_PROJECT_DIR:-.}/scripts/agent_done_gate.py\" --hook claude || true",
+ "timeout": 600,
+ "statusMessage": "Agent done gate: has this work landed?"
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "case \"$CLAUDE_FILE_PATH\" in */docs/*|docs/*) PY=\"$(command -v python 2>/dev/null || command -v python3 2>/dev/null)\"; [ -n \"$PY\" ] && \"$PY\" \"${CLAUDE_PROJECT_DIR:-.}/scripts/ci/docs_privacy_scan.py\" \"$CLAUDE_FILE_PATH\" ;; esac"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/.github/agent-done-gate.json b/.github/agent-done-gate.json
new file mode 100644
index 0000000000..d6b5cbc9a5
--- /dev/null
+++ b/.github/agent-done-gate.json
@@ -0,0 +1,10 @@
+{
+ "base": "main",
+ "required_checks": ["CI gate"],
+ "main_workflows": [".github/workflows/ci.yml"],
+ "ignore_dirty": ["dodaios/ui/web/dist/*", "jarvis/ui/web/dist/*", "wiki/obsidian-vault/*"],
+ "wait_budget_hours": 3.0,
+ "fix_budget_blocks": 8,
+ "hook_wait_seconds": 480,
+ "poll_seconds": 90
+}
diff --git a/.github/workflows/merge-train.yml b/.github/workflows/merge-train.yml
index 479a444f2c..0f8e47d34a 100644
--- a/.github/workflows/merge-train.yml
+++ b/.github/workflows/merge-train.yml
@@ -21,6 +21,17 @@
# head commit its CI tested). A head the queue already failed is held
# until a new push or a train update. Without a queue on main (the
# rollback path) the train squash-merges one green PR per tick instead.
+# 4. Watchdog, for when an agent's session ended before its PR landed:
+# `stuck` (label + one comment per head naming the next step) on a PR
+# green for 30 min but neither queued nor set to auto-merge, red for
+# 60 min with no new commit, or with a conflict the train could not
+# resolve; lifted once it moves. A PR (drafts too) with no commit for
+# 7 days is labelled `stale` and closed after 14 unless labelled `keep`.
+# 5. Merge freeze: while a PR carries a `merge-freeze` label younger than
+# 2 h (scripts/ci/merge_freeze.py), no other PR is enqueued or merged;
+# updates, approvals and reruns go on. An older label is pointed out
+# once on its PR and no longer holds main.
+# A dry run (workflow_dispatch input) only reports all of this.
#
# Trust: three jobs, three privilege levels.
# plan read-only token, no secrets, runs no pull-request code.
@@ -86,6 +97,7 @@ jobs:
pull-requests: read
actions: read
checks: read
+ issues: read # label events: merge-freeze and stale ages
outputs:
updates: ${{ steps.plan.outputs.updates }}
steps:
@@ -193,6 +205,7 @@ jobs:
contents: write
pull-requests: write
actions: write
+ issues: write # the train's labels: stuck, stale, keep, merge-freeze
env:
DRY_RUN: ${{ inputs.dry_run }}
steps:
diff --git a/.gitignore b/.gitignore
index b35b90adca..ec9d9a4791 100644
--- a/.gitignore
+++ b/.gitignore
@@ -201,6 +201,9 @@ Desktop.ini
# and the shared Codex hooks are versioned.
.claude/*
!.claude/skills/
+# The project hooks (the agent done gate and the repo checks) are shared too;
+# personal hooks and permissions belong in .claude/settings.local.json.
+!.claude/settings.json
.codex/*
!.codex/hooks.json
# ...except the security-github skill: RETIRED 2026-08-05. It orchestrated the
diff --git a/.opencode/plugins/agent-done-gate.js b/.opencode/plugins/agent-done-gate.js
new file mode 100644
index 0000000000..b5e2411e0c
--- /dev/null
+++ b/.opencode/plugins/agent-done-gate.js
@@ -0,0 +1,81 @@
+// Agent done gate for OpenCode: an agent stops only when its work has landed.
+//
+// When a session goes idle, ask scripts/agent_done_gate.py whether the
+// session's branch work has landed (PR merged, CI green on main, local main
+// fast-forwarded). If it has not, send the gate's next step back into the
+// session as a new prompt. Any error lets the session rest (fail open).
+// Each decision is logged to ~/.agent-done-gate/opencode.log.
+// See docs/agent-done-gate.md.
+
+import { appendFileSync, mkdirSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+const LOG_DIR = join(homedir(), ".agent-done-gate");
+const running = new Set();
+
+function log(line) {
+ try {
+ mkdirSync(LOG_DIR, { recursive: true });
+ appendFileSync(join(LOG_DIR, "opencode.log"), `${new Date().toISOString()} ${line}\n`);
+ } catch {
+ // logging is best effort
+ }
+}
+
+function pythonCandidates() {
+ return process.platform === "win32" ? ["python", "py"] : ["python3", "python"];
+}
+
+export const AgentDoneGate = async ({ client, $, directory, worktree }) => {
+ const root = worktree || directory;
+ const gate = `${root}/scripts/agent_done_gate.py`;
+
+ async function verdictFor(sessionID) {
+ for (const python of pythonCandidates()) {
+ const result = await $`${python} ${gate} --json --wait 480 --session ${sessionID} --cwd ${directory}`
+ .nothrow()
+ .quiet();
+ const text = result.stdout.toString().trim();
+ if (!text) continue;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ return {
+ event: async ({ event }) => {
+ if (event?.type !== "session.idle") return;
+ const sessionID = event.properties?.sessionID;
+ if (!sessionID || running.has(sessionID)) return;
+ running.add(sessionID);
+ try {
+ // Sub-agent sessions report to their parent; only the root session is gated.
+ const info = await client.session.get({ path: { id: sessionID } }).catch(() => null);
+ if (info?.data?.parentID) return;
+ const verdict = await verdictFor(sessionID);
+ log(`${sessionID} ${directory}: ${verdict ? verdict.verdict : "no answer"}`);
+ if (!verdict || verdict.may_stop !== false) return;
+ // Do not await the reply: the session goes idle again when it is done,
+ // and that idle must be checked, so release the session first.
+ running.delete(sessionID);
+ client.session
+ .prompt({
+ path: { id: sessionID },
+ body: { parts: [{ type: "text", text: verdict.message }] },
+ })
+ .then(() => log(`${sessionID}: the session answered the next step`))
+ .catch((error) => log(`${sessionID}: could not send the next step (${error})`));
+ log(`${sessionID}: sent the next step back into the session`);
+ } catch (error) {
+ log(`${sessionID}: gate skipped (${error})`); // fail open
+ } finally {
+ running.delete(sessionID);
+ }
+ },
+ };
+};
diff --git a/AGENTS.md b/AGENTS.md
index 114c21a184..a01e4ddeaf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,3 +1,7 @@
# All code, comments, logs, and commits must be in **English**.
-# your mind creates the world
\ No newline at end of file
+# your mind creates the world
+
+A standing instruction from the user, the person you are working for. It is about how your turns end. A message with no tool call in it ends your turn, and the work stops there until you are asked to continue. The user has seen you end turns in four ways while work they asked for was still owed, and does not want any of them. One: a long summary of what was done that closes by announcing the next step and has no tool call, so the next thing never starts. Two: an offer to carry on with something unless the user would prefer otherwise, which stops to wait for an answer the user was not going to give. Three: a list of decisions for the user when, by your own account, none of them blocks the rest of the work. Four: deciding that this is a good place to report, because the turn has been long or a milestone is done. Status notes are welcome, and so are your recommendations on open decisions, but put them in the same message as your next tool call and carry on with whatever does not depend on the user's answer. If you notice yourself inviting the user to redirect you or offering to wait, delete it and do the next thing. The stops the user does want are the ones where nothing can move without them, or where the thing blocking you is deliberately protected from you. This does not override the need for confirmation on risky or destructive actions.
+
+You are done when `python scripts/agent_done_gate.py` says DONE; a Stop hook enforces it (docs/agent-done-gate.md).
diff --git a/docs/agent-done-gate.md b/docs/agent-done-gate.md
new file mode 100644
index 0000000000..1d28957dc3
--- /dev/null
+++ b/docs/agent-done-gate.md
@@ -0,0 +1,80 @@
+# Agent done gate
+
+A coding agent ends its turn only when its work has landed. Hooks enforce
+this, not instructions: every coding CLI's Stop event runs
+`scripts/agent_done_gate.py`, and while the answer is WAIT or FIX the agent is
+sent back to work with one imperative next step.
+
+## Done
+
+| # | Condition |
+|---|-----------|
+| D1 | the branch's worktree has no uncommitted changes (generated paths in `ignore_dirty` excepted) |
+| D2 | every local commit of the branch is on the remote |
+| D3 | the branch's pull request is merged into `main` |
+| D4 | the `main_workflows` are green on `main` for the merge commit (or for a later `main` commit that contains it) |
+| D5 | the local `main` checkout contains the merge commit; the gate fast-forwards it, and a checkout with local edits is left alone and noted |
+
+## Verdicts
+
+| Verdict | Meaning | Stop? |
+|---------|---------|-------|
+| DONE | D1–D5 hold | yes |
+| NONE | no branch work in this session | yes |
+| HOLD | draft PR, opt-out label (`wip`, `needs-human`, `do-not-merge`, `no-auto-merge`), or `--hold` | yes |
+| WAIT | CI running, PR queued, merge freeze, main CI running | no |
+| FIX | red checks, conflicts, unpushed commits, auto-merge missing, parked CI run, red main CI for the merge commit | no |
+| STUCK | WAIT longer than `wait_budget_hours` or the same FIX more than `fix_budget_blocks` times | yes, with a report |
+
+The gate fails open: if it cannot check (no `gh`, no network, a bug), the
+session may stop and a note says nothing was verified.
+
+## Which branches
+
+The branch checked out in the hook's `cwd`, plus every branch the session
+created or pushed (`git worktree add -b`, `checkout -b`, `switch -c`, `push`),
+read from the commands in the session transcript. Remembered per session in
+`<git common dir>/agent-done-gate/sessions/`.
+
+## Wiring
+
+| CLI | Where | How it blocks |
+|-----|-------|---------------|
+| Claude Code (also other models run through it) | `.claude/settings.json` Stop hook | `{"decision": "block", "reason": ...}` |
+| Codex | `~/.codex/hooks.json` via `scripts/install_agent_done_gate.py` | same JSON shape; trust the hook once (`/hooks`) |
+| Kimi CLI | `~/.kimi-code/config.toml` via the installer | exit code 2, reason on stderr |
+| OpenCode | `.opencode/plugins/agent-done-gate.js` | on `session.idle`, sends the next step as a prompt |
+
+Codex and Kimi run `~/.agent-done-gate/hook.py`, which finds the session's
+repository and runs that repository's gate; repositories without the gate are
+left alone. Run `python scripts/install_agent_done_gate.py` once per machine
+(`--check`, `--uninstall`). The launcher logs to `~/.agent-done-gate/hook.log`.
+
+While WAIT, the hook itself polls (up to `hook_wait_seconds`) before it answers, so
+an agent does not spin. Agents can also wait explicitly:
+`python scripts/agent_done_gate.py --wait`.
+
+## Commands
+
+```
+python scripts/agent_done_gate.py # verdict, exit 0 = may stop, 3 = continue
+python scripts/agent_done_gate.py --json
+python scripts/agent_done_gate.py --wait # poll while WAIT (up to 9 min)
+python scripts/agent_done_gate.py --hold "the user wants this local"
+python scripts/agent_done_gate.py --release
+```
+
+Use `--hold` only when the user asked not to land a branch.
+
+## Merge freeze
+
+A pull request labelled `merge-freeze` holds `main` still for up to two hours
+(`scripts/ci/merge_freeze.py`): the gate answers WAIT for other PRs,
+`scripts/agent_land.py` requests no auto-merge, and the merge train enqueues
+nothing. An older label no longer counts.
+
+## Configuration
+
+`.github/agent-done-gate.json`: `required_checks`, `main_workflows`,
+`ignore_dirty`, `wait_budget_hours`, `fix_budget_blocks`,
+`hook_wait_seconds`, `poll_seconds`.
diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.md
index 2290db78ed..35aef2f8c2 100644
--- a/docs/ci-pipeline.md
+++ b/docs/ci-pipeline.md
@@ -302,6 +302,40 @@ GitHub adds the pull request to the merge queue itself and the `merge_group`
run starts normally. A pull request opened another way gets the same with
that one command. Drafts and the opt-out labels are left alone.
+**Watchdog.** A coding agent's session can end before its pull request
+lands. Every tick the train also looks for pull requests that stopped moving
+(`scripts/ci/agent_integrate.py`, `watch_verdict` and `stale_sweep`):
+
+- `stuck`: CI green for 30 min but neither in the merge queue nor set to
+ auto-merge; CI red for 60 min with no new commit; or a conflict the train
+ could not resolve (next to `needs-rebase`). The label comes with one
+ comment per head commit that names the next step ("Request auto-merge:
+ `gh pr merge <n> --auto --squash`", "Fix the failing checks: …"); a hidden
+ marker in that comment keeps later ticks quiet. The label goes as soon as
+ the pull request moves (new head, queued, auto-merge requested, or updated
+ by the train). With the merge bot token a green pull request is simply
+ enqueued, so it only gets the label when the queue refuses it.
+- `stale`: an agent pull request, drafts included, with no commit of its own
+ for 7 days (the train's merges of main do not count) gets the label and
+ the comment "No activity for 7 days; this closes in 7 more days unless
+ labelled `keep`." It is closed after 14 days without a commit, and never
+ before the label has been on it for a full week. `keep`, `needs-human`,
+ `merge-freeze` and the opt-out labels exempt a pull request; Dependabot's
+ are never touched. A new commit lifts the label.
+
+**Merge freeze.** A change that rewrites much of the tree (a package move)
+needs main to stand still until it lands. Its author labels it
+`merge-freeze` (`scripts/ci/merge_freeze.py`). While that label is younger
+than 2 h the train enqueues and merges no other pull request; branch updates,
+approvals and reruns go on. An older label no longer holds main, so a dead
+session cannot freeze it for good; the train says so once on that pull
+request.
+
+The train creates its labels (`stuck`, `stale`, `keep`, `merge-freeze`) the
+first time it sets one. A dry run (the workflow's `dry_run` input, or
+`agent_integrate.py train --dry-run`) lists every label, comment and close it
+would make and makes none.
+
**Rollback.** If the queue stalls, disable the "main merge queue" ruleset
(Settings → Rules → Rulesets, or `gh api -X PUT
repos/<owner>/<repo>/rulesets/<id> -f enforcement=disabled`). The train sees
diff --git a/scripts/agent_done_gate.py b/scripts/agent_done_gate.py
new file mode 100644
index 0000000000..abc7bc2f96
--- /dev/null
+++ b/scripts/agent_done_gate.py
@@ -0,0 +1,945 @@
+#!/usr/bin/env python3
+"""Agent done gate: a coding agent may end its turn only when its work has landed.
+
+Every coding CLI's Stop hook calls this script (Claude Code, Codex, Kimi CLI,
+OpenCode; see ``docs/agent-done-gate.md``). It answers with one verdict:
+
+ DONE the work landed: PR merged, CI green on main, local main has it
+ NONE this session has no branch work to land (research, chat)
+ HOLD the PR is a draft / opted out, or the user put the branch on hold
+ WAIT CI is running, the PR is queued, or a merge freeze holds main
+ FIX something only the agent can fix: red checks, conflicts, unpushed
+ commits, missing auto-merge, red CI on main for the merge commit
+ STUCK WAIT or FIX did not move within the budget; stop and report
+
+DONE means all of:
+ D1 no uncommitted tracked changes in the branch's worktree
+ D2 every local commit of the branch is on the remote
+ D3 the branch's pull request is merged into main
+ D4 the main CI workflows are green for the merge commit (or a later main
+ commit that contains it)
+ D5 the local main checkout contains the merge commit (the gate
+ fast-forwards it; a checkout with local edits is left alone and noted)
+
+Which branches belong to a session: the branch checked out in the hook's
+``cwd`` plus every branch the session created or pushed, read from the
+commands in its transcript (sessions often ``cd`` into a worktree while the
+hook still reports the main checkout).
+
+Usage::
+
+ python scripts/agent_done_gate.py # check, human output
+ python scripts/agent_done_gate.py --json
+ python scripts/agent_done_gate.py --wait [SECONDS] # poll while WAIT
+ python scripts/agent_done_gate.py --hold "user wants it local"
+ python scripts/agent_done_gate.py --release
+ python scripts/agent_done_gate.py --hook claude|codex|kimi < hook.json
+
+Exit codes: 0 = may stop, 3 = must continue (WAIT/FIX). A crash of the gate
+itself exits 0 with a warning: a broken gate must never trap a session.
+
+stdlib + ``git`` + ``gh`` only; Windows, macOS and Linux.
+"""
+
+from __future__ import annotations
+
+import argparse
+import fnmatch
+import hashlib
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+from collections.abc import Callable
+from dataclasses import asdict, dataclass, field
+from datetime import UTC, datetime
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from scripts.ci import merge_freeze # noqa: E402
+
+Runner = Callable[[list[str], "Path | None"], subprocess.CompletedProcess]
+
+MAY_STOP = ("DONE", "NONE", "HOLD", "STUCK")
+MUST_CONTINUE = ("WAIT", "FIX")
+EXIT_STOP, EXIT_CONTINUE = 0, 3
+# Worst first: the session's verdict is the worst over its branches.
+SEVERITY = {"FIX": 5, "WAIT": 4, "STUCK": 3, "HOLD": 2, "DONE": 1, "NONE": 0}
+
+OPT_OUT_LABELS = {"no-auto-merge", "do-not-merge", "wip", "needs-human"}
+CONFIG_PATH = ".github/agent-done-gate.json"
+DEFAULT_CONFIG: dict[str, object] = {
+ "base": "main",
+ # Empty = every check / every push workflow counts.
+ "required_checks": [],
+ "main_workflows": [],
+ "wait_budget_hours": 3.0,
+ "fix_budget_blocks": 8,
+ "hook_wait_seconds": 480,
+ "poll_seconds": 90,
+}
+STATE_DIR = "agent-done-gate"
+LAND_HINT = "python scripts/agent_land.py"
+GATE_HINT = "python scripts/agent_done_gate.py"
+
+_FAILED = {"FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "STARTUP_FAILURE", "ACTION_REQUIRED"}
+_PASSED = {"SUCCESS", "NEUTRAL", "SKIPPED"}
+_RUN_ACTIVE = {"queued", "in_progress", "waiting", "pending", "requested"}
+_RUN_OK = {"success", "neutral", "skipped"}
+
+# Commands that create or publish a branch. Matched only inside command
+# strings of the transcript, never inside tool output.
+_BRANCH_PATTERNS = (
+ re.compile(r"worktree\s+add(?:\s+-{1,2}[\w-]+)*?\s+-[bB]\s+([\w./-]+)"),
+ re.compile(r"\b(?:checkout\s+-[bB]|switch\s+-[cC])\s+([\w./-]+)"),
+ re.compile(r"\bpush\b(?:\s+-{1,2}[\w-]+)*\s+[\w.-]+\s+(?:HEAD:)?(?:refs/heads/)?([\w./-]+)"),
+)
+_COMMAND_KEYS = {"command", "cmd", "arguments"}
+
+
+class GateError(Exception):
+ """A fact could not be read; the gate fails open."""
+
+
+# --------------------------------------------------------------------------
+# Plumbing
+# --------------------------------------------------------------------------
+
+
+def default_runner(cmd: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess:
+ try:
+ return subprocess.run( # noqa: S603
+ cmd,
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ timeout=120,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return subprocess.CompletedProcess(cmd, 127, "", str(exc))
+
+
+@dataclass
+class Ctx:
+ cwd: Path
+ run: Runner = default_runner
+ now: Callable[[], float] = time.time
+ config: dict = field(default_factory=lambda: dict(DEFAULT_CONFIG))
+ repo: str = ""
+ common_dir: Path | None = None
+ _freeze: tuple[float, object] | None = None
+
+ def git(self, *args: str, cwd: Path | None = None) -> subprocess.CompletedProcess:
+ return self.run(["git", *args], cwd or self.cwd)
+
+ def git_out(self, *args: str, cwd: Path | None = None) -> str | None:
+ proc = self.git(*args, cwd=cwd)
+ return proc.stdout.strip() if proc.returncode == 0 else None
+
+ def gh_json(self, args: list[str]) -> object:
+ proc = self.run(["gh", *args], self.cwd)
+ if proc.returncode != 0:
+ raise GateError(f"gh {' '.join(args[:3])} failed: {(proc.stderr or '').strip()[:200]}")
+ try:
+ return json.loads(proc.stdout or "null")
+ except ValueError as exc:
+ raise GateError(f"gh {' '.join(args[:3])} returned no JSON") from exc
+
+ def gh_json_soft(self, args: list[str]) -> object:
+ try:
+ return self.gh_json(args)
+ except GateError:
+ return None
+
+ @property
+ def base(self) -> str:
+ return str(self.config.get("base") or "main")
+
+ def freeze(self, exempt: int | None) -> merge_freeze.Freeze | None:
+ """The active merge freeze, cached for ten minutes per gate process."""
+ if self._freeze is None or self.now() - self._freeze[0] > 600:
+ found = merge_freeze.freezes(self.repo, self.gh_json_soft)
+ self._freeze = (self.now(), found)
+ for freeze in self._freeze[1]: # type: ignore[union-attr]
+ if not freeze.expired and freeze.number != exempt:
+ return freeze
+ return None
+
+
+@dataclass
+class Verdict:
+ verdict: str
+ reason: str
+ next: str = ""
+ branch: str = ""
+ pr: int | None = None
+ sha: str = ""
+ checks: dict[str, bool] = field(default_factory=dict)
+ notes: list[str] = field(default_factory=list)
+ # True when the branch needs no more watching (landed, deleted, closed).
+ forget: bool = False
+
+ @property
+ def may_stop(self) -> bool:
+ return self.verdict in MAY_STOP
+
+
+def repo_from_url(url: str) -> str:
+ match = re.search(r"github\.com[:/]+([^/]+)/([^/]+?)(?:\.git)?/?$", url.strip())
+ return f"{match.group(1)}/{match.group(2)}" if match else ""
+
+
+def load_config(root: Path) -> dict:
+ config = dict(DEFAULT_CONFIG)
+ path = root / CONFIG_PATH
+ try:
+ config.update(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError):
+ pass
+ return config
+
+
+def worktrees(ctx: Ctx) -> dict[str, Path]:
+ """branch name -> worktree path, from ``git worktree list --porcelain``."""
+ out = ctx.git_out("worktree", "list", "--porcelain") or ""
+ found: dict[str, Path] = {}
+ path: Path | None = None
+ for line in out.splitlines():
+ if line.startswith("worktree "):
+ path = Path(line[len("worktree ") :])
+ elif line.startswith("branch refs/heads/") and path is not None:
+ found[line[len("branch refs/heads/") :]] = path
+ return found
+
+
+def is_ancestor(ctx: Ctx, older: str, newer: str, cwd: Path | None = None) -> bool:
+ return ctx.git("merge-base", "--is-ancestor", older, newer, cwd=cwd).returncode == 0
+
+
+# --------------------------------------------------------------------------
+# Which branches belong to this session
+# --------------------------------------------------------------------------
+
+
+def _command_strings(node: object, inside: bool = False): # noqa: ANN202
+ if isinstance(node, dict):
+ for key, value in node.items():
+ yield from _command_strings(value, inside or key in _COMMAND_KEYS)
+ elif isinstance(node, list):
+ for value in node:
+ yield from _command_strings(value, inside)
+ elif inside and isinstance(node, str):
+ yield node
+
+
+def branches_in_transcript(text: str) -> list[str]:
+ """Branches the session created or pushed, in order of first mention."""
+ found: list[str] = []
+ for line in text.splitlines():
+ line = line.strip()
+ if not line or not any(word in line for word in ("worktree", "checkout", "switch", "push")):
+ continue
+ try:
+ record = json.loads(line)
+ except ValueError:
+ continue
+ for command in _command_strings(record):
+ for pattern in _BRANCH_PATTERNS:
+ for match in pattern.finditer(command):
+ name = match.group(1).rstrip(".")
+ if name and name not in found:
+ found.append(name)
+ return found
+
+
+# --------------------------------------------------------------------------
+# Session state (budget, remembered branches, holds)
+# --------------------------------------------------------------------------
+
+
+def _state_root(ctx: Ctx) -> Path | None:
+ return ctx.common_dir / STATE_DIR if ctx.common_dir else None
+
+
+def _safe(name: str) -> str:
+ return re.sub(r"[^\w.-]", "_", name)[:120]
+
+
+def load_state(ctx: Ctx, session: str) -> dict:
+ root = _state_root(ctx)
+ if not root or not session:
+ return {}
+ try:
+ return json.loads((root / "sessions" / f"{_safe(session)}.json").read_text("utf-8"))
+ except (OSError, ValueError):
+ return {}
+
+
+def save_state(ctx: Ctx, session: str, state: dict) -> None:
+ root = _state_root(ctx)
+ if not root or not session:
+ return
+ path = root / "sessions" / f"{_safe(session)}.json"
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(state, indent=1), encoding="utf-8")
+ except OSError:
+ pass
+
+
+def hold_path(ctx: Ctx, branch: str) -> Path | None:
+ root = _state_root(ctx)
+ return root / "holds" / f"{_safe(branch)}.json" if root else None
+
+
+def read_hold(ctx: Ctx, branch: str) -> str | None:
+ path = hold_path(ctx, branch)
+ try:
+ return str(json.loads(path.read_text("utf-8")).get("reason") or "on hold") if path else None
+ except (OSError, ValueError):
+ return None
+
+
+# --------------------------------------------------------------------------
+# One branch
+# --------------------------------------------------------------------------
+
+
+def classify_checks(rollup: list[dict], required: list[str]) -> tuple[list[str], list[str], bool]:
+ """(failed names, pending names, every required check present and passed)."""
+ failed: list[str] = []
+ pending: list[str] = []
+ seen: dict[str, str] = {}
+ for check in rollup or []:
+ name = str(check.get("name") or check.get("context") or "?")
+ state = str(check.get("conclusion") or check.get("state") or "").upper()
+ status = str(check.get("status") or "").upper()
+ if status and status != "COMPLETED" and state not in _FAILED | _PASSED:
+ pending.append(name)
+ seen[name] = "pending"
+ elif state in _FAILED:
+ failed.append(name)
+ seen[name] = "failed"
+ elif state in _PASSED:
+ seen[name] = "passed"
+ else:
+ pending.append(name)
+ seen[name] = "pending"
+ if required:
+ green = all(seen.get(name) == "passed" for name in required)
+ else:
+ green = bool(seen) and not failed and not pending
+ return failed, pending, green
+
+
+def own_changes(porcelain: str, ignored: list[str]) -> tuple[list[str], list[str]]:
+ """(tracked, untracked) changed paths from ``git status --porcelain``.
+
+ Build output and runtime folders (``ignore_dirty`` in the config) change
+ on every local build or app run; they are nobody's unfinished work.
+ """
+ tracked: list[str] = []
+ untracked: list[str] = []
+ for line in porcelain.splitlines():
+ if len(line) < 4:
+ continue
+ path = line[3:].split(" -> ")[-1].strip().strip('"')
+ if any(fnmatch.fnmatch(path, glob) for glob in ignored):
+ continue
+ (untracked if line.startswith("??") else tracked).append(path)
+ return tracked, untracked
+
+
+def parked_run(ctx: Ctx, sha: str) -> int | None:
+ data = ctx.gh_json_soft(["api", f"repos/{ctx.repo}/actions/runs?head_sha={sha}&per_page=30"])
+ runs = data.get("workflow_runs", []) if isinstance(data, dict) else []
+ for run in runs:
+ if run.get("conclusion") == "action_required":
+ return int(run.get("id") or 0) or None
+ return None
+
+
+def in_merge_queue(ctx: Ctx, number: int) -> bool:
+ owner, name = ctx.repo.split("/", 1)
+ query = (
+ "query($o:String!,$n:String!,$p:Int!){repository(owner:$o,name:$n)"
+ "{pullRequest(number:$p){mergeQueueEntry{state}}}}"
+ )
+ data = ctx.gh_json_soft(
+ [
+ "api",
+ "graphql",
+ "-f",
+ f"query={query}",
+ "-f",
+ f"o={owner}",
+ "-f",
+ f"n={name}",
+ "-F",
+ f"p={number}",
+ ]
+ )
+ try:
+ return bool(data["data"]["repository"]["pullRequest"]["mergeQueueEntry"]) # type: ignore[index]
+ except (KeyError, TypeError):
+ return False
+
+
+def main_ci_state(ctx: Ctx, sha: str) -> tuple[str, str]:
+ """('success'|'pending'|'failure', detail) for the main workflows at ``sha``.
+
+ A failed or cancelled run for ``sha`` is forgiven when a later main commit
+ that contains ``sha`` has a green run of the same workflow.
+ """
+ workflows = [str(w) for w in ctx.config.get("main_workflows") or []]
+ data = ctx.gh_json(
+ ["api", f"repos/{ctx.repo}/actions/runs?branch={ctx.base}&event=push&per_page=100"]
+ )
+ runs = data.get("workflow_runs", []) if isinstance(data, dict) else []
+ if workflows:
+ runs = [r for r in runs if r.get("path") in workflows or r.get("name") in workflows]
+ by_workflow: dict[str, list[dict]] = {}
+ for run in runs:
+ by_workflow.setdefault(str(run.get("path") or run.get("name")), []).append(run)
+ own = {
+ key: [r for r in group if r.get("head_sha") == sha] for key, group in by_workflow.items()
+ }
+ expected = set(workflows) if workflows else {key for key, group in own.items() if group}
+ if not expected:
+ return "pending", f"no main CI run for {sha[:10]} yet"
+ ctx.git("fetch", "--quiet", "origin", ctx.base)
+ failures: list[str] = []
+ pending: list[str] = []
+ for key in sorted(expected):
+ group = by_workflow.get(key, [])
+ mine = sorted(own.get(key, []), key=lambda r: r.get("created_at") or "", reverse=True)
+ if any(r.get("conclusion") in _RUN_OK for r in mine):
+ continue
+ later_green = [
+ r
+ for r in group
+ if r.get("conclusion") in _RUN_OK
+ and r.get("head_sha") != sha
+ and is_ancestor(ctx, sha, str(r.get("head_sha")))
+ ]
+ if later_green:
+ continue
+ label = (mine[0].get("name") if mine else key) or key
+ if not mine or any(r.get("status") in _RUN_ACTIVE for r in mine):
+ pending.append(str(label))
+ elif mine[0].get("conclusion") in ("cancelled", "skipped", None):
+ pending.append(f"{label} (cancelled; waiting for a later green main run)")
+ else:
+ failures.append(f"{label}: {mine[0].get('html_url', '')}")
+ if failures:
+ return "failure", "; ".join(failures)
+ if pending:
+ return "pending", ", ".join(pending)
+ return "success", ""
+
+
+def sync_local_main(ctx: Ctx, sha: str) -> tuple[bool, str]:
+ """D5: make the local main contain ``sha``. Never stashes, never resets."""
+ base = ctx.base
+ trees = worktrees(ctx)
+ if (
+ f"refs/heads/{base}"
+ and ctx.git_out("rev-parse", "--verify", "--quiet", f"refs/heads/{base}") is None
+ ):
+ return True, f"no local {base} branch"
+ if is_ancestor(ctx, sha, f"refs/heads/{base}"):
+ return True, ""
+ ctx.git("fetch", "--quiet", "origin", base)
+ checkout = trees.get(base)
+ if checkout is None:
+ ctx.git("fetch", "--quiet", "origin", f"{base}:{base}")
+ else:
+ ctx.git("merge", "--ff-only", "--quiet", f"origin/{base}", cwd=checkout)
+ if is_ancestor(ctx, sha, f"refs/heads/{base}"):
+ return True, f"fast-forwarded the local {base}"
+ where = f" at {checkout}" if checkout else ""
+ return False, (
+ f"the local {base} checkout{where} could not be fast-forwarded (local edits or "
+ f"commits of its own); it was left untouched"
+ )
+
+
+def evaluate_branch(ctx: Ctx, branch: str, worktree: Path | None) -> Verdict:
+ base = ctx.base
+ held = read_hold(ctx, branch)
+ if held:
+ return Verdict("HOLD", f"branch {branch} is on hold: {held}", branch=branch)
+ local = ctx.git_out("rev-parse", "--verify", "--quiet", f"refs/heads/{branch}")
+ if local is None:
+ return Verdict(
+ "NONE", f"branch {branch} does not exist locally", branch=branch, forget=True
+ )
+ dirty = ""
+ untracked: list[str] = []
+ if worktree is not None:
+ # Not git_out: stripping would eat the leading status column.
+ proc = ctx.git("status", "--porcelain", cwd=worktree)
+ status = proc.stdout if proc.returncode == 0 else ""
+ ignored = [str(glob) for glob in ctx.config.get("ignore_dirty") or []]
+ tracked, untracked = own_changes(status, ignored)
+ if tracked:
+ # `status` also lists files whose only change is a line ending or
+ # a timestamp; `diff` compares content after normalization.
+ diff = ctx.git("diff", "--name-only", "HEAD", cwd=worktree)
+ if diff.returncode == 0:
+ changed = set(diff.stdout.split("\n"))
+ tracked = [path for path in tracked if path in changed]
+ dirty = "\n".join(tracked)
+ where = f" in {worktree}" if worktree else ""
+ place = str(worktree) if worktree else "its worktree"
+ ahead = int(ctx.git_out("rev-list", "--count", f"origin/{base}..refs/heads/{branch}") or 0)
+ listed = ctx.gh_json(
+ [
+ "pr",
+ "list",
+ "-R",
+ ctx.repo,
+ "--head",
+ branch,
+ "--state",
+ "all",
+ "--limit",
+ "5",
+ "--json",
+ "number,state,isDraft,labels,headRefOid,mergeCommit,mergeStateStatus,"
+ "autoMergeRequest,statusCheckRollup,title,isCrossRepository",
+ ]
+ )
+ # A fork's PR can share the branch name; only this repository's own count.
+ candidates = listed if isinstance(listed, list) else []
+ own = [p for p in candidates if not p.get("isCrossRepository")]
+ prs = sorted(own, key=lambda p: -int(p.get("number", 0)))
+ pr = prs[0] if prs else None
+ checks = {"D1": not dirty}
+ loose = ""
+ if untracked:
+ more = " ..." if len(untracked) > 5 else ""
+ loose = f"untracked files{where} are in no commit: {', '.join(untracked[:5])}{more}"
+
+ if pr is None:
+ if ahead == 0 and not dirty:
+ idle = Verdict("NONE", f"branch {branch} has nothing to land", branch=branch)
+ if loose:
+ idle.notes.append(loose)
+ return idle
+ what = (
+ "uncommitted changes"
+ if ahead == 0
+ else f"{ahead} commit(s) that are in no pull request"
+ )
+ return Verdict(
+ "FIX",
+ f"branch {branch}{where} has {what}",
+ next=f"Commit your own paths and land the branch: run `{LAND_HINT}` in {place}.",
+ branch=branch,
+ checks=checks,
+ )
+
+ number = int(pr["number"])
+ head = str(pr.get("headRefOid") or "")
+ labels = {str(label.get("name")) for label in pr.get("labels") or []}
+ state = str(pr.get("state") or "")
+ verdict = Verdict("WAIT", "", branch=branch, pr=number, checks=checks)
+
+ if dirty:
+ verdict.verdict, verdict.reason = "FIX", f"uncommitted changes{where} (PR #{number})"
+ verdict.next = (
+ f"Commit them and push with `{LAND_HINT}`, or revert them if they are not yours."
+ )
+ return verdict
+
+ # D2: the remote PR head must contain every local commit.
+ pushed = local == head
+ if not pushed and head:
+ if ctx.git("cat-file", "-e", f"{head}^{{commit}}").returncode != 0:
+ ctx.git("fetch", "--quiet", "origin", f"pull/{number}/head")
+ pushed = is_ancestor(ctx, local, head)
+ checks["D2"] = pushed
+
+ if state == "CLOSED":
+ if pushed:
+ return Verdict(
+ "NONE",
+ f"PR #{number} was closed without merging",
+ branch=branch,
+ pr=number,
+ forget=True,
+ )
+ verdict.verdict, verdict.reason = (
+ "FIX",
+ f"PR #{number} is closed and {branch} has newer commits",
+ )
+ verdict.next = f"Land the new commits in a new pull request: run `{LAND_HINT}` in {place}."
+ return verdict
+
+ if not pushed:
+ after = " after it merged" if state == "MERGED" else ""
+ verdict.verdict = "FIX"
+ verdict.reason = f"{branch} has local commits that are not in PR #{number}{after}"
+ verdict.next = f"Push them: run `{LAND_HINT}` in {place}."
+ return verdict
+
+ if state == "OPEN":
+ checks["D3"] = False
+ if pr.get("isDraft") or labels & OPT_OUT_LABELS:
+ why = (
+ "a draft"
+ if pr.get("isDraft")
+ else "labelled " + ", ".join(sorted(labels & OPT_OUT_LABELS))
+ )
+ return Verdict(
+ "HOLD", f"PR #{number} is {why}", branch=branch, pr=number, checks=checks
+ )
+ required = [str(name) for name in ctx.config.get("required_checks") or []]
+ failed, pending, green = classify_checks(pr.get("statusCheckRollup") or [], required)
+ merge_state = str(pr.get("mergeStateStatus") or "")
+ freeze = None if merge_freeze.FREEZE_LABEL in labels else ctx.freeze(exempt=number)
+ if merge_state == "DIRTY":
+ verdict.verdict, verdict.reason = "FIX", f"PR #{number} conflicts with {base}"
+ verdict.next = (
+ f"Run `{LAND_HINT}` in {place}: it rebases onto {base} and "
+ "resolves generated files; resolve the rest yourself."
+ )
+ return verdict
+ if required and any(name in failed for name in required) or (not required and failed):
+ verdict.verdict = "FIX"
+ verdict.reason = f"PR #{number} has failing checks: {', '.join(failed)}"
+ verdict.next = (
+ f"Read the failures (`gh pr checks {number}`), fix them on {branch}, "
+ f"push with `{LAND_HINT}`."
+ )
+ return verdict
+ if not green:
+ if not pending and not failed:
+ run_id = parked_run(ctx, head)
+ if run_id:
+ verdict.verdict = "FIX"
+ verdict.reason = f"the CI run of PR #{number} waits for approval"
+ approve = f"repos/{ctx.repo}/actions/runs/{run_id}/approve"
+ verdict.next = f"Approve it: `gh api -X POST {approve}`."
+ return verdict
+ early = f"; already failed: {', '.join(failed)}" if failed else ""
+ verdict.reason = f"CI is running on PR #{number}{early}"
+ verdict.next = f"Wait for it: `{GATE_HINT} --wait`." + (
+ " You can start fixing the failed jobs now." if failed else ""
+ )
+ return verdict
+ if freeze is not None:
+ verdict.reason = f"PR #{number} is green; {merge_freeze.describe(freeze)}"
+ verdict.next = f"Do not request auto-merge yet. Wait: `{GATE_HINT} --wait`."
+ return verdict
+ if pr.get("autoMergeRequest") is None and not in_merge_queue(ctx, number):
+ verdict.verdict = "FIX"
+ verdict.reason = f"PR #{number} is green but neither queued nor set to auto-merge"
+ verdict.next = f"Request it: `gh pr merge {number} --auto --squash`."
+ return verdict
+ verdict.reason = f"PR #{number} is green and on its way into the merge queue"
+ verdict.next = f"Wait for the merge: `{GATE_HINT} --wait`."
+ return verdict
+
+ # MERGED
+ checks["D3"] = True
+ sha = str((pr.get("mergeCommit") or {}).get("oid") or "")
+ verdict.sha = sha
+ if not sha:
+ verdict.reason = f"PR #{number} merged; its merge commit is not visible yet"
+ verdict.next = f"Wait: `{GATE_HINT} --wait`."
+ return verdict
+ ci, detail = main_ci_state(ctx, sha)
+ checks["D4"] = ci == "success"
+ if ci == "failure":
+ verdict.verdict = "FIX"
+ verdict.reason = (
+ f"CI on {base} is red for the merge commit {sha[:10]} of PR #{number}: {detail}"
+ )
+ verdict.next = (
+ "Find the cause; if it is this change, land a fix (or a revert) in a new pull "
+ f"request from a fresh branch off origin/{base}."
+ )
+ return verdict
+ if ci == "pending":
+ verdict.reason = (
+ f"PR #{number} merged; CI on {base} is still running for {sha[:10]} ({detail})"
+ )
+ verdict.next = f"Wait for it: `{GATE_HINT} --wait`."
+ return verdict
+ ok, note = sync_local_main(ctx, sha)
+ checks["D5"] = ok
+ done = Verdict(
+ "DONE",
+ f"PR #{number} merged, CI on {base} green for {sha[:10]}",
+ branch=branch,
+ pr=number,
+ sha=sha,
+ checks=checks,
+ forget=True,
+ )
+ if note:
+ done.notes.append(note)
+ if loose:
+ done.notes.append(loose)
+ return done
+
+
+# --------------------------------------------------------------------------
+# Session
+# --------------------------------------------------------------------------
+
+
+def session_branches(ctx: Ctx, transcript: Path | None, state: dict) -> list[str]:
+ branches: list[str] = list(state.get("branches") or [])
+ current = ctx.git_out("rev-parse", "--abbrev-ref", "HEAD")
+ if current and current not in ("HEAD", ctx.base) and current not in branches:
+ branches.insert(0, current)
+ if transcript is not None:
+ try:
+ with transcript.open("rb") as handle:
+ offset = int(state.get("scanned", 0) or 0)
+ if offset > transcript.stat().st_size:
+ offset = 0
+ handle.seek(offset)
+ data = handle.read()
+ # Stop at the last full line: a half-written record is read next time.
+ cut = data.rfind(b"\n") + 1
+ text = data[:cut].decode("utf-8", "replace")
+ state["scanned"] = offset + cut
+ except OSError:
+ text = ""
+ for name in branches_in_transcript(text):
+ if name not in branches and name != ctx.base:
+ branches.append(name)
+ state["branches"] = branches
+ return branches
+
+
+def evaluate(ctx: Ctx, transcript: Path | None = None, state: dict | None = None) -> Verdict:
+ state = state if state is not None else {}
+ top = ctx.git_out("rev-parse", "--show-toplevel")
+ if top is None:
+ return Verdict("NONE", f"{ctx.cwd} is not a git repository")
+ common = ctx.git_out("rev-parse", "--path-format=absolute", "--git-common-dir")
+ ctx.common_dir = Path(common) if common else None
+ ctx.config = load_config(Path(top))
+ ctx.repo = repo_from_url(ctx.git_out("remote", "get-url", "origin") or "")
+ branches = session_branches(ctx, transcript, state)
+ if not branches:
+ return Verdict("NONE", "no branch work in this session")
+ if not ctx.repo:
+ return Verdict("NONE", "origin is not a GitHub repository; nothing to check")
+ ctx.git("fetch", "--quiet", "origin", ctx.base)
+ trees = worktrees(ctx)
+ results = [evaluate_branch(ctx, name, trees.get(name)) for name in branches]
+ # Landed, deleted or closed branches are forgotten; an empty new branch is
+ # kept, since its commits may arrive by a push the transcript never shows.
+ state["branches"] = [r.branch for r in results if not r.forget]
+ worst = max(results, key=lambda r: SEVERITY[r.verdict])
+ others = [r for r in results if r is not worst and r.verdict in MUST_CONTINUE]
+ if others:
+ worst.notes.append("also: " + "; ".join(f"{r.verdict} {r.reason}" for r in others))
+ for result in results:
+ if result.verdict == "DONE" and result is not worst:
+ worst.notes.extend(result.notes)
+ return worst
+
+
+def apply_budget(ctx: Ctx, verdict: Verdict, state: dict) -> Verdict:
+ """Turn a WAIT/FIX that does not move into STUCK, so a session can end."""
+ if verdict.verdict not in MUST_CONTINUE:
+ state.pop("budget", None)
+ return verdict
+ now = ctx.now()
+ if verdict.verdict == "WAIT":
+ key = "WAIT"
+ else:
+ key = "FIX:" + hashlib.sha1(verdict.reason.encode("utf-8")).hexdigest()[:12] # noqa: S324
+ budget = state.get("budget") or {}
+ if budget.get("key") != key:
+ budget = {"key": key, "since": now, "blocks": 0}
+ budget["blocks"] = int(budget.get("blocks", 0)) + 1
+ state["budget"] = budget
+ wait_limit = float(ctx.config.get("wait_budget_hours", 3.0)) * 3600
+ fix_limit = int(ctx.config.get("fix_budget_blocks", 8))
+ over = (key == "WAIT" and now - float(budget["since"]) > wait_limit) or (
+ key != "WAIT" and budget["blocks"] > fix_limit
+ )
+ if not over:
+ return verdict
+ stuck = Verdict(
+ "STUCK",
+ f"{verdict.verdict} did not move: {verdict.reason}",
+ next="Stop and tell the user exactly what is blocking and what you tried.",
+ branch=verdict.branch,
+ pr=verdict.pr,
+ sha=verdict.sha,
+ checks=verdict.checks,
+ notes=verdict.notes,
+ )
+ return stuck
+
+
+def message(verdict: Verdict) -> str:
+ lines = [f"Agent done gate: {verdict.verdict}: {verdict.reason}."]
+ if verdict.next:
+ lines.append(verdict.next)
+ lines.extend(f"Note: {note}." for note in verdict.notes)
+ if verdict.verdict in MUST_CONTINUE:
+ lines.append(
+ f"You are done when `{GATE_HINT}` says DONE. Only if the user told you not to land "
+ f'this branch: `{GATE_HINT} --hold "<their words>"`.'
+ )
+ return "\n".join(lines)
+
+
+# --------------------------------------------------------------------------
+# Entry points
+# --------------------------------------------------------------------------
+
+
+def check(
+ ctx: Ctx,
+ *,
+ session: str = "",
+ transcript: Path | None = None,
+ wait_seconds: float = 0,
+ budget: bool = True,
+) -> Verdict:
+ state = {}
+ # The state lives in the git common dir, known only after the first look.
+ probe = ctx.git_out("rev-parse", "--path-format=absolute", "--git-common-dir")
+ ctx.common_dir = Path(probe) if probe else None
+ state = load_state(ctx, session)
+ verdict = evaluate(ctx, transcript, state)
+ deadline = ctx.now() + wait_seconds
+ first_key = (verdict.verdict, verdict.reason)
+ poll = float(ctx.config.get("poll_seconds", 90))
+ while verdict.verdict == "WAIT" and ctx.now() + poll <= deadline:
+ time.sleep(poll)
+ verdict = evaluate(ctx, None, state)
+ if (verdict.verdict, verdict.reason) != first_key:
+ break
+ if budget and session:
+ verdict = apply_budget(ctx, verdict, state)
+ # Read by the desktop app (pane status) without asking GitHub again.
+ state["last"] = {
+ "verdict": verdict.verdict,
+ "reason": verdict.reason,
+ "next": verdict.next,
+ "pr": verdict.pr,
+ "branch": verdict.branch,
+ "cwd": str(ctx.cwd),
+ "at": datetime.now(UTC).isoformat(timespec="seconds"),
+ }
+ save_state(ctx, session, state)
+ return verdict
+
+
+def hook_output(cli: str, verdict: Verdict) -> tuple[str, str, int]:
+ """(stdout, stderr, exit code) in the CLI's own Stop-hook dialect."""
+ text = message(verdict)
+ if cli in ("claude", "codex"):
+ if verdict.verdict in MUST_CONTINUE:
+ return json.dumps({"decision": "block", "reason": text}), "", 0
+ if verdict.verdict in ("DONE", "STUCK", "HOLD") or verdict.notes:
+ return json.dumps({"systemMessage": text}), "", 0
+ return "", "", 0
+ if cli == "kimi":
+ if verdict.verdict in MUST_CONTINUE:
+ return "", text, 2
+ return text if verdict.verdict != "NONE" else "", "", 0
+ raise ValueError(f"unknown hook dialect {cli!r}")
+
+
+def _set_hold(ctx: Ctx, reason: str | None) -> int:
+ branch = ctx.git_out("rev-parse", "--abbrev-ref", "HEAD") or ""
+ common = ctx.git_out("rev-parse", "--path-format=absolute", "--git-common-dir")
+ ctx.common_dir = Path(common) if common else None
+ path = hold_path(ctx, branch)
+ if not branch or branch == "HEAD" or path is None:
+ print("No branch checked out here; nothing to hold.")
+ return 2
+ if reason is None:
+ path.unlink(missing_ok=True)
+ print(f"Released {branch}: the gate checks it again.")
+ return 0
+ path.parent.mkdir(parents=True, exist_ok=True)
+ stamp = datetime.now(UTC).isoformat(timespec="seconds")
+ path.write_text(json.dumps({"reason": reason, "since": stamp}), encoding="utf-8")
+ print(f"{branch} is on hold ({reason}). Tell the user it was not landed.")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--cwd", type=Path, default=None)
+ parser.add_argument("--json", action="store_true")
+ parser.add_argument("--wait", nargs="?", type=float, const=540.0, default=0.0)
+ parser.add_argument("--hook", choices=("claude", "codex", "kimi"))
+ parser.add_argument("--session", default="")
+ parser.add_argument("--transcript", type=Path, default=None)
+ parser.add_argument("--hold", metavar="REASON")
+ parser.add_argument("--release", action="store_true")
+ args = parser.parse_args(argv)
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+
+ payload: dict = {}
+ if args.hook:
+ try:
+ payload = json.loads(sys.stdin.read() or "{}")
+ except ValueError:
+ payload = {}
+ cwd = args.cwd or Path(payload.get("cwd") or os.getcwd())
+ ctx = Ctx(cwd=cwd)
+ if args.hold is not None or args.release:
+ return _set_hold(ctx, None if args.release else args.hold)
+
+ session = args.session or str(payload.get("session_id") or "")
+ transcript = args.transcript or (
+ Path(payload["transcript_path"]) if payload.get("transcript_path") else None
+ )
+ wait = args.wait
+ if args.hook and not wait:
+ wait = float(load_config(cwd).get("hook_wait_seconds", 480))
+ try:
+ verdict = check(
+ ctx,
+ session=session,
+ transcript=transcript,
+ wait_seconds=wait,
+ budget=bool(args.hook or session),
+ )
+ except Exception as exc: # noqa: BLE001 - fail open, always
+ verdict = Verdict("NONE", f"the gate could not check ({type(exc).__name__}: {exc})")
+ verdict.notes.append("gate error; the session may stop, but nothing was verified")
+
+ if args.hook:
+ out, err, code = hook_output(args.hook, verdict)
+ if out:
+ print(out)
+ if err:
+ print(err, file=sys.stderr)
+ return code
+ if args.json:
+ extra = {"may_stop": verdict.may_stop, "message": message(verdict)}
+ print(json.dumps(asdict(verdict) | extra, indent=1))
+ else:
+ print(message(verdict))
+ return EXIT_STOP if verdict.may_stop else EXIT_CONTINUE
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/agent_done_gate_launcher.py b/scripts/agent_done_gate_launcher.py
new file mode 100644
index 0000000000..d8fd93422e
--- /dev/null
+++ b/scripts/agent_done_gate_launcher.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""User-level Stop hook launcher for the agent done gate.
+
+Installed by ``scripts/install_agent_done_gate.py`` into the user's home and
+registered as the Stop hook of CLIs whose hooks live in the user config
+(Codex, Kimi CLI). It finds the git repository of the session's working
+directory and runs that repository's own ``scripts/agent_done_gate.py``.
+A repository without the gate is left alone, so the hook is harmless
+everywhere else.
+
+Usage (from a hook config): ``python <home>/.agent-done-gate/hook.py codex``
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+LOG = Path.home() / ".agent-done-gate" / "hook.log"
+
+
+def log(line: str) -> None:
+ try:
+ LOG.parent.mkdir(parents=True, exist_ok=True)
+ if LOG.exists() and LOG.stat().st_size > 1_000_000:
+ LOG.write_text("", encoding="utf-8")
+ with LOG.open("a", encoding="utf-8") as handle:
+ handle.write(time.strftime("%Y-%m-%dT%H:%M:%S ") + line + "\n")
+ except OSError:
+ pass
+
+
+def main() -> int:
+ dialect = sys.argv[1] if len(sys.argv) > 1 else "codex"
+ raw = sys.stdin.read()
+ try:
+ cwd = str(json.loads(raw or "{}").get("cwd") or os.getcwd())
+ except ValueError:
+ cwd = os.getcwd()
+ cwd = cwd.removeprefix("file:///") if cwd.startswith("file:///") else cwd
+ try:
+ top = subprocess.run(
+ ["git", "-C", cwd, "rev-parse", "--show-toplevel"], # noqa: S607
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return 0
+ if top.returncode != 0:
+ return 0
+ gate = Path(top.stdout.strip()) / "scripts" / "agent_done_gate.py"
+ if not gate.is_file():
+ return 0
+ try:
+ proc = subprocess.run( # noqa: S603
+ [sys.executable, str(gate), "--hook", dialect, "--cwd", cwd],
+ input=raw,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=590,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ log(f"{dialect} {cwd}: gate did not answer ({exc})")
+ return 0
+ log(f"{dialect} {cwd}: exit {proc.returncode} {proc.stdout.strip()[:300]!r}")
+ sys.stdout.write(proc.stdout)
+ sys.stderr.write(proc.stderr)
+ return proc.returncode if proc.returncode in (0, 2) else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/agent_land.py b/scripts/agent_land.py
index b7ea5208ab..b73d5304fa 100644
--- a/scripts/agent_land.py
+++ b/scripts/agent_land.py
@@ -39,7 +39,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
-from scripts.ci import agent_integrate # noqa: E402
+from scripts.ci import agent_integrate, merge_freeze # noqa: E402
from scripts.ci.select_tests import SMOKE # noqa: E402
PY = sys.executable
@@ -86,6 +86,11 @@ def queue_when_green(branch: str, runner=run) -> bool:
if not wants_queue(pull_request):
print("Draft or opted out: not asking GitHub to queue it.")
return False
+ freeze = active_freeze(pull_request, runner)
+ if freeze is not None:
+ print(f"Not requesting auto-merge: {merge_freeze.describe(freeze)}.")
+ print("Run this script again once the freeze is lifted.")
+ return False
asked = runner(["gh", "pr", "merge", branch, "--auto", "--squash"])
if asked.returncode != 0:
print("GitHub did not accept auto-merge; the merge train lands it when green.")
@@ -95,6 +100,32 @@ def queue_when_green(branch: str, runner=run) -> bool:
return True
+def active_freeze(pull_request: dict, runner=run) -> merge_freeze.Freeze | None:
+ """The merge freeze another pull request holds on main, if any (never blocking)."""
+ repo = runner(["gh", "repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])
+ if repo.returncode != 0 or not repo.stdout.strip():
+ return None
+
+ def gh_json(args: list[str]) -> object:
+ out = runner(["gh", *args])
+ try:
+ return json.loads(out.stdout or "null") if out.returncode == 0 else None
+ except ValueError:
+ return None
+
+ number = pull_request.get("number")
+ return merge_freeze.active_freeze(
+ repo.stdout.strip(), gh_json, exempt=int(number) if number else None
+ )
+
+
+def report_gate() -> None:
+ """Print what the agent done gate says now, so the next step is in view."""
+ step("next: the agent done gate")
+ gate = run([PY, "scripts/agent_done_gate.py"])
+ print((gate.stdout + gate.stderr).strip() or "The gate gave no answer.")
+
+
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--remote", default="origin")
@@ -227,12 +258,14 @@ def main(argv: list[str] | None = None) -> int:
if existing.returncode == 0 and existing.stdout.strip():
print(f"PR #{existing.stdout.strip()} updated.")
queue_when_green(branch)
+ report_gate()
return 0
created = run(["gh", "pr", "create", "--fill", "--base", "main", "--label", "auto-merge"])
print(created.stdout + created.stderr)
if created.returncode != 0:
return 7
queue_when_green(branch)
+ report_gate()
return 0
diff --git a/scripts/ci/agent_integrate.py b/scripts/ci/agent_integrate.py
index 9cdbe63304..4f31f6de53 100644
--- a/scripts/ci/agent_integrate.py
+++ b/scripts/ci/agent_integrate.py
@@ -55,9 +55,15 @@ import tempfile
import time
from collections.abc import Callable
from dataclasses import dataclass, field
+from datetime import UTC, datetime
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from scripts.ci import merge_freeze # noqa: E402
+
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
FRONTEND = "dodaios/ui/web/frontend"
@@ -808,6 +814,275 @@ def grant_updates(wanted: list[dict[str, object]], max_updates: int) -> set[int]
return {int(str(entry["number"])) for entry in chosen}
+# ----- watchdog: pull requests whose agent stopped before they landed
+#
+# A coding agent's session can end before its pull request lands. Each tick
+# the train looks for the ones that stopped moving, and says so once:
+#
+# * stuck - green CI but neither queued nor set to auto-merge for
+# GREEN_IDLE_MINUTES; red CI and no new commit for
+# RED_IDLE_MINUTES; or a conflict the train could not resolve.
+# The label goes again as soon as the pull request moves.
+# * stale - no commit for STALE_DAYS (drafts too); closed after CLOSE_DAYS
+# unless labelled `keep`.
+# * a merge freeze (scripts/ci/merge_freeze.py) holds every other pull
+# request out of the queue; an expired one is pointed out once.
+
+STUCK_LABEL = "stuck"
+STALE_LABEL = "stale"
+KEEP_LABEL = "keep"
+GREEN_IDLE_MINUTES = 30.0
+RED_IDLE_MINUTES = 60.0
+STALE_DAYS = 7.0
+CLOSE_DAYS = 14.0
+# The integrate job commits as this author; its merges of main are not the
+# pull request's own activity.
+TRAIN_AUTHOR = "jarvis-merge-train[bot]"
+STALE_EXEMPT = {KEEP_LABEL, "needs-human", merge_freeze.FREEZE_LABEL, *OPT_OUT_LABELS}
+DEPENDABOT_LOGINS = {"dependabot", "dependabot[bot]", "app/dependabot"}
+TRAIN_LABELS: dict[str, tuple[str, str]] = {
+ STUCK_LABEL: ("d93f0b", "The merge train found this pull request not moving"),
+ STALE_LABEL: ("cfd3d7", "No commit for 7 days; the merge train closes it after 14"),
+ KEEP_LABEL: ("0e8a16", "Never closed as stale by the merge train"),
+ merge_freeze.FREEZE_LABEL: ("b60205", "Holds main still for this pull request (2 h at most)"),
+}
+STALE_WARNING = "No activity for 7 days; this closes in 7 more days unless labelled `keep`."
+STALE_MARKER = "<!-- merge-train:stale-warning -->"
+STALE_CLOSING = (
+ "No activity for 14 days, so the merge train closes this pull request. "
+ "Reopen it and push a commit to continue, or label it `keep` before reopening."
+)
+FREEZE_EXPIRED = (
+ "This merge freeze is older than 2 h and no longer holds main. "
+ "Remove the `merge-freeze` label when done, or re-add it to renew."
+)
+
+
+def _now() -> datetime:
+ return datetime.now(UTC)
+
+
+def _try_json(*args: str) -> object:
+ """``gh_json`` that answers ``None`` instead of raising: the watchdog
+ never stops the train."""
+ try:
+ return gh_json(*args)
+ except (subprocess.CalledProcessError, OSError, ValueError):
+ return None
+
+
+def _age(stamp: str | None, now: datetime, unit: float) -> float | None:
+ """Age of an ISO time stamp in ``unit`` seconds; ``None`` when unknown."""
+ when = merge_freeze.parse_time(stamp)
+ return None if when is None else (now - when).total_seconds() / unit
+
+
+def run_finished_at(runs: list[dict]) -> str | None:
+ """When the newest ``pull_request`` CI run of a head finished, or ``None``
+ while it runs (the same run ``run_state`` reads its verdict from)."""
+ pr_runs = [r for r in runs if r.get("event") == "pull_request"]
+ if not pr_runs or any(r.get("status") in _ACTIVE for r in pr_runs):
+ return None
+ latest = max(pr_runs, key=lambda r: r.get("created_at") or "")
+ return latest.get("updated_at") if latest.get("status") == "completed" else None
+
+
+def failing_jobs(repo: str, run_id: int | None, limit: int = 5) -> list[str]:
+ """Names of the failed jobs of a CI run (the first ``limit``)."""
+ if not run_id:
+ return []
+ data = _try_json("api", f"repos/{repo}/actions/runs/{run_id}/jobs?filter=latest&per_page=100")
+ jobs = data.get("jobs", []) if isinstance(data, dict) else []
+ names = [
+ str(job.get("name"))
+ for job in jobs
+ if isinstance(job, dict) and job.get("conclusion") in ("failure", "timed_out")
+ ]
+ # The `CI gate` job only repeats that another one failed.
+ names = [name for name in names if name != "CI gate"] or names
+ return names[:limit] + (["..."] if len(names) > limit else [])
+
+
+def watch_verdict(
+ *,
+ number: int,
+ action: str,
+ state: str,
+ merge_state: str,
+ labels: set[str] | list[str],
+ auto_merge: bool,
+ idle_minutes: float | None,
+ frozen: bool = False,
+ failing: list[str] | None = None,
+) -> dict[str, object] | None:
+ """Why one eligible pull request is stuck, and the one next step; ``None``
+ while it moves. ``idle_minutes``: since its head's CI run finished."""
+ if action == "queued" or auto_merge:
+ return None # GitHub lands it on its own
+ if merge_state == "DIRTY" and "needs-rebase" in labels:
+ # The train already said so with `needs-rebase`; only the label is added.
+ return {
+ "reason": "conflict",
+ "why": "it conflicts with `main` and the merge train could not resolve it",
+ "step": "Merge `main` into this branch and resolve the conflicts: "
+ "`python scripts/agent_land.py --pr`.",
+ "comment": False,
+ }
+ if idle_minutes is None:
+ return None
+ if (
+ state == "success"
+ and merge_state != "DIRTY"
+ and not frozen
+ and idle_minutes >= GREEN_IDLE_MINUTES
+ ):
+ if action == "held":
+ step = (
+ "Push a fix for what failed in the merge queue (or re-add the pull "
+ "request to the queue by hand if it was a flake)."
+ )
+ else:
+ step = f"Request auto-merge: `gh pr merge {number} --auto --squash`."
+ return {
+ "reason": "green-idle",
+ "why": f"its CI has been green for {idle_minutes:.0f} min, but it is neither "
+ "in the merge queue nor set to auto-merge",
+ "step": step,
+ "comment": True,
+ }
+ if state == "failure" and idle_minutes >= RED_IDLE_MINUTES:
+ names = ", ".join(f"`{name}`" for name in failing or [])
+ return {
+ "reason": "red-idle",
+ "why": f"its CI has been red for {idle_minutes:.0f} min with no new commit",
+ "step": f"Fix the failing checks: {names}." if names else "Fix the failing checks.",
+ "comment": True,
+ }
+ return None
+
+
+def stuck_marker(head: str) -> str:
+ return f"<!-- merge-train:stuck:{head} -->"
+
+
+def freeze_marker(freeze: merge_freeze.Freeze) -> str:
+ since = freeze.since.isoformat() if freeze.since else "unknown"
+ return f"<!-- merge-train:freeze-expired:{since} -->"
+
+
+def already_told(repo: str, number: int, marker: str) -> bool:
+ """Whether a train comment carrying ``marker`` is on the pull request.
+ Unknown counts as told: a missed note is cheaper than a repeated one."""
+ data = _try_json("pr", "view", str(number), "--repo", repo, "--json", "comments")
+ if not isinstance(data, dict):
+ return True
+ return any(marker in str(c.get("body") or "") for c in data.get("comments") or [])
+
+
+def _author(pr: dict) -> str:
+ author = pr.get("author") or {}
+ return str(author.get("login") or "") if isinstance(author, dict) else ""
+
+
+def stale_candidate(pr: dict) -> bool:
+ """A pull request the abandoned-PR sweep may look at: an eligible one,
+ drafts included, never Dependabot's."""
+ branch = pr.get("headRefName") or ""
+ if _author(pr) in DEPENDABOT_LOGINS or branch.startswith("dependabot/"):
+ return False
+ if pr.get("baseRefName") != "main" or pr.get("isCrossRepository"):
+ return False
+ labels = {label["name"] for label in pr.get("labels", [])}
+ # The opt-out labels are checked by ``stale_verdict``, which also lifts
+ # `stale` again when one of them is added.
+ return OPT_IN_LABEL in labels or branch.startswith(AGENT_BRANCH_PREFIXES)
+
+
+def stale_verdict(labels: set[str], idle_days: float, labelled_days: float | None) -> str | None:
+ """warn | close | unstale | None for one candidate.
+
+ ``idle_days``: since its last own commit. ``labelled_days``: since the
+ ``stale`` label went on (``None`` when unknown - then it is never closed,
+ so a pull request is always warned a full week before it closes)."""
+ if labels & STALE_EXEMPT or idle_days < STALE_DAYS:
+ return "unstale" if STALE_LABEL in labels else None
+ if STALE_LABEL not in labels:
+ return "warn"
+ if (
+ idle_days >= CLOSE_DAYS
+ and labelled_days is not None
+ and labelled_days >= CLOSE_DAYS - STALE_DAYS
+ ):
+ return "close"
+ return None
+
+
+_ACTIVITY_QUERY = (
+ "query($owner:String!,$name:String!){repository(owner:$owner,name:$name){"
+ "pullRequests(states:OPEN,first:100,orderBy:{field:CREATED_AT,direction:DESC}){nodes{"
+ "number commits(last:20){nodes{commit{committedDate author{name}}}}}}}}"
+)
+
+
+def last_activity(repo: str) -> dict[int, str]:
+ """The newest commit of each open pull request that the train did not
+ make. When the last twenty are all the train's, the oldest of them: the
+ pull request's own last commit is older still, so it is never read as
+ staler than it is."""
+ owner, name = repo.split("/", 1)
+ data = _try_json(
+ "api", "graphql", "-f", f"query={_ACTIVITY_QUERY}", "-f", f"owner={owner}", "-f",
+ f"name={name}",
+ ) # fmt: skip
+ repository = ((data or {}).get("data") or {}).get("repository") or {} # type: ignore[union-attr]
+ nodes = (repository.get("pullRequests") or {}).get("nodes") or []
+ found: dict[int, str] = {}
+ for node in nodes:
+ commits = [
+ (c.get("commit") or {}) for c in ((node or {}).get("commits") or {}).get("nodes") or []
+ ]
+ stamps = [str(c.get("committedDate") or "") for c in commits]
+ own = [
+ str(c.get("committedDate") or "")
+ for c in commits
+ if ((c.get("author") or {}).get("name") or "") != TRAIN_AUTHOR
+ ]
+ if own and max(own):
+ found[int(node["number"])] = max(own)
+ elif any(stamps):
+ found[int(node["number"])] = min(s for s in stamps if s)
+ return found
+
+
+def stale_sweep(repo: str, prs: list[dict], now: datetime) -> list[dict[str, object]]:
+ """One entry per abandoned-PR action (warn, close, unstale). A pull
+ request whose activity cannot be read is left alone."""
+ activity = last_activity(repo)
+ sweep: list[dict[str, object]] = []
+ for pr in prs:
+ if not stale_candidate(pr):
+ continue
+ number = int(pr["number"])
+ labels = {label["name"] for label in pr.get("labels", [])}
+ stamp = activity.get(number)
+ if not stamp:
+ continue
+ # A pull request opened today on old commits is not idle.
+ stamp = max(stamp, str(pr.get("createdAt") or ""))
+ idle_days = _age(stamp, now, 86400)
+ if idle_days is None:
+ continue
+ labelled_days = None
+ if STALE_LABEL in labels and idle_days >= CLOSE_DAYS:
+ events = merge_freeze.issue_events(repo, number, lambda args: _try_json(*args))
+ since = merge_freeze.labelled_at(events, STALE_LABEL)
+ labelled_days = None if since is None else (now - since).total_seconds() / 86400
+ verdict = stale_verdict(labels, idle_days, labelled_days)
+ if verdict:
+ sweep.append({"number": number, "action": verdict, "idle_days": round(idle_days, 1)})
+ return sweep
+
+
# GitHub computes mergeability on demand: the first listing after a push to
# main answers UNKNOWN for every pull request and only starts the computation.
SETTLE_ATTEMPTS = 6
@@ -842,7 +1117,7 @@ def open_pull_requests(
"100",
"--json",
"id,number,title,headRefName,headRefOid,isDraft,labels,baseRefName,"
- "isCrossRepository,mergeable",
+ "isCrossRepository,mergeable,mergeStateStatus,autoMergeRequest,author,createdAt",
)
prs = listing if isinstance(listing, list) else []
computing = sum(1 for pr in prs if eligible(pr) and pr.get("mergeable") == "UNKNOWN")
@@ -853,11 +1128,56 @@ def open_pull_requests(
return prs
-def plan(repo: str, max_updates: int) -> dict[str, object]:
+def freeze_lookup(
+ repo: str, now: datetime
+) -> tuple[Callable[[int], merge_freeze.Freeze | None], list[merge_freeze.Freeze]]:
+ """(the freeze that holds a given pull request back, the expired freezes).
+ One listing per tick, however many pull requests ask."""
+ cache: dict[tuple[str, ...], object] = {}
+
+ def fetch(args: list[str]) -> object:
+ key = tuple(args)
+ if key not in cache:
+ cache[key] = _try_json(*args)
+ return cache[key]
+
+ def held_by(number: int) -> merge_freeze.Freeze | None:
+ return merge_freeze.active_freeze(repo, fetch, now=now, exempt=number)
+
+ expired = [f for f in merge_freeze.freezes(repo, fetch, now=now) if f.expired]
+ return held_by, expired
+
+
+def watch_entry(repo: str, entry: dict) -> dict[str, object] | None:
+ """``watch_verdict`` for a planned entry, plus whether its comment is
+ already on the pull request (``told``) for this head."""
+ idle = entry.get("idle_minutes")
+ failing = None
+ if entry.get("state") == "failure" and idle is not None and idle >= RED_IDLE_MINUTES:
+ failing = failing_jobs(repo, entry.get("run_id")) # type: ignore[arg-type]
+ verdict = watch_verdict(
+ number=int(entry["number"]),
+ action=str(entry["action"]),
+ state=str(entry.get("state") or ""),
+ merge_state=str(entry.get("merge_state") or ""),
+ labels=set(entry.get("labels") or ()),
+ auto_merge=bool(entry.get("auto_merge")),
+ idle_minutes=idle, # type: ignore[arg-type]
+ frozen=bool(entry.get("frozen_by")),
+ failing=failing,
+ )
+ if verdict and verdict["comment"]:
+ verdict["told"] = already_told(repo, int(entry["number"]), stuck_marker(str(entry["head"])))
+ return verdict
+
+
+def plan(repo: str, max_updates: int, now: datetime | None = None) -> dict[str, object]:
"""Decide what the train does this tick. Reads only; runs no PR code."""
+ now = now or _now()
prs = open_pull_requests(repo)
queued = merge_queue_numbers(repo)
queue_runs = queue_runs_by_pr(queue_group_runs(repo)) if queued is not None else {}
+ held_by, expired = freeze_lookup(repo, now)
git("fetch", "--quiet", "origin", "main")
main_sha = git("rev-parse", "origin/main").stdout.strip()
order = sorted(
@@ -882,6 +1202,10 @@ def plan(repo: str, max_updates: int) -> dict[str, object]:
queue_failed=queue_rejected(queue_runs.get(number), runs),
)
note = f"CI {state}, {mergeable or 'unknown'}"
+ freeze = held_by(number)
+ if action == "merge" and freeze:
+ # Updates, approvals and reruns go on; nothing else lands.
+ action, note = "frozen", merge_freeze.describe(freeze)
if action == "merge" and queued is None:
if landing:
action, note = (
@@ -900,13 +1224,30 @@ def plan(repo: str, max_updates: int) -> dict[str, object]:
"note": note,
"state": state,
"labels": sorted(lb["name"] for lb in pr.get("labels", [])),
+ "merge_state": pr.get("mergeStateStatus") or "",
+ "auto_merge": bool(pr.get("autoMergeRequest")),
+ "idle_minutes": _age(run_finished_at(runs), now, 60),
+ "frozen_by": freeze.number if freeze else None,
}
)
granted = grant_updates([e for e in entries if e["action"] == "update"], max_updates)
for entry in entries:
if entry["action"] == "update" and entry["number"] not in granted:
entry["action"], entry["note"] = "wait", "needs an update, waits for a free slot"
- return {"repo": repo, "main": main_sha, "queue": queued is not None, "entries": entries}
+ entry["watch"] = watch_entry(repo, entry)
+ notices = [
+ {"number": f.number, "marker": freeze_marker(f), "age_hours": round(f.age_hours, 1)}
+ for f in expired
+ ]
+ notices = [n for n in notices if not already_told(repo, int(n["number"]), str(n["marker"]))]
+ return {
+ "repo": repo,
+ "main": main_sha,
+ "queue": queued is not None,
+ "entries": entries,
+ "expired_freezes": notices,
+ "stale": stale_sweep(repo, prs, now),
+ }
# ----- integrate: merge -> resolve -> finish, one worktree per pull request
@@ -1195,17 +1536,112 @@ def apply_update(
return f"updated with main ({len(state.get('resolved', []))} conflicts auto-resolved)"
+class _Labels:
+ """Creates the train's labels once per run, the first time one is set
+ (``gh pr edit --add-label`` refuses a label the repository lacks)."""
+
+ def __init__(self, repo: str) -> None:
+ self.repo = repo
+ self.ready = False
+
+ def ensure(self) -> None:
+ if self.ready:
+ return
+ self.ready = True
+ for name, (color, description) in TRAIN_LABELS.items():
+ gh(
+ "label", "create", name, "--repo", self.repo, "--color", color,
+ "--description", description, "--force",
+ ) # fmt: skip
+
+
+def apply_watch(
+ entry: dict, verdict: dict | None, repo: str, dry_run: bool, labels: _Labels
+) -> str | None:
+ """Set or lift the ``stuck`` label for one entry; comment once per head."""
+ number = str(entry["number"])
+ has_label = STUCK_LABEL in (entry.get("labels") or [])
+ if verdict is None:
+ if not has_label:
+ return None
+ if not dry_run:
+ gh("pr", "edit", number, "--repo", repo, "--remove-label", STUCK_LABEL)
+ return f"#{number}: moving again{' (would lift' if dry_run else ' (lifted'} `stuck`)"
+ say = verdict.get("comment") and not verdict.get("told")
+ if dry_run:
+ return f"#{number}: stuck - {verdict['why']}; would label{' and comment' if say else ''}"
+ if not has_label:
+ labels.ensure()
+ gh("pr", "edit", number, "--repo", repo, "--add-label", STUCK_LABEL)
+ if say:
+ body = (
+ f"The merge train found this pull request stuck: {verdict['why']}.\n\n"
+ f"**Next step:** {verdict['step']}\n\n{stuck_marker(str(entry['head']))}"
+ )
+ gh("pr", "comment", number, "--repo", repo, "--body", body)
+ return f"#{number}: stuck - {verdict['why']}. {verdict['step']}"
+
+
+def apply_housekeeping(data: dict, dry_run: bool, labels: _Labels) -> list[str]:
+ """Expired-freeze notices and the abandoned-PR sweep."""
+ repo = data["repo"]
+ lines: list[str] = []
+ for notice in data.get("expired_freezes") or []:
+ number = str(notice["number"])
+ if dry_run:
+ lines.append(f"#{number}: merge freeze expired; would comment")
+ continue
+ body = f"{FREEZE_EXPIRED}\n\n{notice['marker']}"
+ gh("pr", "comment", number, "--repo", repo, "--body", body)
+ lines.append(f"#{number}: merge freeze expired ({notice.get('age_hours')} h); commented")
+ for item in data.get("stale") or []:
+ number, action = str(item["number"]), item["action"]
+ idle = f"no commit for {item.get('idle_days')} days"
+ if dry_run:
+ lines.append(f"#{number}: {idle}; would {action}")
+ continue
+ if action == "warn":
+ labels.ensure()
+ # Label first: if it cannot be set, no comment, so the next tick
+ # does not warn again. The marker guards against a repeat anyway.
+ if gh("pr", "edit", number, "--repo", repo, "--add-label", STALE_LABEL) != 0:
+ lines.append(f"#{number}: {idle}; could not label `stale`")
+ continue
+ if not already_told(repo, int(number), STALE_MARKER):
+ body = f"{STALE_WARNING}\n\n{STALE_MARKER}"
+ gh("pr", "comment", number, "--repo", repo, "--body", body)
+ lines.append(f"#{number}: {idle}; labelled `stale`")
+ elif action == "close":
+ gh("pr", "close", number, "--repo", repo, "--comment", STALE_CLOSING)
+ lines.append(f"#{number}: {idle}; closed")
+ elif action == "unstale":
+ gh("pr", "edit", number, "--repo", repo, "--remove-label", STALE_LABEL)
+ lines.append(f"#{number}: active again; lifted `stale`")
+ return lines
+
+
def apply(root: Path, data: dict, dry_run: bool, token_is_bot: bool) -> int:
repo = data["repo"]
summary: list[str] = []
+ labels = _Labels(repo)
for entry in data.get("entries", []):
number, action, run_id = entry["number"], entry["action"], entry.get("run_id")
+ moved = False # this tick pushed, enqueued or merged it: not stuck
+ verdict = entry.get("watch")
if action == "update":
try:
outcome = apply_update(root, data, entry, dry_run)
except (subprocess.CalledProcessError, OSError) as exc:
outcome = f"update push crashed ({type(exc).__name__}); left for the next tick"
summary.append(f"#{number}: {outcome}")
+ moved = outcome.startswith("updated with main")
+ if outcome.startswith("conflict") and not verdict:
+ verdict = watch_verdict(
+ number=number, action=action, state="", merge_state="DIRTY",
+ labels={"needs-rebase"}, auto_merge=False, idle_minutes=None,
+ ) # fmt: skip
+ elif action == "frozen":
+ summary.append(f"#{number}: green, not enqueued - {entry.get('note', '')}")
elif action == "merge" and data.get("queue") and token_is_bot:
# GitHub starts no merge_group run for an entry GITHUB_TOKEN added:
# it would wait in the queue until the timeout and block the rest.
@@ -1216,29 +1652,31 @@ def apply(root: Path, data: dict, dry_run: bool, token_is_bot: bool) -> int:
elif action == "merge" and data.get("queue"):
if dry_run:
summary.append(f"#{number}: would join the merge queue")
+ moved = True
elif enqueue(entry) == 0:
summary.append(f"#{number}: added to the merge queue")
+ moved = True
else:
summary.append(f"#{number}: merge queue refused it (head moved or not mergeable)")
elif action == "merge":
if dry_run:
summary.append(f"#{number}: would merge")
- continue
- code = gh(
+ moved = True
+ elif gh(
"pr", "merge", str(number), "--repo", repo, "--squash",
"--match-head-commit", entry["head"],
- ) # fmt: skip
- if code == 0:
+ ) == 0: # fmt: skip
summary.append(f"#{number}: merged")
+ moved = True
if token_is_bot:
dispatch_ci("main") # a GITHUB_TOKEN merge fires no push event
else:
summary.append(f"#{number}: merge refused (protection or conflict)")
elif action in ("approve", "rerun"):
if dry_run:
+ code = None
summary.append(f"#{number}: would {action} CI run {run_id}")
- continue
- if action == "approve":
+ elif action == "approve":
code = gh("api", "-X", "POST", f"repos/{repo}/actions/runs/{run_id}/approve")
else:
# Only the failed and cancelled jobs: a whole-run rerun of a
@@ -1246,7 +1684,7 @@ def apply(root: Path, data: dict, dry_run: bool, token_is_bot: bool) -> int:
code = gh("run", "rerun", str(run_id), "--failed", "--repo", repo)
if code == 0:
summary.append(f"#{number}: CI run {run_id} {action}d")
- else:
+ elif code is not None:
summary.append(
f"#{number}: could not {action} CI run {run_id} - approve it in the "
"Actions tab or configure the merge bot app (MERGE_APP_ID)"
@@ -1260,6 +1698,10 @@ def apply(root: Path, data: dict, dry_run: bool, token_is_bot: bool) -> int:
)
else:
summary.append(f"#{number}: waiting ({entry.get('note', '')})")
+ watched = apply_watch(entry, None if moved else verdict, repo, dry_run, labels)
+ if watched:
+ summary.append(watched)
+ summary += apply_housekeeping(data, dry_run, labels)
lines = ["## Merge train", "", *[f"- {line}" for line in summary]]
print("\n".join(lines))
target = os.environ.get("GITHUB_STEP_SUMMARY")
diff --git a/scripts/ci/merge_freeze.py b/scripts/ci/merge_freeze.py
new file mode 100644
index 0000000000..12ac20d096
--- /dev/null
+++ b/scripts/ci/merge_freeze.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Merge freeze: one open pull request may hold main still for a while.
+
+A change that rewrites much of the tree (a package move, a mass rename) needs
+main to stand still until it lands, or every merge in between makes it
+conflict and restarts its CI. Its author puts the label ``merge-freeze`` on
+that pull request. While the label is younger than ``FREEZE_HOURS``:
+
+- ``scripts/agent_done_gate.py`` tells other agents to wait (verdict WAIT);
+- ``scripts/agent_land.py`` does not request auto-merge for other PRs;
+- the merge train does not enqueue other PRs.
+
+An older label no longer counts, so a session that died cannot hold main
+forever; the merge train comments on such a pull request once.
+
+stdlib only. ``gh_json`` is any callable that runs ``gh <args>`` and returns
+the parsed JSON (or ``None`` on failure), so tests pass a fake.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import UTC, datetime
+
+FREEZE_LABEL = "merge-freeze"
+FREEZE_HOURS = 2.0
+
+GhJson = Callable[[list[str]], object]
+
+
+@dataclass(frozen=True)
+class Freeze:
+ number: int
+ title: str
+ since: datetime | None
+ age_hours: float
+ expired: bool
+
+
+def parse_time(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def labelled_at(events: object, label: str = FREEZE_LABEL) -> datetime | None:
+ """When ``label`` was last added, from a ``/issues/<n>/events`` listing."""
+ if not isinstance(events, list):
+ return None
+ stamps = [
+ parse_time(event.get("created_at"))
+ for event in events
+ if isinstance(event, dict)
+ and event.get("event") == "labeled"
+ and (event.get("label") or {}).get("name") == label
+ ]
+ stamps = [stamp for stamp in stamps if stamp is not None]
+ return max(stamps) if stamps else None
+
+
+def issue_events(repo: str, number: int, gh_json: GhJson, *, pages: int = 10) -> list[dict]:
+ """Every event of an issue or pull request, oldest first, across pages.
+
+ One page holds 100 events; a busy pull request has more, and the label
+ event that matters is usually on the last page.
+ """
+ found: list[dict] = []
+ for page in range(1, pages + 1):
+ batch = gh_json(["api", f"repos/{repo}/issues/{number}/events?per_page=100&page={page}"])
+ if not isinstance(batch, list):
+ break
+ found.extend(event for event in batch if isinstance(event, dict))
+ if len(batch) < 100:
+ break
+ return found
+
+
+def freezes(
+ repo: str,
+ gh_json: GhJson,
+ *,
+ now: datetime | None = None,
+ hours: float = FREEZE_HOURS,
+) -> list[Freeze]:
+ """Every open pull request labelled ``merge-freeze``, oldest label first."""
+ now = now or datetime.now(UTC)
+ listed = gh_json(
+ [
+ "pr",
+ "list",
+ "-R",
+ repo,
+ "--state",
+ "open",
+ "--label",
+ FREEZE_LABEL,
+ "--json",
+ "number,title",
+ ]
+ )
+ found: list[Freeze] = []
+ for pr in listed if isinstance(listed, list) else []:
+ number = int(pr.get("number") or 0)
+ if not number:
+ continue
+ since = labelled_at(issue_events(repo, number, gh_json))
+ # Unknown label time counts as expired: a freeze must never hold main forever.
+ age = (now - since).total_seconds() / 3600 if since else hours
+ found.append(Freeze(number, str(pr.get("title") or ""), since, age, age >= hours))
+ return sorted(found, key=lambda freeze: -freeze.age_hours)
+
+
+def active_freeze(
+ repo: str,
+ gh_json: GhJson,
+ *,
+ now: datetime | None = None,
+ hours: float = FREEZE_HOURS,
+ exempt: int | None = None,
+) -> Freeze | None:
+ """The freeze that holds ``exempt`` back right now, if any.
+
+ A pull request that holds a freeze itself is held by none: two freezing
+ pull requests must not lock each other out.
+ """
+ live = [freeze for freeze in freezes(repo, gh_json, now=now, hours=hours) if not freeze.expired]
+ if exempt is not None and any(freeze.number == exempt for freeze in live):
+ return None
+ return live[0] if live else None
+
+
+def describe(freeze: Freeze) -> str:
+ left = max(0.0, FREEZE_HOURS - freeze.age_hours)
+ return (
+ f"merge freeze held by PR #{freeze.number} ({freeze.title}); "
+ f"it lapses in {left * 60:.0f} min at the latest"
+ )
+
+
+def gh_json_cli(args: list[str]) -> object:
+ """Run ``gh`` and parse its JSON output; ``None`` when it fails."""
+ try:
+ out = subprocess.run( # noqa: S603
+ ["gh", *args], # noqa: S607
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ timeout=60,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if out.returncode != 0:
+ return None
+ try:
+ return json.loads(out.stdout or "null")
+ except ValueError:
+ return None
diff --git a/scripts/install_agent_done_gate.py b/scripts/install_agent_done_gate.py
new file mode 100644
index 0000000000..110b91d3a4
--- /dev/null
+++ b/scripts/install_agent_done_gate.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Install the agent done gate's user-level Stop hooks (Codex, Kimi CLI).
+
+Claude Code and OpenCode pick the gate up from the repository itself
+(``.claude/settings.json``, ``.opencode/plugins/agent-done-gate.js``). Codex
+trusts a hook per file path, so a hook in the repository would ask again in
+every new worktree; Kimi CLI reads hooks only from the user config. For those
+two this script copies ``scripts/agent_done_gate_launcher.py`` to
+``~/.agent-done-gate/hook.py`` and registers it as their Stop hook.
+
+ python scripts/install_agent_done_gate.py # install / refresh
+ python scripts/install_agent_done_gate.py --check # report only
+ python scripts/install_agent_done_gate.py --uninstall
+
+Idempotent; it never touches other hooks. Codex asks once to trust the new
+hook (``/hooks`` in the Codex TUI).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+MARKER = ".agent-done-gate"
+
+
+def home() -> Path:
+ return Path(os.environ.get("AGENT_DONE_GATE_HOME") or Path.home())
+
+
+def launcher_path() -> Path:
+ return home() / MARKER / "hook.py"
+
+
+def python_command() -> str:
+ """An interpreter call that works from cmd, PowerShell and sh alike."""
+ if sys.platform == "win32" and shutil.which("py"):
+ return "py -3"
+ exe = sys.executable
+ return f'"{exe}"' if " " in exe else exe
+
+
+def hook_command(dialect: str) -> str:
+ return f'{python_command()} "{launcher_path().as_posix()}" {dialect}'
+
+
+# --------------------------------------------------------------------------
+# Codex: ~/.codex/hooks.json
+# --------------------------------------------------------------------------
+
+
+def codex_file() -> Path:
+ return home() / ".codex" / "hooks.json"
+
+
+def codex_install(data: dict) -> tuple[dict, bool]:
+ hooks = data.setdefault("hooks", {})
+ stop = hooks.setdefault("Stop", [])
+ wanted = {"type": "command", "command": hook_command("codex"), "timeout": 600}
+ for group in stop:
+ for hook in group.get("hooks", []):
+ if MARKER in str(hook.get("command", "")):
+ if hook == wanted:
+ return data, False
+ hook.clear()
+ hook.update(wanted)
+ return data, True
+ stop.append({"hooks": [wanted]})
+ return data, True
+
+
+def codex_uninstall(data: dict) -> tuple[dict, bool]:
+ stop = (data.get("hooks") or {}).get("Stop") or []
+ changed = False
+ for group in stop:
+ before = len(group.get("hooks", []))
+ group["hooks"] = [h for h in group.get("hooks", []) if MARKER not in str(h.get("command"))]
+ changed |= len(group["hooks"]) != before
+ data.get("hooks", {})["Stop"] = [g for g in stop if g.get("hooks")]
+ if not data.get("hooks", {}).get("Stop"):
+ data.get("hooks", {}).pop("Stop", None)
+ return data, changed
+
+
+# --------------------------------------------------------------------------
+# Kimi CLI: ~/.kimi-code/config.toml (older builds: ~/.kimi/config.toml)
+# --------------------------------------------------------------------------
+
+
+def kimi_file() -> Path | None:
+ for folder in (".kimi-code", ".kimi"):
+ path = home() / folder / "config.toml"
+ if path.is_file():
+ return path
+ return None
+
+
+def _toml_string(value: str) -> str:
+ return json.dumps(value) # a JSON string is a valid TOML basic string
+
+
+KIMI_BEGIN = f"# {MARKER} begin: an agent stops only when its work has landed"
+KIMI_END = f"# {MARKER} end"
+
+
+def kimi_block() -> str:
+ return "\n".join(
+ [
+ "",
+ KIMI_BEGIN,
+ "[[hooks]]",
+ 'event = "Stop"',
+ f"command = {_toml_string(hook_command('kimi'))}",
+ "timeout = 600",
+ KIMI_END,
+ "",
+ ]
+ )
+
+
+def kimi_strip(text: str) -> str:
+ """The config without our block (between the begin and end comments)."""
+ pattern = re.compile(rf"\n?{re.escape(KIMI_BEGIN)}\n.*?{re.escape(KIMI_END)}\n?", re.S)
+ return pattern.sub("\n", text).rstrip("\n") + "\n"
+
+
+# --------------------------------------------------------------------------
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--check", action="store_true")
+ parser.add_argument("--uninstall", action="store_true")
+ args = parser.parse_args(argv)
+
+ launcher = launcher_path()
+ source = REPO_ROOT / "scripts" / "agent_done_gate_launcher.py"
+ report: list[str] = []
+
+ if args.uninstall:
+ if launcher.exists() and not args.check:
+ launcher.unlink()
+ report.append(f"launcher removed: {launcher}")
+ elif args.check:
+ same = launcher.is_file() and launcher.read_bytes() == source.read_bytes()
+ report.append(f"launcher {'current' if same else 'missing or stale'}: {launcher}")
+ else:
+ launcher.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source, launcher)
+ report.append(f"launcher installed: {launcher}")
+
+ codex = codex_file()
+ if codex.parent.is_dir():
+ try:
+ data = json.loads(codex.read_text("utf-8")) if codex.is_file() else {}
+ except ValueError:
+ data = None
+ if data is None:
+ report.append(f"codex: {codex} is not valid JSON; left alone")
+ else:
+ change = codex_uninstall if args.uninstall else codex_install
+ data, changed = change(data)
+ if changed and not args.check:
+ codex.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+ state = "would change" if args.check and changed else ("updated" if changed else "ok")
+ report.append(f"codex: {codex} {state}")
+ if changed and not args.uninstall and not args.check:
+ report.append("codex: trust the new Stop hook once (`/hooks` in the Codex TUI)")
+ else:
+ report.append("codex: not installed")
+
+ kimi = kimi_file()
+ if kimi is not None:
+ text = kimi.read_text("utf-8")
+ new = kimi_strip(text) if MARKER in text else text
+ if not args.uninstall:
+ new = new.rstrip("\n") + "\n" + kimi_block()
+ changed = new != text
+ if changed and not args.check:
+ kimi.write_text(new, encoding="utf-8")
+ state = "would change" if args.check and changed else ("updated" if changed else "ok")
+ report.append(f"kimi: {kimi} {state}")
+ else:
+ report.append("kimi: not installed")
+
+ print("\n".join(report))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/unit/ci/test_agent_done_gate.py b/tests/unit/ci/test_agent_done_gate.py
new file mode 100644
index 0000000000..2c3e3d7030
--- /dev/null
+++ b/tests/unit/ci/test_agent_done_gate.py
@@ -0,0 +1,611 @@
+"""`scripts/agent_done_gate.py`: an agent may stop only when its work has landed."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from scripts import agent_done_gate as gate
+from scripts.ci import merge_freeze
+
+REPO = "acme/widget"
+MAIN_SHA = "m" * 40
+MERGE_SHA = "s" * 40
+HEAD_SHA = "h" * 40
+
+
+class FakeWorld:
+ """Answers the git and gh commands the gate runs, from plain fields."""
+
+ def __init__(self, tmp: Path) -> None:
+ self.top = tmp / "repo"
+ self.common = tmp / "repo" / ".git"
+ self.common.mkdir(parents=True, exist_ok=True)
+ self.current = "main"
+ self.trees: dict[str, Path] = {"main": self.top}
+ self.local: dict[str, str] = {"main": MAIN_SHA}
+ self.ahead: dict[str, int] = {}
+ self.status: dict[Path, str] = {}
+ self.eol_only: set[str] = set()
+ self.prs: dict[str, list[dict]] = {}
+ self.ancestors: set[tuple[str, str]] = set()
+ self.main_runs: list[dict] = []
+ self.freeze_prs: list[dict] = []
+ self.freeze_events: dict[int, list[dict]] = {}
+ self.parked: list[dict] = []
+ self.queued: set[int] = set()
+ self.ff_works = True
+ self.is_repo = True
+ self.commands: list[list[str]] = []
+
+ def ok(self, cmd: list[str], out: object = "") -> subprocess.CompletedProcess:
+ text = out if isinstance(out, str) else json.dumps(out)
+ return subprocess.CompletedProcess(cmd, 0, text, "")
+
+ def fail(self, cmd: list[str]) -> subprocess.CompletedProcess:
+ return subprocess.CompletedProcess(cmd, 1, "", "no")
+
+ def __call__(self, cmd: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess:
+ self.commands.append(cmd)
+ if cmd[0] == "git":
+ return self.git(cmd, cmd[1:], cwd)
+ return self.gh(cmd, cmd[1:])
+
+ def git(self, cmd: list[str], args: list[str], cwd: Path | None) -> subprocess.CompletedProcess:
+ if not self.is_repo:
+ return self.fail(cmd)
+ if args[:2] == ["rev-parse", "--show-toplevel"]:
+ return self.ok(cmd, str(self.top))
+ if args[:3] == ["rev-parse", "--path-format=absolute", "--git-common-dir"]:
+ return self.ok(cmd, str(self.common))
+ if args[:2] == ["rev-parse", "--abbrev-ref"]:
+ return self.ok(cmd, self.current)
+ if args[:3] == ["rev-parse", "--verify", "--quiet"]:
+ name = args[3].removeprefix("refs/heads/")
+ return self.ok(cmd, self.local[name]) if name in self.local else self.fail(cmd)
+ if args[:2] == ["remote", "get-url"]:
+ return self.ok(cmd, f"https://github.com/{REPO}.git")
+ if args[:3] == ["worktree", "list", "--porcelain"]:
+ lines = []
+ for branch, path in self.trees.items():
+ lines += [f"worktree {path}", "HEAD x", f"branch refs/heads/{branch}", ""]
+ return self.ok(cmd, "\n".join(lines))
+ if args[:2] == ["status", "--porcelain"]:
+ return self.ok(cmd, self.status.get(cwd, ""))
+ if args[:3] == ["diff", "--name-only", "HEAD"]:
+ lines = self.status.get(cwd, "").splitlines()
+ paths = [line[3:] for line in lines if not line.startswith("??")]
+ return self.ok(cmd, "\n".join(p for p in paths if p not in self.eol_only))
+ if args[:2] == ["rev-list", "--count"]:
+ name = args[2].split("refs/heads/")[-1]
+ return self.ok(cmd, str(self.ahead.get(name, 0)))
+ if args[:2] == ["merge-base", "--is-ancestor"]:
+ older, newer = args[2], args[3]
+ if older == newer or (older, newer) in self.ancestors:
+ return self.ok(cmd)
+ return self.fail(cmd)
+ if args[:2] == ["merge", "--ff-only"]:
+ if self.ff_works:
+ self.ancestors.add((MERGE_SHA, "refs/heads/main"))
+ return self.ok(cmd)
+ return self.fail(cmd)
+ if args[:2] == ["cat-file", "-e"]:
+ return self.ok(cmd)
+ if args[0] == "fetch":
+ return self.ok(cmd)
+ raise AssertionError(f"unexpected git {args}")
+
+ def gh(self, cmd: list[str], args: list[str]) -> subprocess.CompletedProcess:
+ if args[:2] == ["pr", "list"] and "--head" in args:
+ return self.ok(cmd, self.prs.get(args[args.index("--head") + 1], []))
+ if args[:2] == ["pr", "list"] and "--label" in args:
+ return self.ok(cmd, self.freeze_prs)
+ if args[0] == "api" and args[1].startswith(f"repos/{REPO}/issues/"):
+ number = int(args[1].split("/")[4])
+ return self.ok(cmd, self.freeze_events.get(number, []))
+ if args[0] == "api" and "actions/runs?branch=" in args[1]:
+ return self.ok(cmd, {"workflow_runs": self.main_runs})
+ if args[0] == "api" and "actions/runs?head_sha=" in args[1]:
+ return self.ok(cmd, {"workflow_runs": self.parked})
+ if args[:2] == ["api", "graphql"]:
+ number = int(next(a for a in args if a.startswith("p=")).split("=")[1])
+ entry = {"state": "QUEUED"} if number in self.queued else None
+ return self.ok(
+ cmd, {"data": {"repository": {"pullRequest": {"mergeQueueEntry": entry}}}}
+ )
+ raise AssertionError(f"unexpected gh {args}")
+
+ # helpers -----------------------------------------------------------
+ def branch(self, name: str, *, ahead: int = 1, sha: str = HEAD_SHA) -> Path:
+ path = self.top.parent / name.replace("/", "-")
+ self.trees[name] = path
+ self.local[name] = sha
+ self.ahead[name] = ahead
+ return path
+
+ def pr(self, branch: str, **fields: object) -> dict:
+ pr = {
+ "number": 7,
+ "state": "OPEN",
+ "isDraft": False,
+ "labels": [],
+ "headRefOid": HEAD_SHA,
+ "mergeCommit": None,
+ "mergeStateStatus": "CLEAN",
+ "autoMergeRequest": None,
+ "statusCheckRollup": [],
+ "title": "feat: x",
+ }
+ pr.update(fields)
+ self.prs[branch] = [pr]
+ return pr
+
+
+def gate_ci(conclusion: str | None, status: str = "COMPLETED") -> dict:
+ return {"name": "CI gate", "status": status, "conclusion": conclusion}
+
+
+def main_run(sha: str, conclusion: str | None, status: str = "completed") -> dict:
+ return {
+ "path": ".github/workflows/ci.yml",
+ "name": "CI",
+ "head_sha": sha,
+ "status": status,
+ "conclusion": conclusion,
+ "created_at": "2026-10-19T10:00:00Z",
+ "html_url": "https://example.invalid/run",
+ }
+
+
+def world(tmp_path: Path) -> FakeWorld:
+ world = FakeWorld(tmp_path)
+ (world.top / ".github").mkdir(parents=True, exist_ok=True)
+ (world.top / gate.CONFIG_PATH).write_text(
+ json.dumps(
+ {
+ "required_checks": ["CI gate"],
+ "main_workflows": [".github/workflows/ci.yml"],
+ "ignore_dirty": ["app/dist/*"],
+ }
+ ),
+ encoding="utf-8",
+ )
+ return world
+
+
+def run_gate(world: FakeWorld, branches: list[str] | None = None) -> gate.Verdict:
+ ctx = gate.Ctx(cwd=world.top, run=world)
+ return gate.evaluate(ctx, None, {"branches": branches or []})
+
+
+# --------------------------------------------------------------------------
+# NONE / HOLD
+# --------------------------------------------------------------------------
+
+
+def test_outside_a_repository_the_session_may_stop(world: FakeWorld) -> None:
+ world.is_repo = False
+ assert run_gate(world).verdict == "NONE"
+
+
+def test_a_session_on_main_with_no_branch_work_stops_at_once_without_asking_github(
+ world: FakeWorld,
+) -> None:
+ verdict = run_gate(world)
+ assert verdict.verdict == "NONE"
+ assert not any(cmd[0] == "gh" for cmd in world.commands)
+
+
+def test_a_branch_with_nothing_on_it_needs_no_landing(world: FakeWorld) -> None:
+ world.branch("claude/idea", ahead=0)
+ assert run_gate(world, ["claude/idea"]).verdict == "NONE"
+
+
+def test_a_draft_or_an_opted_out_pull_request_is_a_hold(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", isDraft=True)
+ assert run_gate(world, ["claude/x"]).verdict == "HOLD"
+ world.pr("claude/x", labels=[{"name": "needs-human"}])
+ assert run_gate(world, ["claude/x"]).verdict == "HOLD"
+
+
+def test_a_branch_the_user_put_on_hold_is_not_checked(world: FakeWorld) -> None:
+ world.branch("claude/x", ahead=3)
+ ctx = gate.Ctx(cwd=world.top, run=world)
+ ctx.common_dir = world.common
+ path = gate.hold_path(ctx, "claude/x")
+ path.parent.mkdir(parents=True)
+ path.write_text(json.dumps({"reason": "keep it local"}), encoding="utf-8")
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "HOLD"
+ assert "keep it local" in verdict.reason
+
+
+# --------------------------------------------------------------------------
+# FIX
+# --------------------------------------------------------------------------
+
+
+def test_commits_in_no_pull_request_must_be_landed(world: FakeWorld) -> None:
+ world.branch("claude/x", ahead=2)
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert "agent_land.py" in verdict.next
+
+
+def test_uncommitted_work_blocks_but_generated_files_do_not(world: FakeWorld) -> None:
+ path = world.branch("claude/x")
+ world.pr("claude/x", statusCheckRollup=[gate_ci(None, "IN_PROGRESS")])
+ world.status[path] = " M app/dist/bundle.js\n?? app/dist/new.css\n"
+ assert run_gate(world, ["claude/x"]).verdict == "WAIT"
+ world.status[path] = " M app/dist/bundle.js\n M src/feature.py\n"
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert verdict.checks["D1"] is False
+
+
+def test_red_required_checks_are_named(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr(
+ "claude/x",
+ statusCheckRollup=[
+ {"name": "tests-linux (6)", "status": "COMPLETED", "conclusion": "FAILURE"},
+ gate_ci("FAILURE"),
+ ],
+ )
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert "tests-linux (6)" in verdict.reason
+ assert "gh pr checks 7" in verdict.next
+
+
+def test_a_conflicting_pull_request_must_be_rebased(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", mergeStateStatus="DIRTY")
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert "conflicts" in verdict.reason
+
+
+def test_a_green_pull_request_without_auto_merge_must_request_it(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", statusCheckRollup=[gate_ci("SUCCESS")])
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert "gh pr merge 7 --auto --squash" in verdict.next
+
+
+def test_unpushed_local_commits_must_be_pushed(world: FakeWorld) -> None:
+ world.branch("claude/x", sha="l" * 40)
+ world.pr("claude/x", statusCheckRollup=[gate_ci("SUCCESS")])
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert verdict.checks["D2"] is False
+
+
+def test_a_parked_ci_run_must_be_approved(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x")
+ world.parked = [{"id": 99, "conclusion": "action_required"}]
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert "actions/runs/99/approve" in verdict.next
+
+
+def test_red_ci_on_main_for_the_merge_commit_is_the_agents_to_fix(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "failure")]
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "FIX"
+ assert verdict.checks["D3"] is True and verdict.checks["D4"] is False
+
+
+# --------------------------------------------------------------------------
+# WAIT
+# --------------------------------------------------------------------------
+
+
+def test_running_ci_means_wait_and_names_early_failures(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr(
+ "claude/x",
+ statusCheckRollup=[
+ {"name": "tests-windows (2)", "status": "COMPLETED", "conclusion": "FAILURE"},
+ {"name": "tests-linux (1)", "status": "IN_PROGRESS", "conclusion": None},
+ ],
+ )
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "WAIT"
+ assert "tests-windows (2)" in verdict.reason
+ assert "--wait" in verdict.next
+
+
+def test_a_queued_pull_request_waits(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", statusCheckRollup=[gate_ci("SUCCESS")])
+ world.queued.add(7)
+ assert run_gate(world, ["claude/x"]).verdict == "WAIT"
+
+
+def test_a_merge_freeze_by_another_pull_request_means_wait(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", statusCheckRollup=[gate_ci("SUCCESS")])
+ world.freeze_prs = [{"number": 733, "title": "package move"}]
+ world.freeze_events = {
+ 733: [
+ {
+ "event": "labeled",
+ "label": {"name": merge_freeze.FREEZE_LABEL},
+ "created_at": "2999-01-01T00:00:00Z",
+ }
+ ]
+ }
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "WAIT"
+ assert "#733" in verdict.reason
+ assert "Do not request auto-merge" in verdict.next
+
+
+def test_an_expired_freeze_no_longer_holds_main() -> None:
+ def gh_json(args: list[str]) -> object:
+ if args[:2] == ["pr", "list"]:
+ return [{"number": 733, "title": "move"}]
+ stamp = "2026-10-19T10:00:00Z"
+ return [{"event": "labeled", "label": {"name": "merge-freeze"}, "created_at": stamp}]
+
+ now = merge_freeze.parse_time("2026-10-19T13:00:00Z")
+ assert merge_freeze.active_freeze(REPO, gh_json, now=now) is None
+ early = merge_freeze.parse_time("2026-10-19T11:00:00Z")
+ assert merge_freeze.active_freeze(REPO, gh_json, now=early).number == 733
+ assert merge_freeze.active_freeze(REPO, gh_json, now=early, exempt=733) is None
+
+
+def test_merged_but_main_ci_still_running_waits(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, None, "in_progress")]
+ assert run_gate(world, ["claude/x"]).verdict == "WAIT"
+ world.main_runs = []
+ assert run_gate(world, ["claude/x"]).verdict == "WAIT"
+
+
+# --------------------------------------------------------------------------
+# DONE
+# --------------------------------------------------------------------------
+
+
+def test_merged_green_on_main_and_local_main_fast_forwarded_is_done(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "DONE"
+ assert verdict.checks == {"D1": True, "D2": True, "D3": True, "D4": True, "D5": True}
+ assert ["git", "merge", "--ff-only", "--quiet", "origin/main"] in world.commands
+
+
+def test_a_cancelled_main_run_is_forgiven_by_a_later_green_run(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ later = "n" * 40
+ world.main_runs = [main_run(MERGE_SHA, "cancelled"), main_run(later, "success")]
+ world.ancestors.add((MERGE_SHA, later))
+ assert run_gate(world, ["claude/x"]).verdict == "DONE"
+
+
+def test_a_local_main_with_edits_is_left_alone_and_noted(world: FakeWorld) -> None:
+ world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ world.ff_works = False
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "DONE"
+ assert verdict.checks["D5"] is False
+ assert "left untouched" in verdict.notes[0]
+
+
+def test_the_worst_branch_decides_for_the_session(world: FakeWorld) -> None:
+ world.branch("claude/a")
+ world.pr("claude/a", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ world.branch("claude/b", ahead=1)
+ verdict = run_gate(world, ["claude/a", "claude/b"])
+ assert verdict.verdict == "FIX"
+ assert verdict.branch == "claude/b"
+
+
+# --------------------------------------------------------------------------
+# Budget, transcript, hook dialects, fail-open
+# --------------------------------------------------------------------------
+
+
+def test_a_fix_that_does_not_move_becomes_stuck(world: FakeWorld) -> None:
+ clock = [1000.0]
+ ctx = gate.Ctx(cwd=world.top, run=world, now=lambda: clock[0])
+ state: dict = {}
+ fix = gate.Verdict("FIX", "same red check")
+ results = [gate.apply_budget(ctx, fix, state).verdict for _ in range(9)]
+ assert results[:8] == ["FIX"] * 8
+ assert results[8] == "STUCK"
+
+
+def test_a_wait_longer_than_the_budget_becomes_stuck(world: FakeWorld) -> None:
+ clock = [0.0]
+ ctx = gate.Ctx(cwd=world.top, run=world, now=lambda: clock[0])
+ state: dict = {}
+ assert gate.apply_budget(ctx, gate.Verdict("WAIT", "ci 1"), state).verdict == "WAIT"
+ clock[0] = 2 * 3600
+ assert gate.apply_budget(ctx, gate.Verdict("WAIT", "ci 2"), state).verdict == "WAIT"
+ clock[0] = 3 * 3600 + 1
+ assert gate.apply_budget(ctx, gate.Verdict("WAIT", "queue"), state).verdict == "STUCK"
+ assert gate.apply_budget(ctx, gate.Verdict("DONE", "ok"), state).verdict == "DONE"
+ assert "budget" not in state
+
+
+def test_branches_come_from_commands_never_from_tool_output() -> None:
+ lines = [
+ {
+ "type": "tool_use",
+ "input": {"command": "git worktree add -q -b claude/one ../one origin/main"},
+ },
+ {"type": "tool_result", "content": "hint: git checkout -b someone-else"},
+ {
+ "payload": {
+ "item": {
+ "type": "CommandExecution",
+ "command": ["pwsh", "-c", "git switch -c codex/two"],
+ }
+ }
+ },
+ {
+ "type": "tool_use",
+ "input": {"command": "git push -u origin HEAD:refs/heads/claude/three"},
+ },
+ {"type": "tool_use", "input": {"command": "git worktree add -b <agent>/<topic> <path>"}},
+ ]
+ text = "\n".join(json.dumps(line) for line in lines)
+ assert gate.branches_in_transcript(text) == ["claude/one", "codex/two", "claude/three"]
+
+
+ ("cli", "verdict", "expected_code", "blocks"),
+ [
+ ("claude", "FIX", 0, True),
+ ("codex", "WAIT", 0, True),
+ ("claude", "DONE", 0, False),
+ ("kimi", "FIX", 2, True),
+ ("kimi", "NONE", 0, False),
+ ],
+)
+def test_hook_dialects(cli: str, verdict: str, expected_code: int, blocks: bool) -> None:
+ out, err, code = gate.hook_output(cli, gate.Verdict(verdict, "why", next="do this"))
+ assert code == expected_code
+ if cli in ("claude", "codex"):
+ decoded = json.loads(out) if out else {}
+ assert (decoded.get("decision") == "block") is blocks
+ if blocks:
+ assert "do this" in decoded["reason"]
+ else:
+ assert bool(err) is blocks
+
+
+def test_a_crashing_gate_lets_the_session_stop(monkeypatch: pytest.MonkeyPatch, capsys) -> None:
+ def boom(*_: object, **__: object) -> None:
+ raise RuntimeError("gh exploded")
+
+ monkeypatch.setattr(gate, "check", boom)
+ monkeypatch.setattr("sys.stdin", __import__("io").StringIO(json.dumps({"cwd": "."})))
+ assert gate.main(["--hook", "claude", "--wait", "1"]) == 0
+ assert "gh exploded" in capsys.readouterr().out
+
+
+def test_agent_land_requests_no_auto_merge_during_another_prs_freeze() -> None:
+ from scripts import agent_land
+
+ commands: list[list[str]] = []
+ view = {"number": 7, "isDraft": False, "labels": []}
+ label = {"event": "labeled", "label": {"name": "merge-freeze"}}
+ answers = {
+ ("pr", "view"): view,
+ ("repo", "view"): REPO,
+ ("pr", "list"): [{"number": 733, "title": "package move"}],
+ ("api", f"repos/{REPO}/issues/733/events?per_page=100&page=1"): [
+ label | {"created_at": "2999-01-01T00:00:00Z"}
+ ],
+ }
+
+ def runner(cmd: list[str], **_: object) -> subprocess.CompletedProcess:
+ commands.append(cmd)
+ answer = answers.get(tuple(cmd[1:3]))
+ if answer is None:
+ return subprocess.CompletedProcess(cmd, 1, "", "no")
+ text = answer if isinstance(answer, str) else json.dumps(answer)
+ return subprocess.CompletedProcess(cmd, 0, text, "")
+
+ assert agent_land.queue_when_green("claude/x", runner) is False
+ assert all(cmd[:3] != ["gh", "pr", "merge"] for cmd in commands)
+
+
+def _freeze_answers(numbers: list[int], stamp: str | None) -> merge_freeze.GhJson:
+ def gh_json(args: list[str]) -> object:
+ if args[:2] == ["pr", "list"]:
+ return [{"number": n, "title": f"pr {n}"} for n in numbers]
+ if stamp is None:
+ return []
+ return [{"event": "labeled", "label": {"name": "merge-freeze"}, "created_at": stamp}]
+
+ return gh_json
+
+
+def test_two_freezing_pull_requests_do_not_lock_each_other_out() -> None:
+ gh_json = _freeze_answers([733, 740], "2026-10-19T10:00:00Z")
+ now = merge_freeze.parse_time("2026-10-19T10:30:00Z")
+ assert merge_freeze.active_freeze(REPO, gh_json, now=now, exempt=733) is None
+ assert merge_freeze.active_freeze(REPO, gh_json, now=now, exempt=740) is None
+ assert merge_freeze.active_freeze(REPO, gh_json, now=now, exempt=7) is not None
+
+
+def test_a_freeze_whose_label_time_is_unknown_does_not_hold_main() -> None:
+ gh_json = _freeze_answers([733], None)
+ assert merge_freeze.active_freeze(REPO, gh_json) is None
+
+
+def test_label_events_are_read_across_pages() -> None:
+ def gh_json(args: list[str]) -> object:
+ page = int(args[1].rsplit("page=", 1)[1])
+ if page == 1:
+ return [{"event": "commented"}] * 100
+ return [{"event": "labeled", "label": {"name": "merge-freeze"}, "created_at": "x"}]
+
+ events = merge_freeze.issue_events(REPO, 1, gh_json)
+ assert len(events) == 101
+
+
+def test_untracked_files_are_a_note_not_an_endless_fix(world: FakeWorld) -> None:
+ path = world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ world.status[path] = "?? scratch.log\n"
+ verdict = run_gate(world, ["claude/x"])
+ assert verdict.verdict == "DONE"
+ assert any("scratch.log" in note for note in verdict.notes)
+
+
+def test_a_line_ending_only_change_is_not_unfinished_work(world: FakeWorld) -> None:
+ path = world.branch("claude/x")
+ world.pr("claude/x", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ world.status[path] = " M .claude/settings.json\n"
+ world.eol_only.add(".claude/settings.json")
+ assert run_gate(world, ["claude/x"]).verdict == "DONE"
+
+
+def test_an_empty_new_branch_is_remembered_until_it_lands(world: FakeWorld) -> None:
+ world.branch("claude/new", ahead=0)
+ ctx = gate.Ctx(cwd=world.top, run=world)
+ state: dict = {"branches": ["claude/new"]}
+ assert gate.evaluate(ctx, None, state).verdict == "NONE"
+ assert state["branches"] == ["claude/new"]
+ world.pr("claude/new", state="MERGED", mergeCommit={"oid": MERGE_SHA})
+ world.main_runs = [main_run(MERGE_SHA, "success")]
+ assert gate.evaluate(ctx, None, state).verdict == "DONE"
+ assert state["branches"] == []
+
+
+def test_a_half_written_transcript_line_is_read_on_the_next_check(
+ world: FakeWorld, tmp_path: Path
+) -> None:
+ transcript = tmp_path / "t.jsonl"
+ full = json.dumps({"input": {"command": "git checkout -b claude/one"}})
+ transcript.write_text(full + "\n" + '{"input": {"command": "git checkout -b claude/tw', "utf-8")
+ ctx = gate.Ctx(cwd=world.top, run=world)
+ state: dict = {}
+ assert gate.session_branches(ctx, transcript, state) == ["claude/one"]
+ with transcript.open("a", encoding="utf-8") as handle:
+ handle.write('o"}}\n')
+ assert gate.session_branches(ctx, transcript, state) == ["claude/one", "claude/two"]
diff --git a/tests/unit/ci/test_merge_train_watchdog.py b/tests/unit/ci/test_merge_train_watchdog.py
new file mode 100644
index 0000000000..081cfd4944
--- /dev/null
+++ b/tests/unit/ci/test_merge_train_watchdog.py
@@ -0,0 +1,470 @@
+"""The merge train's watchdog: stuck pull requests, merge freezes, abandoned ones.
+
+Small fakes stand in for ``gh``; nothing reaches GitHub.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+
+from scripts.ci import agent_integrate, merge_freeze
+
+NOW = datetime(2026, 10, 19, 12, 0, tzinfo=UTC)
+REPO = "example/project"
+
+
+def _iso(delta: timedelta) -> str:
+ return (NOW - delta).isoformat().replace("+00:00", "Z")
+
+
+class _FakeGh:
+ """Records gh calls instead of reaching GitHub."""
+
+ def __init__(self):
+ self.calls: list[tuple[str, ...]] = []
+
+ def __call__(self, *args: str) -> int:
+ self.calls.append(args)
+ return 0
+
+ def named(self, *prefix: str) -> list[tuple[str, ...]]:
+ return [c for c in self.calls if c[: len(prefix)] == prefix]
+
+
+class _FakeGhJson:
+ """Answers ``gh_json`` reads from a table keyed by the first matching
+ argument fragment; records every question."""
+
+ def __init__(self, answers: dict[str, object]):
+ self.answers = answers
+ self.asked: list[tuple[str, ...]] = []
+
+ def __call__(self, *args: str) -> object:
+ self.asked.append(args)
+ joined = " ".join(args)
+ for fragment, answer in self.answers.items():
+ if fragment in joined:
+ return answer
+ return None
+
+
+def _verdict(**overrides):
+ base = {
+ "number": 7,
+ "action": "merge",
+ "state": "success",
+ "merge_state": "CLEAN",
+ "labels": set(),
+ "auto_merge": False,
+ "idle_minutes": 31.0,
+ }
+ return agent_integrate.watch_verdict(**{**base, **overrides})
+
+
+# ----- C2: stuck pull requests
+
+
+def test_green_but_never_queued_for_half_an_hour_is_stuck():
+ verdict = _verdict()
+ assert verdict["reason"] == "green-idle" and verdict["comment"]
+ assert verdict["step"] == "Request auto-merge: `gh pr merge 7 --auto --squash`."
+ assert _verdict(idle_minutes=29.0) is None
+ assert _verdict(idle_minutes=None) is None # CI still running
+
+
+def test_a_pull_request_github_lands_by_itself_is_never_stuck():
+ assert _verdict(action="queued") is None
+ assert _verdict(auto_merge=True) is None
+ assert _verdict(auto_merge=True, state="failure", idle_minutes=500.0) is None
+
+
+def test_a_merge_freeze_is_an_expected_wait_not_a_stuck_one():
+ assert _verdict(frozen=True, idle_minutes=100.0) is None
+ # A red one is still told: the freeze does not fix its CI.
+ assert _verdict(frozen=True, state="failure", idle_minutes=100.0)["reason"] == "red-idle"
+
+
+def test_a_head_the_queue_failed_asks_for_a_fix_not_for_auto_merge():
+ verdict = _verdict(action="held")
+ assert verdict["reason"] == "green-idle" and verdict["step"].startswith("Push a fix")
+
+
+def test_red_without_a_new_commit_for_an_hour_names_the_failing_checks():
+ verdict = _verdict(state="failure", idle_minutes=60.0, failing=["Lint", "Tests (ubuntu)"])
+ assert verdict["reason"] == "red-idle"
+ assert verdict["step"] == "Fix the failing checks: `Lint`, `Tests (ubuntu)`."
+ assert _verdict(state="failure", idle_minutes=59.0) is None
+ assert _verdict(state="failure", idle_minutes=90.0)["step"] == "Fix the failing checks."
+
+
+def test_an_unresolved_conflict_is_stuck_without_a_second_comment():
+ verdict = _verdict(merge_state="DIRTY", labels={"needs-rebase"}, idle_minutes=None)
+ assert verdict["reason"] == "conflict" and verdict["comment"] is False
+ # A conflict the train has not tried yet is its own job, not stuck.
+ assert _verdict(merge_state="DIRTY", action="wait") is None
+
+
+def test_run_finished_at_reads_the_newest_completed_pull_request_run():
+ done = {"event": "pull_request", "status": "completed", "conclusion": "success"}
+ runs = [
+ {**done, "created_at": "2026-10-19T10:00:00Z", "updated_at": "2026-10-19T10:20:00Z"},
+ {**done, "created_at": "2026-10-19T11:00:00Z", "updated_at": "2026-10-19T11:15:00Z"},
+ {**done, "event": "workflow_dispatch", "created_at": "2026-10-19T11:30:00Z"},
+ ]
+ assert agent_integrate.run_finished_at(runs) == "2026-10-19T11:15:00Z"
+ running = [*runs, {"event": "pull_request", "status": "in_progress", "created_at": "z"}]
+ assert agent_integrate.run_finished_at(running) is None
+ assert agent_integrate.run_finished_at([]) is None
+
+
+def test_failing_jobs_leave_out_the_gate_that_only_repeats_them(monkeypatch):
+ jobs = {
+ "jobs": [
+ {"name": "Lint", "conclusion": "failure"},
+ {"name": "Tests", "conclusion": "success"},
+ {"name": "Windows", "conclusion": "timed_out"},
+ {"name": "CI gate", "conclusion": "failure"},
+ ]
+ }
+ monkeypatch.setattr(agent_integrate, "gh_json", _FakeGhJson({"/jobs": jobs}))
+ assert agent_integrate.failing_jobs(REPO, 12) == ["Lint", "Windows"]
+ assert agent_integrate.failing_jobs(REPO, None) == []
+
+
+def test_a_planned_entry_reads_its_failing_jobs_and_earlier_comment(monkeypatch):
+ marker = agent_integrate.stuck_marker("a" * 40)
+ fake = _FakeGhJson(
+ {
+ "/runs/12/jobs": {"jobs": [{"name": "Lint", "conclusion": "failure"}]},
+ "pr view": {"comments": [{"body": marker}]},
+ }
+ )
+ monkeypatch.setattr(agent_integrate, "gh_json", fake)
+ entry = {
+ **_entry(),
+ "state": "failure",
+ "run_id": 12,
+ "merge_state": "CLEAN",
+ "auto_merge": False,
+ "idle_minutes": 75.0,
+ "frozen_by": None,
+ }
+ verdict = agent_integrate.watch_entry(REPO, entry)
+ assert verdict["step"] == "Fix the failing checks: `Lint`." and verdict["told"] is True
+ asked = len(fake.asked)
+ # A moving pull request costs no further question.
+ assert agent_integrate.watch_entry(REPO, {**entry, "idle_minutes": 5.0}) is None
+ assert len(fake.asked) == asked
+
+
+def _plan(entries, **extra):
+ return {"repo": REPO, "main": "m" * 40, "queue": True, "entries": entries, **extra}
+
+
+def _entry(number=7, action="wait", labels=(), watch=None, head="a" * 40):
+ return {
+ "number": number,
+ "branch": f"claude/{number}",
+ "head": head,
+ "id": f"PR_{number}",
+ "action": action,
+ "labels": list(labels),
+ "watch": watch,
+ }
+
+
+def test_a_stuck_pull_request_is_labelled_and_told_its_next_step_once(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ verdict = {**_verdict(), "told": False}
+ agent_integrate.apply(tmp_path, _plan([_entry(watch=verdict)]), False, True)
+ assert len(fake.named("label", "create")) == len(agent_integrate.TRAIN_LABELS)
+ assert ("pr", "edit", "7", "--repo", REPO, "--add-label", "stuck") in fake.calls
+ (comment,) = fake.named("pr", "comment")
+ body = comment[-1]
+ assert "**Next step:** Request auto-merge: `gh pr merge 7 --auto --squash`." in body
+ assert agent_integrate.stuck_marker("a" * 40) in body
+
+ # The next tick: labelled, and the comment for this head is already there.
+ quiet = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", quiet)
+ told = _entry(labels=["stuck"], watch={**verdict, "told": True})
+ agent_integrate.apply(tmp_path, _plan([told]), False, True)
+ assert not quiet.calls
+
+
+def test_a_new_head_gets_its_own_comment_even_while_still_labelled(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ verdict = {**_verdict(state="failure", idle_minutes=70.0), "told": False}
+ agent_integrate.apply(
+ tmp_path, _plan([_entry(labels=["stuck"], watch=verdict, head="b" * 40)]), False, True
+ )
+ assert not fake.named("pr", "edit") # the label is already on
+ (comment,) = fake.named("pr", "comment")
+ assert agent_integrate.stuck_marker("b" * 40) in comment[-1]
+
+
+def test_already_told_reads_the_marker_and_stays_quiet_when_it_cannot_read(monkeypatch):
+ marker = agent_integrate.stuck_marker("a" * 40)
+ comments = {"comments": [{"body": "hello"}, {"body": f"stuck\n\n{marker}"}]}
+ monkeypatch.setattr(agent_integrate, "gh_json", _FakeGhJson({"pr view": comments}))
+ assert agent_integrate.already_told(REPO, 7, marker)
+ assert not agent_integrate.already_told(REPO, 7, agent_integrate.stuck_marker("c" * 40))
+ monkeypatch.setattr(agent_integrate, "gh_json", _FakeGhJson({}))
+ assert agent_integrate.already_told(REPO, 7, marker)
+
+
+def test_the_stuck_label_goes_once_the_pull_request_moves(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ agent_integrate.apply(tmp_path, _plan([_entry(labels=["stuck"])]), False, True)
+ assert fake.calls == [("pr", "edit", "7", "--repo", REPO, "--remove-label", "stuck")]
+
+
+def test_enqueueing_a_green_pull_request_is_moving_it(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ verdict = {**_verdict(), "told": False}
+ entry = _entry(action="merge", labels=["stuck"], watch=verdict)
+ agent_integrate.apply(tmp_path, _plan([entry]), False, False) # merge bot token
+ assert len(fake.named("api", "graphql")) == 1
+ assert ("pr", "edit", "7", "--repo", REPO, "--remove-label", "stuck") in fake.calls
+ assert not fake.named("pr", "comment")
+
+
+def test_github_token_cannot_enqueue_so_the_green_pull_request_is_labelled(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ verdict = {**_verdict(), "told": False}
+ agent_integrate.apply(tmp_path, _plan([_entry(action="merge", watch=verdict)]), False, True)
+ assert not fake.named("api", "graphql")
+ assert fake.named("pr", "comment") and fake.named("pr", "edit")
+
+
+def test_a_conflict_the_train_could_not_resolve_adds_stuck_to_needs_rebase(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ state = tmp_path / "state" / "pr-7.json"
+ state.parent.mkdir(parents=True)
+ state.write_text(json.dumps({"status": "conflict", "unresolved": ["a.py"]}), "utf-8")
+ agent_integrate.apply(tmp_path, _plan([_entry(action="update")]), False, True)
+ edits = fake.named("pr", "edit")
+ assert ("pr", "edit", "7", "--repo", REPO, "--add-label", "needs-rebase") in edits
+ assert ("pr", "edit", "7", "--repo", REPO, "--add-label", "stuck") in edits
+ assert len(fake.named("pr", "comment")) == 1 # the needs-rebase report only
+
+
+def test_a_dry_run_reports_the_watchdog_and_touches_nothing(tmp_path, monkeypatch, capsys):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ plan = _plan(
+ [_entry(watch={**_verdict(), "told": False}), _entry(number=8, labels=["stuck"])],
+ stale=[{"number": 9, "action": "close", "idle_days": 15.0}],
+ expired_freezes=[{"number": 10, "marker": "<!-- m -->", "age_hours": 3.0}],
+ )
+ agent_integrate.apply(tmp_path, plan, True, True)
+ assert not fake.calls
+ out = capsys.readouterr().out
+ assert "would label and comment" in out and "would lift" in out
+ assert "#9: no commit for 15.0 days; would close" in out
+ assert "#10: merge freeze expired; would comment" in out
+
+
+# ----- C3: merge freeze
+
+
+def _freeze_answers(labelled: dict[int, timedelta]) -> dict[str, object]:
+ answers: dict[str, object] = {
+ "--label merge-freeze": [{"number": n, "title": f"PR {n}"} for n in labelled]
+ }
+ for number, age in labelled.items():
+ answers[f"issues/{number}/events"] = [
+ {"event": "labeled", "label": {"name": "merge-freeze"}, "created_at": _iso(age)}
+ ]
+ return answers
+
+
+def test_a_young_freeze_holds_every_other_pull_request(monkeypatch):
+ fake = _FakeGhJson(_freeze_answers({50: timedelta(minutes=30)}))
+ monkeypatch.setattr(agent_integrate, "gh_json", fake)
+ held_by, expired = agent_integrate.freeze_lookup(REPO, NOW)
+ assert held_by(7).number == 50
+ assert held_by(50) is None # the freeze holder itself may land
+ assert expired == []
+ listings = [a for a in fake.asked if "--label" in a]
+ assert len(listings) == 1 # one listing per tick, however many ask
+
+
+def test_an_expired_freeze_holds_nothing_and_is_listed_for_one_notice(monkeypatch):
+ fake = _FakeGhJson(_freeze_answers({50: timedelta(hours=3)}))
+ monkeypatch.setattr(agent_integrate, "gh_json", fake)
+ held_by, expired = agent_integrate.freeze_lookup(REPO, NOW)
+ assert held_by(7) is None
+ assert [f.number for f in expired] == [50]
+ marker = agent_integrate.freeze_marker(expired[0])
+ assert expired[0].since.isoformat() in marker
+
+
+def test_a_frozen_pull_request_is_neither_enqueued_nor_merged(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ entry = _entry(action="frozen")
+ entry["note"] = "merge freeze held by PR #50 (move); it lapses in 60 min at the latest"
+ agent_integrate.apply(tmp_path, _plan([entry]), False, False)
+ agent_integrate.apply(tmp_path, {**_plan([entry]), "queue": False}, False, False)
+ assert not fake.calls
+
+
+def test_the_expired_freeze_notice_carries_its_marker(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ plan = _plan([], expired_freezes=[{"number": 50, "marker": "<!-- f -->", "age_hours": 3.1}])
+ agent_integrate.apply(tmp_path, plan, False, True)
+ ((*_, body),) = fake.named("pr", "comment")
+ assert body.startswith(agent_integrate.FREEZE_EXPIRED) and body.endswith("<!-- f -->")
+ assert "older than 2 h" in agent_integrate.FREEZE_EXPIRED
+ assert merge_freeze.FREEZE_LABEL == "merge-freeze"
+
+
+# ----- C4: abandoned pull requests
+
+
+def _pr(number=7, branch="claude/x", labels=(), **extra):
+ return {
+ "number": number,
+ "headRefName": branch,
+ "baseRefName": "main",
+ "isDraft": True,
+ "isCrossRepository": False,
+ "labels": [{"name": name} for name in labels],
+ "author": {"login": "someone"},
+ "createdAt": _iso(timedelta(days=30)),
+ **extra,
+ }
+
+
+def test_drafts_count_but_dependabot_forks_and_other_branches_never_do():
+ assert agent_integrate.stale_candidate(_pr())
+ assert agent_integrate.stale_candidate(_pr(branch="feature/x", labels=["auto-merge"]))
+ assert not agent_integrate.stale_candidate(_pr(branch="feature/x"))
+ assert not agent_integrate.stale_candidate(_pr(author={"login": "app/dependabot"}))
+ assert not agent_integrate.stale_candidate(
+ _pr(branch="dependabot/pip/x", labels=["auto-merge"])
+ )
+ assert not agent_integrate.stale_candidate(_pr(isCrossRepository=True))
+ assert not agent_integrate.stale_candidate(_pr(baseRefName="release"))
+
+
+def test_stale_verdicts():
+ verdict = agent_integrate.stale_verdict
+ assert verdict(set(), 6.9, None) is None
+ assert verdict(set(), 7.0, None) == "warn"
+ assert verdict({"stale"}, 10.0, 3.0) is None # warned, the week is not over
+ assert verdict({"stale"}, 14.0, 7.0) == "close"
+ # Warned only yesterday (the train is new, the pull request old): a full week first.
+ assert verdict({"stale"}, 40.0, 1.0) is None
+ assert verdict({"stale"}, 40.0, None) is None # label age unknown: never closed
+ assert verdict({"stale"}, 2.0, 8.0) == "unstale" # a new commit
+ for exempt in ("keep", "needs-human", "merge-freeze", "wip", "do-not-merge"):
+ assert verdict({exempt}, 40.0, None) is None
+ assert verdict({exempt, "stale"}, 40.0, 30.0) == "unstale"
+
+
+def _activity(*prs: tuple[int, list[tuple[timedelta, str]]]) -> dict:
+ nodes = [
+ {
+ "number": number,
+ "commits": {
+ "nodes": [
+ {"commit": {"committedDate": _iso(age), "author": {"name": who}}}
+ for age, who in commits
+ ]
+ },
+ }
+ for number, commits in prs
+ ]
+ return {"data": {"repository": {"pullRequests": {"nodes": nodes}}}}
+
+
+def test_the_trains_own_merges_of_main_are_not_activity(monkeypatch):
+ train = agent_integrate.TRAIN_AUTHOR
+ answer = _activity(
+ (1, [(timedelta(days=20), "agent"), (timedelta(days=1), train)]),
+ (2, [(timedelta(days=9), train), (timedelta(days=2), train)]),
+ (3, []),
+ )
+ monkeypatch.setattr(agent_integrate, "gh_json", _FakeGhJson({"graphql": answer}))
+ found = agent_integrate.last_activity(REPO)
+ assert found[1] == _iso(timedelta(days=20))
+ # Only train commits in view: the oldest of them, never staler than the truth.
+ assert found[2] == _iso(timedelta(days=9))
+ assert 3 not in found
+
+
+def test_stale_sweep_warns_closes_and_lifts(monkeypatch):
+ week = timedelta(days=8)
+ answers = {
+ "graphql": _activity(
+ (1, [(week, "agent")]),
+ (2, [(timedelta(days=15), "agent")]),
+ (3, [(timedelta(hours=3), "agent")]),
+ (4, [(timedelta(days=30), "agent")]),
+ (5, [(timedelta(days=30), "agent")]),
+ ),
+ "issues/2/events": [
+ {"event": "labeled", "label": {"name": "stale"}, "created_at": _iso(week)}
+ ],
+ }
+ fake = _FakeGhJson(answers)
+ monkeypatch.setattr(agent_integrate, "gh_json", fake)
+ prs = [
+ _pr(1),
+ _pr(2, labels=["stale"]),
+ _pr(3, labels=["stale"]),
+ _pr(4, labels=["keep"]),
+ _pr(5, branch="dependabot/npm/x", author={"login": "app/dependabot"}),
+ _pr(6), # its activity could not be read
+ # Opened today on a month-old commit.
+ _pr(1, createdAt=_iso(timedelta(hours=1))),
+ ]
+ sweep = agent_integrate.stale_sweep(REPO, prs, NOW)
+ assert [(item["number"], item["action"]) for item in sweep] == [
+ (1, "warn"),
+ (2, "close"),
+ (3, "unstale"),
+ ]
+
+
+def test_the_sweep_acts_only_outside_a_dry_run(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ monkeypatch.setattr(agent_integrate, "already_told", lambda *_: False)
+ stale = [
+ {"number": 1, "action": "warn", "idle_days": 8.0},
+ {"number": 2, "action": "close", "idle_days": 15.0},
+ {"number": 3, "action": "unstale", "idle_days": 0.1},
+ ]
+ agent_integrate.apply(tmp_path, _plan([], stale=stale), True, True)
+ assert not fake.calls
+ agent_integrate.apply(tmp_path, _plan([], stale=stale), False, True)
+ warning = f"{agent_integrate.STALE_WARNING}\n\n{agent_integrate.STALE_MARKER}"
+ assert ("pr", "comment", "1", "--repo", REPO, "--body", warning) in fake.calls
+ assert ("pr", "edit", "1", "--repo", REPO, "--add-label", "stale") in fake.calls
+ close = ("pr", "close", "2", "--repo", REPO, "--comment", agent_integrate.STALE_CLOSING)
+ assert close in fake.calls
+ assert ("pr", "edit", "3", "--repo", REPO, "--remove-label", "stale") in fake.calls
+ assert agent_integrate.STALE_WARNING == (
+ "No activity for 7 days; this closes in 7 more days unless labelled `keep`."
+ )
+
+
+def test_the_train_creates_its_labels_idempotently_and_once_per_run(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ stale = [{"number": n, "action": "warn", "idle_days": 8.0} for n in (1, 2)]
+ agent_integrate.apply(tmp_path, _plan([], stale=stale), False, True)
+ created = fake.named("label", "create")
+ assert {c[2] for c in created} == {"stuck", "stale", "keep", "merge-freeze"}
+ assert all("--force" in c for c in created) and len(created) == 4