Skip to content

fix(agents): decide cursor token refresh from the token, and gate launches on it - #222

Closed
Hitin wants to merge 7 commits into
AixleHQ:developfrom
Hitin:feature/cursor-token-refresh-from-token
Closed

Hitin wants to merge 7 commits into
AixleHQ:developfrom
Hitin:feature/cursor-token-refresh-from-token

Conversation

@Hitin

@Hitin Hitin commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Completed Cursor CLI sessions could show — for Tokens and Cost on a run that looked healthy. The meter was fine; the credential it authenticated with was dead, and nothing in the system could tell.

A stored accessToken with exp = 2026-07-31 was still being handed out on 2026-09-07. The session worked anyway — the CLI inside the container hits its own 401 and re-authenticates by device login — so only server-side calls made with the stored token broke, Cursor's usage Dashboard API among them. The run finished COMPLETED, with a duration and no usage.

The credential was active the whole time. SessionService#preflight_agent_credential! gated the launch on status, i.e. on whether the refresh sweep had already marked the row broken — and the sweep never selected it, because scope :refresh_due filters where.not(expires_at: nil) and this row's expires_at was NULL. Never selected → never refreshed → never mark_refresh_error!'d → still active. Preflight had nothing to look at.

The fix

One condition, at the launch gate:

credential = AgentCredential.find_by(user_id: user.id, company_id: company.id, agent_type: agent_type)
return if credential.nil?

raise AgentCredential::PreflightError, credential unless credential.active?
raise AgentCredential::PreflightError, credential if credential.agent_type == "cursor_cli" &&
                                                     credential.expires_at.nil?

A cursor_cli accessToken is a JWT carrying its own exp; CursorCliAdapter#token_expires_at has parsed it since well before this branch; and

before_save :sync_expires_at, if: :will_save_change_to_encrypted_config_data?

derives the column from it on every write of config_data — creation, re-auth, a refresh, and the merge-back in AgentSessionStrategy#persist_refreshed_credentials. So for this agent a NULL expiry never means "this login has no expiry", as it legitimately does for an API-key or Bedrock claude_code credential. It can only mean nobody derived it.

That is the exact state of the production row this PR was opened for — status: active, expires_at IS NULL — so it is refused at the gate, with the existing AgentCredential::PreflightError and its "sign in again" CTA, and the auth_setup exemption preserved. No network was added to the preflight path, matching Oauth::Preflight and CloudAuth::Preflight.

It also makes the affected population finite rather than an open class of bug: a refused launch sends the user to re-auth, re-auth writes config_data, and the column heals. The set is the rows whose config_data has not been written since that callback landed — which matches the "expired weeks earlier" in the incident.

What this gives up, explicitly

  1. A NULL-expiry row whose token is still alive is refused, not launched. For a person that is one unnecessary re-auth. For a workflow step it is worse: preflight_agent_credential! also runs for automated runs and LaunchStepSessionActivity wraps PreflightError in a non-retryable Temporal ApplicationError, so such a run dies rather than self-healing. Cursor grants die at 60 days and these rows have not been written since July, so the population is expected to be small — but it is not zero.
  2. A populated-but-past expiry is not refused at the gate. Such a row is inside the sweep's window and is condemned there instead, which takes MAX_REFRESH_FAILURES = 3 ticks (~15 min on */5).
  3. Nothing is repaired server-side. The population drains through users re-authenticating, not through a sweep pass.

Do not pair this condition with a backfill of expires_at. A backfill writes a past timestamp for a dead token, which removes the NULL the condition relies on; the row then launches and waits ~15 min for the sweep to condemn it. The condition and a backfill are alternatives, not complements.

Divergence from the task's acceptance criteria, for the record. The task asked for two parts. Part 1 — the adapter decides its own refresh from the token, a NULL-expiry row reaches it through a production caller, an unreadable exp means refresh, the margin_ms is ignored comment removed — is gone in full after review, and that comment is back verbatim by request. Part 2 survives as the single condition above. codex_adapter.rb untouched, the one Part 1 constraint that held, is still true.

Considered and removed: CursorCliAdapter#refresh! honouring margin_ms

An earlier revision made the adapter decide for itself, the way ClaudeCodeAdapter#refresh! decides from its OAuth blocks:

def refresh!(credential, margin_ms: REFRESH_MARGIN_MS)
  exp = token_expires_at(credential.config_data).to_i
  return { status: :not_needed, detail: nil } if exp.positive? && (exp - now_ms) > margin_ms

It is out, after review, and base_adapter.rb, cursor_cli_adapter.rb and cursor_cli_adapter_test.rb are byte-identical to develop — including the honest marker on the ignored argument:

# margin_ms is ignored: this agent stores no per-block expiry to compare it
# against, so a call is already the decision to refresh.
def refresh!(credential, margin_ms: nil) # rubocop:disable Lint/UnusedMethodArgument

Three reasons, none of them about the incident:

  1. It protected nothing reachable. Both callers select rows by the expires_at column before the adapter is consulted — .refresh_due(15.minutes) and #expiring_within?(60.minutes) — so nothing reaches #refresh! that is not already inside its own margin. The :not_needed branch could only fire when the column and the token disagree, which today needs a hand-edited expires_at. A real scenario, but not this PR's, and it was costing 66 lines of test.
  2. The BaseAdapter doc rewrite that came with it stated a rule its main implementer breaks. The paragraph said an expiry the adapter cannot read is never "never expires" and must be refreshed. ClaudeCodeAdapter#refresh! deliberately does the opposite (next unless exp.positive? && ...), because for Claude a missing expiresAt means the block is not an OAuth login at all. Each rule is right for its own agent; written in the base class as a general contract, it mis-teaches whoever implements the next adapter.
  3. It removed BaseAdapter#now_ms. That helper's only caller was the reverted line, while the identical expression stays inline in ClaudeCodeAdapter#refresh! as a local variable shadowing the inherited method of the same name.

