Repository navigation
Conversation
`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.
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]>
|
[Must] Source: 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 That is the exact state of the production row this PR was opened for — Why the rest is not carrying weightThe closed loop has an exit the summary does not mention. before_save :sync_expires_at, if: :will_save_change_to_encrypted_config_data?and The adapter hook answers a question the column already answers, for
The margin-honouring What this gives up, explicitlyI would rather state the cost than have it discovered later.
One interaction to avoidDo not pair this condition with a backfill of Two follow-ups worth their own tasks
|
…oken-refresh-from-token
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.
|
Addressed — the PR is reduced to the single condition. Head is now
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:
Kept the margin-honouring Diff: 8 files / +553 −20 → 5 files / +226 −13. 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 Tests were rebuilt around the one condition, in The One thing to flag: this drops the task's Part 1 acceptance bullet "a Full suite green on this exact commit — https://github.com/Hitin/flow/actions/runs/35097726641 ( |
|
[Recommendation] Source: 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
|
…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]>
|
Both taken — head is now 1.
|
|
Heads-up on an overlap, not an objection: #279 edits the same method. It adds, after the same The two conditions do not overlap: this PR's case is a row whose expiry was never derived ( They will conflict in git — same lines. Whichever lands second rebases; the merge is mechanical (two One thing #279 may make cheaper for this PR's "what this gives up" §1: it also declares a per-runtime lifecycle ( |
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]>
|
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 2. develop moved. #279 rewrote the same lines of What I'd suggest reconsidering, now that a refresh exists. A The cleanest form uses the lifecycle contract #279 added: a runtime declaring |
|
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 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 The launch gate is in — #279. What remains is one sweep change, and it belongs on top of #287: a runtime that declares Thanks for chasing it: the 404 had been in Sentry for weeks with nobody reading it, and this is what made us look. |
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(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]>
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
accessTokenwithexp = 2026-07-31was 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 finishedCOMPLETED, with a duration and no usage.The credential was
activethe whole time.SessionService#preflight_agent_credential!gated the launch onstatus, i.e. on whether the refresh sweep had already marked the row broken — and the sweep never selected it, becausescope :refresh_duefilterswhere.not(expires_at: nil)and this row'sexpires_atwasNULL. Never selected → never refreshed → nevermark_refresh_error!'d → stillactive. Preflight had nothing to look at.The fix
One condition, at the launch gate:
A
cursor_cliaccessTokenis a JWT carrying its ownexp;CursorCliAdapter#token_expires_athas parsed it since well before this branch; andderives the column from it on every write of
config_data— creation, re-auth, a refresh, and the merge-back inAgentSessionStrategy#persist_refreshed_credentials. So for this agent aNULLexpiry never means "this login has no expiry", as it legitimately does for an API-key or Bedrockclaude_codecredential. 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 existingAgentCredential::PreflightErrorand its "sign in again" CTA, and theauth_setupexemption preserved. No network was added to the preflight path, matchingOauth::PreflightandCloudAuth::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 whoseconfig_datahas not been written since that callback landed — which matches the "expired weeks earlier" in the incident.What this gives up, explicitly
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 andLaunchStepSessionActivitywrapsPreflightErrorin a non-retryable TemporalApplicationError, 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.MAX_REFRESH_FAILURES = 3ticks (~15 min on*/5).Do not pair this condition with a backfill of
expires_at. A backfill writes a past timestamp for a dead token, which removes theNULLthe 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 unreadableexpmeans refresh, themargin_ms is ignoredcomment 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.rbuntouched, the one Part 1 constraint that held, is still true.Considered and removed:
CursorCliAdapter#refresh!honouringmargin_msAn earlier revision made the adapter decide for itself, the way
ClaudeCodeAdapter#refresh!decides from its OAuth blocks:It is out, after review, and
base_adapter.rb,cursor_cli_adapter.rbandcursor_cli_adapter_test.rbare byte-identical todevelop— including the honest marker on the ignored argument:Three reasons, none of them about the incident:
expires_atcolumn 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_neededbranch could only fire when the column and the token disagree, which today needs a hand-editedexpires_at. A real scenario, but not this PR's, and it was costing 66 lines of test.BaseAdapterdoc 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 missingexpiresAtmeans 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.BaseAdapter#now_ms. That helper's only caller was the reverted line, while the identical expression stays inline inClaudeCodeAdapter#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 forcodexat 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
:heldpath produces this incident's exact symptom and is untouched: when a live container holds the credential, the sweep skips the row andAgentSessionStrategy#refresh_expiring_credential!logswith #{left || '?'}m of token lifeand starts on the stored copy.claude_codehas 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 returnpermanent: true— which leavesrefresh_expiring_credential!'sraise AgentCredential::PreflightError, credential if permanentunreachable for this agent, andAgentCredential.permanent_failure?'s documentedinvalid_granttext fallback matching neithercursor_clinorcodex. Also its own task.Scope
cursor_clionly.codex_adapter.rbandcodex_adapter_test.rbare unchanged — that agent shows the samemargin_ms-ignoring shape, but this incident did not happen on it and it has auth modes Cursor does not (anOPENAI_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.rbandcursor_cli_adapter.rbare also unchanged, after two rounds of review. The first revision addedTOKEN_DERIVED_REFRESH_AGENT_TYPES, anORbranch in.refresh_due,#refresh_worth_attempting?and aBaseAdapter#credential_unusable_reasonhook, so aNULL-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 decryptedconfig_dataand 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 themargin_mschange 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_usagecorrelation-window work from #192,persist_refreshed_credentialsnot picking up an in-container device login, token→cost conversion, and the container-sideBaseAdapter#credential_preflighthook are all out of scope.Related issues
Refs
AixleHQ/flow#192(closed unmerged) — this replaces that PR'sexpiry_unknown+#backfill_expires_at!approach rather than layering on it. That approach repairs the column for rows that already have a readableexp; it leavesbackfill_expires_at!returningnilwhentoken_expires_atyields nothing (so such a row staysNULL), andexpiry_unknown.find_eachre-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
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; acursor_clicredential whose expiry is derived but past → launches, left to the sweep and to provisioning; a healthycursor_clicredential → launches; anauth_setupsession on aNULL-expiry row → launches; regression: aclaude_codeAPI-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_allcould not run here. The full suite was therefore run through the same reusablecode-check.ymlon 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 forpull_requestandworkflow_dispatchinci.yml(be-checks,fe-checks,secret-scan); onlybuild-cacheandcoverage-badgesdiffer, and both are gated ongithub.event_name == 'push'.This PR's own checks are held at
action_requireduntil a maintainer approves workflow runs from the fork.Checklist
git commit -s).organization has executed the Corporate CLA.
make check_allpasses — run in CI rather than locally (no Docker/Coder in this environment); see above.🤖 Generated with Claude Code