The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): PR acceptance runs gh as the assignee profile's login
Yuan Lifdac8a1896fd
diff --git a/hermes_cli/kanban_pr_acceptance.py b/hermes_cli/kanban_pr_acceptance.pyindex 9a3b7bfada8..d789f29800f 100644--- a/hermes_cli/kanban_pr_acceptance.py+++ b/hermes_cli/kanban_pr_acceptance.py@@ -2,6 +2,11 @@Network work happens outside SQLite transactions. The lifecycle owner persistsreceipts only after rechecking the captured run/status/contract under its lock.++``gh`` runs as the card's assignee profile (``profile_home``), not the ambient+login: :func:`_gh_env` resolves that profile's own credentials/config for the+subprocess — a multi-profile host's default ``gh`` login cannot read another+org's private repos (#122689)."""from __future__ import annotations@@ -22,21 +27,76 @@ def validate_contract(value: str | None) -> str:return value-def _api(endpoint: str, *, query: str | None = None, paginate: bool = False):+def _api(endpoint: str, *, query: str | None = None, paginate: bool = False,+ profile_home: str | None = None):command = ["gh", "api", endpoint, "--hostname", "github.com"]if query is not None:command += ["-f", "query=" + query]if paginate:command += ["--paginate", "--slurp"]- result = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True,- text=True, encoding="utf-8", errors="replace", timeout=30, check=True)+ try:+ result = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True,+ text=True, encoding="utf-8", errors="replace", timeout=30,+ check=True, env=_gh_env(profile_home))+ except subprocess.CalledProcessError as exc:+ # 401/403/404 = the login cannot see this repository (wrong profile identity+ # or missing grant), not a transient API failure. Persist only the status+ # code + endpoint, never gh's stderr (credentials/host details).+ denied = re.search(r"HTTP (40[134])", exc.stderr or "")+ if denied:+ raise _GateAuthError(f"HTTP {denied[1]} on {endpoint.split('?')[0]}") from None+ raisevalue = json.loads(result.stdout)if isinstance(value, dict) and value.get("errors"):raise ValueError("GitHub returned incomplete GraphQL evidence")return value-def collect_acceptance(contract: str, published_pr: str | None) -> dict:+class _GateAuthError(RuntimeError):+ """gh was refused at HTTP 401/403/404 (or GraphQL returned no repository):+ this profile's login cannot see the repo — an identity problem to fix, not+ an infrastructure blip to retry."""+++def _gh_env(profile_home: str | None) -> dict[str, str] | None:+ """Child env for ``gh``: the card's profile identity when one is resolvable.++ The completion boundary runs in the worker (assignee), the CLI, or a+ reviewer/dispatcher turn, so an ambient ``gh`` login is whichever process+ happened to call it (#122689). ``served_profile_child_env(inherit_credentials=True)``+ is the seam for "this child acts for that profile": it scrubs the launch+ profile's credential residue and overlays the target profile's own+ ``GH_TOKEN``/``GH_CONFIG_DIR`` (its ``.env`` + external secret sources).+ ``None`` keeps the ambient env — unassigned cards behave exactly as before.+ """+ if not profile_home:+ return None+ from tools.environments.local import _is_routed_home, hermes_subprocess_env, served_profile_child_env+ base = hermes_subprocess_env(inherit_credentials=True)+ if _is_routed_home(profile_home):+ # gh's config dir decides which login `gh api` uses, yet it is a path, not a+ # credential, so no scrub list sees it; the target's own value is overlaid from its .env.+ base.pop("GH_CONFIG_DIR", None)+ return served_profile_child_env(base=base, target_home=profile_home, inherit_credentials=True)+++def _assignee_profile_home(conn, task_id: str) -> str | None:+ """Home whose ``gh`` login must read the contract repo — the assignee's, resolved+ exactly as the dispatcher resolves the worker's home — or None (unassigned,+ control-plane lane, profile gone) so the ambient login is used rather than a guess."""+ row = conn.execute("SELECT assignee FROM tasks WHERE id = ?", (task_id,)).fetchone()+ assignee = row["assignee"] if row else None+ if not assignee:+ return None+ from hermes_cli.profiles import normalize_profile_name, resolve_profile_env+ try:+ return resolve_profile_env(normalize_profile_name(assignee))+ except (FileNotFoundError, ValueError):+ return None+++def collect_acceptance(contract: str, published_pr: str | None,+ profile_home: str | None = None) -> dict:receipt = {"ok": False, "classification": "missing", "head_sha": None,"pr_url": published_pr, "checks": [],"recovery": "Fix required failures, rerun infrastructure checks or wait, then retry completion. "@@ -54,14 +114,19 @@ def collect_acceptance(contract: str, published_pr: str | None) -> dict:query = '''{repository(owner:%s,name:%s){pullRequest(number:%d){headRefOid baseRefName statebaseRef{branchProtectionRule{requiredStatusChecks{context app{databaseId}}}}}}}''' % (json.dumps(owner), json.dumps(name), number)- pr = _api("graphql", query=query)["data"]["repository"]["pullRequest"]+ repository = _api("graphql", query=query, profile_home=profile_home)["data"]["repository"]+ if repository is None:+ # A private repo the login cannot read resolves to null, not an error.+ raise _GateAuthError(f"HTTP 404 on graphql {repo}")+ pr = repository["pullRequest"]sha, branch = pr["headRefOid"], pr["baseRefName"]receipt["head_sha"] = shaif not re.fullmatch(r"[0-9a-f]{40}", sha) or pr["state"] not in {"OPEN", "MERGED"}:raise ValueError("PR is closed or current head is unavailable")protection = (pr.get("baseRef") or {}).get("branchProtectionRule") or {}required = {(r["context"], (r.get("app") or {}).get("databaseId")) for r in protection.get("requiredStatusChecks", [])}- rules = _api(f"repos/{repo}/rules/branches/{quote(branch, safe='')}?per_page=100", paginate=True)+ rules = _api(f"repos/{repo}/rules/branches/{quote(branch, safe='')}?per_page=100",+ paginate=True, profile_home=profile_home)for page in rules:for rule in page:if rule["type"] == "required_status_checks":@@ -71,11 +136,13 @@ def collect_acceptance(contract: str, published_pr: str | None) -> dict:if not required:receipt["detail"] = "No repository-required checks are configured; explicitly use a local-only contract for non-CI tasks."return receipt- pages = _api(f"repos/{repo}/commits/{sha}/check-runs?per_page=100&filter=latest", paginate=True)+ pages = _api(f"repos/{repo}/commits/{sha}/check-runs?per_page=100&filter=latest",+ paginate=True, profile_home=profile_home)runs = [run for page in pages for run in page["check_runs"]]if len({r["id"] for r in runs}) != pages[0]["total_count"]:raise ValueError("Incomplete check-run pagination")- statuses = [{**s, "sha": sha} for page in _api(f"repos/{repo}/commits/{sha}/statuses?per_page=100", paginate=True) for s in page]+ statuses = [{**s, "sha": sha} for page in _api(f"repos/{repo}/commits/{sha}/statuses?per_page=100",+ paginate=True, profile_home=profile_home) for s in page]outcomes = []for context, app_id in sorted(required, key=str):matching = [r for r in runs if r["name"] == context and@@ -96,13 +163,18 @@ def collect_acceptance(contract: str, published_pr: str | None) -> dict:"head_sha": check.get("head_sha", check.get("sha")),"classification": classification, "conclusion": outcome})# Re-read after all pages: old-head successes are never transferable.- current = _api(f"repos/{repo}/pulls/{number}")+ current = _api(f"repos/{repo}/pulls/{number}", profile_home=profile_home)if current["head"]["sha"] != sha or current["base"]["ref"] != branch or (current["state"] == "closed" and not current.get("merged")):receipt.update(classification="stale", detail="PR head/base changed while collecting evidence; retry.")return receiptreceipt["classification"] = next((x for x in outcomes if x != "success"), "missing" if not outcomes else "success")receipt["ok"] = receipt["classification"] == "success"return receipt+ except _GateAuthError as exc:+ receipt.update(classification="auth",+ detail=f"GitHub refused the acceptance read ({exc}) as the assignee profile's gh login; "+ "fix that profile's GitHub credentials/access to the repository, then retry completion.")+ return receiptexcept (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, IndexError):# Never persist gh stderr (credentials/host details); the failed phase is actionable.receipt.update(classification="infra", detail="GitHub acceptance evidence unavailable or incomplete; check gh authentication/API access and retry.")diff --git a/hermes_cli/kanban_pr_acceptance_store.py b/hermes_cli/kanban_pr_acceptance_store.pyindex cf6a8327f3d..92c842e7ee3 100644--- a/hermes_cli/kanban_pr_acceptance_store.py+++ b/hermes_cli/kanban_pr_acceptance_store.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom hermes_cli.kanban_db_connect import write_txn-from hermes_cli.kanban_pr_acceptance import _PR, collect_acceptance+from hermes_cli.kanban_pr_acceptance import _PR, _assignee_profile_home, collect_acceptancedef _snapshot(conn, task_id):@@ -29,7 +29,10 @@ def prepare_acceptance(conn, task_id, expected_run_id, metadata):conn.execute("UPDATE tasks SET completion_contract=? WHERE id=?", (published_pr, task_id))snapshot = (run_id, status, published_pr)contract = published_pr- return snapshot, collect_acceptance(contract, published_pr)+ # The assignee profile's gh login owns the repo: acceptance must not run as+ # the ambient login of whichever process completes the card (#122689).+ return snapshot, collect_acceptance(contract, published_pr,+ profile_home=_assignee_profile_home(conn, task_id))def record_acceptance(conn, task_id, acceptance):diff --git a/tests/hermes_cli/test_kanban_pr_acceptance.py b/tests/hermes_cli/test_kanban_pr_acceptance.pyindex 8573affe977..671baa490b8 100644--- a/tests/hermes_cli/test_kanban_pr_acceptance.py+++ b/tests/hermes_cli/test_kanban_pr_acceptance.py@@ -129,3 +129,47 @@ def test_acceptance_receipts_and_terminal_write_share_run_ownership(github):assert kb.get_task(conn, tid).status != "done"assert conn.execute("SELECT count(*) FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,)).fetchone()[0] == 0github.pop("race")+++# --- #122689: acceptance must read the repo as the ASSIGNEE profile's gh login ---+[email protected]("posix")+def test_acceptance_runs_gh_as_the_assignee_profile(tmp_path, monkeypatch):+ """The gh child env carries the assignee's own GH credentials (its .env),+ never the ambient/launch residue, and an invisible repo is classified+ `auth` naming the repository — not a retryable `infra` failure."""+ from pathlib import Path++ launch_home = tmp_path / "home"+ launch_home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(launch_home))+ assignee_home = launch_home / "profiles" / "b"+ assignee_home.mkdir(parents=True)+ (assignee_home / ".env").write_text("GH_TOKEN=b-token\n", encoding="utf-8")+ # Ambient residue that must NOT decide the login.+ monkeypatch.setenv("GH_TOKEN", "launch-token")+ monkeypatch.setenv("GH_CONFIG_DIR", "/nonexistent/launch/gh")++ env_dump = tmp_path / "gh_env.json"+ shim = tmp_path / "bin"+ shim.mkdir()+ gh = shim / "gh"+ gh.write_text(f"#!{sys.executable}\nimport json, os\n"+ f"json.dump(dict(os.environ), open({str(env_dump)!r}, 'w'))\n"+ "print(json.dumps({'data': {'repository': None}}))\n")+ gh.chmod(0o755)+ monkeypatch.setenv("PATH", str(shim) + os.pathsep + os.environ["PATH"])+ kb.init_db()+ with connect() as conn:+ tid = kb.create_task(conn, title="as-b", completion_contract="acme/repo", assignee="b")+ assert not kb.complete_task(conn, tid, result="done",+ metadata={"published_pr": "https://github.com/acme/repo/pull/7"})+ assert kb.get_task(conn, tid).status != "done"+ receipts = [json.loads(r[0]) for r in conn.execute(+ "SELECT payload FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,))]+ assert receipts[-1]["classification"] == "auth"+ assert "acme/repo" in receipts[-1]["detail"]+ captured = json.loads(env_dump.read_text())+ assert captured["GH_TOKEN"] == "b-token"+ assert captured.get("GH_CONFIG_DIR") != "/nonexistent/launch/gh"+ assert "credentials" in (kb.get_task(conn, tid).last_failure_error or "")diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex b682fb89176..0add7545930 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -65,6 +65,12 @@ neutral **required** evidence cannot complete the card. Neither can zero-runacceptance, unreadable policy or GitHub API failures. A repository without requiredchecks needs a local-only contract. `gh` must be authenticated with read access tothe repository's checks and rules; no remote writes are performed by this gate.+Acceptance reads run as the **assignee profile's** `gh` login — its `GH_TOKEN` /+`GH_CONFIG_DIR` from the profile's own `.env`, never the ambient login of the+process completing the card. On multi-profile hosts (one GitHub identity per+org), sign `gh` in per profile (`GH_CONFIG_DIR` in that profile's `.env`). A+login that cannot see the repository is rejected with `classification=auth`,+naming the repository, instead of a retryable infra failure.Rejection retains the active card and workspace. Durable `pr_acceptance` eventsstore PR URL, SHA, required contexts, check IDs/URLs, classifications and recovery