Honouring the argument is still the better interface and still worth doing: the launch path passes SESSION_REFRESH_THRESHOLD (60 minutes) into an argument that is discarded, so "refresh if it dies within the hour" means "refresh unconditionally", and rotating a single-use grant that has hours left is not free. Doing it properly means doing it for codex at the same time and deciding, per adapter, what an unreadable expiry means — which is exactly what reason 2 shows cannot be compressed into five lines of base-class doc. Its own task, with its own evidence.

Known limitation, not addressed here

The :held path produces this incident's exact symptom and is untouched: when a live container holds the credential, the sweep skips the row and AgentSessionStrategy#refresh_expiring_credential! logs with #{left || '?'}m of token life and starts on the stored copy. claude_code has the same hole. It needs its own task.

Separately, refresh_cursor_token! sees the server's verdict and drops it into a log line, so #refresh! can never return permanent: true — which leaves refresh_expiring_credential!'s raise AgentCredential::PreflightError, credential if permanent unreachable for this agent, and AgentCredential.permanent_failure?'s documented invalid_grant text fallback matching neither cursor_cli nor codex. Also its own task.

Scope

cursor_cli only. codex_adapter.rb and codex_adapter_test.rb are unchanged — that agent shows the same margin_ms-ignoring shape, but this incident did not happen on it and it has auth modes Cursor does not (an OPENAI_API_KEY-only credential has no JWT to read), so it is left for its own task with its own regression evidence.

agent_credential.rb, refresh_expiring_tokens_activity.rb, base_adapter.rb and cursor_cli_adapter.rb are also unchanged, after two rounds of review. The first revision added TOKEN_DERIVED_REFRESH_AGENT_TYPES, an OR branch in .refresh_due, #refresh_worth_attempting? and a BaseAdapter#credential_unusable_reason hook, so a NULL-expiry row would reach the adapter through the sweep. All of it was removed: it is a permanent code branch guarding a population that drains on its own, and the hook decrypted config_data and parsed a JWT at every launch to answer what the column — derived from the same call, in the same transaction — already answers for the only adapter that implemented it. The second revision was the margin_ms change above.

What is left in production code is eight lines in one method. The PR went 8 files / +553 −20 → 5 files / +226 −13 → 2 files / +113 −5.

The collect_usage correlation-window work from #192, persist_refreshed_credentials not picking up an in-container device login, token→cost conversion, and the container-side BaseAdapter#credential_preflight hook are all out of scope.

Related issues

Refs AixleHQ/flow#192 (closed unmerged) — this replaces that PR's expiry_unknown + #backfill_expires_at! approach rather than layering on it. That approach repairs the column for rows that already have a readable exp; it leaves backfill_expires_at! returning nil when token_expires_at yields nothing (so such a row stays NULL), and expiry_unknown.find_each re-decrypting those unresolvable rows on every 5-minute tick forever. It is also the backfill this condition must not be paired with — see above.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Refactor / chore
  • Breaking change

How was this tested?

New tests, all behaviour-level:

  • test/services/session_service_test.rb — the exact production row (cursor_cli, status: active, expires_at IS NULL) → refused, with no session created; a cursor_cli credential whose expiry is derived but past → launches, left to the sweep and to provisioning; a healthy cursor_cli credential → launches; an auth_setup session on a NULL-expiry row → launches; regression: a claude_code API-key credential, which legitimately has no expiry to derive, → launches.

Verified in CI, not locally. This session had no Docker and no Ruby, so make check_all could not run here. The full suite was therefore run through the same reusable code-check.yml on the exact head commit of this branch, dispatched in the fork: Hitin/flow run 35100710078 (head_sha eba3ddf4). The set of evaluating jobs is identical for pull_request and workflow_dispatch in ci.yml (be-checks, fe-checks, secret-scan); only build-cache and coverage-badges differ, and both are gated on github.event_name == 'push'.

This PR's own checks are held at action_required until a maintainer approves workflow runs from the fork.

Checklist

  • I read CONTRIBUTING.md.
  • All my commits are signed off for the DCO (git commit -s).
  • I have signed (or will sign) the CLA when the bot prompts me — or my
    organization has executed the Corporate CLA.
  • make check_all passes — run in CI rather than locally (no Docker/Coder in this environment); see above.
  • I added/updated tests where it makes sense.
  • I updated documentation where it makes sense.
  • My commits use clear, descriptive messages.

🤖 Generated with Claude Code

aixle-developer-agent added 2 commits September 9, 2026 12:58
`agent_credentials.expires_at` is written only when config_data is written, and
config_data is routinely written only by a refresh — so a row whose expiry was
never derived sat in a closed loop: NULL reads as "never expires" in
`refresh_due` and `#expiring_within?`, so it was never selected, never
refreshed, never written, and stayed NULL. Nothing complained, and the stored
token died where only server-side callers could see it (the Cursor usage
Dashboard API among them, which is why completed sessions showed no tokens and
no cost while the CLI in the container quietly re-authenticated against its own
401).

CursorCliAdapter and CodexAdapter already knew how to read the JWT `exp` in
`#token_expires_at` and threw that away in `#refresh!`. Both now honour
`margin_ms` and derive the decision from the stored token, the way
ClaudeCodeAdapter does from its OAuth blocks, which makes the column an
optimisation for row selection instead of the only gate.

An `exp` that cannot be read is deliberately NOT "never expires" — the token
still dies with its grant — so it means refresh, never skip.
…al status

`preflight_agent_credential!` asked only whether the refresh sweep had already
marked the credential broken. The sweep only selects rows with a non-NULL
`expires_at`, so a credential whose expiry was never derived is never selected,
never marked, and stays `active` however dead its token is — preflight had
nothing to look at and the session launched, ran, and produced a duration with
no usage.

It now also asks the adapter holding the token, mirroring
`CloudAuth::Preflight.unusable_reason`: an expired stored token, or one whose
expiry cannot be read, is refused with the existing PreflightError and its
"sign in again" CTA. Unreadable counts as expired for the same reason
CloudAuth::Preflight treats unparseable dates as past — prompting a reconnect
beats handing a session a credential nothing can refresh.

No network is added to the preflight path, and the answer is opt-in per adapter
(BaseAdapter returns nil), so an API-key or Bedrock login — which legitimately
carries no readable expiry — is unaffected. The auth_setup exemption stays: it
exists to replace the very credential being checked.
@Hitin
Hitin marked this pull request as draft September 9, 2026 13:28
Comment thread app/services/agents/codex_adapter.rb Resolved
aixle-developer-agent and others added 2 commits September 9, 2026 14:07
Review feedback on AixleHQ#222: task #1649 puts codex_adapter.rb
explicitly out of scope, so codex_adapter.rb and its test are restored to
develop.

Codex carries the same margin_ms-ignoring shape, but this incident did not
happen on it and there is no regression evidence for it here. It also has
auth modes Cursor does not — an OPENAI_API_KEY-only credential has no JWT to
read — so the "unreadable exp means refresh" rule lands differently there and
deserves its own reasoning. Keeping a credential-lifecycle change to one
runtime per PR also means reverting the Cursor rollout would not revert Codex.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d tokens

Review feedback on AixleHQ#222, two threads.

1. The adapter-side decision was unreachable for the rows this fix is about.
Both production callers gated on the denormalised expires_at column before
consulting an adapter: `AgentCredential.refresh_due` filtered
`where.not(expires_at: nil)` and `#refresh_if_expiring!` returned :not_needed
via `#expiring_within?`, which is false for NULL. So a row whose expiry was
never derived stayed in its closed loop and `#refresh!` was never called —
the observable effect of the previous commit was only that the sweep did less
work on healthy rows.

Both gates now let a NULL-expiry row through, but only for the agent types
whose adapter derives the expiry from the token itself and answers :not_needed
when there is nothing to do (AgentCredential::TOKEN_DERIVED_REFRESH_AGENT_TYPES
— cursor_cli). An adapter that refreshes on every call must not be listed:
selecting its NULL rows would rotate a live grant every five minutes.
Coverage moved up a level accordingly — the adapter test that called
`#refresh!` directly is replaced by `.refresh_due` and `#refresh_if_expiring!`
tests on a row with `expires_at IS NULL`.

2. The preflight condemned credentials that were still recoverable.
`CursorCliAdapter#credential_unusable_reason` now passes any credential that
still holds a refreshToken, matching the two precedents it cites:
`Oauth::Preflight.usable?` (`!cred.expired? || cred.refreshable?`) and
`CloudAuth::Preflight.unusable_reason` ("reauthorization_required" only when
the refresh token is blank AND the expiry is past). An expired accessToken
with a live refreshToken is rotated at provisioning by
`AgentSessionStrategy#refresh_expiring_credential!` a few steps after the
gate, so refusing it sent the user to a re-authentication they did not need —
and for a workflow step it was worse: `LaunchStepSessionActivity` wraps
PreflightError in a non-retryable Temporal ApplicationError, killing a run
that self-heals today. The strict reading is kept for what nothing can
rescue: expired or unreadable with no refresh token.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Hitin
Hitin marked this pull request as ready for review September 10, 2026 06:06
@Hitin Hitin changed the title fix(agents): decide cursor/codex token refresh from the token, and gate launches on it fix(agents): decide cursor token refresh from the token, and gate launches on it Sep 10, 2026
@Hitin

Hitin commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

[Must] Source: AgentCredential#sync_expires_at and CursorCliAdapter#token_expires_at, both unchanged on this branch; AgentSessionStrategy#refresh_expiring_credential!; LaunchStepSessionActivity.

The diagnosis in this PR is right, and the two review rounds above landed in the right place on both of the trade-offs raised. My concern is not correctness but size: I think the incident is closed by a single condition, and that the machinery around it is paying for a loop that is already closed elsewhere.

Concretely, I would like this PR reduced to:

# app/services/session_service.rb
       credential = AgentCredential.find_by(user_id: user.id, company_id: company.id, agent_type: agent_type)
-      return if credential.nil? || credential.active?
-
-      raise AgentCredential::PreflightError, credential
+      return if credential.nil?
+
+      raise AgentCredential::PreflightError, credential unless credential.active?
+      raise AgentCredential::PreflightError, credential if credential.agent_type == "cursor_cli" &&
+                                                           credential.expires_at.nil?

A cursor_cli accessToken is a JWT carrying its own exp, and #sync_expires_at
derives the column from it on every write of config_data — so for this agent a NULL
expiry never means "this login has no expiry", as it legitimately does for an API-key
or Bedrock claude_code credential. It only ever means nobody derived it. The reasoning
belongs in the PR body and the commit message rather than in the service.

That is the exact state of the production row this PR was opened for — status: active, expires_at IS NULL — so it is refused at the gate, with the existing PreflightError and its "sign in again" CTA, and the auth_setup exemption preserved.

Why the rest is not carrying weight

The closed loop has an exit the summary does not mention. sync_expires_at derives the column from the token on every write of config_data:

before_save :sync_expires_at, if: :will_save_change_to_encrypted_config_data?

and CursorCliAdapter#token_expires_at has parsed the JWT exp since well before this branch. So creation, re-auth, a refresh, and the merge-back in AgentSessionStrategy#persist_refreshed_credentials all populate expires_at today. A NULL expiry on a cursor_cli row is therefore not an open class of bug but a finite set — rows whose config_data has not been written since that callback landed, which matches the "expired weeks earlier" in the incident. TOKEN_DERIVED_REFRESH_AGENT_TYPES, #refresh_worth_attempting?, the OR branch in .refresh_due and the two call-site changes in #refresh_if_expiring! are a permanent code branch guarding a population that drains on its own: a refused launch sends the user to re-auth, re-auth writes config_data, and the column heals.

The adapter hook answers a question the column already answers, for cursor_cli. #credential_unusable_reason decrypts config_data and parses a JWT at every launch. The column is derived from that same call, in the same transaction as the token, so for this agent the two cannot disagree except when the column was never derived — which is the case the one condition tests. The hook's generality is real for claude_code, where a NULL expiry legitimately means an API-key or Bedrock login, but that is exactly why BaseAdapter has to return nil there: the only adapter that implements it is the one whose column can be trusted.

refresh_expiring_tokens_activity.rb is comment-only (+9 / −3, no code), so it drops out with the scope change.

The margin-honouring #refresh! is defensible on its own merits and harmless to keep — it makes refresh! safe to call without a caller-side gate — but it is not load-bearing here either: both callers still gate on the column, so the adapter is only reached for rows already inside the window.

What this gives up, explicitly

I would rather state the cost than have it discovered later.

  1. A NULL-expiry row whose token is still alive is refused, not launched. For a person that is one unnecessary re-auth. For a workflow step it is worse: LaunchStepSessionActivity wraps PreflightError in a non-retryable Temporal ApplicationError, so a run dies where the allowlist version would have refreshed and continued. Given Cursor grants die at 60 days and these rows have not been written since July, I expect that population to be small — but it is not zero, and the decision should be made with that in view.
  2. A populated-but-past expiry is no longer refused at the gate. "token_expired" goes away as a launch-time verdict; such a row is condemned by the sweep instead, which takes MAX_REFRESH_FAILURES = 3 ticks (~15 min on */5) to reach status: :error.
  3. Nothing is repaired server-side. The population drains through users re-authenticating rather than through a sweep pass.

One interaction to avoid

Do not pair this condition with a backfill of expires_at unless the adapter also learns to report a permanent failure. A backfill writes a past timestamp for a dead token, which removes the NULL the condition relies on; the row then launches and waits ~15 min for the sweep to condemn it. The condition and a backfill are alternatives, not complements.

Two follow-ups worth their own tasks

  • refresh_cursor_token! sees the server's verdict and drops it into a log line, so #refresh! can never return permanent: true. That leaves an existing launch abort unreachable for this agent — refresh_expiring_credential! already has raise AgentCredential::PreflightError, credential if permanent, and claude_code reaches it via request_oauth_refresh's invalid_grant branch. AgentCredential.permanent_failure?'s documented text fallback ("the invalid_grant text is the fallback for single-block agents") currently matches neither cursor_cli nor codex.
  • The :held path produces this incident's exact symptom and is untouched by either version of this PR: when a live container holds the credential, the sweep skips the row and refresh_expiring_credential! logs with #{left || '?'}m of token life and starts on the stored copy. claude_code has the same hole. Worth naming in the PR description as a known limitation.

aixle-developer-agent added 2 commits September 16, 2026 12:42
Review asked for the PR to be cut back to the single condition that closes the
incident, and the machinery around it removed. This does that.

The gate is now, in preflight_agent_credential!:

    raise AgentCredential::PreflightError, credential unless credential.active?
    raise AgentCredential::PreflightError, credential if credential.agent_type == "cursor_cli" &&
                                                         credential.expires_at.nil?

Why the column is trustworthy enough to be the whole test for this agent: a
cursor_cli accessToken is a JWT carrying its own `exp`, CursorCliAdapter#token_
expires_at has parsed it since well before this branch, and

    before_save :sync_expires_at, if: :will_save_change_to_encrypted_config_data?

derives the column from it on EVERY write of config_data — creation, re-auth, a
refresh, and the merge-back in AgentSessionStrategy#persist_refreshed_credentials.
So for cursor_cli a NULL expiry never means "this login has no expiry", as it
legitimately does for an API-key or Bedrock claude_code credential. It can only
mean nobody derived it. That is the exact state of the production row this PR was
opened for: status active, expires_at IS NULL, token dead since July.

It also makes the population finite rather than an open class of bug: a refused
launch sends the user to re-auth, re-auth writes config_data, and the column
heals. Removed accordingly, as a permanent branch guarding a draining set:

  - AgentCredential::TOKEN_DERIVED_REFRESH_AGENT_TYPES, the OR branch in
    .refresh_due, #refresh_worth_attempting? and the two call sites in
    #refresh_if_expiring! — agent_credential.rb is back to develop byte for byte;
  - BaseAdapter#credential_unusable_reason and the CursorCliAdapter override that
    implemented it: the hook decrypts config_data and parses a JWT at every
    launch to answer what the column, derived from the same call in the same
    transaction, already answers for the only adapter that implements it;
  - the comment-only change to refresh_expiring_tokens_activity.rb, which drops
    out with the scope.

Kept: the margin-honouring CursorCliAdapter#refresh!. It is not load-bearing here
— both callers still select rows by the column, so the adapter is only reached
for rows already inside the window — but it makes #refresh! safe to call without
a caller-side gate and stops it burning a single-use grant on a token with hours
of life left. The misleading "margin_ms is ignored" comment and its
rubocop:disable go with it, and an exp it cannot read still means refresh, never
skip.

What this gives up, deliberately:

  1. A NULL-expiry row whose token is still alive is refused rather than
     launched. One unnecessary re-auth for a person; for a workflow step,
     launch_step_session_activity wraps PreflightError in a non-retryable
     Temporal ApplicationError, so a run dies where it would have self-healed.
     Cursor grants die at 60 days and these rows have not been written since
     July, so the population is expected to be small — not zero.
  2. A populated-but-past expiry is no longer refused at the gate. Such a row is
     inside the sweep's window and is condemned there instead, after
     MAX_REFRESH_FAILURES = 3 ticks (~15 min on */5).
  3. Nothing is repaired server-side; the population drains through re-auth.

Do not pair this condition with a backfill of expires_at: a backfill writes a
past timestamp for a dead token, removing the NULL the condition relies on. They
are alternatives, not complements.

codex_adapter.rb remains untouched.
@Hitin

Hitin commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Addressed — the PR is reduced to the single condition. Head is now 597212a7.

preflight_agent_credential! is exactly the diff you wrote:

raise AgentCredential::PreflightError, credential unless credential.active?
raise AgentCredential::PreflightError, credential if credential.agent_type == "cursor_cli" &&
                                                     credential.expires_at.nil?

The reasoning moved to the PR body and the commit message; the service keeps a short note on why a NULL expiry means something different for this agent, and points at the description for the incident.

Removed, as a permanent branch guarding a draining population:

  • TOKEN_DERIVED_REFRESH_AGENT_TYPES, the OR branch in .refresh_due, #refresh_worth_attempting? and both #refresh_if_expiring! call sites — app/models/agent_credential.rb is back to develop byte for byte;
  • BaseAdapter#credential_unusable_reason and the CursorCliAdapter override — you're right that for the only adapter implementing it the column is derived from the same call in the same transaction, so the hook was re-answering a question the column already answers, at a decrypt and a JWT parse per launch;
  • the comment-only change to refresh_expiring_tokens_activity.rb, which drops out with the scope;
  • the four model tests and four adapter tests that covered them.

Kept the margin-honouring #refresh!, on your "harmless to keep" — with its doc rewritten, since it claimed a reachability that no longer holds and referenced the constant that is gone. It now says plainly that both callers still select by the column, so this does not widen what gets refreshed; it just makes #refresh! safe to call without a caller-side gate and stops it burning a single-use grant on a token with hours of life left.

Diff: 8 files / +553 −20 → 5 files / +226 −13. codex_adapter.rb untouched throughout.

All three costs are now stated in the PR body verbatim as you listed them — the refused-but-alive NULL row (and the non-retryable ApplicationError that makes it worse for a workflow step), "token_expired" disappearing as a launch-time verdict, and nothing being repaired server-side. The body also carries your warning that this condition and a backfill of expires_at are alternatives, not complements; there is no backfill in the PR.

Tests were rebuilt around the one condition, in session_service_test.rb: the exact production row (cursor_cli, active, expires_at IS NULL) → refused with no session created; a cursor_cli row whose expiry is derived but past → launches, i.e. cost 2 above is pinned rather than implied; healthy → launches; auth_setup on a NULL-expiry row → launches; and a claude_code API-key credential, which legitimately has no expiry to derive, → launches.

The :held path is named as a known limitation in the description, with the left || '?' detail, and both of your follow-ups are filed as their own tasks rather than carried here.

One thing to flag: this drops the task's Part 1 acceptance bullet "a cursor_cli credential with expires_at IS NULL is refreshed through a production caller" — that bullet was precisely what .refresh_due and #refresh_worth_attempting? satisfied. Taking your call over the description, and it is written down in the body so it isn't discovered later.

Full suite green on this exact commit — https://github.com/Hitin/flow/actions/runs/35097726641 (head_sha 597212a7): Backend Checks (be_check_all), Frontend Checks (fe_check_all), Secret Scan all ✅. upstream/develop was also merged in first (643edc8c → 064a48d0), cleanly.

@Hitin

Hitin commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

[Recommendation] Source: ClaudeCodeAdapter#refresh! on this branch; AgentCredential.refresh_due / #expiring_within?, both back to develop after 597212a7.

Thanks for the reduction — and for pinning cost 2 with a test rather than leaving it in the description. Two more things to take out, and the first is me taking back my own "harmless to keep".

1. Drop the margin_ms change too

It no longer protects anything reachable. With the allowlist gone, both callers select by the column before the adapter is consulted — .refresh_due(15.minutes) and #expiring_within?(60.minutes) — so nothing reaches #refresh! that is not already inside its own margin. The :not_needed branch can only fire when the column and the token disagree, which today needs a hand-edited expires_at (the Administrate dashboard permits the attribute). That is a real scenario, but it is not this PR's, and test/services/agents/cursor_cli_adapter_test.rb is 66 lines covering it.

The BaseAdapter doc rewrite that comes with it states a rule its main implementer breaks. This is the part I should have caught in the first pass:

# @param margin_ms [Integer, nil] how close to expiry a token must be to be worth
#   refreshing. ... An expiry the adapter cannot
#   read is NOT "never expires": the token still dies with its grant, so such a
#   credential must be refreshed, never skipped.

ClaudeCodeAdapter#refresh! does the opposite, deliberately:

exp = block["expiresAt"].to_i
next unless exp.positive? && (exp - now_ms) <= margin_ms   # unreadable exp → skip

Both are right for their own agent — for Claude a missing expiresAt means the block is not an OAuth login at all, so there is nothing to refresh. But the rule is written in the base class as a general one, and the next person to add an adapter will read it as the contract and get it backwards. Reverting the paragraph makes the original text true again, since Cursor stops honouring the argument.

It also removes BaseAdapter#now_ms and with it a shadowing. After this revision that helper has exactly one caller — cursor_cli_adapter.rb:193 — while the identical expression it was meant to share stays inline in ClaudeCodeAdapter#refresh!:

# claude_code_adapter.rb:241
now_ms  = (Time.current.to_f * 1000).to_i

a local variable shadowing the inherited method of the same name. Legal, but a reader of refresh! cannot tell which one line 252 resolves to. Dropping margin_ms deletes the helper's only caller, so the helper goes with it and the question never arises.

What is given up. Honouring margin_ms is the better interface: the launch path passes SESSION_REFRESH_THRESHOLD (60 minutes) and that value is discarded today, so a caller asking "refresh if it dies within the hour" gets "refresh unconditionally" — and an unnecessary rotation of a single-use grant is not free, as the without_live_session comment explains. Worth fixing. It is just not this PR's subject, has no observed failure behind it, and doing it properly probably means doing it for codex at the same time and deciding what an unreadable expiry means per adapter — which is the reasoning the BaseAdapter paragraph tried to compress into five lines and got wrong for Claude.

2. Put the preflight_agent_credential! doc back

The nine explanatory lines added above the method belong in the PR description and the commit message, which already carry them. One sentence does have to change, though — a straight revert would leave the comment describing the method incorrectly, since the new condition refuses credentials the sweep has not marked:

-    # Block a launch whose agent credential the refresh sweep has marked broken, so
-    # the user gets "sign in again" instead of a container that fails on an expired
-    # token.
+    # Block a launch whose agent credential is broken, so the user gets "sign in again"
+    # instead of a container that fails on an expired token.
     #
     # An auth_setup session is exempt: it exists to REPLACE the broken credential,
     # so gating it on that credential locks the user out of the only flow that can
     # clear the error.

That drops, among the rest, # No network, matching Oauth::Preflight and CloudAuth::Preflight. — the contract for an adapter method that decrypted credentials at every launch. Reading an expires_at column raises no network question, so the line no longer tells a reader anything.

Resulting PR

base_adapter.rb and cursor_cli_adapter.rb back to develop — including the honest marker on the ignored argument:

# margin_ms is ignored: this agent stores no per-block expiry to compare it
# against, so a call is already the decision to refresh.
def refresh!(credential, margin_ms: nil) # rubocop:disable Lint/UnusedMethodArgument

Which leaves the whole production change as:

    # Block a launch whose agent credential is broken, so the user gets "sign in again"
    # instead of a container that fails on an expired token.
    #
    # An auth_setup session is exempt: it exists to REPLACE the broken credential,
    # so gating it on that credential locks the user out of the only flow that can
    # clear the error.
    def preflight_agent_credential!(user, company, agent_type, session_type: nil)
      return if session_type == "auth_setup"
      return unless agent_type.present? && company.present?

      credential = AgentCredential.find_by(user_id: user.id, company_id: company.id, agent_type: agent_type)
      return if credential.nil?

      raise AgentCredential::PreflightError, credential unless credential.active?
      raise AgentCredential::PreflightError, credential if credential.agent_type == "cursor_cli" &&
                                                           credential.expires_at.nil?
    end

Two files — session_service.rb and session_service_test.rb — from the eight this started at.

…t condition

Second reduction of this PR, following the maintainer's [Recommendation] on
AixleHQ#222. What is left in production code is one condition in
`preflight_agent_credential!`; `base_adapter.rb`, `cursor_cli_adapter.rb` and
`cursor_cli_adapter_test.rb` are byte-identical to `develop` again.

Why the margin_ms change goes, even though honouring the argument is the better
interface:

* It no longer protects anything reachable. With the agent-type allowlist gone
  from `AgentCredential`, both callers select rows by the denormalised
  `expires_at` column before the adapter is consulted -- `.refresh_due(15
  .minutes)` and `#expiring_within?(60.minutes)` -- so nothing reaches
  `#refresh!` that is not already inside its own margin. The `:not_needed`
  branch can only fire when the column and the token disagree, which today
  needs a hand-edited `expires_at`. A real scenario, but not this PR's, and it
  was costing 66 lines of test.

* The `BaseAdapter` doc rewrite that came with it stated a rule its main
  implementer breaks. The paragraph said an expiry the adapter cannot read is
  never "never expires" and must be refreshed; `ClaudeCodeAdapter#refresh!`
  deliberately skips such a block, because for Claude a missing `expiresAt`
  means the block is not an OAuth login at all. Each rule is right for its own
  agent, but it was written in the base class as a general contract, where the
  next adapter author would read it backwards.

* It removes `BaseAdapter#now_ms`, whose only caller this was, while the
  identical expression stays inline in `ClaudeCodeAdapter#refresh!` as a local
  variable shadowing the inherited method of the same name.

Honouring `margin_ms` is still worth doing: the launch path passes
`SESSION_REFRESH_THRESHOLD` (60 minutes) and that value is discarded today, so
a caller asking "refresh if it dies within the hour" gets "refresh
unconditionally", and an unnecessary rotation of a single-use grant is not
free. Doing it properly means doing it for `codex` at the same time and
deciding per adapter what an unreadable expiry means -- which is exactly the
reasoning the reverted paragraph tried to compress into five lines and got
wrong for Claude. It belongs in its own task, with its own evidence.

The nine explanatory lines above `preflight_agent_credential!` also go: they
live in the PR description and in the commit message of 597212a, which is
where the argument belongs. One sentence of the restored comment had to change
rather than be reverted verbatim, because the new condition refuses credentials
the refresh sweep has *not* marked:

    -# Block a launch whose agent credential the refresh sweep has marked broken
    +# Block a launch whose agent credential is broken

That also drops `# No network, matching Oauth::Preflight and
CloudAuth::Preflight.`, which was the contract for an adapter method decrypting
credentials at every launch. Reading an `expires_at` column raises no network
question.

Behaviour is unchanged from 597212a: `session_service_test.rb` is untouched
and still passes, since its five preflight cases go through `#sync_expires_at`
and `CursorCliAdapter#token_expires_at`, both equal to `develop` on this
branch. `codex_adapter.rb` has not been touched at any step.

Diverges from the task's acceptance criteria, deliberately and for the record:
Part 1 is now gone in full -- the margin-honouring `#refresh!`, the "unreadable
exp means refresh" rule and the removal of the `margin_ms is ignored` marker
were all Part 1 items, and the maintainer asks for the marker back verbatim.
Part 2 survives as the single condition.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Hitin

Hitin commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Both taken — head is now eba3ddf4. base_adapter.rb, cursor_cli_adapter.rb and cursor_cli_adapter_test.rb are byte-identical to develop again, and the PR is the two files you named.

1. margin_ms — dropped

Reverted in full, including the marker on the ignored argument, back verbatim:

# margin_ms is ignored: this agent stores no per-block expiry to compare it
# against, so a call is already the decision to refresh.
def refresh!(credential, margin_ms: nil) # rubocop:disable Lint/UnusedMethodArgument

Your third argument is the one I had not seen. I checked it rather than took it: after this revert git grep -n now_ms app/ shows claude_code_adapter.rb only, where every hit is the local now_ms = (Time.current.to_f * 1000).to_i on line 241 — so the helper's last caller was indeed cursor_cli_adapter.rb:193, and the shadowing it was meant to remove it never removed. It goes with the argument.

The doc point stands too, and it is worse in the base class than in either adapter: ClaudeCodeAdapter#refresh! skipping an unreadable expiresAt is right for Claude, Cursor refusing to skip one is right for Cursor, and writing either of them as the contract for #refresh! mis-teaches whoever implements the next adapter. Reverting the paragraph makes the original two lines true again, since Cursor stops honouring the argument.

On what this gives up — agreed, and it is the part I would rather not lose: the launch path passes SESSION_REFRESH_THRESHOLD (60 minutes) into an argument that is discarded, so "refresh if it dies within the hour" means "refresh unconditionally", and rotating a single-use grant that still has hours on it is not free. I have not filed it as a follow-up, because doing it properly is the per-adapter decision about what an unreadable expiry means — for cursor_cli, codex and claude_code at once — and that is a design question, not a queued fix. Happy to open it if you want it on the board rather than in this thread.

2. preflight_agent_credential! doc — put back

Reverted to your diff exactly, one sentence changed rather than restored:

    # Block a launch whose agent credential is broken, so the user gets "sign in again"
    # instead of a container that fails on an expired token.
    #
    # An auth_setup session is exempt: it exists to REPLACE the broken credential,
    # so gating it on that credential locks the user out of the only flow that can
    # clear the error.

# No network, matching Oauth::Preflight and CloudAuth::Preflight. went with the rest, for the reason you give — it was the contract for a method that decrypted config_data at every launch, and reading a column raises no network question. The reasoning those nine lines carried is in the PR description and in the commit message of 597212a7, and this commit's message repeats why the one sentence could not be a straight revert.

Resulting PR

app/services/session_service.rb       |  11 ++--
test/services/session_service_test.rb | 107 ++++++++++++++++++++++++++++++++++
2 files changed, 113 insertions(+), 5 deletions(-)

Production change is the eight lines you wrote and nothing else. session_service_test.rb is untouched from 597212a7: its five cases go through #sync_expires_at and CursorCliAdapter#token_expires_at, both back to develop on this branch, so none of them depended on the reverted code. codex_adapter.rb has not been touched at any step.

Acceptance criteria, for the record

This removes what was left of the task's Part 1. The margin-honouring #refresh!, the "unreadable exp means refresh" rule and the removal of the margin_ms is ignored marker were all Part 1 items, and the marker is back verbatim at your request. Part 2 survives as the single condition. Noted in the commit message and in the description so it is not discovered later as an omission.

@artempartos

Copy link
Copy Markdown
Contributor

Heads-up on an overlap, not an objection: #279 edits the same method.

It adds, after the same active? check, a refusal for a credential whose base login has already expired and which nothing on the launch path will repair — no server-side refresh for that runtime, or another live container holding the same tokens so the sweep stands down. That is the 2026-09-17 production chain: a ready session pinned a Claude credential for 20 h, the token died with refresh_error still nil, and the next launch handed the dead token to a container that printed Login expired for 30 minutes before the watchdog cancelled it.

The two conditions do not overlap: this PR's case is a row whose expiry was never derived (NULL), which nothing can judge expired, and #279's is a row whose expiry is real and in the past. Both are needed.

They will conflict in git — same lines. Whichever lands second rebases; the merge is mechanical (two raise lines after unless credential.active?).

One thing #279 may make cheaper for this PR's "what this gives up" §1: it also declares a per-runtime lifecycle (BaseAdapter#credential_lifecycle) with a contract test that rejects exactly the shape behind this bug — refresh: :server with no readable expiry, which is the reason refresh_due never selected these rows. It does not repair the existing NULL population, so this PR's gate is still what drains it.

artempartos added a commit that referenced this pull request Sep 17, 2026
A device login run inside the freshly built image on 2026-09-18, with the proxy
recording, answered the 404 that has been in Sentry since 2026-09-05. The CLI
talks only to `api2.cursor.sh`, and its shipped bundle (2026.09.15) contains
exactly three auth endpoints — `/auth/poll`, `/auth/exchange_user_api_key`,
`/auth/cursor_dev_session_token`. There is no token-refresh call anywhere in it,
and `authenticator.cursor.sh`, the host our refresh posted to, appears nowhere.
The stored `refreshToken` is written by the poll and never exchanged; the access
token simply carries 60 days (issued 2026-09-18, exp 2026-11-16).

So the endpoint was not broken, it was never real. `cursor_cli` now declares
`reauth_only` with the measured TTL, which takes it out of the refresh sweep and
makes an expired login refuse the launch with "sign in again" instead of waiting
for a renewal that cannot come. `refresh!` and `refresh_cursor_token!` are gone,
and with them the ~10 404s an evening the web process was making from
`fetch_available_models` — an unauthorized model list now says so and stops.

PR #222's `NULL`-expiry gate remains the right complement: it drains the rows
whose expiry was never derived, which this does not touch.

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

Copy link
Copy Markdown
Contributor

Two things have changed under this PR since it was opened, both worth knowing before it lands.

1. The refresh works again — #287. The 404 was ours, not Cursor's. The desktop IDE's own _performAccessTokenRefresh posts JSON to ${backendUrl}/oauth/token with backendUrl = https://api2.cursor.sh and its own client id; of the four things our call specified, only the path was right (wrong host, form encoding instead of JSON, an invented client_id). Corrected and confirmed live: 200 {access_token, id_token, shouldLogout}, 60-day token. Six months of production HTTP logs plus both CLI bundles say the CLI itself never refreshes, and authenticator.cursor.sh never appears in either.

2. develop moved. #279 rewrote the same lines of preflight_agent_credential!: it now takes excluding_session_id: and raises on credential.unrecoverably_expired?. This PR's condition goes in the same place, so expect a conflict — the merge is mechanical, but it is no longer a clean apply.

What I'd suggest reconsidering, now that a refresh exists. A NULL expiry says nobody ever derived it, not that the token is dead — and a working refresh can settle which it is. Refreshing such a row populates expires_at through sync_expires_at and the credential heals; a refresh that comes back 401 is a dead grant and condemns it properly, which sends the user to re-auth on evidence rather than on suspicion. That also removes this PR's own stated cost — the workflow step that dies non-retryably because a live-but-underived credential was refused.

