diff --git a/AGENTS.md b/AGENTS.md index fb92cb286b..dfea07f7e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -623,89 +623,97 @@ mock.module("./some-module", () => ({ | Test helpers | `test/model-based/helpers.ts` | | Add documentation | `docs/src/content/docs/` | - + ## Long-term Knowledge ### Architecture - -* **Sentry API: events require org+project, issues have legacy global endpoint**: Sentry's event-fetching API endpoint is \`GET /api/0/projects/{org}/{project}/events/{event\_id}/\` — requires both org and project in the URL path. There is NO equivalent of the legacy \`/api/0/issues/{id}/\` endpoint for events. Event IDs (UUIDs) are project-scoped in Sentry's storage layer (ClickHouse/Snuba). Contrast with issues: \`getIssue()\` uses \`/api/0/issues/{id}/\` which works WITHOUT org context (issues have global numeric IDs). The issue response includes \`project.slug\` and \`organization.slug\`, enabling a two-step lookup: fetch issue → extract org/project → fetch event. For traces: \`getDetailedTrace()\` uses \`/organizations/{org}/trace/{traceId}/\` — needs only org, not project. Possible workaround for event view without org/project: use the Discover endpoint \`/organizations/{org}/events/\` with \`query=id:{eventId}\` and \`dataset=errors\` to search across all projects in an org. - -* **Sentry CLI has two distribution channels with different runtimes**: The Sentry CLI ships via two completely independent build pipelines: 1. \*\*Standalone binary\*\* (GitHub Releases): Built with \`Bun.build()\` + \`compile: true\` via \`script/build.ts\`. Produces native executables (\`sentry-{platform}-{arch}\`) with Bun runtime embedded. Runs under Bun. 2. \*\*npm package\*\*: Built with esbuild via \`script/bundle.ts\`. Produces a single minified CJS file (\`dist/bin.cjs\`) with \`#!/usr/bin/env node\` shebang. Requires Node.js 22+ (for \`node:sqlite\`). Key esbuild settings: \`platform: 'node'\`, \`target: 'node22'\`, \`format: 'cjs'\`. Aliases \`@sentry/bun\` → \`@sentry/node\`. Injects Bun API polyfills from \`script/node-polyfills.ts\`. Bun API polyfills cover: \`Bun.file()\`, \`Bun.write()\`, \`Bun.which()\`, \`Bun.spawn()\`, \`Bun.sleep()\`, \`Bun.Glob\`, \`Bun.randomUUIDv7()\`, \`Bun.semver.order()\`, and \`bun:sqlite\` (→ \`node:sqlite\` DatabaseSync). The npm bundle is CJS, so \`require()\` calls in source are native and resolved at bundle time by esbuild — no ESM/CJS conflict. CI smoke-tests with \`node dist/bin.cjs --help\` on Node 22 and 24. - -* **gh CLI config directory convention and XDG compliance**: The \`gh\` CLI (GitHub CLI), which is the explicit UX model for Sentry CLI per AGENTS.md, stores config at: \`$GH\_CONFIG\_DIR\` > \`$XDG\_CONFIG\_HOME/gh\` > \`$HOME/.config/gh\` (follows XDG on all platforms including macOS). Most other major CLIs (docker, aws, kubectl, cargo) use \`~/.toolname/\` rather than XDG. macOS \`~/Library/Application Support/\` is Apple-blessed for app data but uncommon for CLI tools and surprising to developers. The Sentry CLI currently uses \`~/.sentry/\` with \`SENTRY\_CONFIG\_DIR\` as an override env var. - -* **API client wraps all errors as CliError subclasses — no raw exceptions escape**: The Sentry CLI API client (src/lib/api-client.ts) guarantees that all errors thrown by API functions like getCurrentUser() are CliError subclasses (ApiError or AuthError). In unwrapResult(), known error types (AuthError, ApiError) are re-thrown directly, and everything else — including raw network TypeErrors from ky — goes through throwApiError() which wraps them as ApiError. This means command implementations do NOT need their own try-catch for error display: the central error handler in app.ts exceptionWhileRunningCommand catches CliError and displays a clean message without stack trace. Only add try-catch when the command needs to handle the error specially (e.g., login needs to continue without user info on failure, not crash). The Seer bot flagged whoami.ts for lacking try-catch around getCurrentUser() — this was a false positive because of this guarantee. - -* **Issue list multi-target mode has no cursor pagination — only org-all mode supports --cursor**: In the Sentry CLI \`issue list\` command, cursor-based pagination (\`--cursor\` / \`-c last\`) is supported in BOTH org-all mode (\`sentry issue list \/\`) and multi-target mode (auto-detect, explicit, project-search). Org-all uses a standard single cursor from the Sentry API. Multi-target mode uses a \*\*compound cursor\*\* — a pipe-separated string where each position corresponds to a project in the sorted target fingerprint order. Empty segments mean the project is exhausted (no more pages). The compound cursor is built by \`encodeCompoundCursor()\` and decoded by \`decodeCompoundCursor()\` in list.ts. The context key for multi-target cursors includes a fingerprint of the sorted target list (\`buildMultiTargetContextKey\`) so that cursor stored for one set of detected projects is not accidentally reused for a different set. When resuming with a compound cursor, \`handleResolvedTargets\` skips Phase 1/Phase 2 budget logic and instead fetches one page per project using each project's stored cursor. Projects with exhausted cursors (empty segments) are filtered into \`exhaustedTargets\` and excluded from \`activeTargets\` to prevent re-fetching from scratch. The 'more results available' hint now suggests both \`-n \\` and \`-c last\` in multi-target mode, but only when \`hasAnyCursor\` is true (at least one project has a next cursor stored). - -* **Sentry CLI resolve-target cascade has 5 priority levels with env var support**: The resolve-target module (src/lib/resolve-target.ts) resolves org/project context through a strict 5-level priority cascade: 1. Explicit CLI flags (both org and project must be provided together) 2. SENTRY\_ORG / SENTRY\_PROJECT environment variables 3. Config defaults (SQLite defaults table) 4. DSN auto-detection (source code, .env files, SENTRY\_DSN env var) 5. Directory name inference (matches project slugs with word boundaries) SENTRY\_PROJECT supports combo notation: \`SENTRY\_PROJECT=org/project\` (slash presence auto-splits). When combo form is used, SENTRY\_ORG is ignored. If SENTRY\_PROJECT contains a slash but the combo parse fails (e.g. \`org/\` or \`/project\`), the entire SENTRY\_PROJECT value is discarded — it does NOT fall through to be used as a plain project slug alongside SENTRY\_ORG. Only SENTRY\_ORG (if set) provides the org in this case. The resolveFromEnvVars() helper is injected into all four resolution functions: resolveAllTargets, resolveOrgAndProject, resolveOrg, and resolveOrgsForListing. This matches the convention used by legacy sentry-cli and Sentry Webpack plugin. Added in PR #280. + +* **@sentry/node-core pulls in @apm-js-collab/code-transformer (3.3MB) but it's tree-shaken**: The dependency chain \`@sentry/node\` → \`@sentry/node-core\` → \`@apm-js-collab/tracing-hooks\` → \`@apm-js-collab/code-transformer\` adds a 3.3MB input file to the esbuild bundle analysis. However, esbuild fully tree-shakes it out — it contributes 0 bytes to the final npm bundle output. This was verified by checking both the released 0.13.0 bundle and the current build: neither contains any \`code-transformer\` or \`apm-js-collab\` strings. Don't be alarmed by its presence in metafile inputs. + +* **GitHub Packages has no generic/raw file registry — only typed registries**: GitHub Packages only supports typed registries (Container/npm/Maven/NuGet/RubyGems) — there is no generic file store where you can upload a binary and get a download URL. For distributing arbitrary binaries: the Container registry (ghcr.io) via ORAS works but requires a 3-step download (token → manifest → blob). The npm registry at \`npm.pkg.github.com\` requires authentication even for public packages, making it unsuitable for install scripts. This means for binary distribution on GitHub without GitHub Releases, GHCR+ORAS is the only viable GitHub Packages option. + +* **cli.sentry.dev is served from gh-pages branch via GitHub Pages**: The \`cli.sentry.dev\` domain points to GitHub Pages for the getsentry/cli repo, confirmed by the CNAME file on the gh-pages branch containing \`cli.sentry.dev\`. The branch contains the Astro/Starlight docs site output plus the install script at \`/install\`. Craft's gh-pages target manages this branch, wiping and replacing all content on each stable release. The docs are built as a zip artifact named \`gh-pages.zip\` (matched by Craft's \`DEFAULT\_DEPLOY\_ARCHIVE\_REGEX: /^(?:.+-)?gh-pages\\.zip$/\`). + +* **npm bundle requires Node.js >= 22 due to node:sqlite polyfill**: The Sentry CLI npm package (dist/bin.cjs) requires Node.js >= 22 because the bun:sqlite polyfill uses Node.js 22's built-in \`node:sqlite\` module. The \`require('node:sqlite')\` happens during module loading (via esbuild's inject option) — before any user code runs. package.json declares \`engines: { node: '>=22' }\` but pnpm/npm don't enforce this by default. A runtime version guard in the esbuild banner catches this early with a clear error message pointing users to either upgrade Node.js or use the standalone binary (\`curl -fsSL https://cli.sentry.dev/install | bash\`). + +* **parseSentryUrl does not handle subdomain-style SaaS URLs**: The URL parser in src/lib/sentry-url-parser.ts handles both path-based (\`/organizations/{org}/...\`) and subdomain-style (\`https://{org}.sentry.io/issues/123/\`) SaaS URLs. The \`matchSubdomainOrg()\` function extracts the org from the hostname when it ends with \`.sentry.io\`, supports \`/issues/{id}/\`, \`/issues/{id}/events/{eventId}/\`, and \`/traces/{traceId}/\` paths. Region subdomains (\`us\`, \`de\`) are filtered out by requiring org slugs to be longer than 2 characters. Confirmed against getsentry/sentry codebase: the subdomain IS the org slug directly (e.g., \`my-org.sentry.io\`), NOT a fixed prefix like \`o.sentry.io\`. The Sentry backend builds permalinks via \`organization.absolute\_url()\` → \`generate\_organization\_url(slug)\` using the \`system.organization-base-hostname\` template \`{slug}.sentry.io\` (src/sentry/organizations/absolute\_url.py:72-92). When customer domains are enabled (production SaaS), \`customer\_domain\_path()\` strips \`/organizations/{slug}/\` from paths. Region subdomains are filtered by Sentry's \`subdomain\_is\_region()\`, aligning with the \`org.length <= 2\` check. Self-hosted uses path-based: \`/organizations/{org\_slug}/issues/{id}/\`. + +* **Numeric issue ID resolution returns org:undefined despite API success**: Numeric issue ID resolution now uses a multi-step approach in \`resolveNumericIssue()\` (extracted from \`resolveIssue\` to reduce cognitive complexity). Resolution order: (1) \`resolveOrg({ cwd })\` tries DSN/env/config for org context, (2) if org found, uses \`getIssueInOrg(org, id)\` with region routing, (3) if no org, falls back to unscoped \`getIssue(id)\`, (4) extracts org from \`issue.permalink\` via \`parseSentryUrl\` as final fallback. The \`explicit-org-numeric\` case now uses \`getIssueInOrg(parsed.org, id)\` instead of the unscoped endpoint. \`getIssueInOrg\` was added to api-client.ts using the SDK's \`retrieveAnIssue\` with the standard \`getOrgSdkConfig + unwrapResult\` pattern. The \`resolveOrgAndIssueId\` wrapper (used by \`explain\`/\`plan\`) no longer throws "Organization is required" for bare numeric IDs when the permalink contains the org slug. + +* **Install script nightly channel support**: The curl install script (\`cli.sentry.dev/install\`) supports \`--channel nightly\`. For nightly: downloads the binary directly from the \`nightly\` release tag (no version.json fetch needed — just uses \`nightly\` as both download tag and display string). Passes \`--channel nightly\` to \`$binary cli setup --install --method curl --channel nightly\` so the channel is persisted in DB. Usage: \`curl -fsSL https://cli.sentry.dev/install | bash -s -- --channel nightly\`. The install script does NOT fetch version.json — that's only used by the upgrade/version-check flow to compare versions. ### Decision - -* **whoami should be separate from auth status command**: The \`sentry auth whoami\` command should be a dedicated command separate from \`sentry auth status\`. They serve different purposes: \`status\` shows everything about auth state (token, expiry, defaults, org verification), while \`whoami\` just shows user identity (name, email, username, ID) by fetching live from \`/auth/\` endpoint. \`sentry whoami\` should be a top-level alias (like \`sentry issues\` → \`sentry issue list\`). \`whoami\` should support \`--json\` for machine consumption and be lightweight — no credential verification, no defaults listing. - -* **Issue list global limit with fair per-project distribution and representation guarantees**: The \`issue list\` command's \`--limit\` flag specifies a global total across all detected projects, not per-project. The fetch strategy uses two phases in \`fetchWithBudget\`: Phase 1 divides the limit evenly (\`ceil(limit / numTargets)\`) and fetches in parallel. Phase 2 (\`runPhase2\`) redistributes surplus budget to targets that hit their quota and have more results (via cursor resume using \`startCursor\` param added to \`listIssuesAllPages\`). After fetching, \`trimWithProjectGuarantee\` ensures at least 1 issue per project is shown before filling remaining slots from the globally-sorted list. This prevents high-volume projects from completely hiding quiet ones. When more projects exist than the limit, the projects with the highest-ranked first issues get representation. JSON output for multi-target mode wraps in \`{ data: \[...], hasMore: bool }\` (with optional \`errors\` array) to align with org-all mode's existing \`data\` wrapper. A compound cursor is stored so \`-c last\` can resume multi-target pagination. - -* **Sentry CLI config dir should stay at ~/.sentry/, not move to XDG**: Decision: Don't move the Sentry CLI config directory from ~/.sentry/ to ~/.config/sentry/ or ~/Library/Application Support/. The readonly database errors seen in telemetry (100% macOS) are caused by Unix permission issues from \`sudo brew install\` creating root-owned files, not by the directory location. Moving to any other path would have identical permission problems if created by root. The SENTRY\_CONFIG\_DIR env var already exists as an escape hatch. All three fixes have been implemented in PR #288: 1. Setup steps are non-fatal with bestEffort() try-catch wrapper 2. tryRepairReadonly() detects root-owned files and prints actionable \`sudo chown -R \ ~/.sentry\` message 3. \`sentry cli fix\` command handles ownership detection and repair (chown when run as root via sudo) + +* **Nightly release: delete-then-upload instead of clobber for asset management**: The publish-nightly CI job deletes ALL existing release assets before uploading new ones, rather than using \`gh release upload --clobber\`. This ensures that if asset names change (e.g., removing a platform or renaming files), stale assets don't linger on the nightly release indefinitely. Pattern: \`gh release view nightly --json assets --jq '.assets\[].name' | while read -r name; do gh release delete-asset nightly "$name" --yes; done\` followed by \`gh release upload nightly \\` (no --clobber needed since assets were cleared). + +* **Raw markdown output for non-interactive terminals, rendered for TTY**: Design decision for getsentry/cli: output raw CommonMark markdown when stdout is not interactive (piped, redirected, CI), and only render through marked-terminal when a human is looking at it in a TTY. Detection: \`const isInteractive = process.stdout.isTTY\` — no \`process.env.CI\` check needed, since if a CI runner allocates a pseudo-TTY it can render the styled output fine. Override env vars with precedence: \`SENTRY\_PLAIN\_OUTPUT\` (most specific) > \`NO\_COLOR\` > auto-detect via \`isTTY\`. \`SENTRY\_PLAIN\_OUTPUT=1\` forces raw markdown even on TTY; \`SENTRY\_PLAIN\_OUTPUT=0\` forces rendered even when piped. \`NO\_COLOR\` (no-color.org standard) also triggers plain mode since rendered output is ANSI-colored. Chalk auto-disables colors when piped, so pre-embedded ANSI codes become plain text in raw mode. Output modes: \`--json\` → JSON (unchanged), TTY → rendered markdown via marked-terminal, non-TTY → raw CommonMark. For streaming formatters (log/trace row-by-row output), TTY keeps current ANSI-colored padded text for efficient incremental display, while non-TTY emits markdown table rows with header+separator on first write, producing valid markdown files when redirected. ### Gotcha - -* **brew is not in VALID\_METHODS but Homebrew formula passes --method brew**: Homebrew install support for Sentry CLI was merged to main via PR #277. The implementation includes: 'brew' as a valid installation method in \`parseInstallationMethod()\` (src/lib/upgrade.ts), \`isHomebrewInstall()\` detection via Cellar realpath check (always checked first before stored install info), version pinning errors with dedicated 'unsupported\_operation' error reason, architecture validation, and post\_install setup that skips redundant work on \`brew upgrade\`. The upgrade command includes a 'brew' case that tells users to run \`brew upgrade getsentry/tools/sentry\`. Uses .gz compressed artifacts. The Homebrew formula lives in a tap at getsentry/tools. - -* **Stricli defaultCommand blends default command flags into route completions**: When a Stricli route map has \`defaultCommand\` set, requesting completions for that route (e.g. \`\["issues", ""]\`) returns both the subcommand names AND the default command's flags/positional completions. This means completion tests that compare against \`extractCommandTree()\` subcommand lists will fail for groups with defaultCommand, since the actual completions include extra entries like \`--limit\`, \`--query\`, etc. Solution: track \`hasDefaultCommand\` in the command tree and skip strict subcommand-matching assertions for those groups. - -* **Codecov patch coverage requires --coverage flag on ALL test invocations**: In the Sentry CLI, the test script runs \`bun run test:unit && bun run test:isolated\`. Only \`test:unit\` has \`--coverage --coverage-reporter=lcov\`. The \`test:isolated\` run (for tests using \`mock.module()\`) does NOT generate coverage. This means code paths exercised only in isolated tests won't count toward Codecov patch coverage. To boost patch coverage, either: (1) add \`--coverage\` to the isolated test script, or (2) write additional unit tests that call the real (non-mocked) functions where possible. For env var resolution, since env vars short-circuit at step 2 before any DB/API calls, unit tests can call the real resolve functions without mocking dependencies. - -* **Multiregion mock must include all control silo API routes**: When changing which Sentry API endpoint a function uses (e.g., switching getCurrentUser() from /users/me/ to /auth/), the mock route must be updated in BOTH test/mocks/routes.ts (single-region) AND test/mocks/multiregion.ts createControlSiloRoutes() (multi-region). Missing the multiregion mock causes 404s in multi-region test scenarios. The multiregion control silo mock serves auth, user info, and region discovery routes. Cursor Bugbot caught this gap when /api/0/auth/ was added to routes.ts but not multiregion.ts. - -* **Sentry /users/me/ endpoint returns 403 for OAuth tokens — use /auth/ instead**: The Sentry \`/users/me/\` endpoint returns 403 for OAuth tokens (including OAuth App tokens). The \`/auth/\` endpoint works with ALL token types (OAuth, API tokens, OAuth App tokens) and returns the authenticated user's information. \`/auth/\` lives on the control silo (sentry.io for SaaS, not regional endpoints). The sentry-mcp project uses this pattern: always route \`/auth/\` to the main sentry.io host for SaaS, bypassing regional endpoints. In the Sentry CLI, \`getControlSiloUrl()\` already handles this routing correctly. The \`getCurrentUser()\` function in \`src/lib/api-client.ts\` should use \`/auth/\` instead of \`/users/me/\`. The \`SentryUserSchema\` (with \`.passthrough()\`) handles the \`/auth/\` response since it only requires \`id\` and makes \`email\`, \`username\`, \`name\` optional. - -* **Bun mock.module() leaks globally across test files in same process**: Bun's mock.module() replaces the ENTIRE barrel module globally and leaks state across test files run in the same bun test process. If test file A mocks 'src/lib/api-client.js' to stub listOrganizations, ALL subsequent test files in that process see the mock instead of the real module. This caused ~100 test failures when test/isolated/resolve-target.test.ts ran alongside unit tests. Solution: tests using mock.module() must run in a separate bun test invocation (separate process). In package.json, the 'test' script uses 'bun run test:unit && bun run test:isolated' instead of 'bun test' to ensure process isolation. The test/isolated/ directory exists specifically for tests that use mock.module(). The file even documents this with a comment about Bun leaking mock.module() state (referencing getsentry/cli#258). - -* **Test suite has 131 pre-existing failures from DB schema drift and mock issues**: The Sentry CLI test suite had 131 pre-existing failures (1902 pass) caused by two root issues: (1) Bun's mock.module() in test/isolated/resolve-target.test.ts leaked globally, poisoning api-client.js (listOrganizations → undefined), db/defaults.js, db/project-cache.js, db/dsn-cache.js, and dsn/index.js for all subsequent test files — this caused ~80% of failures. (2) Minor issues: project root path resolution in temp dirs (11), DSN Detector module tests (17), E2E timeouts (2). Fix: changed package.json 'test' script from 'bun test' to 'bun run test:unit && bun run test:isolated' so isolated tests with mock.module() run in a separate Bun process. Result: 1931 tests, 0 failures. Key lesson: Bun's mock.module() replaces the ENTIRE barrel module globally and leaks across test files in the same process — tests using mock.module() must be isolated in separate bun test invocations. - -* **pagination\_cursors table schema mismatch requires repair migration**: The pagination\_cursors SQLite table could be created with a single-column PK (command\_key TEXT PRIMARY KEY) by earlier code versions, instead of the expected composite PK (PRIMARY KEY (command\_key, context)). This caused 'SQLiteError: ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint' at runtime. Fixed by: (1) migration 5→6 that detects wrong PK via hasCompositePrimaryKey() and drops/recreates the table, (2) repairWrongPrimaryKeys() in repairSchema() for auto-repair, (3) isSchemaError() now catches 'on conflict clause does not match' to trigger auto-repair, (4) getSchemaIssues() reports 'wrong\_primary\_key' diagnostic. CURRENT\_SCHEMA\_VERSION bumped to 6. Data loss is acceptable since pagination cursors are ephemeral (5-min TTL). The hasCompositePrimaryKey() helper inspects sqlite\_master DDL for the expected PRIMARY KEY clause. - -* **resolveCursor must be called inside org-all closure, not before dispatch**: In list commands using dispatchOrgScopedList with cursor pagination (e.g., project/list.ts), resolveCursor() must be called inside the 'org-all' override closure, not before dispatchOrgScopedList. If called before, it throws a ContextError before dispatch can throw the correct ValidationError for --cursor being used in non-org-all modes. - -* **Bun.$ (shell tagged template) has no Node.js polyfill in Sentry CLI**: The Sentry CLI's node-polyfills.ts (used for the npm/Node.js distribution) provides shims for Bun.file(), Bun.write(), Bun.which(), Bun.spawn(), Bun.sleep(), Bun.Glob, Bun.randomUUIDv7(), Bun.semver.order(), and bun:sqlite — but NOT for Bun.$ (the tagged template shell). Any source code using Bun.$\`command\` will crash when running via the npm distribution (node dist/bin.cjs). Use execSync from node:child\_process instead for shell commands that need to work in both runtimes. The Bun.which polyfill already uses this pattern. As of PR #288, there are zero Bun.$ usages in the source code. AGENTS.md has been updated to document this: the Bun.$ row in the Quick Bun API Reference table has a ⚠️ warning, and a new exception block shows the execSync workaround. The phrasing 'Until a shim is added' signals that adding a Bun.$ polyfill is a desired future improvement. When someone adds the shim, remove the exception note and the ⚠️ from the table. - -* **Homebrew post-install runs as installing user — permission errors crash setup**: When Sentry CLI is installed via Homebrew, the formula runs \`sentry cli setup --method brew --no-modify-path\` as a post-install step. This can fail with SQLiteError (SQLITE\_CANTOPEN on ~/.sentry/cli.db) or EPERM on ~/.local/share/zsh/site-functions/\_sentry. Root cause is Unix permission issues from \`sudo brew install\` creating root-owned files (NOT macOS TCC). Fixed in PR #288 with three changes: 1. \*\*setup.ts\*\*: \`bestEffort()\` wrapper makes every post-install step non-fatal — Homebrew post\_install no longer aborts with scary errors. 2. \*\*telemetry.ts\*\*: \`tryRepairReadonly()\` detects root-owned files via \`statSync().uid === 0\` and prints actionable \`sudo chown -R \ \\` message using real username from SUDO\_USER/USER/USERNAME/os.userInfo(). Has \`win32\` platform guard since uid checks are meaningless on Windows. 3. \*\*fix.ts\*\*: \`sentry cli fix\` has full ownership detection — checks config files for wrong uid, prints chown instructions when not root, performs actual \`chown\` when run via \`sudo sentry cli fix\`. Uses \`resolveUid()\` via \`execFileSync('id', \['-u', username])\` (not \`Bun.$\` — no node shim). Guards against chown-to-root (targetUid === 0) and bails early when real UID can't be resolved. The \`getRealUsername()\` helper lives in \`src/lib/utils.ts\` (shared between telemetry.ts and fix.ts). It checks SUDO\_USER → USER → USERNAME → os.userInfo().username → '$(whoami)', with userInfo() wrapped in try-catch since it can throw on some systems. - -* **handleProjectSearch ContextError resource must be "Project" not config.entityName**: In src/lib/org-list.ts handleProjectSearch, the first argument to ContextError is the resource name rendered as "${resource} is required.". Always pass "Project" (not config.entityName like "team" or "repository") since the error is about a missing project slug, not a missing entity of the command's type. A code comment documents the rationale inline. + +* **pnpm overrides with version-range keys don't force upgrades of already-compatible resolutions**: pnpm overrides gotchas: (1) Version-range selectors like \`"minimatch@>=10.0.0 <10.2.1": ">=10.2.1"\` don't reliably force re-resolution of already-compatible transitive deps. Workaround: blanket override \`"minimatch": ">=10.2.1"\` — but verify with \`pnpm why\` that no other major versions exist first. (2) \`>=\` targets can cross major versions — \`"ajv@<6.14.0": ">=6.14.0"\` resolves to v8.x, breaking v6 consumers. Always use \`^\` to constrain within the same major. (3) Overrides become orphaned when the dependency tree changes (package removal, transitive dep renames). Audit with \`pnpm why \\` after tree changes; remove overrides that return empty. (4) For lockfile merge conflicts, just \`git checkout --theirs pnpm-lock.yaml\` then \`pnpm install\` — never manually resolve. + +* **ghcr.io blob download: curl -L breaks because auth header leaks to Azure redirect**: ghcr.io blob download: \`curl -L\` with Authorization header fails because curl forwards the auth header to the Azure redirect target, which rejects it with 404. Fix: two-step — extract redirect URL without following, then curl the redirect without auth header. ORAS CLI handles this internally but install scripts using plain curl need the manual approach. + +* **GitHub Actions: use deterministic timestamps across jobs, not Date.now()**: GitHub Actions gotchas: (1) Use deterministic timestamps across jobs — never use \`Date.now()\` independently per job. Derive from \`github.event.head\_commit.timestamp\` converted to Unix seconds. (2) Skipped \`needs\` jobs don't block downstream — outputs are empty strings, use conditional \`if: needs.job.outputs.value != ''\` to skip steps. (3) upload-artifact strips directory prefixes from glob paths — \`dist-bin/sentry-\*\` stores as \`sentry-\*\` at root. download-artifact puts files at \`artifacts/sentry-\*\`, not \`artifacts/dist-bin/sentry-\*\`. + +* **Bun binary build requires SENTRY\_CLIENT\_ID env var**: The build script (\`script/bundle.ts\`) requires \`SENTRY\_CLIENT\_ID\` environment variable and exits with code 1 if missing. When building locally, use \`bun run --env-file=.env.local build\` or set the env var explicitly. The binary build (\`bun run build\`) also needs it. Without it you get: \`Error: SENTRY\_CLIENT\_ID environment variable is required.\` + +* **marked and marked-terminal must be devDependencies in bundled CLI projects**: In the getsentry/cli project, all npm packages used at runtime must be bundled by the build step (esbuild). Packages like \`marked\` and \`marked-terminal\` belong in \`devDependencies\`, not \`dependencies\`. The CI \`check:deps\` step enforces this — anything in \`dependencies\` that isn't a true runtime requirement (native addon, bin entry) will fail the check. This applies to all packages consumed only through the bundle. + +* **CodeQL flags incomplete markdown cell escaping — must escape backslash before pipe**: When escaping user content for markdown table cells, replacing only \`|\` with \`\\|\` triggers CodeQL's "Incomplete string escaping or encoding" alert (high severity). The fix is to escape backslashes first, then pipes: \`str.replace(/\\\\/g, "\\\\\\\\" ).replace(/\\|/g, "\\\\|")\`. In getsentry/cli this is centralized as \`escapeMarkdownCell()\` in \`src/lib/formatters/markdown.ts\`. All formatters that build markdown table rows (human.ts, log.ts, trace.ts) must use this helper instead of inline \`.replace()\` calls. + +* **Multiple mockFetch calls replace each other — use unified mocks for multi-endpoint tests**: In getsentry/cli tests, \`mockFetch()\` sets \`globalThis.fetch\` to a new function. Calling it twice replaces the first mock entirely. A common bug: calling \`mockBinaryDownload()\` then \`mockGitHubVersion()\` means the binary download URL hits the version mock (returns 404). Fix: create a single unified fetch mock that handles ALL endpoints the test needs (version API, binary download, npm registry, version.json). Pattern: \`\`\`typescript mockFetch(async (url) => { const urlStr = String(url); if (urlStr.includes('releases/latest')) return versionResponse; if (urlStr.includes('version.json')) return nightlyResponse; return new Response(gzipped, { status: 200 }); // binary download }); \`\`\` This caused multiple test failures when trying to test the full upgrade→download→setup pipeline. + +* **GHCR packages created as private by default — must manually make public once**: When first pushing to \`ghcr.io/getsentry/cli\` via ORAS or Docker, the container package is created with \`visibility: private\`. Anonymous pulls fail until the package is made public. This is a one-time manual step via GitHub UI at the package settings page (Danger Zone → Change visibility → Public). The GitHub Packages API for changing visibility requires org admin scopes that aren't available via \`gh auth\` by default. For the getsentry/cli nightly distribution, the package has already been made public. + +* **Craft gh-pages target wipes entire branch on publish**: Craft's \`GhPagesTarget.commitArchiveToBranch()\` runs \`git rm -r -f .\` before extracting the docs archive, deleting ALL existing files on the gh-pages branch. Any additional files placed there (e.g., nightly binaries in a \`nightly/\` directory) would be wiped on every stable release. The \`cli.sentry.dev\` site is served from the gh-pages branch (CNAME file confirms this). If using gh-pages for hosting non-docs files, either accept the brief outage window until the next main push re-adds them, add a \`postReleaseCommand\` in \`.craft.yml\` to restore the files, or use a different hosting mechanism entirely. + +* **GitHub immutable releases prevent rolling nightly tag pattern**: The getsentry/cli repo has immutable releases enabled (org/repo setting, will NOT be turned off). This means: (1) once a release is published, its assets cannot be modified or deleted, (2) a tag used by a published release can NEVER be reused, even after deleting the release — \`gh release delete nightly --cleanup-tag\` followed by \`gh release create nightly\` fails with \`tag\_name was used by an immutable release\`. Draft releases ARE mutable but use unpredictable \`/download/untagged-xxx/\` URLs instead of tag-based URLs, and publishing a draft with a previously-used tag also fails. This breaks the original nightly design of a single rolling \`nightly\` tag. The \`nightly\` tag is now permanently poisoned. New approach needed: per-version release tags (e.g., \`0.13.0-dev.1772062077\`) with API-based discovery of the latest prerelease. + +* **useTestConfigDir without isolateProjectRoot causes DSN scanning of repo tree**: In getsentry/cli tests, \`useTestConfigDir()\` creates temp dirs under \`.test-tmp/\` inside the repo tree. When code calls \`detectDsn(cwd)\` with this temp dir as cwd (e.g., via \`resolveOrg({ cwd })\`), \`findProjectRoot\` walks up from \`.test-tmp/prefix-xxx\` and finds the repo's \`.git\` directory, causing DSN detection to scan the actual source code for Sentry DSNs. This can trigger network calls that hit test fetch mocks (returning 404s or unexpected responses), leading to 5-second test timeouts. Fix: always use \`useTestConfigDir(prefix, { isolateProjectRoot: true })\` when the test exercises any code path that might call \`resolveOrg\`, \`detectDsn\`, or \`findProjectRoot\` with the config dir as cwd. The \`isolateProjectRoot\` option creates a \`.git\` directory inside the temp dir, stopping the upward walk immediately. + +* **mock.module bleeds across Bun test files — never include test/isolated/ in test:unit**: In Bun's test runner, \`mock.module()\` pollutes the shared module registry for ALL subsequently-loaded test files in the same \`bun test\` invocation. Including \`test/isolated/\` in \`test:unit\` caused 132 failures because the \`node:child\_process\` mock leaked into DB tests, config tests, and others that transitively import child\_process. The \`test:isolated\` script MUST remain separate from \`test:unit\`. This also means isolated test coverage does NOT appear in Codecov PR patch coverage — only \`test:unit\` feeds lcov. Accept that code paths requiring \`mock.module\` (e.g., \`node:child\_process spawn\` wrappers like \`runCommand\`, \`isInstalledWith\`, \`executeUpgradeHomebrew\`, \`executeUpgradePackageManager\`) will have zero Codecov coverage. + +* **version-check.test.ts has pre-existing unmocked fetch calls**: In getsentry/cli, \`test/lib/version-check.test.ts\` makes unmocked fetch calls to \`https://api.github.com/repos/getsentry/cli/releases/latest\` and to Sentry's ingest endpoint. These are pre-existing issues that produce \`\[TEST] Unexpected fetch call\` warnings in test output but don't cause test failures. Not related to any specific PR — existed before the Homebrew changes. + +* **@sentry/api SDK passes Request object to custom fetch — headers lost on Node.js**: The @sentry/api SDK creates a \`Request\` object with Content-Type set in its headers, then calls \`\_fetch(request2)\` with only one argument (no init). In sentry-client.ts's \`authenticatedFetch\`, \`init\` is undefined, so \`prepareHeaders(init, token)\` creates empty headers from \`new Headers(undefined)\`. When \`fetch(Request, {headers})\` is called, Node.js strictly follows the spec where init headers replace Request headers entirely — stripping Content-Type. This causes HTTP 415 'Unsupported media type' errors on POST requests (e.g., startSeerIssueFix). Bun may merge headers instead, so the bug only manifests under Node.js runtime. Fix: \`prepareHeaders\` must accept the input parameter and fall back to \`input.headers\` when \`init\` is undefined. Also fix method extraction: \`init?.method\` returns undefined for Request-only calls, defaulting to 'GET' even for POST requests. + +* **Several commands bypass telemetry by importing buildCommand from @stricli/core directly**: src/lib/command.ts wraps Stricli's buildCommand to auto-capture flag/arg telemetry via Sentry. But trace/list, trace/view, log/view, api.ts, and help.ts import buildCommand directly from @stricli/core, silently skipping telemetry. Fix: change their imports to use ../../lib/command.js. Consider adding a Biome lint rule (noRestrictedImports equivalent) to prevent future regressions. + +* **@sentry/api SDK issues filed to sentry-api-schema repo**: All @sentry/api SDK issues should be filed to https://github.com/getsentry/sentry-api-schema/ and assigned to @MathurAditya724. Two known issues: (1) unwrapResult() discards Link response headers, silently truncating listTeams/listRepositories at 100 items and preventing cursor pagination. (2) No paginated variants exist for team/repo/issue list endpoints, forcing callers to bypass the SDK with raw requests. + +* **Esbuild banner template literal double-escape for newlines**: When using esbuild's \`banner\` option with a TypeScript template literal containing string literals that need \`\n\` escape sequences: use \`\\\\\\\n\` in the TS source. The chain is: TS template literal \`\\\\\\\n\` → esbuild banner output \`\\\n\` → JS runtime interprets as newline. Using only \`\\\n\` in the TS source produces a literal newline character inside a JS double-quoted string, which is a SyntaxError. This applies to any esbuild banner/footer that injects JS strings containing escape sequences. Discovered in script/bundle.ts for the Node.js version guard error message. + +* **Craft minVersion >= 2.21.0 silently disables custom bump-version.sh**: Craft minVersion >= 2.21.0 with no \`preReleaseCommand\` switches from running \`bash scripts/bump-version.sh\` to automatic version bumping via publish targets. If the only target is \`github\` (which doesn't support auto-bump), the version bump silently does nothing. Fix: explicitly set \`preReleaseCommand: bash scripts/bump-version.sh\` in \`.craft.yml\`. + +* **npm OIDC only works for publish — npm info/view still needs traditional auth**: npm OIDC auth only works for \`publish\` — \`npm info\`, \`npm view\`, \`npm install\`, and \`npm access\` still need traditional auth (NPM\_TOKEN). For public packages, \`npm info\` works without auth. For private packages, a read-only NPM\_TOKEN is still needed alongside OIDC for version checks. ### Pattern - -* **Ownership check before permission check in CLI fix commands**: When a CLI fix/repair command checks filesystem health, ownership issues must be diagnosed BEFORE permission issues. If files are root-owned, chmod will fail with EPERM anyway — no point attempting it. The ordering in \`sentry cli fix\` is: (1) ownership check (stat().uid vs process.getuid()), (2) permission check (only if ownership is OK), (3) schema check (only if filesystem is accessible). When ownership repair succeeds (via sudo), skip the permission check since chown doesn't change mode bits — permissions may still need fixing on a subsequent non-sudo run. - -* **Sentry CLI Pattern A error: 133 events from missing context, mostly AI agents**: The #1 user error pattern in Sentry CLI (CLI-17, 110+ events, 50 users) is 'Organization and project is required' — users running commands without any org/project context. Breakdown by command: issue list (54), event view (41), issues alias (9), trace view (4). 24/110 events have --json flag (AI agent/CI usage). Many event view calls pass just an event ID with no org/project positional arg. Users are on CI (Ubuntu on Azure) or macOS with --json. The fix is multi-pronged: (1) SENTRY\_ORG/SENTRY\_PROJECT env var support (PR #280), (2) improved error messages mentioning env vars, (3) future: event view cross-project search. - -* **Store analysis/plan files in gitignored .plans/ directory**: For the Sentry CLI project, analysis and planning documents (like bug triage notes from automated review tools) are stored in .plans/ directory which is added to .gitignore. This keeps detailed analysis accessible locally without cluttering the repository. Previously such analysis was being added to AGENTS.md which is committed. - -* **Sentry CLI issue resolution wraps getIssue 404 in ContextError with ID hint**: In resolveIssue() (src/commands/issue/utils.ts), bare getIssue() calls for numeric and explicit-org-numeric cases should catch ApiError with status 404 and re-throw as ContextError that includes: (1) the ID the user provided, (2) a hint about access/deletion, (3) a suggestion to use short-ID format (\-\) if the user confused numeric group IDs with short-ID suffixes. Without this, the user gets a generic 'Issue not found' without knowing which ID failed or what to try instead. - -* **Sentry CLI setFlagContext redacts sensitive flags before telemetry**: The setFlagContext() function in src/lib/telemetry.ts must redact sensitive flag values (like --token) before setting Sentry tags. A SENSITIVE\_FLAGS set contains flag names that should have their values replaced with '\[REDACTED]' instead of the actual value. This prevents secrets from leaking into telemetry. The scrub happens at the source (in setFlagContext itself) rather than in beforeSend, so the sensitive value never reaches the Sentry SDK. - -* **Non-essential DB cache writes should be guarded with try-catch**: In the Sentry CLI, commands that write to the local SQLite cache as a side effect (e.g., setUserInfo() to update cached user identity) should wrap those writes in try-catch when the write is not essential to the command's primary purpose. If the DB is in a bad state (read-only filesystem, corrupted, schema mismatch), the cache write would throw and crash the command even though the primary operation (e.g., displaying user identity, completing login) already succeeded. Pattern: wrap non-essential setUserInfo() calls in try-catch, silently swallow errors. Applied in both whoami.ts and login.ts. Cursor Bugbot flagged the whoami.ts case — the cache update is a nice-to-have side effect that shouldn't prevent showing the fetched user data. - -* **Login --token flow: getCurrentUser failure must not block authentication**: In src/commands/auth/login.ts --token flow, the token is saved via setAuthToken() before fetching user info via getCurrentUser(). If getCurrentUser() fails after the token is saved, the user would be in an inconsistent state (isAuthenticated() true, getUserInfo() undefined). The fix: wrap getCurrentUser()+setUserInfo() in try-catch, log warning to stderr on failure but let login succeed. The 'Logged in as' line is conditional on user info being available. This differs from getUserRegions() failure which should clearAuth() and fail hard (indicates invalid token). Both Sentry Seer and Cursor Bugbot flagged this as a real bug and both suggested the same fix pattern. - -* **Sentry CLI api command: normalizeFields auto-corrects colon separators with stderr warning**: The \`sentry api\` command's \`--field\` flag requires \`key=value\` format with \`=\` separator. Users frequently confuse this with Sentry search syntax (\`key:value\`) or pass timestamps containing colons (e.g., \`since:2026-02-25T11:20:00\`). The \`normalizeFields()\` function in \`src/commands/api.ts\` auto-corrects \`:\` to \`=\` (splitting on first colon) and prints a warning to stderr, rather than crashing. This is safe because the correction only triggers when no \`=\` exists at all (the field would fail anyway). The normalization runs at the command level in \`func()\` before \`prepareRequestOptions()\`, keeping the parsing functions pure. Fields with \`=\` or ending in \`\[]\` pass through unchanged. The three downstream parsing functions (\`processField\`, \`buildQueryParams\`, \`buildRawQueryParams\`) use \`ValidationError\` instead of raw \`Error\` for truly uncorrectable fields, ensuring clean formatting through the central error handler. PR #302, fixes CLI-9H and CLI-93. - -* **Sentry CLI plural aliases use route maps with defaultCommand, not direct command refs**: In the Sentry CLI, plural command aliases (issues, projects, orgs, repos, teams, logs, traces) in app.ts point directly to list commands as leaf routes. To prevent \`sentry projects list\` from misinterpreting 'list' as a project slug, all list commands use \`buildListCommand(routeName, config)\` from \`src/lib/list-command.ts\` instead of \`buildCommand(config)\`. \`buildListCommand\` is a transparent wrapper around \`buildCommand\` that intercepts the first positional arg (target) before calling the original func. It checks if the target matches a known subcommand of the singular route (e.g. "list", "view" for "project") and replaces it with \`undefined\` (auto-detect mode) + prints a gentle stderr hint. Subcommand names are extracted dynamically per-route via \`getSubcommandsForRoute(routeName)\`, which lazy-loads the Stricli route map with \`require('../app.js')\` (breaks circular dependency, cached after first call). Three abstraction levels: - \`buildListCommand(routeName, config)\` — any list command gets interception (all 6 commands) - \`buildOrgListCommand(config, docs, routeName)\` — full factory for simple org-scoped lists (team, repo), uses buildListCommand internally - Manual \`buildListCommand\` + custom func — complex commands keep their logic (project, issue, trace, log) Migration per command is one line: \`buildCommand({...})\` → \`buildListCommand("project", {...})\`. Known trade-off: a project literally named 'list' or 'view' can't be targeted via plural alias path. Users can use \`sentry project list list\` or \`sentry projects /list\` for this edge case. PR #281. - -* **Bun supports require() in ESM modules natively — ignore ESM-only linter warnings**: Bun natively supports \`require()\` in ESM modules (files with \`"type": "module"\` in package.json). This is different from Node.js where require() is not available in ESM. AI code reviewers (BugBot, Seer) may flag \`require()\` in ESM as high-severity bugs — these are false positives when the runtime is Bun. The Sentry CLI uses \`require()\` for lazy dynamic imports to break circular dependencies (e.g. \`require('../app.js')\` in list-command.ts to extract route subcommand names). For the npm distribution, this is also safe because esbuild bundles everything into a single CJS file (\`dist/bin.cjs\`) where \`require()\` is native — esbuild resolves and inlines all requires at bundle time. Bun docs: https://bun.sh/docs/runtime/modules#using-require + +* **CLI UX: auto-correct common user mistakes with stderr warnings instead of hard errors**: When a CLI command can unambiguously detect a common user mistake (like using the wrong separator character), prefer auto-correcting the input and printing a warning to stderr over throwing a hard error. This is safe when: (1) the input is already invalid and would fail anyway, (2) there's no ambiguity in the correction, and (3) the warning goes to stderr so it doesn't interfere with JSON/stdout output. Implementation pattern: normalize inputs at the command level before passing to pure parsing functions, keeping the parsers side-effect-free. The \`gh\` CLI (GitHub CLI) is the UX model — match its conventions. + +* **Bun.spawn is writable — use direct assignment for test spying instead of mock.module**: Unlike \`node:child\_process\` imports (which require \`mock.module\` and isolated test files), \`Bun.spawn\` is a writable property on the global \`Bun\` object. Tests can replace it directly in \`beforeEach\`/\`afterEach\` without module-level mocking: \`\`\`typescript let originalSpawn: typeof Bun.spawn; beforeEach(() => { originalSpawn = Bun.spawn; Bun.spawn = ((cmd, \_opts) => ({ exited: Promise.resolve(0), })) as typeof Bun.spawn; }); afterEach(() => { Bun.spawn = originalSpawn; }); \`\`\` This avoids the mock.module bleed problem entirely and works in regular \`test:unit\` files (counts toward Codecov). Used successfully in \`test/commands/cli/upgrade.test.ts\` to test \`runSetupOnNewBinary\` and \`migrateToStandaloneForNightly\` which spawn child processes via \`Bun.spawn\`. + +* **Formatter return type migration: string\[] to string for markdown rendering**: The formatter functions (\`formatLogDetails\`, \`formatTraceSummary\`, \`formatOrgDetails\`, \`formatProjectDetails\`, \`formatIssueDetails\`) were migrated from returning \`string\[]\` (array of lines) to returning \`string\` (rendered markdown). When updating tests for this migration: (1) remove \`.join("\n")\` calls, (2) replace \`.map(stripAnsi)\` with \`stripAnsi(result)\`, (3) replace \`Array.isArray(result)\` checks with \`typeof result === "string"\`, (4) replace line-by-line exact match tests (\`lines\[0] === "..."\`, \`lines.some(l => l.includes(...))\`) with content-based checks (\`result.includes(...)\`) since markdown tables render with Unicode box-drawing characters, not padded text columns. The \`writeTable()\` function also changed from text-padded columns to markdown table rendering. + +* **Markdown table structure for marked-terminal: blank header row + separator + data rows**: When building markdown tables for \`marked-terminal\` rendering in this codebase, the pattern is: blank header row (\`| | |\`), then separator (\`|---|---|\`), then data rows (\`| \*\*Label\*\* | value |\`). Putting data rows before the separator produces malformed tables where cell values don't render. This was discovered when the SDK section in \`log.ts\` had the data row before the separator, causing the SDK name to not appear in output. All key-value detail sections (Context, SDK, Trace, Source Location, OpenTelemetry) in \`formatLogDetails\`, \`formatOrgDetails\`, \`formatProjectDetails\`, \`formatIssueDetails\`, and \`formatTraceSummary\` use this pattern. + +* **Org-scoped SDK calls follow getOrgSdkConfig + unwrapResult pattern**: All org-scoped API calls in src/lib/api-client.ts follow this pattern: (1) call \`getOrgSdkConfig(orgSlug)\` which resolves the org's regional URL and returns an SDK client config, (2) spread config into the SDK function call: \`{ ...config, path: { organization\_id\_or\_slug: orgSlug, ... } }\`, (3) pass result to \`unwrapResult(result, errorContext)\`. There are 14+ usages of this pattern. The \`getOrgSdkConfig\` function (line ~167) calls \`resolveOrgRegion(orgSlug)\` then \`getSdkConfig(regionUrl)\`. Follow this exact pattern when adding new org-scoped endpoints like \`getIssueInOrg\`. + +* **PR workflow: wait for Seer and Cursor BugBot before resolving**: After pushing a PR in the getsentry/cli repo, the CI pipeline includes Seer Code Review and Cursor Bugbot as required or advisory checks. Both typically take 2-3 minutes. The workflow is: push → wait for all CI (including npm build jobs which test the actual bundle) → check for inline review comments from Seer/BugBot → fix if needed → repeat. Use \`gh pr checks \ --watch\` to monitor. Review comments are fetched via \`gh api repos/OWNER/REPO/pulls/NUM/comments\` and \`gh api repos/OWNER/REPO/pulls/NUM/reviews\`. + +* **Isolated test files for mock.module in Bun tests**: In the getsentry/cli repo, tests that use Bun's \`mock.module()\` must be placed in \`test/isolated/\` as separate test files AND run via the separate \`test:isolated\` script (not \`test:unit\`). \`mock.module\` affects the entire module registry and bleeds into ALL subsequently-loaded test files in the same \`bun test\` invocation. Attempting to include \`test/isolated/\` in \`test:unit\` caused 132 test failures from \`node:child\_process\` mock pollution. Consequence: isolated test coverage does NOT appear in Codecov PR patch metrics. For code using \`Bun.spawn\` (not \`node:child\_process\`), prefer direct property assignment (\`Bun.spawn = mockFn\`) in regular test files instead — \`Bun.spawn\` is writable and doesn't require mock.module. + +* **OpenCode worktree blocks checkout of main — use stash + new branch instead**: When working in the getsentry/cli repo, \`git checkout main\` fails because main is used by an OpenCode worktree at \`~/.local/share/opencode/worktree/\`. Workaround: stash changes, fetch, create a new branch from origin/main (\`git stash && git fetch && git checkout -b \ origin/main && git stash pop\`), then pop stash. Do NOT try to checkout main directly. This also applies when rebasing onto latest main — you must use \`origin/main\` as the target, never the local \`main\` branch. ### Preference - -* **General coding preference**: Prefer explicit error handling over silent failures - -* **Code style**: User prefers no backwards-compat shims, fix callers directly - -* **Progress message format: 'N and counting (up to M)...' pattern**: User prefers progress messages that frame the limit as a ceiling rather than an expected total. Format: \`Fetching issues, 30 and counting (up to 50)...\` — not \`Fetching issues... 30/50\`. The 'up to' framing makes it clear the denominator is a max, not an expected count, avoiding confusion when fewer items exist than the limit. For multi-target fetches, include target count: \`Fetching issues from 10 projects, 30 and counting (up to 50)...\`. Initial message before any results: \`Fetching issues (up to 50)...\` or \`Fetching issues from 10 projects (up to 50)...\`. + +* **.opencode directory should be gitignored**: The \`.opencode/\` directory (used by OpenCode for plans, session data, etc.) should be in \`.gitignore\` and never committed. It was added to \`.gitignore\` alongside \`.idea\` and \`.DS\_Store\` in the editor/tool ignore section. + +* **CI scripts: prefer jq/sed over node -e for JSON manipulation**: Reviewer (BYK) prefers using standard Unix tools (\`jq\`, \`sed\`, \`awk\`) over \`node -e\` for simple JSON manipulation in CI workflow scripts. For example, reading/modifying package.json version: \`jq -r .version package.json\` to read, \`jq --arg v "$NEW" '.version = $v' package.json > tmp && mv tmp package.json\` to write. This avoids requiring Node.js to be installed in CI steps that only need basic JSON operations, and is more readable for shell-centric workflows. diff --git a/src/commands/issue/list.ts b/src/commands/issue/list.ts index e4b06a75ee..485d47975d 100644 --- a/src/commands/issue/list.ts +++ b/src/commands/issue/list.ts @@ -10,6 +10,7 @@ import { buildOrgAwareAliases } from "../../lib/alias.js"; import { API_MAX_PER_PAGE, findProjectsBySlug, + getProject, type IssuesPage, listIssuesAllPages, listIssuesPaginated, @@ -55,8 +56,10 @@ import { } from "../../lib/org-list.js"; import { withProgress } from "../../lib/polling.js"; import { + fetchProjectId, type ResolvedTarget, resolveAllTargets, + toNumericId, } from "../../lib/resolve-target.js"; import { getApiBaseUrl } from "../../lib/sentry-client.js"; import type { @@ -282,22 +285,46 @@ async function resolveTargetsFromParsedArg( cwd: string ): Promise { switch (parsed.type) { - case "auto-detect": + case "auto-detect": { // Use existing resolution logic (DSN detection, config defaults) - return resolveAllTargets({ cwd, usageHint: USAGE_HINT }); + const result = await resolveAllTargets({ cwd, usageHint: USAGE_HINT }); + // DSN-detected and directory-inferred targets already carry a projectId. + // Env var / config-default paths return targets without one, so enrich + // them now using the project API. Any failure silently falls back to + // slug-based querying — the target was already resolved, so we never + // surface a ResolutionError here (that's only for the explicit case). + result.targets = await Promise.all( + result.targets.map(async (t) => { + if (t.projectId !== undefined) { + return t; + } + try { + const info = await getProject(t.org, t.project); + const id = toNumericId(info.id); + return id !== undefined ? { ...t, projectId: id } : t; + } catch { + return t; + } + }) + ); + return result; + } - case "explicit": - // Single explicit target + case "explicit": { + // Single explicit target — fetch project ID for API query param + const projectId = await fetchProjectId(parsed.org, parsed.project); return { targets: [ { org: parsed.org, project: parsed.project, + projectId, orgDisplay: parsed.org, projectDisplay: parsed.project, }, ], }; + } case "org-all": { // List all projects in the specified org @@ -305,6 +332,7 @@ async function resolveTargetsFromParsedArg( const targets: ResolvedTarget[] = projects.map((p) => ({ org: parsed.org, project: p.slug, + projectId: toNumericId(p.id), orgDisplay: parsed.org, projectDisplay: p.name, })); @@ -341,6 +369,7 @@ async function resolveTargetsFromParsedArg( const targets: ResolvedTarget[] = matches.map((m) => ({ org: m.orgSlug, project: m.slug, + projectId: toNumericId(m.id), orgDisplay: m.orgSlug, projectDisplay: m.name, })); @@ -386,7 +415,7 @@ async function fetchIssuesForTarget( const { issues, nextCursor } = await listIssuesAllPages( target.org, target.project, - options + { ...options, projectId: target.projectId } ); return { success: true, @@ -928,19 +957,22 @@ async function handleResolvedTargets( } const validResults: IssueListResult[] = []; - const failures: Error[] = []; + const failures: { target: ResolvedTarget; error: Error }[] = []; - for (const result of results) { + for (let i = 0; i < results.length; i++) { + // biome-ignore lint/style/noNonNullAssertion: index within bounds + const result = results[i]!; if (result.success) { validResults.push(result.data); } else { - failures.push(result.error); + // biome-ignore lint/style/noNonNullAssertion: index within bounds + failures.push({ target: activeTargets[i]!, error: result.error }); } } if (validResults.length === 0 && failures.length > 0) { // biome-ignore lint/style/noNonNullAssertion: guarded by failures.length > 0 - const first = failures[0]!; + const { error: first } = failures[0]!; const prefix = `Failed to fetch issues from ${targets.length} project(s)`; // Propagate ApiError so telemetry sees the original status code @@ -997,10 +1029,14 @@ async function handleResolvedTargets( hasMore: hasMoreToShow, }; if (failures.length > 0) { - output.errors = failures.map((e) => + output.errors = failures.map(({ target: t, error: e }) => e instanceof ApiError - ? { status: e.status, message: e.message } - : { message: e.message } + ? { + project: `${t.org}/${t.project}`, + status: e.status, + message: e.message, + } + : { project: `${t.org}/${t.project}`, message: e.message } ); } writeJson(stdout, output); @@ -1008,9 +1044,12 @@ async function handleResolvedTargets( } if (failures.length > 0) { + const failedNames = failures + .map(({ target: t }) => `${t.org}/${t.project}`) + .join(", "); stderr.write( muted( - `\nNote: Failed to fetch issues from ${failures.length} project(s). Showing results from ${validResults.length} project(s).\n` + `\nNote: Failed to fetch issues from ${failedNames}. Showing results from ${validResults.length} project(s).\n` ) ); } diff --git a/src/lib/api-client.ts b/src/lib/api-client.ts index 5a8f615a19..73d118dc80 100644 --- a/src/lib/api-client.ts +++ b/src/lib/api-client.ts @@ -1050,12 +1050,19 @@ export async function listIssuesPaginated( perPage?: number; sort?: IssueSort; statsPeriod?: string; + /** Numeric project ID. When provided, uses the `project` query param + * instead of `project:` search syntax, avoiding "not actively + * selected" errors. */ + projectId?: number; } = {} ): Promise> { - // Only add project filter when projectSlug is non-empty; an empty slug would - // produce "project:" (a truthy string that .filter(Boolean) won't remove), - // sending a malformed query to the API for org-wide listing. - const projectFilter = projectSlug ? `project:${projectSlug}` : ""; + // When we have a numeric project ID, use the `project` query param (Array) + // instead of `project:` in the search query. The API's `project` param + // selects the project directly, bypassing the "actively selected" requirement. + let projectFilter = ""; + if (!options.projectId && projectSlug) { + projectFilter = `project:${projectSlug}`; + } const fullQuery = [projectFilter, options.query].filter(Boolean).join(" "); const config = await getOrgSdkConfig(orgSlug); @@ -1064,6 +1071,7 @@ export async function listIssuesPaginated( ...config, path: { organization_id_or_slug: orgSlug }, query: { + project: options.projectId ? [options.projectId] : undefined, // Convert empty string to undefined so the SDK omits the param entirely; // sending `query=` causes the Sentry API to behave differently than // omitting the parameter. @@ -1116,6 +1124,8 @@ export async function listIssuesAllPages( limit: number; sort?: IssueSort; statsPeriod?: string; + /** Numeric project ID for direct project selection via query param. */ + projectId?: number; /** Resume pagination from this cursor instead of starting from the beginning. */ startCursor?: string; /** Called after each page is fetched. Useful for progress indicators. */ @@ -1141,6 +1151,7 @@ export async function listIssuesAllPages( perPage, sort: options.sort, statsPeriod: options.statsPeriod, + projectId: options.projectId, }); allResults.push(...response.data); diff --git a/src/lib/db/project-cache.ts b/src/lib/db/project-cache.ts index d49784d573..4a5e42f5a6 100644 --- a/src/lib/db/project-cache.ts +++ b/src/lib/db/project-cache.ts @@ -12,6 +12,7 @@ type ProjectCacheRow = { org_name: string; project_slug: string; project_name: string; + project_id?: string; cached_at: number; last_accessed: number; }; @@ -30,6 +31,7 @@ function rowToCachedProject(row: ProjectCacheRow): CachedProject { orgName: row.org_name, projectSlug: row.project_slug, projectName: row.project_name, + projectId: row.project_id, cachedAt: row.cached_at, }; } @@ -78,6 +80,7 @@ export async function setCachedProject( org_name: info.orgName, project_slug: info.projectSlug, project_name: info.projectName, + project_id: info.projectId ?? null, cached_at: now, last_accessed: now, }, @@ -124,6 +127,7 @@ export async function setCachedProjectByDsnKey( org_name: info.orgName, project_slug: info.projectSlug, project_name: info.projectName, + project_id: info.projectId ?? null, cached_at: now, last_accessed: now, }, diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 4c4aeb922d..5bde0dbb6e 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -14,7 +14,7 @@ import type { Database } from "bun:sqlite"; import { stringifyUnknown } from "../errors.js"; -export const CURRENT_SCHEMA_VERSION = 6; +export const CURRENT_SCHEMA_VERSION = 7; /** Environment variable to disable auto-repair */ const NO_AUTO_REPAIR_ENV = "SENTRY_CLI_NO_AUTO_REPAIR"; @@ -85,6 +85,7 @@ export const TABLE_SCHEMAS: Record = { org_name: { type: "TEXT", notNull: true }, project_slug: { type: "TEXT", notNull: true }, project_name: { type: "TEXT", notNull: true }, + project_id: { type: "TEXT", addedInVersion: 7 }, cached_at: { type: "INTEGER", notNull: true, @@ -708,6 +709,11 @@ export function runMigrations(db: Database): void { db.exec(EXPECTED_TABLES.pagination_cursors as string); } + // Migration 6 -> 7: Add project_id column to project_cache for numeric project filtering + if (currentVersion < 7) { + addColumnIfMissing(db, "project_cache", "project_id", "TEXT"); + } + if (currentVersion < CURRENT_SCHEMA_VERSION) { db.query("UPDATE schema_version SET version = ?").run( CURRENT_SCHEMA_VERSION diff --git a/src/lib/resolve-target.ts b/src/lib/resolve-target.ts index 4bd4bb11fa..5e834293ac 100644 --- a/src/lib/resolve-target.ts +++ b/src/lib/resolve-target.ts @@ -38,6 +38,7 @@ import { getDsnSourceDescription, } from "./dsn/index.js"; import { + ApiError, AuthError, ContextError, ResolutionError, @@ -46,6 +47,23 @@ import { import { warning } from "./formatters/colors.js"; import { isAllDigits } from "./utils.js"; +/** + * Convert a string or numeric ID to a positive integer, or `undefined` if the + * value is absent, non-numeric, or not a positive integer. + * + * Sentry project/org IDs are always positive integers, so `0` and negative + * values are treated as absent rather than valid IDs. + */ +export function toNumericId( + id: string | number | null | undefined +): number | undefined { + if (id === null || id === undefined) { + return; + } + const n = Number(id); + return Number.isInteger(n) && n > 0 ? n : undefined; +} + /** * Resolved organization and project target for API calls. */ @@ -54,6 +72,8 @@ export type ResolvedTarget = { org: string; /** Project slug for API calls */ project: string; + /** Numeric project ID for API query params (avoids "not actively selected" errors) */ + projectId?: number; /** Human-readable org name (falls back to slug) */ orgDisplay: string; /** Human-readable project name (falls back to slug) */ @@ -135,6 +155,7 @@ export async function resolveFromDsn( return { org: cached.orgSlug, project: cached.projectSlug, + projectId: toNumericId(cached.projectId), orgDisplay: cached.orgName, projectDisplay: cached.projectName, detectedFrom, @@ -150,11 +171,13 @@ export async function resolveFromDsn( orgName: projectInfo.organization.name, projectSlug: projectInfo.slug, projectName: projectInfo.name, + projectId: projectInfo.id, }); return { org: projectInfo.organization.slug, project: projectInfo.slug, + projectId: toNumericId(projectInfo.id), orgDisplay: projectInfo.organization.name, projectDisplay: projectInfo.name, detectedFrom, @@ -165,6 +188,7 @@ export async function resolveFromDsn( return { org: dsn.orgId, project: dsn.projectId, + projectId: toNumericId(projectInfo.id), orgDisplay: dsn.orgId, projectDisplay: projectInfo.name, detectedFrom, @@ -223,6 +247,7 @@ async function resolveDsnByPublicKey( return { org: cached.orgSlug, project: cached.projectSlug, + projectId: toNumericId(cached.projectId), orgDisplay: cached.orgName, projectDisplay: cached.projectName, detectedFrom, @@ -244,11 +269,13 @@ async function resolveDsnByPublicKey( orgName: projectInfo.organization.name, projectSlug: projectInfo.slug, projectName: projectInfo.name, + projectId: projectInfo.id, }); return { org: projectInfo.organization.slug, project: projectInfo.slug, + projectId: toNumericId(projectInfo.id), orgDisplay: projectInfo.organization.name, projectDisplay: projectInfo.name, detectedFrom, @@ -294,6 +321,7 @@ async function resolveDsnToTarget( return { org: cached.orgSlug, project: cached.projectSlug, + projectId: toNumericId(cached.projectId), orgDisplay: cached.orgName, projectDisplay: cached.projectName, detectedFrom, @@ -311,11 +339,13 @@ async function resolveDsnToTarget( orgName: projectInfo.organization.name, projectSlug: projectInfo.slug, projectName: projectInfo.name, + projectId: projectInfo.id, }); return { org: projectInfo.organization.slug, project: projectInfo.slug, + projectId: toNumericId(projectInfo.id), orgDisplay: projectInfo.organization.name, projectDisplay: projectInfo.name, detectedFrom, @@ -327,6 +357,7 @@ async function resolveDsnToTarget( return { org: dsn.orgId, project: dsn.projectId, + projectId: toNumericId(projectInfo.id), orgDisplay: dsn.orgId, projectDisplay: projectInfo.name, detectedFrom, @@ -456,6 +487,7 @@ async function inferFromDirectoryName(cwd: string): Promise { const targets: ResolvedTarget[] = matches.map((m) => ({ org: m.orgSlug, project: m.slug, + projectId: toNumericId(m.id), orgDisplay: m.organization?.name ?? m.orgSlug, projectDisplay: m.name, detectedFrom, @@ -519,6 +551,38 @@ function resolveFromEnvVars(): { return null; } +/** + * Fetch the numeric project ID for an explicit org/project pair. + * + * Throws on auth errors and 404s (user-actionable). Returns undefined + * for transient failures (network, 500s) so the command can still + * attempt slug-based querying as a fallback. + */ +export async function fetchProjectId( + org: string, + project: string +): Promise { + try { + const projectInfo = await getProject(org, project); + return toNumericId(projectInfo.id); + } catch (error) { + if (error instanceof AuthError) { + throw error; + } + if (error instanceof ApiError && error.status === 404) { + throw new ResolutionError( + `Project '${project}'`, + `not found in organization '${org}'`, + `sentry issue list ${org}/`, + [ + `Check the project slug at https://sentry.io/organizations/${org}/projects/`, + ] + ); + } + return; + } +} + /** * Resolve all targets for monorepo-aware commands. * diff --git a/src/types/config.ts b/src/types/config.ts index f4981dd2fa..770df0538f 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -15,6 +15,7 @@ export const CachedProjectSchema = z.object({ orgName: z.string(), projectSlug: z.string(), projectName: z.string(), + projectId: z.string().optional(), cachedAt: z.number(), }); diff --git a/test/commands/issue/list.test.ts b/test/commands/issue/list.test.ts index 44a8370e51..9b54b24f2f 100644 --- a/test/commands/issue/list.test.ts +++ b/test/commands/issue/list.test.ts @@ -90,6 +90,18 @@ function createContext() { return { context, stdout, stderr }; } +/** Return a mock project response if the URL matches the default test project endpoint, or null. */ +function mockDefaultProject(url: string): Response | null { + if (url.includes("/api/0/projects/test-org/test-project/")) { + return Response.json({ + id: "789", + slug: "test-project", + name: "Test Project", + }); + } + return null; +} + /** Build a mock issue response */ function mockIssue(overrides?: Record) { return { @@ -114,6 +126,8 @@ describe("issue list: error propagation", () => { // listIssues hits: /api/0/organizations/test-org/issues/?query=project:test-project globalThis.fetch = mockFetch(async (input, init) => { const req = new Request(input, init); + const projectResp = mockDefaultProject(req.url); + if (projectResp) return projectResp; if (req.url.includes("/issues/")) { return new Response( JSON.stringify({ detail: "Invalid query: unknown field" }), @@ -140,6 +154,8 @@ describe("issue list: error propagation", () => { test("throws ApiError with 404 status when project not found", async () => { globalThis.fetch = mockFetch(async (input, init) => { const req = new Request(input, init); + const projectResp = mockDefaultProject(req.url); + if (projectResp) return projectResp; if (req.url.includes("/issues/")) { return new Response(JSON.stringify({ detail: "Project not found" }), { status: 404, @@ -165,6 +181,8 @@ describe("issue list: error propagation", () => { test("throws ApiError with 429 status on rate limiting", async () => { globalThis.fetch = mockFetch(async (input, init) => { const req = new Request(input, init); + const projectResp = mockDefaultProject(req.url); + if (projectResp) return projectResp; if (req.url.includes("/issues/")) { return new Response(JSON.stringify({ detail: "Too many requests" }), { status: 429, @@ -190,6 +208,8 @@ describe("issue list: error propagation", () => { test("preserves ApiError detail from original error", async () => { globalThis.fetch = mockFetch(async (input, init) => { const req = new Request(input, init); + const projectResp = mockDefaultProject(req.url); + if (projectResp) return projectResp; if (req.url.includes("/issues/")) { return new Response( JSON.stringify({ detail: "Invalid search query: bad syntax" }), @@ -297,6 +317,7 @@ describe("issue list: partial failure handling", () => { expect(output.data.length).toBe(1); expect(output.errors.length).toBe(1); expect(output.errors[0].status).toBe(400); + expect(output.errors[0].project).toBe("org-two/myproj"); }); test("stderr warning on partial failures in human output", async () => { @@ -363,13 +384,17 @@ describe("issue list: partial failure handling", () => { "myproj" ); - expect(stderr.output).toContain("Failed to fetch issues from 1 project(s)"); + expect(stderr.output).toContain( + "Failed to fetch issues from org-two/myproj" + ); expect(stderr.output).toContain("Showing results from 1 project(s)"); }); test("JSON output wraps in {data, hasMore} object", async () => { globalThis.fetch = mockFetch(async (input, init) => { const req = new Request(input, init); + const projectResp = mockDefaultProject(req.url); + if (projectResp) return projectResp; if (req.url.includes("/issues/")) { return new Response(JSON.stringify([mockIssue()]), { status: 200, @@ -464,17 +489,29 @@ describe("issue list: org-all mode (cursor pagination)", () => { nextCursor: undefined, }); + // The explicit target path calls fetchProjectId → getProject before listing. + // Spy on getProject so we don't hit the network. + const getProjectSpy = spyOn(apiClient, "getProject").mockResolvedValue({ + id: "1", + slug: "test-project", + name: "Test Project", + } as Awaited>); + const { context } = createOrgAllContext(); - // Using a real-looking cursor value (not "last") bypasses DB lookup. - // The command should resolve, fetch, and complete without throwing. - await expect( - orgAllFunc.call( - context, - { limit: 10, sort: "date", json: false, cursor: "1735689600:0:0" }, - "test-org/test-project" - ) - ).resolves.toBeUndefined(); + try { + // Using a real-looking cursor value (not "last") bypasses DB lookup. + // The command should resolve, fetch, and complete without throwing. + await expect( + orgAllFunc.call( + context, + { limit: 10, sort: "date", json: false, cursor: "1735689600:0:0" }, + "test-org/test-project" + ) + ).resolves.toBeUndefined(); + } finally { + getProjectSpy.mockRestore(); + } }); test("returns paginated JSON with hasMore=false when no nextCursor", async () => { @@ -841,6 +878,15 @@ describe("issue list: compound cursor resume", () => { const req = new Request(input, init); const url = req.url; + // fetchProjectId enrichment for explicit target + if (url.includes("/api/0/projects/test-org/proj-a/")) { + return Response.json({ + id: "100", + slug: "proj-a", + name: "Proj A", + }); + } + // listIssues for proj-a: resumed from cursor if (url.includes("/organizations/test-org/issues/")) { const cursor = new URL(url).searchParams.get("cursor"); diff --git a/test/lib/api-client.test.ts b/test/lib/api-client.test.ts index 64538d6459..23f336d66b 100644 --- a/test/lib/api-client.test.ts +++ b/test/lib/api-client.test.ts @@ -1265,4 +1265,82 @@ describe("listIssuesPaginated", () => { expect(url.searchParams.get("limit")).toBe("20"); expect(url.searchParams.get("sort")).toBe("freq"); }); + + test("uses project query param instead of project:slug when projectId is provided", async () => { + let capturedUrl = ""; + + globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + if (req.url.includes("/issues/")) { + capturedUrl = req.url; + return new Response(JSON.stringify([]), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(JSON.stringify([]), { status: 200 }); + }; + + await listIssuesPaginated("my-org", "my-proj", { projectId: 12_345 }); + + const url = new URL(capturedUrl); + // Should use project=12345 query param + expect(url.searchParams.get("project")).toBe("12345"); + // Should NOT include project:my-proj in the search query + const query = url.searchParams.get("query") ?? ""; + expect(query).not.toContain("project:my-proj"); + }); + + test("uses project:slug in query when projectId is not provided", async () => { + let capturedUrl = ""; + + globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + if (req.url.includes("/issues/")) { + capturedUrl = req.url; + return new Response(JSON.stringify([]), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(JSON.stringify([]), { status: 200 }); + }; + + await listIssuesPaginated("my-org", "my-proj"); + + const url = new URL(capturedUrl); + // Should NOT have project query param + expect(url.searchParams.has("project")).toBe(false); + // Should include project:my-proj in the search query + expect(url.searchParams.get("query")).toContain("project:my-proj"); + }); + + test("combines projectId with custom query without project:slug", async () => { + let capturedUrl = ""; + + globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + if (req.url.includes("/issues/")) { + capturedUrl = req.url; + return new Response(JSON.stringify([]), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + return new Response(JSON.stringify([]), { status: 200 }); + }; + + await listIssuesPaginated("my-org", "my-proj", { + projectId: 12_345, + query: "is:unresolved", + }); + + const url = new URL(capturedUrl); + // Should use project=12345 query param + expect(url.searchParams.get("project")).toBe("12345"); + // Search query should contain custom query but not project:slug + const query = url.searchParams.get("query") ?? ""; + expect(query).toContain("is:unresolved"); + expect(query).not.toContain("project:my-proj"); + }); }); diff --git a/test/lib/resolve-target.test.ts b/test/lib/resolve-target.test.ts index 86ea86560c..0fc1b73bcc 100644 --- a/test/lib/resolve-target.test.ts +++ b/test/lib/resolve-target.test.ts @@ -8,14 +8,20 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { array, constantFrom, assert as fcAssert, property } from "fast-check"; - +import { DEFAULT_SENTRY_URL } from "../../src/lib/constants.js"; +import { setAuthToken } from "../../src/lib/db/auth.js"; +import { setOrgRegion } from "../../src/lib/db/regions.js"; +import { AuthError, ResolutionError } from "../../src/lib/errors.js"; import { + fetchProjectId, isValidDirNameForInference, resolveAllTargets, resolveOrg, resolveOrgAndProject, resolveOrgsForListing, + toNumericId, } from "../../src/lib/resolve-target.js"; +import { mockFetch, useTestConfigDir } from "../helpers.js"; // ============================================================================ // Arbitraries for Property-Based Testing @@ -101,6 +107,63 @@ describe("isValidDirNameForInference edge cases", () => { }); }); +// ============================================================================ +// toNumericId — pure function for ID coercion +// ============================================================================ + +describe("toNumericId", () => { + test("returns undefined for undefined", () => { + expect(toNumericId(undefined)).toBeUndefined(); + }); + + test("returns undefined for null", () => { + expect(toNumericId(null)).toBeUndefined(); + }); + + test("converts string number to number", () => { + expect(toNumericId("123")).toBe(123); + }); + + test("returns number as-is", () => { + expect(toNumericId(123)).toBe(123); + }); + + test("returns undefined for string '0' (not a valid Sentry ID)", () => { + expect(toNumericId("0")).toBeUndefined(); + }); + + test("returns undefined for numeric 0 (not a valid Sentry ID)", () => { + expect(toNumericId(0)).toBeUndefined(); + }); + + test("returns undefined for negative numbers (not valid Sentry IDs)", () => { + expect(toNumericId(-1)).toBeUndefined(); + }); + + test("returns undefined for non-integer floats", () => { + expect(toNumericId(1.5)).toBeUndefined(); + }); + + test("returns undefined for empty string", () => { + expect(toNumericId("")).toBeUndefined(); + }); + + test("returns undefined for non-numeric string", () => { + expect(toNumericId("abc")).toBeUndefined(); + }); + + test("returns undefined for negative numbers", () => { + expect(toNumericId(-1)).toBeUndefined(); + expect(toNumericId("-5")).toBeUndefined(); + }); + + test("returns undefined for Infinity", () => { + expect(toNumericId(Number.POSITIVE_INFINITY)).toBeUndefined(); + expect(toNumericId(Number.NEGATIVE_INFINITY)).toBeUndefined(); + expect(toNumericId("Infinity")).toBeUndefined(); + }); +}); + // ============================================================================ // Environment Variable Resolution (SENTRY_ORG / SENTRY_PROJECT) // @@ -111,6 +174,8 @@ describe("isValidDirNameForInference edge cases", () => { // ============================================================================ describe("Environment variable resolution (SENTRY_ORG / SENTRY_PROJECT)", () => { + useTestConfigDir("test-resolve-target-"); + beforeEach(() => { delete process.env.SENTRY_ORG; delete process.env.SENTRY_PROJECT; @@ -178,6 +243,8 @@ describe("Environment variable resolution (SENTRY_ORG / SENTRY_PROJECT)", () => }); expect(result?.org).toBe("flag-org"); expect(result?.project).toBe("flag-project"); + // Explicit path no longer fetches projectId + expect(result?.projectId).toBeUndefined(); }); test("resolveOrgAndProject: ignores empty/whitespace-only values", async () => { @@ -242,6 +309,9 @@ describe("Environment variable resolution (SENTRY_ORG / SENTRY_PROJECT)", () => cwd: "/tmp", }); expect(result.targets[0]?.org).toBe("flag-org"); + expect(result.targets[0]?.project).toBe("flag-project"); + // Explicit path no longer fetches projectId + expect(result.targets[0]?.projectId).toBeUndefined(); }); // --- resolveOrgsForListing --- @@ -252,3 +322,74 @@ describe("Environment variable resolution (SENTRY_ORG / SENTRY_PROJECT)", () => expect(result.orgs).toContain("env-org"); }); }); + +// ============================================================================ +// fetchProjectId — async project ID lookup with error handling +// ============================================================================ + +describe("fetchProjectId", () => { + useTestConfigDir("test-fetchProjectId-"); + + let originalFetch: typeof globalThis.fetch; + + beforeEach(() => { + originalFetch = globalThis.fetch; + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + }); + + test("returns numeric project ID on success", async () => { + await setAuthToken("test-token"); + await setOrgRegion("test-org", DEFAULT_SENTRY_URL); + globalThis.fetch = mockFetch(async (input, init) => { + const req = new Request(input, init); + if (req.url.includes("/api/0/projects/test-org/test-project/")) { + return Response.json({ id: "456", slug: "test-project" }); + } + return new Response("Not found", { status: 404 }); + }); + + const result = await fetchProjectId("test-org", "test-project"); + expect(result).toBe(456); + }); + + test("throws ResolutionError on 404", async () => { + await setAuthToken("test-token"); + await setOrgRegion("test-org", DEFAULT_SENTRY_URL); + globalThis.fetch = mockFetch( + async () => + new Response(JSON.stringify({ detail: "Not found" }), { + status: 404, + }) + ); + + expect(fetchProjectId("test-org", "test-project")).rejects.toThrow( + ResolutionError + ); + }); + + test("rethrows AuthError when not authenticated", async () => { + // No auth token set — refreshToken() will throw AuthError + await setOrgRegion("test-org", DEFAULT_SENTRY_URL); + + expect(fetchProjectId("test-org", "test-project")).rejects.toThrow( + AuthError + ); + }); + + test("returns undefined on transient server error", async () => { + await setAuthToken("test-token"); + await setOrgRegion("test-org", DEFAULT_SENTRY_URL); + globalThis.fetch = mockFetch( + async () => + new Response(JSON.stringify({ detail: "Internal error" }), { + status: 500, + }) + ); + + const result = await fetchProjectId("test-org", "test-project"); + expect(result).toBeUndefined(); + }); +});