Skip to content

fix(agents): stop credentials dying while a session pins them, and say so when they do - #279

Merged
artempartos merged 13 commits into
developfrom
artempartos/harness-cred-refresh-strategy
Sep 17, 2026
Merged

artempartos merged 13 commits into
developfrom
artempartos/harness-cred-refresh-strategy

Conversation

@artempartos

Copy link
Copy Markdown
Contributor

Why

On 2026-09-17 production was read directly, and one chain explains both "Claude auth keeps dropping" and "runs fall off":

  1. A credential is skipped by the refresh sweep and by the launch-time top-up while any active session holds it. ready counts, and an interactive session sits in ready until the 25-hour reaper — against an 8-hour Claude token.
  2. So the token died while pinned, unattempted: refresh_error nil, refresh_failure_count 0, because no refresh was ever tried. Credential 19 was pinned 20 h by session 16739; credential 99 by its own auth session for 20.8 h. Six claude_code logins have since gone permanently invalid_grant.
  3. The next launch handed that dead token to a container, which printed Login expired · Please run /login and produced nothing. The launch gate could not stop it — the row was still active.
  4. The no-output watchdog cancelled the session 30 minutes later: 355 such sessions in 14 days, 138 (41 %) carrying that banner.
  5. CompleteStepActivity fails a step only on session.state == "failed"; the watchdog leaves cancelled, so the step fell through to mark_completed! — 53 step runs completed on a cancelled session, 52 workflow runs reported COMPLETED with 0 sub-steps done.

Separately: only three of seven runtimes could refresh at all, and which ones was a hand-maintained literal.

The design is in docs/design/agent-credential-lifecycle.md.

What this changes

Stop the silent green run (fix(agents): refuse to launch on a login nothing can renew)

  • AgentCredential#unrecoverably_expired? — an expired base login that neither a server-side refresh nor another holder will repair. The preflight and the launch-time top-up both refuse it, with the existing "sign in again" CTA.
  • #base_token_expires_at on the adapter so the verdict reads the login the CLI cannot run without: Claude's designOauth is an add-on, and its lapsing must not refuse launches that would have worked.
  • CompleteStepActivity treats a cancelled session as failed, and fails the step outright when the terminal shows an expired login (AuthErrorDetector, the counterpart of QuotaErrorDetector, matching the banners production logs actually carry).
  • The no-output watchdog names that banner instead of reporting "no output".

One contract per runtime (refactor(agents): declare a credential lifecycle per runtime)

  • Each adapter declares #credential_lifecycle (expiry / refresh owner / rotation / nominal TTL); AgentCredential.refreshable_agent_types is derived from it.
  • A contract test rejects the inconsistent combinations — a server refresh with no expiry (never swept: the cursor_cli NULL-expiry population) or no implementation, an expiry with no implementation, and an expiry nothing can renew that does not declare reauth_required_on_expiry. Grok is that last case: it stores no refresh token at all.

The prod fix: one writer, read-through both ways

  • feat(agents): refresh a pinned token and hand it to its holders — the sweep splits held credentials. Every holder silent for 10 minutes ⇒ refresh, then write the rotated token straight into those containers (Agents::CredentialDelivery). A holder mid-turn still defers; an unreadable container counts as working, never as parked. Delivery writes the token file only — #credential_files, not the whole rendered configuration a delivery has no workflow_config for.
  • feat(agents): report a container-rotated token as it happens — the in-container watcher posts changed auth files to POST /agents/credentials (derived per-session key, adapter-owned paths only, same locked read-merge-write with the rotation guard). A pod killed by an OOM or an eviction no longer takes the rotation with it.

Coverage — feat(agents): refresh Kiro CLI tokens server-side (social refreshToken + Builder ID/IdC CreateToken; the credential is SQLite bytes, edited on a temp copy). Four of seven runtimes now refresh server-side.

Visibility — connection_status gains error ("Sign-in required"), the profile prints the vendor's reason, and crossing into error mails the owner once (AgentCredentialMailer). A condemned credential used to render "Connected".

Images — antigravity-cli joins the CI matrix (it was built by the Makefile and never published, so AGENT_IMAGE_ANTIGRAVITY_CLI had no image to resolve). Every image records its CLI version at /etc/aixle-cli-version — three CLIs install from vendor scripts with no version to pin — and a weekly canary rebuild reports it. The canary publishes only its own tags; it never moves latest.