The cleanest form uses the lifecycle contract #279 added: a runtime declaring expiry: :token cannot legitimately have a NULL expiry, so the sweep can select those rows and let the refresh decide. Happy to implement that on top of #287 if you'd rather not carry it here — say the word and I will, and this PR can keep the launch gate as the backstop for whatever the sweep condemns.

@artempartos

Copy link
Copy Markdown
Contributor

Closing this one — not because the diagnosis was wrong, but because the ground under it moved twice and what is left is better solved elsewhere. The investigation here was right about the thing that mattered: a cursor_cli credential can be active with a NULL expiry however dead its token is, and a run on it finishes green with no tokens and no cost. That observation is what sent us looking, and it deserves saying plainly that it was correct.

Where each part of it now lives:

The cause is fixed — #287. The refresh was not failing because Cursor moved an endpoint; our call was wrong. The desktop IDE posts JSON to ${backendUrl}/oauth/token with backendUrl = https://api2.cursor.sh and its own client id, and of the four things our call specified only the path was right. Corrected and confirmed against the live service: 200 {access_token, id_token, shouldLogout}, a 60-day token. So a NULL-expiry row is no longer a row nothing can help — one refresh populates expires_at through sync_expires_at and the credential heals, or the refresh comes back 401 and condemns it on evidence.

The launch gate is in — #279. preflight_agent_credential! now refuses a credential whose base login has expired and which neither a server-side refresh nor another holder will repair, for every runtime rather than one. It rewrote the same lines this PR edits, so landing this would have needed a conflict resolution first.

What remains is one sweep change, and it belongs on top of #287: a runtime that declares expiry: :token cannot legitimately carry a NULL expiry, so the sweep should select those rows and let the refresh decide. That reaches the whole existing population without waiting for each user to re-authenticate, and without the cost this PR names in its own "what this gives up" §1 — a workflow step dying non-retryably because a live credential was refused for lacking a derived column.

Thanks for chasing it: the 404 had been in Sentry for weeks with nobody reading it, and this is what made us look.

artempartos added a commit that referenced this pull request Sep 17, 2026
A NULL `expires_at` means two different things and the sweep treated both as
"leave alone". For a runtime whose credential genuinely has no expiry — an API
key — that is correct. For one that declares `expiry: :token` it cannot be: the
token carries an expiry by construction, so a NULL says nobody wrote the column,
and the row sat outside every sweep however dead it was. That is the population
behind the Cursor credentials that stayed `active` with a token months past its
end while their sessions finished green, having authenticated with nothing.

`refresh_due` now also selects those rows, and the refresh settles which reading
is true: it succeeds and `sync_expires_at` fills the column in on the way through
— so the row is never undetermined again — or it is rejected and the credential
is condemned on evidence rather than on suspicion. This reaches the existing
population without waiting for each user to re-authenticate, which is what the
launch-gate alternative in #222 would have required.

Also: `cursor_cli` declares the lifetime that is now measured (60 days) and
`rotation: :static`, because the exchange returns no new refresh token — there is
no grant family, so no holder can be rotated out from under another.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Artem Petrov <[email protected]>
artempartos added a commit that referenced this pull request Sep 17, 2026
* fix(cursor): refresh against the endpoint the IDE actually uses

Our token refresh had been answering 404 since 2026-09-05, and the fault was
ours. Reading the desktop IDE's own bundle shows `_performAccessTokenRefresh`
posting JSON to `${backendUrl}/oauth/token` with `backendUrl =
https://api2.cursor.sh` and its own client id. Of the four things our call
specified, only the path was right: the host was `authenticator.cursor.sh` (a
real OAuth server, but a different one, which does not know this client), the
body was form-encoded rather than JSON, and the client id was an invented slug.

Corrected and confirmed against the live service with a freshly minted
credential: the call answers `{access_token, id_token, shouldLogout}` with a
60-day token.

Two things about the response shape matter. There is **no new refresh token**, and
the one issued at login carries its own 60-day expiry — so keeping it would let a
credential die on schedule however often we refreshed. The IDE writes the new
access token into both slots, which is what makes a signed-in IDE never need
signing in again, and this now does the same. And a 200 carrying
`shouldLogout: true` is the server ending the session, so it is reported as a
permanent failure rather than retried three times before the row is condemned.

Also here: the write-back URL is derived from `internal_base` like the MCP and
cloud-credential URLs beside it, instead of hardcoding `http://web:4002` — any
deployment whose internal host differs would have posted rotated tokens to
whatever answered there.

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

* fix(agents): sweep the credentials whose expiry was never derived

A NULL `expires_at` means two different things and the sweep treated both as
"leave alone". For a runtime whose credential genuinely has no expiry — an API
key — that is correct. For one that declares `expiry: :token` it cannot be: the
token carries an expiry by construction, so a NULL says nobody wrote the column,
and the row sat outside every sweep however dead it was. That is the population
behind the Cursor credentials that stayed `active` with a token months past its
end while their sessions finished green, having authenticated with nothing.

`refresh_due` now also selects those rows, and the refresh settles which reading
is true: it succeeds and `sync_expires_at` fills the column in on the way through
— so the row is never undetermined again — or it is rejected and the credential
is condemned on evidence rather than on suspicion. This reaches the existing
population without waiting for each user to re-authenticate, which is what the
launch-gate alternative in #222 would have required.

Also: `cursor_cli` declares the lifetime that is now measured (60 days) and
`rotation: :static`, because the exchange returns no new refresh token — there is
no grant family, so no holder can be rotated out from under another.

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

* fix(profile): scale "expiring soon" to how long the token actually lives

The badge turned amber 30 minutes before expiry whatever the runtime. For
Claude's 8-hour token that is a useful warning; for Cursor's 60-day one it is a
notice nobody will be looking at, half an hour before a two-month credential
stops working.

The window is now a tenth of the lifetime the adapter declares — 48 minutes at 8
hours, 6 days at 60 days — floored at the old 30 minutes so a short-lived or
undeclared token behaves exactly as before.

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

---------

Signed-off-by: Artem Petrov <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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