Skip to content

fix(git): per-agent GitHub PAT now propagates to existing containers (#1264) - #1271

Merged
vybe merged 4 commits into
devfrom
fix/1264-per-agent-pat-propagation
Jun 19, 2026
Merged

vybe merged 4 commits into
devfrom
fix/1264-per-agent-pat-propagation

Conversation

@dolho

@dolho dolho commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

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/...), every fetch/push failed, and the endpoint's "restart the agent" advice was a no-op. Affected agents silently accumulated 100+ unpushed commits with last_sync_status: "never".

Key insight

startup.sh already re-templates origin from GITHUB_PAT on 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

Path Before After
set_agent_github_pat (routers/git.py) stored PAT, returned "restart agent" (no-op) live propagation, no restart: 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 skips) + re-templates the live remote; note reflects the real outcome
lifecycle recreate (lifecycle.py:385) if env_vars.get('GITHUB_PAT') — skipped tokenless containers forever gate on db.get_git_config(agent_name) so a later-configured PAT is injected on restart; startup.sh then fixes the remote
check_github_pat_env_matches (helpers.py) tokenless container → "no update needed" tokenless + effective PAT + git configured → mismatch (recreate re-injects)

New git_service.update_remote_pat reuses the proven init set-url/add pattern + _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): .env add-if-missing, single-agent propagation (stopped short-circuit + running inject/re-template with mocked agent HTTP), and the recreate-decision matrix.
  • 45 pass across the PAT suites including the 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 .env inject + in-container git remote set-url → successful push). The container I/O reuses the already-proven initialize_github_sync primitives and the existing startup.sh self-heal, but a manual verification on a real GitHub-native agent is worthwhile before release.

Related to #1264

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread src/backend/services/git_service.py Outdated
container_name = f"agent-{agent_name}"
try:
git_dir = await _detect_git_dir(container_name)
url = _git_remote_url(github_pat, github_repo)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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"}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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"}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread src/backend/services/git_service.py Outdated
container_name = f"agent-{agent_name}"
try:
git_dir = await _detect_git_dir(container_name)
url = _git_remote_url(github_pat, github_repo)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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"}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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".

@dolho

dolho commented Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

Code review (high-effort, recall-biased) — 9 findings

Reviewed 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 logger.warning paths and found no leak (git remote set-url/add never echo the URL; only fetch/clone do, which this command doesn't run).

# Sev File Issue
1 high helpers.py:464 Matcher fires for the global PAT (via get_github_pat_for_agent fallback), so setting a global PAT force-recreates every tokenless git agent. Gate on the per-agent PAT.
2 high lifecycle.py:385 Same overreach on recreate — injects the global PAT into previously-tokenless containers (#211 deliberately never does this). Scope to per-agent PAT; keep this gate ≡ the matcher to preserve loop-convergence.
3 med routers/git.py:603 "applied immediately" can be reported when only .env was written but the live remote (the thing auth actually uses for git push) wasn't re-templated. Base the claim on remote_updated.
4 low git_service.py:192 PAT interpolated unescaped into a bash -c string (latent — PAT is GitHub-validated/canonical, but an unguarded shell sink).
5 low propagation_service.py:73 The "needs PAT" predicate is re-derived in 3 places that must stay identical (loop risk if they drift) — unify into one helper.
6 low propagation_service.py:73 .env read/patch/inject duplicates _propagate_to_agent; share it.
7 low git_service.py:192 set-url command duplicates initialize_github_sync step 3; extract a helper. Also fix the x-access-token: docstring (code uses oauth2:).
8 low propagation_service.py:97 Redundant 2nd get_git_config fetch + getattr masking a possible field rename.
9 low propagation_service.py:73 Fleet-wide list_all_agents_fast() to check one agent — use get_agent_container(name).

#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.

dolho and others added 2 commits June 19, 2026 13:33
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]>
@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

…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]>
@dolho
dolho requested a review from vybe June 19, 2026 11:07

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@vybe
vybe merged commit 6e74dc0 into dev Jun 19, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants