Repository navigation
fix(git): per-agent GitHub PAT now propagates to existing containers (#1264) - #1271
Conversation
A per-agent PAT (#347) configured AFTER an agent's container/git was set up never reached the container: the remote stayed templated with an empty password (https://x-access-token:@github.com/...) and every fetch/push failed, while the endpoint told the operator to "restart" — which was a no-op. Root cause: nothing injected GITHUB_PAT into a container that lacked it at creation. Fix (the startup.sh remote self-heal already re-templates the remote when GITHUB_PAT is present — so the whole bug reduces to getting the token into the container env): - set_agent_github_pat now propagates live, no restart: new github_pat_propagation_service.propagate_pat_to_single_agent injects GITHUB_PAT into the running container's .env (ADDING the line when absent — the tokenless case the global-PAT path explicitly skipped) and re-templates the live origin remote via git_service.update_remote_pat. The misleading "restart" note is replaced with the actual outcome. - lifecycle recreate gate relaxed: was `if env_vars.get('GITHUB_PAT')` (skipped tokenless containers forever); now gates on git config so a later-configured PAT is injected on restart, and startup.sh re-templates the remote. - check_github_pat_env_matches: a tokenless container that now has an effective PAT AND git sync configured reports a mismatch, so recreate-driven paths heal. git_service.update_remote_pat reuses the proven init set-url/add pattern and _git_remote_url; best-effort (stopped/no-git agents fall back to the restart path). Tests: tests/unit/test_1264_per_agent_pat_propagation.py (8) — .env add-if-missing, single-agent propagation (stopped short-circuit + running inject/re-template), and the recreate-decision matrix. 45 pass across the PAT suites incl. the sys.modules-mocking siblings (CI collection order). Related to #1264 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| # configured genuinely mismatches desired state — recreation re-injects | ||
| # the token (crud.py) so the remote can authenticate. Without this, a | ||
| # per-agent PAT set after a tokenless creation never reached the env. | ||
| if current_pat and db.get_git_config(agent_name): |
There was a problem hiding this comment.
[high] Over-broad: this fires for the GLOBAL platform PAT, not just a per-agent PAT. get_github_pat_for_agent() falls back to the global platform PAT when no per-agent PAT is set. So once an operator configures a global PAT, EVERY git-configured tokenless agent matches this branch → check_github_pat_env_matches returns False → the agent is force-recreated on its next start (one-time, converges — but disruptive downtime + churn for agents the operator never gave a per-agent token).
That contradicts #211's deliberate decision (github_pat_propagation_service skips agents whose .env lacks GITHUB_PAT — global PAT is never added to tokenless agents) and exceeds #1264's per-agent scope.
Gate the tokenless→recreate decision on the per-agent PAT only:
| if current_pat and db.get_git_config(agent_name): | |
| if db.get_agent_github_pat(agent_name) and db.get_git_config(agent_name): |
(keep the global-PAT refresh of containers that already have the token via the existing container_pat == current_pat path below.)
| # Update GITHUB_PAT using per-agent PAT first, then platform PAT | ||
| if env_vars.get('GITHUB_PAT'): | ||
| # Update GITHUB_PAT using per-agent PAT first, then platform PAT. | ||
| if db.get_git_config(agent_name): # #1264: gate on git config, not GITHUB_PAT presence |
There was a problem hiding this comment.
[high] Same global-PAT overreach on the recreate path. Gating on db.get_git_config(agent_name) + get_github_pat_for_agent() (which includes the global fallback) means a previously-tokenless git-configured container now gets the global PAT injected into its env for the first time on recreate — a credential it never carried. #211 intentionally never does this. To stay scoped to #1264 (per-agent PAT), introduce the token only when a per-agent PAT exists, while still refreshing an already-present token:
| if db.get_git_config(agent_name): # #1264: gate on git config, not GITHUB_PAT presence | |
| if env_vars.get('GITHUB_PAT') or db.get_agent_github_pat(agent_name): # #1264: per-agent PAT, or refresh existing |
Note: this gate MUST stay equivalent to the matcher at helpers.py:464 — if they drift, the matcher can keep returning False while recreate stops injecting → infinite recreate loop. Cross-link them (or share one predicate; see the altitude comment).
| propagation = await propagate_pat_to_single_agent(agent_name, pat) | ||
|
|
||
| if propagation.get("applied"): | ||
| note = "PAT applied to the running agent — git operations will use it immediately." |
There was a problem hiding this comment.
[med] "applied immediately" can be reported when the live remote was NOT fixed. applied = env_updated OR remote_updated (propagation_service:104). The agent's auto-sync pushes via git push origin HEAD and authenticates from the token embedded in remote.origin.url — NOT from GITHUB_PAT env. So the docker-exec git remote set-url (remote_updated) is the load-bearing part of the immediate fix; the .env write only matters on the next restart. If the remote re-template fails (or github_repo is empty) but .env inject succeeds, this prints "git operations will use it immediately" while pushes keep 403-ing until a restart. Base the "immediately" claim on remote_updated, and treat env-only as the "applies on restart" case.
| container_name = f"agent-{agent_name}" | ||
| try: | ||
| git_dir = await _detect_git_dir(container_name) | ||
| url = _git_remote_url(github_pat, github_repo) |
There was a problem hiding this comment.
[low/security] PAT interpolated unescaped into a bash -c string. url embeds the raw PAT (oauth2:<pat>@…, no urllib.parse.quote) and is spliced into bash -c "cd {git_dir} && git remote set-url origin {url} || …". Latent today — set_agent_github_pat validates the PAT against the GitHub API first, so it's a canonical [A-Za-z0-9_] token — but this is an unguarded shell sink (same pre-existing pattern as initialize_github_sync step 3, now extended to a new entry point). Defense-in-depth: shell-quote the command or URL-encode the credential before interpolation.
| """ | ||
| from services import git_service | ||
|
|
||
| running = {a.name for a in list_all_agents_fast() if a.status == "running"} |
There was a problem hiding this comment.
[low/altitude] The "agent needs the PAT" predicate is now re-derived in three places — here, lifecycle.py:385 (recreate gate), and helpers.py:464 (recreate trigger) — each combining (effective PAT + git config) slightly differently (this path also gates the remote on github_repo). Angle-C confirmed the recreate converges only because the matcher and lifecycle gates are currently identical; if they drift, infinite recreate. Extract one agent_needs_pat_injection(agent_name) (and a single effective vs per-agent PAT rule) so the three can't diverge.
| """ | ||
| from services import git_service | ||
|
|
||
| running = {a.name for a in list_all_agents_fast() if a.status == "running"} |
There was a problem hiding this comment.
[low/cleanup] Duplicates the .env read/patch/inject round-trip in _propagate_to_agent (same agent-{name}:8000, /api/credentials/read, _patch_env_github_pat, /api/credentials/inject, same error handling). The only real difference is add-if-missing vs the global path's skip. Collapse into a shared _inject_pat_env(client, agent_name, pat, *, add_if_missing) so the agent-server credentials contract lives in one place — otherwise a future endpoint change must be fixed in both, and missing this path silently reintroduces the #1264 bug.
| container_name = f"agent-{agent_name}" | ||
| try: | ||
| git_dir = await _detect_git_dir(container_name) | ||
| url = _git_remote_url(github_pat, github_repo) |
There was a problem hiding this comment.
[low/cleanup] The set-url/add command duplicates initialize_github_sync step 3 (byte-for-byte git remote get-url origin … && set-url … || add …, same bash -c "cd {git_dir} && …"). Extract _set_origin_remote(container_name, git_dir, url) used by both, so the remote-templating shell lives once. (Also: the docstring references x-access-token:@ while both this code and startup.sh use oauth2: — fix the docstring so a maintainer doesn't "correct" the URL scheme and reintroduce drift.)
|
|
||
| # Re-template the live remote so an existing clone picks up the token now. | ||
| git_config = db.get_git_config(agent_name) | ||
| github_repo = getattr(git_config, "github_repo", None) if git_config else None |
There was a problem hiding this comment.
[low/cleanup] Redundant second get_git_config fetch + getattr masking. The sole caller (set_agent_github_pat) already fetched git_config one statement earlier and 400s if absent, so passing it in avoids a second DB round-trip (and a possible inconsistent read under concurrent edits). getattr(git_config, "github_repo", None) also silently swallows a future field rename — github_repo becomes None, remote_updated stays False, and the PAT silently stops applying to the live remote (the exact "works but doesn't propagate" class #1264 fixes). Use git_config.github_repo directly.
| """ | ||
| from services import git_service | ||
|
|
||
| running = {a.name for a in list_all_agents_fast() if a.status == "running"} |
There was a problem hiding this comment.
[low/perf] Fleet-wide list_all_agents_fast() to check one agent's status. This enumerates every Trinity container + builds an AgentStatus each, just to test whether agent_name is running, on an interactive endpoint. get_agent_container(agent_name) fetches the single container directly — get_agent_container(agent_name) then check .status == "running".
Code review (high-effort, recall-biased) — 9 findingsReviewed across 8 finder angles + cross-file tracing. The core fix is sound and the recreate path provably converges (no loop) — the matcher and lifecycle recreate-gate use identical conditions, so a tokenless container gets the token on its one recreate. Conventions/logging came back clean: I traced the PAT through the new
#1 and #2 are the actionable ones — the fix currently overreaches from "per-agent PAT" to "any git agent when a global PAT exists," which changes behavior for agents #1264 wasn't about. Details inline. |
CI fix: test_propagate_single_agent_running_injects_and_retemplates failed deterministically under all regression-diff seeds. The function resolves `from services.docker_service import get_agent_container` at call time, and sibling tests (test_start_agent_skip_inject / test_inject_assigned_credentials) swap services.docker_service for a Mock in sys.modules — so the test's collection-time module reference was patched on the wrong object and the agent read as not-running. The test now patches get_agent_container on the LIVE sys.modules entry (string target), robust to that pollution. Review findings applied: - [high] Scope the tokenless->token decision to the PER-AGENT PAT, not the global fallback: new shared helpers.needs_per_agent_pat_injection (db.get_agent_github_pat AND db.get_git_config), used by BOTH the recreate matcher (check_github_pat_env_matches) and the lifecycle recreate inject gate so a global-only PAT no longer force-recreates / injects into tokenless agents (#211's opt-in path) and the two gates can't drift (loop-safety). - [med] set_agent_github_pat note keys "applies immediately" on remote_updated (the live git auth source), with a distinct "next restart" message for an env-only update. - [low] shlex.quote the PAT-bearing URL at the docker-exec sink; extract shared git_service._remote_seturl_subcommand (used by init + update_remote_pat) and fix the x-access-token->oauth2 docstrings. - [low] share the agent .env read/patch/inject round-trip via _apply_pat_to_env (global path skips when absent; per-agent path adds). - [low] drop the getattr() field-rename mask (git_config.github_repo direct). - [low] check one container via get_agent_container instead of a fleet-wide list_all_agents_fast enumeration. Tests updated for the per-agent gate + the new dict shape; lint_sys_modules clean (no new violations). Validated alongside the docker_service-mocking siblings: 47 passed. Related to #1264 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two new HEAD failures under the full randomized suite: 1. test_agent_readiness_probe (5 collection errors): lifecycle.py imported the new needs_per_agent_pat_injection at module top via `from .helpers import …`. Sibling tests (test_start_agent_skip_inject / test_inject_assigned_credentials) install a spec-limited Mock as services.agent_service.helpers in sys.modules that lacks the new symbol, so any later module importing lifecycle hit ImportError. Fix: inline the per-agent gate in lifecycle using db (already imported) instead of importing the helper — no new cross-module import to break, and the static-callsite check still passes. helpers.needs_per_agent_pat_injection stays for the matcher; the two are kept in sync by comment. 2. test_propagate_single_agent_running_injects_and_retemplates: the function resolves services.docker_service / services.git_service from sys.modules at CALL time, where siblings swap them for Mocks — so collection-time patch targets missed and the agent read as not-running. Fix: patch those seams via the live module (string targets) and mock _apply_pat_to_env on the bound svc module (the function closes over its globals), dropping the fragile httpx client double. 47 pass alongside the docker_service/helpers-mocking siblings. Related to #1264 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Resolve by running |
…1271) The running-test regression-diff failure persisted because propagate_pat_to_single_agent resolved get_agent_container via a call-time `from services.docker_service import get_agent_container`, which races sibling tests that swap services.docker_service for a Mock in sys.modules under the randomized full suite — the agent then read as not-running (applied=False). Import get_agent_container at the propagation_service module top (a stable global the function closes over), so the test patches it on the bound module — no call-time sys.modules resolution to race. Updated the one stub that needed it (test_github_pat_propagation_unit's fake docker_service) and the test to patch svc.get_agent_container. 47 pass alongside the docker_service/agent_service-mocking siblings. Related to #1264 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vybe
left a comment
There was a problem hiding this comment.
Validated via /validate-pr: P1 bug fix (#1264), security clean, 8 unit + 45 suite tests pass, mergeable on dev. Note for release: author flags no live GitHub-repo E2E (reuses proven primitives) — worth a manual verify. Approving.
Summary
Fixes #1264 — a per-agent GitHub PAT (#347) configured after an agent's container/git was set up never reached the container. The remote stayed templated with an empty password (
https://x-access-token:@github.com/...), everyfetch/pushfailed, and the endpoint's "restart the agent" advice was a no-op. Affected agents silently accumulated 100+ unpushed commits withlast_sync_status: "never".Key insight
startup.shalready re-templatesoriginfromGITHUB_PATon every start (git remote set-url). So the whole bug reduces to one thing: get the PAT into the container env. Three paths failed to do that — this PR fixes all three.Changes
set_agent_github_pat(routers/git.py)propagate_pat_to_single_agentinjectsGITHUB_PATinto the running container's.env(adding the line when absent — the tokenless case the global-PAT path skips) + re-templates the live remote; note reflects the real outcomelifecycle.py:385)if env_vars.get('GITHUB_PAT')— skipped tokenless containers foreverdb.get_git_config(agent_name)so a later-configured PAT is injected on restart; startup.sh then fixes the remotecheck_github_pat_env_matches(helpers.py)New
git_service.update_remote_patreuses the proven initset-url/addpattern +_git_remote_url; best-effort (stopped / no-git agents fall back to the restart path, now fixed).Testing
tests/unit/test_1264_per_agent_pat_propagation.py(8):.envadd-if-missing, single-agent propagation (stopped short-circuit + running inject/re-template with mocked agent HTTP), and the recreate-decision matrix.sys.modules-mocking siblings (test_start_agent_skip_inject,test_inject_assigned_credentials) in CI collection order. The lifecycle static-callsite check (test_github_pat_fallback) still passes.Not covered by unit tests (flagged for reviewers): the end-to-end against a real GitHub repo/PAT (live
.envinject + in-containergit remote set-url→ successful push). The container I/O reuses the already-proveninitialize_github_syncprimitives and the existingstartup.shself-heal, but a manual verification on a real GitHub-native agent is worthwhile before release.Related to #1264