The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): PR acceptance never falls through to the launch user's gh login
teknium137daf85b2ad0
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 761ae82c506..2a57e0c29d2 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -503,6 +503,8 @@ def refresh_codex_oauth_pure(refresh_payload, refreshed_access = _refresh_payload_access_token(response, provider="openai-codex", invalid_response=None,invalid_json=("Codex token refresh returned invalid JSON.", "codex_refresh_invalid_json"),+ # A 200 with a non-JSON body is an edge/proxy misfire, not a revoked grant: never relogin.+ invalid_json_relogin=False,missing_access=("Codex token refresh response was missing access_token.","codex_refresh_missing_access_token"))diff --git a/hermes_cli/kanban_pr_acceptance.py b/hermes_cli/kanban_pr_acceptance.pyindex d789f29800f..88f437285ad 100644--- a/hermes_cli/kanban_pr_acceptance.py+++ b/hermes_cli/kanban_pr_acceptance.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport jsonimport reimport subprocess+from pathlib import Pathfrom urllib.parse import quote_REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+")@@ -45,6 +46,8 @@ def _api(endpoint: str, *, query: str | None = None, paginate: bool = False,denied = re.search(r"HTTP (40[134])", exc.stderr or "")if denied:raise _GateAuthError(f"HTTP {denied[1]} on {endpoint.split('?')[0]}") from None+ if exc.returncode == 4: # gh's authentication-required exit: this profile has no login+ raise _GateAuthError(f"gh has no login for {endpoint.split('?')[0]}") from Noneraisevalue = json.loads(result.stdout)if isinstance(value, dict) and value.get("errors"):@@ -73,35 +76,42 @@ def _gh_env(profile_home: str | None) -> dict[str, str] | None:return Nonefrom tools.environments.local import _is_routed_home, hermes_subprocess_env, served_profile_child_envbase = hermes_subprocess_env(inherit_credentials=True)- if _is_routed_home(profile_home):+ routed = _is_routed_home(profile_home)+ if routed:# 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)+ env = served_profile_child_env(base=base, target_home=profile_home, inherit_credentials=True)+ if routed and not (env.keys() & {"GH_TOKEN", "GITHUB_TOKEN", "GH_CONFIG_DIR"}):+ # HOME/XDG_CONFIG_HOME are still the launch process's: without a login of its own the+ # child would fall through to ~/.config/gh/hosts.yml — the ambient login. Pin gh's config+ # to a profile-owned dir so it fails "not logged in" (exit 4 -> auth) instead.+ env["GH_CONFIG_DIR"] = str(Path(profile_home) / "gh")+ return env-def _assignee_profile_home(conn, task_id: str) -> str | None:+def _assignee_profile_home(assignee: str | None) -> 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+ exactly as the dispatcher resolves the worker's home — or None (unassigned) so the+ ambient login is used. An assigned card whose profile cannot be resolved is an+ identity failure (``auth``), never a silent fall-through to the ambient login."""if not assignee:return Nonefrom hermes_cli.profiles import normalize_profile_name, resolve_profile_envtry:return resolve_profile_env(normalize_profile_name(assignee))except (FileNotFoundError, ValueError):- return None+ raise _GateAuthError(f"assignee profile {assignee!r} cannot be resolved") from Nonedef collect_acceptance(contract: str, published_pr: str | None,- profile_home: str | None = None) -> dict:+ assignee: 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. ""Use kanban_block if human input is needed; receipts remain on the task event log."}try:+ profile_home = _assignee_profile_home(assignee)declared = _PR.fullmatch(contract)url = contract if declared else published_prmatch = _PR.fullmatch(url or "")@@ -171,8 +181,9 @@ def collect_acceptance(contract: str, published_pr: str | None,receipt["ok"] = receipt["classification"] == "success"return receiptexcept _GateAuthError as exc:+ login = f"assignee profile {assignee!r}'s gh login" if assignee else "the ambient gh login"receipt.update(classification="auth",- detail=f"GitHub refused the acceptance read ({exc}) as the assignee profile's gh login; "+ detail=f"GitHub refused the acceptance read ({exc}) as {login}; ""fix that profile's GitHub credentials/access to the repository, then retry completion.")return receiptexcept (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, IndexError):diff --git a/hermes_cli/kanban_pr_acceptance_store.py b/hermes_cli/kanban_pr_acceptance_store.pyindex 92c842e7ee3..bbc56b6725c 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, _assignee_profile_home, collect_acceptance+from hermes_cli.kanban_pr_acceptance import _PR, collect_acceptancedef _snapshot(conn, task_id):@@ -31,8 +31,8 @@ def prepare_acceptance(conn, task_id, expected_run_id, metadata):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))+ assignee = conn.execute("SELECT assignee FROM tasks WHERE id=?", (task_id,)).fetchone()["assignee"]+ return snapshot, collect_acceptance(contract, published_pr, assignee=assignee)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 671baa490b8..a31fbac7afd 100644--- a/tests/hermes_cli/test_kanban_pr_acceptance.py+++ b/tests/hermes_cli/test_kanban_pr_acceptance.py@@ -173,3 +173,60 @@ def test_acceptance_runs_gh_as_the_assignee_profile(tmp_path, monkeypatch):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 "")++[email protected]("posix")+def test_assignee_without_own_gh_login_never_falls_through_to_ambient_login(tmp_path, monkeypatch):+ """An assignee profile with no GH_TOKEN/GH_CONFIG_DIR of its own must not inherit the+ launch user's ~/.config/gh (HOME/XDG_CONFIG_HOME stay the launch process's): gh is pinned+ to a profile-owned config dir, its 'not logged in' exit is classified `auth` naming the profile."""+ 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("", encoding="utf-8")+ monkeypatch.setenv("GH_TOKEN", "launch-token")+ monkeypatch.setenv("GH_CONFIG_DIR", "/nonexistent/launch/gh")+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "launch-xdg"))++ env_dump = tmp_path / "gh_env.json"+ shim = tmp_path / "bin"+ shim.mkdir()+ gh = shim / "gh"+ # Real gh: GH_CONFIG_DIR wins; a config dir without hosts.yml means "not logged in" (exit 4).+ gh.write_text(f"#!{sys.executable}\nimport json, os, pathlib, sys\n"+ f"pathlib.Path({str(env_dump)!r}).write_text(json.dumps(dict(os.environ)), encoding='utf-8')\n"+ "if 'GH_CONFIG_DIR' in os.environ and not os.path.exists(os.environ['GH_CONFIG_DIR']):\n"+ " sys.exit(4)\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"})+ receipt = json.loads(conn.execute(+ "SELECT payload FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,)).fetchone()[0])+ assert receipt["classification"] == "auth"+ assert "'b'" in receipt["detail"] and "no login" in receipt["detail"]+ captured = json.loads(env_dump.read_text(encoding="utf-8-sig"))+ assert captured["GH_CONFIG_DIR"] == str(assignee_home / "gh")+ assert "GH_TOKEN" not in captured and "GITHUB_TOKEN" not in captured+++def test_assigned_card_with_unresolvable_profile_is_auth_not_ambient(tmp_path, monkeypatch):+ """A card assigned to a profile that no longer exists must not run gh as the completing+ process's ambient login: classification `auth` naming the profile, gh never invoked."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("PATH", str(tmp_path / "empty-bin")) # any gh spawn would fail as infra+ kb.init_db()+ with connect() as conn:+ tid = kb.create_task(conn, title="as-ghost", completion_contract="acme/repo", assignee="ghost")+ assert not kb.complete_task(conn, tid, result="done",+ metadata={"published_pr": "https://github.com/acme/repo/pull/7"})+ receipt = json.loads(conn.execute(+ "SELECT payload FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,)).fetchone()[0])+ assert receipt["classification"] == "auth"+ assert "'ghost'" in receipt["detail"] and "cannot be resolved" in receipt["detail"]diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 0add7545930..66e72242300 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -68,9 +68,15 @@ the 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 theprocess 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.+org), sign `gh` in per profile (`GH_CONFIG_DIR` in that profile's `.env`). The+token must live in the profile's `.env` (or a configured secret source): a+`GH_TOKEN` merely exported in the shell or a systemd unit is scrubbed from the+`gh` child and never re-added. An assignee profile with no `gh` login of its+own — or one that no longer exists — is refused `not logged in` rather than+falling through to `~/.config/gh`; unassigned cards still use the ambient+login. A login that cannot see the repository is rejected with+`classification=auth`, naming the profile and 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@@ -1432,8 +1438,9 @@ Every transition appends a row to `task_events`. Each row carries an optional `r| `reconciled` | `{reason, claim_lock, claim_expires, worker_pid}` | Orphaned-card reconciliation: the card was `running` with broken claim bookkeeping (`claim_lock` or `claim_expires` NULL — crash mid-claim, manual SQL, DB restore) and no live worker, so none of the TTL/crash/stale paths could ever recover it. The dispatcher requeued it to `ready` with an explanatory comment. Gated by `kanban.reconcile_orphans` in config.yaml (default `true`). || `respawn_guarded` | `{reason}` | Dispatcher refused to re-spawn this ready task this tick. Reasons: `infrastructure_cooldown` (the host refused the last spawn — no restart-safe systemd scope — and the cooldown has not elapsed; never counted against the card), `rate_limit_cooldown` (the last run hit a quota wall; same cooldown, never counted), `blocker_auth` (last failure was a quota/auth/429 error — wait for the rate window to reset), `recent_success` (a completed run happened in the last hour — wait for review before re-running), `active_pr` (a GitHub PR URL appears in a recent comment — a prior worker already opened a PR). The task stays in `ready`; the next tick gets another chance to spawn. If the underlying condition persists, the normal `consecutive_failures` circuit breaker will auto-block via `gave_up` after `failure_limit` failures. || `spawn_failed` | `{error, failures}` | One spawn attempt failed (missing PATH, workspace unmountable, …). Counter increments; task returns to `ready` for retry. |+| `skipped_nonspawnable` | `{assignee}` | Dispatcher refused to spawn because the assignee profile does not exist in this home (or is not in `kanban.dispatch_profiles`). Written once per card — repeated only when another event landed in between — so `show`/`tail` name the missing profile without a row per tick. The card stays in `ready`; reassign it or install the profile. || `protocol_violation` | `{pid, claimer, exit_code, protocol_violation, worker_output?}` | Worker exited successfully while the task was still `running`, usually because it answered without a terminal board call (`kanban_complete`, `kanban_request_review` or `kanban_block`). Emitted on every violation (the payload's `protocol_violation: true` marker is copied into the run metadata and feeds the violation-only retry budget). Below the budget — up to `_PROTOCOL_VIOLATION_FAILURE_LIMIT` (default 3) *consecutive* violations, per-task `max_retries` overriding — the task simply returns to `ready` for another attempt; when the streak reaches the bound the dispatcher also emits `gave_up` and auto-blocks. `worker_output` carries the worker's own last printed text (usually its explanation of why it stopped), also folded into `last_failure_error` and shown to the retry worker as the prior-attempt error. |-| `gave_up` | `{failures, effective_limit, limit_source, error, terminal_provider?}` | Circuit breaker fired after N consecutive non-successful attempts. Task auto-blocks with the last error. The effective limit resolves as task `max_retries`, then dispatcher `failure_limit` / `kanban.failure_limit`, then the built-in default. `terminal_provider: true` means the worker exited `78` on a provider error a retry cannot fix (credential revoked, model gone) and the breaker fired on that first attempt, sticky, regardless of the limit. |+| `gave_up` | `{failures, effective_limit, limit_source, error, terminal_provider?}` | Circuit breaker fired after N consecutive non-successful attempts. Task auto-blocks with the last error. The effective limit resolves as task `max_retries`, then dispatcher `failure_limit` / `kanban.failure_limit`, then the built-in default. `terminal_provider: true` means the worker exited `78` on a provider error a retry cannot fix (credential revoked, model gone) — including a startup credential failure that explicitly requires re-login (`hermes auth` / `setup`), which exits `78` before the first turn; other startup failures exit `1` — and the breaker fired on that first attempt, sticky, regardless of the limit. |`hermes kanban tail <id>` shows these for a single task. `hermes kanban watch` streams them board-wide.