What this does not settle

  • Whether a CLI re-reads its credential file mid-run is unverified (probe 3 of the broker research). The idle rule is chosen so the answer only has to hold for a session that is asleep.
  • The 10-minute idle probe is an exec per holder per sweep and says nothing about a session that never goes quiet. The durable replacement is the held_until lease in §Layer 2c.
  • Cursor's refresh endpoint still answers 404 HTML, antigravity still has no server-side refresh, and no refresh event log exists yet — each is listed in the doc with what it is blocked on.
  • fix(agents): decide cursor token refresh from the token, and gate launches on it #222 touches the same preflight method; it should land before or after this, not alongside.

Verification

rubocop clean on the whole tree. Targeted suites run in Docker against a throwaway Postgres: agents, models, container strategies, temporal activities, mailers, the new integration test, plus Profile/Show under vitest and tsc --noEmit. The full check_all is CI's — this worktree is outside the compose mount.

New coverage: AuthErrorDetector, the lifecycle contract, the write-back endpoint (auth, rotation guard, path allowlist, body cap, auth-session refusal), and the sweep's held path — the sweep's test moves off mocked relations onto real rows, the canonical runtime fake and a WebMock'd token endpoint.

🤖 Generated with Claude Code

artempartos and others added 13 commits September 17, 2026 22:55
Records what refreshes today (three of seven runtimes), the production chain
measured on 2026-09-17 — an idle `ready` session pins a credential out of the
refresh sweep until its token dies unattempted, and the resulting empty run is
reported COMPLETED — and the layered plan out of it: a declared lifecycle per
adapter, container/server read-through in both directions, refresh
observability, and an image-freshness programme.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
A credential pinned by a live session is skipped by the refresh sweep and by the
launch-time top-up alike, so its token can die with `refresh_error` still nil —
nothing ever attempted a refresh. The launch then handed that dead token to a new
container, which printed "Login expired" and produced nothing until the no-output
watchdog reaped it 30 minutes later. Worse, the step it belonged to still passed:
the watchdog reaches a session through `fail_session`, which for an admitted
session cancels rather than fails, and CompleteStepActivity only failed a step on
`failed`.

Four changes, each on that chain:

* `AgentCredential#unrecoverably_expired?` — an expired base login that neither a
  server-side refresh nor another holder will repair. The session preflight and
  the launch-time top-up both refuse it, with the existing "sign in again" CTA.
* `base_token_expires_at` on the adapter, so the verdict reads the login the CLI
  cannot run without rather than the soonest expiry across every block. Claude's
  designOauth is an add-on: its lapsing must not refuse launches that would work.
* `CompleteStepActivity` treats a cancelled session as a failed one, and fails the
  step outright when the terminal shows an expired login (`AuthErrorDetector`,
  the counterpart of `QuotaErrorDetector` and matching on the banners production
  logs actually carry).
* The no-output watchdog names that banner in its message instead of reporting
  "no output" for what is really a dead credential.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
Which runtimes the refresh sweep touches was a literal — `REFRESHABLE_AGENT_TYPES
= %w[claude_code codex cursor_cli]` — maintained separately from the two methods
that make a refresh work, `#token_expires_at` and `#refresh!`. Nothing tied them
together, so a runtime could ship an expiry it could not act on (a working
credential painted "expired" an hour after login) or a refresh the sweep could
never select, because `refresh_due` filters on a non-null expiry. Both shapes are
in production today.

Each adapter now declares `#credential_lifecycle` — expiry, refresh owner,
rotation, nominal TTL — `AgentCredential.refreshable_agent_types` is derived from
it, and a contract test rejects the inconsistent combinations: a server-side
refresh without an expiry or without an implementation, an expiry with no
implementation, and an expiry nothing can renew that does not declare
`reauth_required_on_expiry`.

Grok is the case that last clause exists for: it stores no refresh token at all,
so its expiry is a re-login instruction, and the launch gate now treats it as one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
`antigravity-cli` was in the Makefile and not in the CI matrix, so nothing ever
published `ghcr.io/aixlehq/flow-antigravity-cli` and the setting that names it had
no image to resolve. It joins the matrix.

