fix(linear-bot): track workspace auth health
Summary
Linear auth rot now fails visibly and stops wasting work. A revoked app, dead refresh token, malformed token, missing token, or missing refresh token writes durable workspace auth state, and later Linear-triggered work short-circuits until OAuth reconnect succeeds.
This keeps Cole's #864 feedback intact. Auth failures do not create Linear reconnect comments. The reconnect URL is in structured logs, and LINEAR_API_KEY is used only for the pre-existing completion-result fallback.
Fixes #865. Depends on #864.
What changed
- App revocation and permanent token failures set sticky
reauthorization_required; retryable token reads settransient_failure. - AgentSession starts, follow-ups, completion callbacks, and tool-call callbacks all use the shared auth context.
- Completion results still fall back to the existing
LINEAR_API_KEYcomment path when AgentSession OAuth is unavailable. This is result delivery, not an auth-failure notice. - Auth-state writes are best-effort. If KV fails while recording an auth failure, completion result delivery can still fall back and the KV failure is logged.
- Stale, signed auth-health webhooks return
200with{ ok: true, skipped: true, reason: "stale_timestamp" }and do not mutate auth state, delete tokens, record delivery dedupe, or enqueue work. OAuthApp revokeddeletes the stored token and keeps reauth sticky until a successful OAuth callback.PermissionChange teamAccessChangedrecords Linear team-access diagnostics only. It does not brick a workspace.- Dead Linear client compatibility wrappers were removed. Active callers now go through
getLinearAuthContext.
Explicit non-goals
- No auth-failure Linear comments, per maintainer feedback on #864.
- No notification-failure record for missing or rejected
LINEAR_API_KEY. That #865 criterion was intentionally dropped with the removed comment path. - No dashboard or
/statusread surface in this PR. The auth-health record is ready for that follow-up, but this PR does not build it. - No retry/backoff subsystem for transient failures. The gateway re-probes on later requests.
Validation
npm test -w @open-inspect/linear-botnpm run typecheck -w @open-inspect/linear-botnpm run lint -w @open-inspect/linear-botnpm run build -w @open-inspect/linear-botgit diff --checkce-test-browser mode:pipeline: skipped. No browser-rendered files or routes changed, andagent-browseris available.
Manual testing already done on this PR branch
- Deployed the PR branch to the Cloudflare preview environment.
- Reconnected Linear OAuth against the preview Linear bot.
- Assigned a Linear issue to the agent.
- Verified the integration starts a coding session from Linear and the session runs successfully.
- Verified repository access/classification works.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
Adds explicit Linear workspace auth health state, stateful OAuth handling, auth-health webhook processing, and auth-failure fallback comments across callback and agent-session flows. Tests cover auth-state transitions, OAuth routes, webhook validation, and fallback notification behavior.
Changes
Linear Auth Health State and OAuth Hardening
| Layer / File(s) | Summary |
|---|---|
Auth state types and KV helpers packages/linear-bot/src/types.ts, packages/linear-bot/src/kv-store.ts, packages/linear-bot/src/kv-store.test.ts |
Defines Linear workspace auth status, notification, and persisted auth-state types. Implements KV auth-state reads and writes, notification fingerprint lifecycle, OAuth state signing and verification, and related KV tests. |
Structured Linear auth context packages/linear-bot/src/utils/linear-client.ts, packages/linear-bot/src/utils/linear-client.test.ts |
Refactors OAuth token retrieval into structured failure results, adds auth context and reconnect URL handling, records installation identity during code exchange, and updates post-comment responses to include HTTP status. Tests cover token refresh, auth-context state changes, fallback comment persistence, and token exchange. |
OAuth routes and auth-health webhooks packages/linear-bot/src/index.ts, packages/linear-bot/src/index.test.ts |
Updates OAuth authorize/callback routing to persist and consume state, adds trace IDs to callback token exchange, and introduces auth-health webhook parsing, timestamp validation, deduplication, and auth-state updates for OAuthApp and PermissionChange events. Tests cover OAuth routes, webhook validation, stale timestamp handling, and auth-health state transitions. |
Agent session auth-failure fallback packages/linear-bot/src/webhook-handler.ts, packages/linear-bot/src/webhook-handler.test.ts |
Adds auth-failure comment formatting and fallback posting for agent-session webhook handling. Follow-up and new-session paths now use auth context results, log enhanced auth metadata, and include organizationId in follow-up callback context. Tests cover follow-up callback context and auth-failure comment behavior. |
Callback auth context and fallback comments packages/linear-bot/src/callbacks.ts, packages/linear-bot/src/callbacks.test.ts, packages/linear-bot/src/test-helpers.ts |
Switches callback handling to auth-context results for tool-call and completion flows, adds completion-specific auth-failure comment formatting, and posts auth-failure fallback comments when completion auth lookup fails. Test helpers and callback tests cover signed payloads and auth-failure behavior for tool-call and completion callbacks. |
OAuth setup instructions packages/linear-bot/README.md |
Updates the Linear OAuth application setup checklist to enable OAuth app and Permission changes events instead of Issues and Comments. |
Estimated code review effort: 5 (Critical) | ~120 minutes
Possibly related issues
#865: Directly aligns with explicit Linear workspace auth state,getLinearAuthContext, OAuth state validation, revocation handling, permission-change handling, and fallback notification behavior.
Possibly related PRs
- ColeMurray/background-agents#536: Both PRs modify
packages/linear-bot/src/webhook-handler.tsin the new-session flow and adjust auth-failure behavior. - ColeMurray/background-agents#627: Both PRs touch
packages/linear-bot/src/index.tswebhook handling aroundLinear-Delivery-based deduplication. - ColeMurray/background-agents#827: Both PRs adjust webhook deduplication TTL logic in
kv-store.tsand related webhook handling tests.
Suggested reviewers: ColeMurray
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Linked Issues check | ✅ Passed | The PR implements explicit workspace auth state, shared auth context, OAuth state validation, and callback/webhook coverage requested by #865. |
| Out of Scope Changes check | ✅ Passed | The changes stay focused on Linear auth-health tracking, OAuth handling, webhook/callback paths, tests, and related docs. |
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title clearly matches the main change: adding durable Linear workspace auth health tracking. |
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
Keep the OAuth state TTL source-of-truth in milliseconds.
Addressed: OAuth state now uses OAUTH_STATE_TTL_MS; KV TTL values are kept as millisecond constants and converted at the write boundary.
Extract the refresh skew into a named millisecond constant.
Addressed: the token refresh comparison now uses OAUTH_TOKEN_REFRESH_SKEW_MS.
OAUTH_STATE_TTL_SECONDSbakes seconds into a TypeScript constant.
Addressed: OAuth state now uses OAUTH_STATE_TTL_MS; KV TTLs are converted to seconds only at the expirationTtl boundary. The OAuth state flow is now signed and does not use KV get/delete.
5 * 60 * 1000is a duration literal in TypeScript source.
Addressed: extracted OAUTH_TOKEN_REFRESH_SKEW_MS and kept the refresh comparison in milliseconds.
Validation run after the review-fix commit:
npm run lintnpm run format:checknpm run typechecknpm testnpm run build
All passed. The first npm run build attempt hit a stale concurrent Next build lock; the immediate retry passed.
Addressed the CodeRabbit pass in 1da9e206.
Covered:
- scoped stale webhook timestamp rejection to auth-health webhooks
- added leased notification attempts and strict current-attempt completion
- replaced KV-backed OAuth state with signed state validation
- preserved persisted webhook auth reasons
- validated stored OAuth token shape before use
- used APP_NAME in Linear auth-failure fallback copy
- moved duration literals to named millisecond constants
Validation passed locally:
- npm run lint
- npm run format:check
- npm run typecheck
- npm test
- npm run build
Stop restating the lease/TTL defaults as raw millisecond math.
Addressed in c68990e: exported the Linear auth notification lease and OAuth state TTL constants from kv-store.ts, and updated kv-store.test.ts to use those constants instead of restating 5 * 60 * 1000 / 10 * 60 * 1000.
Validation passed after the follow-up:
npm run lintnpm run format:checknpm run typechecknpm testnpm run build
- a removed team no longer bricks the whole workspace.
- trimming tests to what is actually needed.
addressed the earlier #864 feedback around linear fallback comments. removed the auth-failure comment from this PR as well. pr description is also updated.