Three of these CLIs — claude, cursor, kiro — are installed from a vendor script
with no version to pin, so the same Dockerfile built a month apart is different
software, authentication included, and nothing recorded which build a tag carried.
Each image now writes its CLI version to `/etc/aixle-cli-version`, and a weekly
canary build reports it in the run summary. The canary publishes only its own
dated tags: finding a vendor-side break is its job, moving `latest` is not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
The sweep skipped any credential a live container held, because rotating a grant
invalidates the copy that container runs on. For a session doing work that is the
right call; for one parked at a prompt it meant the token was never refreshed at
all. On 2026-09-17 two production credentials sat pinned for twenty hours by
sessions nobody returned to, and six `claude_code` logins have since gone
permanently invalid — killed by the guard that was protecting them.

The sweep now splits the two cases. A credential whose every holder has been
silent for ten minutes is refreshed, and the rotated token is written straight
into those containers (`Agents::CredentialDelivery`) so the copy they hold is the
live one. A holder mid-turn still defers, and a container that cannot be read
counts as working, never as parked — unknown must not pass for idle.

Delivery writes the token file and nothing else: `#config_files` renders the whole
container configuration from a workflow_config a delivery does not have, so
`#credential_files` is the narrow counterpart (for Claude, `.credentials.json`
alone). A failed delivery is logged, never raised — the refresh is already
persisted, and the container was running on a dying token either way.

What this does not settle is whether a CLI re-reads its credential file without a
restart; the probe is recorded in docs/design/agent-credential-lifecycle.md. The
idle rule is chosen so the answer only has to hold for a session that is asleep.

The activity's test moves off mocked relations onto real rows, the canonical
runtime fake and a WebMock'd token endpoint.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
The CLI inside a container renews its own tokens, and until now the result only
reached us at session cleanup. A container killed by an OOM, an eviction or a lost
node never gets there, so the rotation died with it and the database kept a
refresh token the vendor had already rotated out — which, under reuse detection,
can revoke the whole family rather than fail once.

The watcher now watches the adapter's auth files and posts them to
`POST /agents/credentials` as they change, debounced and rate-floored, skipping a
payload identical to the last one it sent. The endpoint authenticates with a
derived per-session key (`Agents::SessionKey`, the CloudAuth::SessionKey
construction with its own purpose), accepts only paths the agent's adapter names
as its own, and runs the same locked read-merge-write as cleanup — so the
rotation guard still refuses to put an older token back over a newer one.

An auth_setup session is refused: a login in progress is AgentAuthStrategy's to
capture, including the rule that a design re-login must not resurrect a stale
base block.

`Agents::CredentialCapture` is the capture logic lifted out of AgentBaseStrategy
so the cleanup path and the endpoint cannot drift on what a credential is, and
`#auth_file_paths` becomes a BaseAdapter method rather than something callers
test for with respond_to?.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
A credential the refresh sweep had condemned still rendered "Connected" on the
profile: `connection_status` read only the expiry, and a row in `status: error`
whose expiry was nil or in the future fell through to active. Nothing else said
anything either — the OAuth integrations got a mailer in oauth-unification §4.6,
agent logins got none — so the first sign of a dead login was a workflow run that
came back empty.

The status now reports `error` as "Sign-in required", the card spells out what the
vendor said (`refresh_error`, visible rather than behind a hover — without it the
badge is a support ticket), and crossing into error mails the owner once, with
that reason and a link to the profile. `reauth_required` is exposed alongside, so
a runtime that cannot refresh at all reads as a sign-in rather than as something
a sweep will fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
Kiro's login is a SQLite database rather than a JSON document, so it was the one
shipped runtime whose access token simply died an hour after login: the sweep had
nothing to read an expiry from and no endpoint to renew against.

Both renewal paths come off the CLI's own traffic. A social login (Google /
GitHub) renews against Kiro's own refreshToken endpoint, where the refresh token
is the whole request; Builder ID / IAM Identity Center is ordinary AWS SSO OIDC
CreateToken, signed with the client registration stored beside the token and sent
to that registration's region — which need not be the profile's. The row key names
the login family, so it selects the path.

The response is camelCase and the row the CLI reads back is snake_case, so the
refreshed token is translated on the way in, `expiresIn` is resolved to an
absolute instant, and fields the response did not mention are kept — an IdC
refresh returns no new refresh token and must not blank the one that works. The
database is edited on a temp copy and read back as bytes, because the credential
IS those bytes.

Also here, both prerequisites of the above:

* `expiry_ms` moves from GrokAdapter to BaseAdapter — three runtimes now need the
  same ISO8601 / epoch-seconds / epoch-ms normalisation.
* `parse_json` treats nil as {}. JSON.parse(nil) raises TypeError, not the
  ParserError this rescued, and an absent row is an ordinary outcome.

Kiro's declared lifecycle moves with it, from container_only to server, which is
what puts it in the sweep.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
Records the shipped shape where it differs from the sketch: the sweep splits held
credentials by whether their holders are parked rather than waiting on a lease,
and the lease stays as the durable replacement for the per-sweep idle probe.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
A file written through the runtime defaults to uid 0. For a token the CLI has to
rewrite when it rotates next, root ownership leaves it depending on the directory
permissions to replace the file at all — so the delivery writes it as the
container user, the way SessionContextService writes every other agent-owned file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
…t ended badly

The banner's words appear in healthy output too — an agent editing an auth flow,
a CLI's own help text quoted into the pane — and failing a finished step over a
quoted string is worse than the failure this detects. The check now runs inside
the failed/cancelled branch, which is where the production chain lives.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
Production said the proxy could see everything and we were recording none of it.
Across 30 days: `claude_code` produced 621 HTTP logs containing only
`api.anthropic.com`, because `platform.claude.com` — where the CLI renews its own
grant — was not in the tracked domains. `cursor_cli` produced 44 logs of
`api2.cursor.sh` and nothing from `cursor.com`, which is where its auth moved and
where our own server-side refresh has been 404ing since 2026-09-05.
`antigravity_cli` ran 51 sessions and produced zero records, because the adapter
never collected the log at all. Only `kiro_cli` showed its authentication —
`oidc.us-west-2.amazonaws.com/token` and
`prod.us-east-1.auth.desktop.kiro.dev/refreshToken`, which is exactly the protocol
this branch implements, region included.

Widening the capture is only safe after the logger stops writing secrets, so that
comes first. Credential-bearing headers are redacted on every entry — API hosts
carry the access token on *every* request, so those tokens were already being
stored in session logs — and an auth endpoint's bodies are dropped without being
buffered, because a refresh token is the whole grant rather than eight hours of
one. Endpoint, method, status and timing survive; they are what makes a token
lifecycle observable.

Then: the auth hosts join the tracked domains for Claude, Codex and Cursor, and
antigravity_cli starts collecting its proxy log.

`gemini_cli` and `grok` produce no records at all despite the proxy running and
their adapters collecting the path — a client that ignores HTTP(S)_PROXY, which is
its own investigation and is written down rather than guessed at.

The logger lives in the agent images, so its half needs a rebuild; the
tracked-domain changes apply to the next session.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
Rebuilding every agent image from scratch found the Grok one no longer builds.
`@xai-official/grok` 1.0.34 changed its layout three ways: the native payload is
no longer a `@xai-official/grok-linux-*` sibling package, it is unpacked by the
package's own postinstall (as root, the user running `npm install`) rather than by
the agent user's first launch, and the unpacked file carries the version in its
name. The build asserted a fixed path in the agent's home, which nothing writes
any more.

It now asserts what actually proves the install — the payload exists after the
postinstall, and the CLI runs as the agent user. Verified by a full rebuild:
`grok 1.0.34`. What is lost is the guarantee that the decompression was paid at
build time for the agent's home; a session may now pay it once on first launch,
which is written down rather than papered over.

Also: `AGENT_CREDENTIAL_SYNC_URL` gets its row in the configuration reference and
in the docs-portal copy that must match it byte for byte.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
@artempartos
artempartos force-pushed the artempartos/harness-cred-refresh-strategy branch from 9a188bf to fa23b57 Compare September 17, 2026 19:02
@artempartos
artempartos merged commit f87c75d into develop Sep 17, 2026
7 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.

1 participant