From 1653b9b31e0694b820f36157901a2f6ba7ef64dd Mon Sep 17 00:00:00 2001 From: mathuraditya724 Date: Thu, 23 Jul 2026 01:03:08 +0530 Subject: [PATCH] fix(init): allow org admins to create projects when member creation is disabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The preflight check in `assertOrgScopedCreationCanProceed` only checked for `org:write` scope to bypass the `allowMemberProjectCreation` flag. In Sentry's role hierarchy, the `admin` role has `project:write` and `project:admin` but NOT `org:write` (only `manager` and `owner` have it). This caused org admins to see the misleading error: "Project creation is disabled for members in " The fix broadens the scope check to also recognize `project:write` and `project:admin`, which correctly identifies admin/manager/owner roles as capable of creating projects regardless of the member creation flag. Verified against SENTRY_ROLES in sentry/conf/server.py: - member: project:read only — correctly blocked - admin: project:write, project:admin — now allowed - manager: org:write — already allowed - owner: org:write — already allowed --- .lore.md | 206 ++++++++++++++++++++++++++++++-- src/lib/init/preflight.ts | 26 +++- test/lib/init/preflight.test.ts | 50 ++++++++ 3 files changed, 266 insertions(+), 16 deletions(-) diff --git a/.lore.md b/.lore.md index cb1270faed..961ce4b09b 100644 --- a/.lore.md +++ b/.lore.md @@ -19,15 +19,9 @@ * **bspatch.ts: TRDIFF10 patch application — inline SHA-256, streaming zstd, CoW old-file copy**: TRDIFF10 header: 32 bytes (magic + controlLen + diffLen + newSize, all i64 LE). Control block decompressed fully via \`zstdDecompressSync\` (needs random access). Diff + extra blocks streamed via \`createZstdStreamReader\` (Node Transform → Web ReadableStream → \`BufferedStreamReader\`). \`applyPatch()\` ALWAYS computes SHA-256 inline and returns it — no separate verification step. \`loadOldBinary()\` copies to temp via \`COPYFILE\_FICLONE\` (CoW reflink, falls back to regular copy) then reads into memory. \`cleanupPatchResources()\` runs all cleanup steps regardless of prior failures. Write errors captured early via \`writer.on('error')\` to avoid ERR\_UNHANDLED\_ERROR on ENOSPC/EIO. - -* **check-fragments.ts: validates fragment files against actual route names**: \`script/check-fragments.ts\`: validates fragment files against actual route names (Check 1-4) AND validates subcommand coverage within fragments (Check 5). Check 5: for each route with >1 command, verifies fragment mentions each subcommand via a heading (outside fenced code blocks) or \`sentry \ \\` code reference. Default commands handled: if fragment contains bare \`sentry \\`, the default command is covered. Default commands detected from route map (\`defaultCommand\` field in route index files). Fenced code block content stripped before heading scan to avoid false positives from bash comments. Warnings by default; \`--strict\` makes them errors. Run via \`pnpm run check:fragments\`. CI \`check-generated\` job triggers when \`changes.outputs.skill == 'true'\`. - * **check:stale-refs: generic toolchain consistency scanner derived from package.json**: \`script/check-stale-references.ts\`: reads \`packageManager\` from \`package.json\` (e.g., \`pnpm@10.11.0\`), derives stale PMs dynamically, and scans dev-facing docs/scripts for stale \`\ run\`, \`\ remove\`, \`\ add -d\` commands and \`requires \\`/\`\ installed\` prerequisite prose. Excludes: user-facing install instructions (fenced code blocks with \`install -g\`/\`add -g\`), the check script itself, and \`node\_modules/\`. Added to CI lint job. \*\*Generic\*\*: if project migrates from pnpm to yarn, changing \`packageManager\` in \`package.json\` auto-flags all \`pnpm run\` references in dev docs — no manual pattern updates needed. Trap: script must exclude itself from scanning or its own JSDoc examples trigger false positives. - -* **collapse=lifetime in issue list: LIFETIME\_FIELDS, buildListApiOptions, and API gotcha**: \`src/commands/issue/list.ts\` \`LIFETIME\_FIELDS = new Set(\['count','userCount','firstSeen','lastSeen'])\` — fields stripped by \`collapse=lifetime\` on the list endpoint. \`buildListApiOptions(json, fields)\`: \`collapseLifetime\` only true when \`json && fields !== undefined && fields.length > 0 && !fields.some(f => LIFETIME\_FIELDS.has(f))\`. Human output NEVER collapses lifetime. \`buildIssueListCollapse()\` always starts with \`\['filtered','unhandled']\`, conditionally adds \`'lifetime'\` then \`'stats'\`. \`ISSUE\_DETAIL\_COLLAPSE\` safely includes \`'lifetime'\` — detail endpoint preserves top-level fields regardless. \`IssueViewOutputSchema\` in \`src/types/sentry.ts\` extends \`SentryIssueSchema\` with enrichment fields (\`event\`, \`org\`, \`replayIds\`, \`trace\`) added by \`jsonTransformIssueView\`. Wired via \`schema: IssueViewOutputSchema\` on output config in \`view.ts\`. NOTE: \`count\`/\`userCount\`/\`firstSeen\`/\`lastSeen\` always present on \`issue view\` (detail endpoint) — only potentially absent on \`issue list\` when collapse=lifetime is active. - * **Consola chosen as CLI logger with Sentry createConsolaReporter integration**: Consola is the CLI logger with Sentry \`createConsolaReporter\` integration. Two reporters: FancyReporter (stderr) + Sentry structured logs. Level via \`SENTRY\_LOG\_LEVEL\`. \`buildCommand\` injects hidden \`--log-level\`/\`--verbose\` flags. \`withTag()\` creates independent instances; \`setLogLevel()\` propagates via registry. All user-facing output must use consola, not raw stderr. \`HandlerContext\` intentionally omits stderr. Telemetry opt-out priority: (1) \`SENTRY\_CLI\_NO\_TELEMETRY=1\`, (2) \`DO\_NOT\_TRACK=1\`, (3) \`metadata.defaults.telemetry\`, (4) default on. Shell completions set \`SENTRY\_CLI\_NO\_TELEMETRY=1\` in \`bin.ts\` before imports. Timing queued to \`completion\_telemetry\_queue\` SQLite table; normal runs drain via \`DELETE ... RETURNING\`. \`ENV\_VAR\_REGISTRY\` in \`src/lib/env-registry.ts\` is single source for all honored env vars; \`topLevel: true\` + \`briefDescription\` surfaces in \`--help\`. Add install-script-only vars with \`installOnly: true\`. @@ -67,12 +61,21 @@ * **isSentrySaasUrl vs isSaaSTrustOrigin: two intentional SaaS checks**: \`src/lib/sentry-urls.ts\` exports two SaaS-detection helpers with intentional split: (1) \`isSentrySaasUrl(url)\` — hostname-only check (\`sentry.io\` or \`\*.sentry.io\`), accepts any protocol/port. Used for routing/UX: custom-headers warning, \`getSentryBaseUrl\`/\`isSelfHosted\`, region resolution skip, telemetry \`is\_self\_hosted\` tag. (2) \`isSaaSTrustOrigin(url)\` — stricter: additionally requires \`https:\` and default port. Used for security decisions: token-host trust comparison, sentryclirc URL trust check, URL-arg trust, login refusal. Rule: hostname-only for routing/UX (don't break users behind TLS-terminating proxies with \`http://sentry.io\`); strict for credential scoping. JSDoc on \`isSentrySaasUrl\` points callers to \`isSaaSTrustOrigin\` for security contexts. Keep both implementations in sync re: hostname matching. + +* **issue list collapse=stats/lifetime API gotcha: SEEN\_STATS\_FIELDS, LIFETIME\_FIELDS, buildListApiOptions**: \`src/commands/issue/list.ts\` \`LIFETIME\_FIELDS = new Set(\['count','userCount','firstSeen','lastSeen'])\` — fields stripped by \`collapse=lifetime\` on the list endpoint. \`buildListApiOptions(json, fields)\`: \`collapseLifetime\` only true when \`json && fields !== undefined && fields.length > 0 && !fields.some(f => LIFETIME\_FIELDS.has(f))\`. Human output NEVER collapses lifetime. \`buildIssueListCollapse()\` always starts with \`\['filtered','unhandled']\`, conditionally adds \`'lifetime'\` then \`'stats'\`. \`ISSUE\_DETAIL\_COLLAPSE\` safely includes \`'lifetime'\` — detail endpoint preserves top-level fields regardless. \`IssueViewOutputSchema\` in \`src/types/sentry.ts\` extends \`SentryIssueSchema\` with enrichment fields (\`event\`, \`org\`, \`replayIds\`, \`trace\`) added by \`jsonTransformIssueView\`. Wired via \`schema: IssueViewOutputSchema\` on output config in \`view.ts\`. NOTE: \`count\`/\`userCount\`/\`firstSeen\`/\`lastSeen\` always present on \`issue view\` (detail endpoint) — only potentially absent on \`issue list\` when collapse=lifetime is active. + * **Issue list sort values: SortValue type, VALID\_SORT\_VALUES, getComparator, and SDK IssueSort**: In \`src/commands/issue/list.ts\`: \`SortValue\` type (line 141, @internal) and \`VALID\_SORT\_VALUES\` array (line 143) are the CLI's local sort constraints. \`IssueSort\` in \`src/lib/api/issues.ts\` (lines 40–42) is derived from \`@sentry/api\` SDK via \`NonNullable\\['sort']>\` — no API layer change needed when adding new sort values. SDK already includes \`'date' | 'freq' | 'inbox' | 'new' | 'recommended' | 'trends' | 'user'\`. To add a new sort value: (1) add to \`SortValue\` union and \`VALID\_SORT\_VALUES\`, (2) add case to \`getComparator()\` switch (default falls back to date), (3) update flag \`brief\` string, (4) change \`default\` if needed. \`appendIssueFlags()\` guards \`--sort\` omission only when \`flags.sort !== 'date'\` — update guard if default changes. * **maxZipTotalSize: 2GiB memory-safety budget separate from server maxFileSize policy**: \`PrepareDifsOptions.maxZipTotalSize\` (default \`DEFAULT\_MAX\_ZIP\_TOTAL\_SIZE\` = 2GiB) is a cumulative uncompressed-extraction budget per \`.zip\` archive and a container size cap — it bounds peak decompression memory. It is distinct from \`maxFileSize\` (per-entry server upload policy). Commands do not need to pass \`maxZipTotalSize\` explicitly; \`prepareDifs\` applies the 2GiB default automatically. \`0\` disables the budget. Passed through \`prepareZipDifs\` → \`readZipDifEntries\` as \`maxTotalSize\`. + +* **preprod API has no list endpoint — only 4 paths exist in api-schema.json**: The Sentry preprod/build API has no list operation. Only 4 paths exist in \`api-schema.json\`: \`organizations/{org}/preprodartifacts/{artifact\_id}/install-details/\`, \`organizations/{org}/preprodartifacts/{artifact\_id}/size-analysis/\`, \`projects/{org}/{project}/preprod/size-analysis/status-check-rules/\`, \`projects/{org}/{project}/preprodartifacts/build-distribution/latest/\`. \`@sentry/api\` SDK exports confirm no list operation. A \`build list\` command cannot be implemented without a new server-side endpoint. + + +* **preprod-artifacts.ts: auth token only sent to region-origin URLs, artifacts streamed to disk**: Two hard invariants in \`src/lib/api/preprod-artifacts.ts\`: (1) Auth token is NEVER sent to third-party/signed storage URLs — \`isRegionOrigin()\` gates token attachment so it only goes to region-origin requests. (2) Large artifacts are NEVER buffered in memory — always streamed to disk via \`pipeline()\` + \`createWriteStream()\`. Constants: \`SNAPSHOT\_ARCHIVE\_POLL\_MS=2000\`, \`SNAPSHOT\_ARCHIVE\_TIMEOUT\_MS=300\_000\`. \`apiRequestToRegion\` params type: \`Record\\`. + * **Sentry CLI authenticated fetch architecture with response caching**: Authenticated fetch + response cache: \`createAuthenticatedFetch\`: auth headers, 30s timeout, max 2 retries, 401 refresh, span tracing. \`buildAttemptFactory\` clones \`Request\`; do NOT materialize FormData (strips boundary). Per-endpoint timeout overrides (e.g. \`/autofix/\` 120s). Response cache RFC 7234 at \`~/.sentry/cache/responses/\`, GET 2xx only. TTL tiers: stable=5min, volatile=60s, immutable=24h. \`@sentry/api\` SDK passes Request with no init — undefined init → empty headers stripping Content-Type (HTTP 415); fall back to \`input.headers\` when init undefined. Guard \`Array.isArray(data)\` before \`.map()\` (SDK returns \`{}\` for 204/empty). Tests mocking fetch MUST call \`useTestConfigDir()\` + \`setAuthToken()\` + \`resetCacheState()\` + \`disableResponseCache()\` + \`resetAuthenticatedFetch()\` in beforeEach — GET response cache checked BEFORE fetch, so prior test cache hits produce 0 calls. @@ -146,6 +149,12 @@ ### Gotcha + +* **@sentry/symbolic wasm-pack test never exercises the shipped artifact — use npm pack smoke test instead**: Trap: \`wasm-pack test\` looks like the right way to test \`@sentry/symbolic\` — it builds and runs tests. But it builds its own glue code and never loads the \`--target web\` \`symbolic.js\` + \`initSync\` + package \`exports\`/\`files\` that consumers actually import. Fix: use a packaged-artifact smoke test: \`npm pack\` → install tarball into tmp dir → \`import '@sentry/symbolic'\` → assert via \`node:test\`. This catches exports-map/resolution breakage and runtime errors (e.g., the \`Object\` naming bug) that \`wasm-pack test\` misses entirely. Test files live in the package dir but are excluded from \`files\[]\`; run via \`cd symbolic-wasm/npm && npm test\`. + + +* **@sentry/symbolic: naming wasm export class \`Object\` shadows JS global — breaks Object.create and Object.getPrototypeOf**: Trap: wasm-bindgen generates a JS class named after the Rust struct — naming it \`Object\` looks fine in Rust. But it shadows the JS global \`Object\` for the entire module: \`Object.create\` (used in \`objects()\`) and \`Object.getPrototypeOf\` (used in \`initSync\`) break with \`TypeError: Object.getPrototypeOf is not a function\`. Fix (PR #993): rename the export to \`ObjectFile\` via \`#\[wasm\_bindgen(js\_name = "ObjectFile")]\` and \`#\[wasm\_bindgen(js\_class = "ObjectFile")]\` — Rust struct name \`Object\` unchanged. Discovered via packaged-artifact smoke test, not \`wasm-pack test\`. Similarly, \`ObjectDebugSession\` needed \`AsSelf\` impl (PR #997) — check all new wasm-exposed types for missing \`AsSelf\` impls before using \`derived\_from\_cell!\`. + * **@stricli/core -H alias patch: pin version to 1.2.7, never remove aliases**: Trap: When Stricli throws on \`-H\` aliases used for \`--header\` or \`--host\`, removing the aliases from command files looks like the simple fix. But the project intentionally uses \`-H\` for curl-style API usage. Fix: the in-repo patch for @stricli/core (targeting 1.2.7) removes \`-H\` from the reserved list. Pin version to \`1.2.7\` (not \`^1.2.8\`) so the patch applies. Never remove \`-H\` alias usages from command files. Added in commit \`78c9b04a5\`. Cursor Bugbot and Seer both flag \`-H\` removal as blocking. @@ -155,6 +164,9 @@ * **acquireLock ENOENT: parent directory may not exist — must mkdir before writeFileSync**: acquireLock ENOENT: parent directory may not exist — must mkdir before writeFileSync + +* **Atomic-write test tautology: 'no temp files' test passes even without atomic behavior**: Trap: a test that checks 'no \`.tmp\` files left behind after install' looks like it guards atomic write behavior. But if the non-atomic path (\`writeFile\` directly) never creates \`.tmp\` files in the first place, the \`leftovers\` filter is trivially empty and the test passes with the atomic code removed entirely — confirmed via mutation test on \`byk/fix/agent-skills-atomic-write\`. Fix: the test must exercise the overwrite/update path (where a concurrent reader could observe truncation) AND inject a fault (e.g., mock \`rename\` to throw) to verify cleanup. A test that only runs the happy-path fresh-install never touches the race condition the feature guards against. Per red-green directive: if the test passes with the guard deleted, it isn't testing the guard. + * **batch-queue.ts: 404 from upstream treated as transient — provider never disabled**: Trap: \`BatchProvider.submit()\` returns \`null\` for any non-401/403 HTTP error, including 404. \`submitBatch()\` treats \`null\` as transient and falls back — no disable happens. For providers that don't implement \`/v1/messages/batches\` (e.g. MiniMax), this causes a wasted HTTP round-trip every 30s forever. Fix: add \`"not-found"\` return value for 404 in both Anthropic and OpenAI submit methods. In \`submitBatch()\`, handle \`"not-found"\` with provider-level disable: add \`disabledBatchProviders: Set\\` (keyed by provider name), persist to \`kv\_meta\` via \`setKV()\`, restore on startup. Add fast-path bypass in both \`flush()\` and \`prompt()\`. Provider-level (not per-session) because the URL is baked in at construction — one provider per process. \`groupKey()\` = \`authFingerprint(cred)|providerID\`; per-credential disable was removed in favor of per-session historically. @@ -173,24 +185,51 @@ * **bundle-sources.ts exit code 1 for no-sources relies on cli.ts never resetting exitCode — fragile invariant**: Trap: using \`this.process.exitCode = 1\` directly (at \`bundle-sources.ts:145\`) instead of throwing \`OutputError\`(=60) looks like a valid shortcut. It works today because \`cli.ts:622-649\` never resets \`exitCode\` on a clean return. But this is a fragile invariant — if \`cli.ts\` ever resets \`exitCode\`, the no-sources case silently exits 0. The \`OutputError\`(=60) idiom is the correct pattern. The \`exitCode=1\` approach was kept for consistency with \`check.ts\` pattern; a comment was added explaining the choice. Consider migrating to \`OutputError\` in a future cleanup. + +* **check:fragments only validates file existence — not subcommand coverage depth**: RESOLVED in PR #1024. \`script/check-fragments.ts\` now has Check 5: for each route with >1 command, verifies the fragment mentions each subcommand via a heading (outside fenced code blocks) or \`sentry \ \\` code reference. Default commands (e.g., \`local serve\`) are handled — if the fragment contains \`sentry \\` bare, the default command is considered covered. Default commands detected from route map \`defaultCommand\` field. Fenced code block content stripped before heading scan to avoid bash-comment false positives. Warnings (not errors) by default; \`--strict\` flag makes them errors. + * **check.ts hasId() uses !== null but ObjectFile.codeId is string|undefined — null guard mismatch**: Trap: \`check.ts\` \`hasId()\` guards \`o.codeId !== null && o.codeId.length > 0\`. Looks correct because old \`DifObjectInfo.codeId\` was \`string | null\`. But \`ObjectFile.codeId\` in \`@sentry/symbolic\` 13.4.0 is \`string | undefined\` — the getter returns \`undefined\` (not \`null\`) when Rust returns \`None\`. If \`DifObjectInfo.codeId\` is mapped as \`string | null\` (via \`?? null\`), the \`!== null\` guard works. If mapped as \`string | undefined\` (via \`?? undefined\`), the guard silently passes \`undefined\` through. Fix: ensure \`parseDebugFile\` maps \`codeId\` to \`string | null\` (using \`obj.codeId ?? null\`) so \`check.ts\`'s existing \`!== null\` guard remains correct without touching \`check.ts\`. + +* **chunk-upload gzip wire format: never emit Content-Encoding: gzip with file\_gzip field**: Trap: gzip-compressed chunks look like they should use \`Content-Encoding: gzip\` alongside the \`file\_gzip\` multipart field — standard HTTP compression convention. But zstd-aware Sentry servers reject that combination with 400 to avoid ambiguity. Fix: gzip path uses ONLY the \`file\_gzip\` multipart field with NO \`Content-Encoding\` header (legacy protocol). Zstd path uses \`Content-Encoding: zstd\` + \`file\` field (requires server opt-in via getsentry/sentry#113760+). This is a standing directive from code comments in \`src/lib/api/chunk-upload.ts\`. + * **ci.yml NODE\_VERSION pins must be exact patch — floating major silently reuses buggy cached patch**: Trap: using a floating major version like \`22.x\` in ci.yml looks safe and auto-updates. But GitHub Actions caches the resolved binary — a CVE fix (e.g. CVE-2026-48931 requiring 22.23.1/24.18.0) won't be picked up until the cache expires, silently running the vulnerable patch. Fix: always pin exact patch versions in ci.yml env vars (\`NODE\_VERSION\_22: "22.23.1"\`, \`NODE\_VERSION\_24: "24.18.0"\`). Update pins explicitly when a CVE fix requires a new patch. * **Ctrl+C mid-write on Node < 22.15 leaks lock blocking next run**: Trap: On Node < 22.15, default SIGINT (Ctrl+C) terminates the process without running exit handlers. If this happens mid-write, the WASM lock directory persists, blocking the next CLI invocation for up to 60 seconds. Fix: Add a global SIGINT handler that calls db.close() before process.exit(). + +* **dashboard revisions/restore and issue events subcommands are undocumented in fragment files**: RESOLVED in PR #1024. \`docs/src/fragments/commands/dashboard.md\` now documents \`revisions\` and \`restore\`. \`docs/src/fragments/commands/issue.md\` now documents \`events\` and \`@latest\`/\`@most\_frequent\` selectors. \`docs/src/fragments/commands/cli.md\` now documents \`defaults\` and \`import\`. \`check:fragments\` (Check 5) now validates subcommand coverage within fragment files — not just file existence. When adding new subcommands, always update the corresponding fragment in \`docs/src/fragments/commands/\` AND run \`pnpm run check:fragments\` to verify coverage. + + +* **debug-files upload: partial size-drop silently exits 0 — doUpload must receive oversizedCount**: Trap: \`doNothingToUpload\` (all-dropped path) correctly calls \`setExitCode(1)\` when \`oversizedCount > 0\`, establishing the contract that oversized files → non-zero exit. But \`doUpload\` (partial-drop path) did not receive \`oversizedCount\`/\`maxFileSize\` — so uploading 3 files where 1 was oversized exited 0 silently. Fix (PR #1146): pass \`oversizedCount\` and \`maxFileSize\` to \`doUpload\`; append scan-oversize message to failures hint; call \`setExitCode(1)\` when \`oversizedCount > 0\` even with no upload failures. Warden finding 9LL-87A on PR #1140. + + +* **delta-upgrade intermediate files: always alternate .patching.a/.b — never write to source path**: Trap: writing patch output to the same path as input looks like a simple in-place update. Fix: \`applyPatchesSequentially()\` alternates between \`${destPath}.patching.a\` and \`${destPath}.patching.b\` because the old binary is mmap'd for reading — writing to the source path truncates it and corrupts output. Single-patch chains apply old→dest directly (safe, different paths). \`cleanupIntermediates()\` called in \`finally\` block removes both intermediates via \`unlinkSync\` (ignoring errors) — always runs even on failure. This is a standing directive: 'Always clean up intermediate files, even on failure' and 'never target the same path.' + * **DEVELOPMENT.md hand-written prose is not covered by any staleness check**: DEVELOPMENT.md hand-written prose is not covered by any staleness check * **difFromCandidateBuffer: PE entries must be allowed through format filter when portablepdb is requested**: Trap: the format filter in \`difFromCandidateBuffer\` rejects PE files when \`--type portablepdb\` is specified, because \`peekFormat\` returns \`'pe'\` not \`'portablepdb'\`. But embedded PPDBs live inside PE files — blocking the PE at the format-filter stage means the PPDB is never extracted. Fix: when \`filters.formats\` includes \`'portablepdb'\`, also allow \`'pe'\` through the format gate so the parser can inspect the PE for an embedded PPDB. The PE itself is still dropped after extraction if it has no features. + +* **embeddedPpdbDif: oversized extracted PPDB dropped silently — oversizedCount not incremented**: Trap: \`embeddedPpdbDif()\` (scan.ts:628-633) returns \`null\` when the decompressed PPDB exceeds \`maxFileSize\`, but does NOT increment \`oversizedCount\`. Looks correct because the PPDB is a derived artifact, not a scanned file. But the user gets no signal that a PPDB was found and dropped — silent data loss. The existing directive (PR #1146) requires \`oversizedCount > 0\` → non-zero exit and scan-oversize message. Fix: increment \`oversizedCount\` (or return a sentinel) when an extracted PPDB is size-gated out, so the caller can report it. + * **encodeChunk silently mislabels payloads if called with 'zstd' on zstd-less runtime**: Trap: encodeChunk in chunk-upload.ts (lines 186-201, 252-254) accepts 'zstd' as input but silently falls back to gzip when zstdCompressAsync is null. The content-encoding header still claims 'zstd', causing the server to reject the payload. Fix: When zstdCompressAsync is null, reject 'zstd' input explicitly rather than silently mislabeling. + +* **error-reporting.ts: three independent 4xx classifiers must stay in sync — isUserError, classifySilenced, isUserApiError**: Trap: \`classifySilenced\` (Sentry capture gate), \`isUserError\` in \`errors.ts\` (upgrade nudge via \`getErrorUpdateNotification\`), and \`isUserApiError\` in \`telemetry.ts\` (span attribution) all classify 4xx errors independently. Adding a new silence rule to only one leaves the others out of sync — e.g., query-parse 400s were silenced in \`classifySilenced\` but still triggered the upgrade nudge until \`isUserError\` was updated. Fix: whenever a new error classification is added (e.g., \`isSearchQueryParseError\`, \`isNetworkError\`), update all three classifiers. Export shared predicates from \`errors.ts\` so all three import the same function. + + +* **eval-skill-fork.yml has no setup-node step — floating Node version bypasses pins**: Trap: \`.github/workflows/eval-skill-fork.yml\` job \`eval\` has no \`actions/setup-node\` step at all — it runs on the runner image's system Node (e.g. 24.17.0/22.23.0), the exact versions the Node-pin PR (#1145) aimed to avoid. The PR's claim 'every setup-node step is pinned' is technically true but the intent is unmet because this job never calls setup-node. Fix: add a pinned \`actions/setup-node@v6\` step with \`node-version: ${{ env.NODE\_VERSION\_24 }}\` before \`pnpm install\` in the \`eval\` job. Discovered via subagent adversarial review of PR #1145. + + +* **eval-skill-fork.yml missing setup-node — fork PRs exposed to Node regression**: Trap: PR #1145 pinned Node versions in all 4 main workflow files and the PR description claimed completeness. But \`.github/workflows/eval-skill-fork.yml\` job \`eval\` (lines 27–57) has no \`actions/setup-node\` step — it runs on the runner's system Node. This is the exact workflow exhibiting \`ERR\_STREAM\_PREMATURE\_CLOSE\` (CVE-2026-48931 regression in Node 24.17.0/22.23.0). Fix: add \`actions/setup-node@v6\` with \`node-version: ${{ env.NODE\_VERSION\_24 }}\` before \`pnpm install\` in that job. When pinning Node versions across CI, always grep ALL workflow files for \`setup-node\` AND check for jobs that invoke Node without an explicit setup step. + * **existsSync+realpathSync TOCTOU: catch ENOENT instead**: Trap: \`if (!existsSync(p)) return resolve(p); return realpathSync(p)\` looks safe but has a TOCTOU race. Also: \`realpathSync\` inside async is inconsistent. Fix: call \`await realpath(p)\` (node:fs/promises) directly; catch \`ENOENT\` to fall back to \`resolve(p)\`; log non-ENOENT errors via \`logger.debug(msg, error)\` before falling back. When mocking in vitest, mock \`node:fs/promises\` not \`node:fs\`. RELATED: In cleanup/unlink catch blocks, only log non-ENOENT errors — \`ENOENT\` during cleanup is expected. Pattern: \`if ((error as NodeJS.ErrnoException).code !== 'ENOENT') logger.debug(msg, error)\`. Pre-existing silent \`catch { // Ignore }\` blocks must be fixed to log non-ENOENT errors. Confirmed fixed in PR #1046 (\`fix/install-binary-symlink-self-copy\`). @@ -209,6 +248,9 @@ * **GitHub CI skips pull\_request workflows entirely when PR has merge conflicts**: Trap: missing CI jobs on a PR look like a workflow trigger bug or branch filter issue — easy to spend time investigating ci.yml triggers. Fix: check \`mergeable\`/\`mergeStateStatus\` first. When a PR is \`CONFLICTING\` (GitHub cannot compute the merge ref), ALL \`pull\_request\`-triggered workflows are silently skipped — only \`pull\_request\_target\` and CodeQL/external checks still run. Confirmed on sentry-cli (TypeScript) PR #1123: full Build/lint/test suite absent because \`mergeStateStatus: DIRTY\`. Resolution: rebase or resolve conflicts, then CI triggers normally. + +* **isNetworkError must NOT match ApiError(status=0) — TLS cert errors share status 0**: Trap: \`ApiError\` with \`status === 0\` looks like a network failure (no HTTP response received) and is tempting to include in \`isNetworkError()\`. But TLS certificate errors are also wrapped as \`ApiError(status=0)\` — once wrapped, \`isTlsCertError()\` cannot reliably re-detect them. Silencing all status-0 errors would suppress actionable TLS config issues. Fix: \`isNetworkError()\` matches ONLY \`error instanceof TypeError && error.message === 'fetch failed'\` (the unambiguous undici network signature). \`ApiError(status=0)\` is handled separately via an explicit \`error.status === 0\` branch in \`isUserError()\` with a comment explaining the TLS overlap. Callers that want status-0 treated as user-env check it explicitly. + * **issue list --sort recommended: client-side re-sort must be skipped for single-project results**: Trap: applying \`getComparator('recommended')\` to single-project results looks like consistent behavior. Fix: the \`isMultiProject\` guard at list.ts:1144-1148 is the ONLY client-side issue sort — it's intentionally skipped for single-project results because re-sorting would silently replace the server's recommended ranking with a \`lastSeen\` fallback. \`getComparator('recommended')\` returns \`compareDates(a.lastSeen, b.lastSeen)\` — same as \`date\` sort — so applying it to single-project results would corrupt the server's relevance ranking without any visible error. @@ -230,9 +272,6 @@ * **MastraClient has no dispose API — use AbortController for cleanup**: MastraClient has no \`close()\`/\`dispose()\` API — cleanup via \`ClientOptions.abortSignal\` (constructor) or per-prompt \`signal\`. Without explicit abort, Bun's fetch dispatcher keep-alive sockets hold the event loop alive past natural exit. Pattern in \`src/lib/init/wizard-runner.ts\`: create \`AbortController\` per \`runWizard\`, pass \`abortSignal: controller.signal\` to \`new MastraClient(...)\`, abort via \`using \_ = { \[Symbol.dispose]: () => controller.abort() }\`. Custom \`fetch\` wrapper must preserve \`init.signal\` via spread. Tests capture \`ClientOptions\` via \`spyOn(MastraClient.prototype, 'getWorkflow').mockImplementation(function() { capturedOpts.push(this.options); ... })\`. - -* **Multi-region fan-out: distinguish all-403 from empty orgs with hasSuccessfulRegion flag**: In \`listOrganizationsUncached\` (\`src/lib/api/organizations.ts\`), \`Promise.allSettled\` collects multi-region results. Don't use \`flatResults.length === 0\` to detect all-regions-failed — a region returning 200 OK with zero orgs pushes nothing into \`flatResults\`. Track a \`hasSuccessfulRegion\` boolean on any \`"fulfilled"\` settlement. Only re-throw 403 \`ApiError\` when \`!hasSuccessfulRegion && lastScopeError\`. - * **node-sqlite3-wasm param passing incompatibility**: Trap: node-sqlite3-wasm uses array parameter binding while node:sqlite uses spread syntax. Looks like drivers should be interchangeable. Fix: adapter layer in sqlite.ts converts between formats. WAL not supported in WASM version. @@ -248,15 +287,15 @@ * **OpenCode skill scan is session-scoped — new skill files installed mid-session are invisible until restart**: Trap: \`installAgentSkills()\` writes skill files to \`~/.claude/skills/sentry-cli/\` and the files appear on disk immediately — looks like OpenCode will pick them up. But OpenCode scans skills once per session at startup via \`InstanceState.make\` and memoizes the result for the session lifetime — no hot-reload. Fix: any session that started before the skill directory was created will show the old count forever. Users must start a new OpenCode session after \`sentry setup\` installs skills. Confirmed: \`init count=6\` appeared in every log across 2 days because \`~/.claude/skills/sentry-cli/\` didn't exist until Jun 25 19:38 UTC; \`debug skill\` immediately returned 7 in a fresh process. + +* **OutputError must not be preceded by a yield — causes double-render**: Trap: \`OutputError\` looks like a normal error you can throw after yielding a partial result, since other error types allow prior yields. Fix: \`OutputError\` (src/lib/errors.ts:292) is handled in \`src/lib/command.ts:723\` by re-rendering \`err.data\` via \`handleYieldedValue()\` then re-throwing — so any prior \`yield\` of the same data causes double-render. For FAILED/NOT\_RAN terminal states in \`build size\`, throw \`OutputError(result)\` directly without yielding first. + * **parseWithHash short-circuits before the main validateResourceId guard — must self-validate (CLI-1G1)**: GitHub-style \`org/project#SHORTID\` issue identifiers handled by \`parseWithHash()\` in \`src/lib/arg-parsing.ts\`, inserted in \`parseIssueArg\` AFTER the \`@\`-selector block and BEFORE the \`validateResourceId(input.replace(/\\//g,''))\` guard (line ~1115, which rejects \`#\`). Because it runs before that guard, \`parseWithHash\` MUST validate BOTH the project prefix AND the fragment itself. \`validateResourceId\` permits \`:\`, so \`:\` mixed with \`#\` is rejected explicitly. Semantics: \`org/project#ID\` → delegates to \`parseWithSlash('org/project/ID')\`; \`project#ID\` → \`project-search\` via \`parseProjectIdentifier\`; \`#ID\` → bare identifier via \`parseBareIssueIdentifier\`. \`parseProjectIdentifier\` is shared with \`parseWithColon\`. BEHAVIORAL CHANGE: \`CLI-G#anchor\` went from \`ValidationError\` → \`project-search{projectSlug:'cli-g', suffix:'ANCHOR'}\`. Test at \`arg-parsing.test.ts\` injection-hardening block updated accordingly. * **pnpm nested script invocation loses TTY — inline tsx to fix**: Trap: pnpm nested script invocation loses TTY — inline tsx to fix — Trap: \`"cli": "pnpm tsx src/bin.ts"\` creates nested pnpm invocations (pnpm → /bin/sh → pnpm → /bin/sh → tsx → node). Each inner pnpm layer pipes stdio, so \`process.stdin.isTTY\` and \`process.stdout.isTTY\` are \`undefined\` in the final Node process. Fix: inline tsx directly — \`"cli": "tsx --import ./script/require-shim.mjs src/bin.ts"\` and same for \`dev\`. - -* **pnpm test runs generate:docs + generate:sdk before vitest — too slow for direct invocation**: Trap: \`pnpm test\` (or \`pnpm run test:unit\`) runs \`generate:docs && generate:sdk\` before vitest, making the full suite take minutes even for small changes — looks like a normal test command. Fix: invoke vitest directly to skip doc/SDK generation: \`vitest run test/lib test/commands test/types\`. This drops runtime from minutes to ~2-10s. Use \`pnpm run test:unit\` only when you need the generated artifacts to be fresh (e.g., testing doc generation itself). - * **pnpm test triggers generate:docs + generate:sdk pre-steps — always times out in CI-like environments**: Trap: \`pnpm test\` looks like the standard way to run tests. But \`test:unit\` = \`pnpm run generate:docs && pnpm run generate:sdk && vitest run test/lib test/commands test/types --coverage\` — the doc/SDK generation pre-steps cause 120s+ timeouts. Fix: run vitest directly on specific test files: \`npx vitest run test/lib/dif test/commands/debug-files\` (or similar scoped paths). Use \`pnpm test\` only for final pre-commit validation. \`test:init-eval\` is the only script without the preamble (uses \`--testTimeout 600000\` instead). @@ -266,6 +305,9 @@ * **prepareZipDifs oversizedCount must NOT feed exit-driving counter — format unknown pre-decompression**: Trap: zip entry oversized warnings look like they should increment \`oversizedCount\` in \`prepareDifs\`, just like on-disk file oversize does — both are 'too large' signals. But a compressed entry's format is unknown until inflated, so it can't be attributed to the requested \`--type\`. Counting it would turn an unrelated oversized asset inside a \`.zip\` into a false 'all matched files too large' failure and wrong exit code. Fix: \`prepareZipDifs\` returns \`PreparedDif\[]\` (not \`{ prepared, oversizedCount }\`); oversized zip entries warn per-entry inside \`readZipDifEntries\` only. The \`oversizedCount\` counter in \`prepareDifs\` is exclusively for format-accurate on-disk files. + +* **preprod build-distribution/latest requires appId + platform query params**: Trap: \`projects/\/\/preprodartifacts/build-distribution/latest/\` looks like it should return the latest build without params. Fix: it requires \`?appId=\\&platform=apple|android\` — omitting either returns 400 \`{"appId":\["This field is required."],"platform":\["This field is required."]}\`. Platform accepts ONLY \`"apple"\` or \`"android"\` — Electron and other platforms are unsupported. Without a real appId that matches an uploaded build, \`latestArtifact\` will be \`null\` (valid 200, no error). + * **print-sources must never claim to preview bundle-sources while listing sources bundle-sources would skip**: Never use node\_modules/. This ensures that dependencies are managed correctly and reduces the risk of dependency conflicts. @@ -275,6 +317,12 @@ * **ruzstd partial decompression: must validate output size explicitly**: Trap: \`ruzstd::StreamingDecoder\` (unlike \`zstd::bulk::decompress\`) silently returns a partial result when passed a too-small \`size\` — it does NOT error. Fix: read \`size + 1\` bytes into the output buffer, then assert \`decompressed.len() == size\`; return \`None\` on mismatch. This matches \`zstd::bulk::decompress\` error-on-mismatch semantics. Confirmed via test: exact(560)→Some(560)✓, toosmall(550)→None✓, toolarge(570)→None✓. + +* **scan.ts difFromBuffer: calls embeddedPpdbDif for ALL formats — doubles WASM memory for non-PE files**: Trap: \`difFromBuffer()\` (scan.ts:662) calls \`embeddedPpdbDif()\` unconditionally for every buffer regardless of format — ELF, Mach-O, Breakpad all trigger a full \`new Archive(data)\` + \`objects()\` + \`asPe()\` before returning \`undefined\`. Looks correct because \`asPe()\` returns \`undefined\` for non-PE. But it contradicts the peek-before-parse strategy and doubles peak WASM linear memory across the whole scan. Fix: gate \`embeddedPpdbDif\` on \`format === 'pe'\` by threading \`peeked.format\` (on-disk path, scan.ts:511) or \`format\` (zip path, scan.ts:722) into \`difFromBuffer\`; or cheap-gate inside \`embeddedPpdbDif\` via \`peekFormat(header)\` before full parse. + + +* **scan.ts: oversized PE early-return must not skip embedded PPDB extraction**: Trap: in \`prepareFileDif\` (src/lib/dif/scan.ts), gating on a PE's on-disk size vs \`maxFileSize\` looks like a safe early-exit optimization — but it isn't PPDB-aware. A large assembly can contain a small embedded .pdb well within the limit, yet the pre-fix code returned before \`embeddedPpdbDif\` ever ran, silently dropping the extractable PDB (Bugbot finding, PR #1163, bug 47). Fix: \`embeddedPpdbDif\` cheap-peeks only the first \`PEEK\_HEADER\_BYTES\` (4096) via \`peekFormat()\` to confirm PE format before doing a second full \`Archive\` parse, so oversized-container gating never blocks embedded-content extraction. The oversized signal instead threads end-to-end: \`embeddedPpdbDif\` → \`difFromBuffer\` → \`readMatchedDif\` → \`prepareFileDif\` → \`prepareDifs\` (\`oversizedCount+=1\`), and is only counted when \`portablepdb\` format is actually requested via \`formatMatches\`. + * **sentry-cli SKILL.md has non-standard frontmatter fields (version, requires) — safe for OpenCode but worth knowing**: SKILL.md frontmatter includes \`version\` and \`requires: {bins: \["sentry"], auth: true}\` — fields not in the OpenCode skill spec. OpenCode's \`isSkillFrontmatter()\` only validates \`name: string\` and optional \`description: string\`; extra fields are silently ignored. gray-matter (js-yaml) parses the nested \`requires\` object without error. Trap: nested objects in frontmatter look like they'd cause a YAML parse failure or schema rejection. They don't — confirmed via gray-matter test and zero "failed to load skill" log entries. The skill loads correctly; absence from a session is always a stale-snapshot issue, not a parse issue. @@ -299,6 +347,9 @@ * **strip fails on Node SEA binaries — must strip BEFORE fossilize injection**: Strip debug symbols must happen BEFORE fossilize SEA injection. Trap: \`strip --strip-unneeded\` on a plain Node binary saves ~17 MiB and still runs — looks like it should work on the final SEA binary too. But after postject injects the SEA blob, \`strip\` fails: 'section .text can't be allocated in segment 2'. Fix: as of fossilize 0.7.0, stripping is built into fossilize itself — it strips the copied binary (already unsigned for macOS/Windows) BEFORE calling postject. Cross-strip from Linux to macOS silently fails (caught); native macOS runners strip correctly with \`strip -x\`. Windows skipped (no debug symbols). \`stripCachedNodeBinaries()\` was removed from \`script/build.ts\` in fossilize 0.7.0 update — fossilize handles it natively. + +* **SUPERSEDED — org listing no longer fans out per region**: In \`listOrganizationsUncached\` (\`src/lib/api/organizations.ts\`), \`Promise.allSettled\` collects multi-region results. Don't use \`flatResults.length === 0\` to detect all-regions-failed — a region returning 200 OK with zero orgs pushes nothing into \`flatResults\`. Track a \`hasSuccessfulRegion\` boolean on any \`"fulfilled"\` settlement. Only re-throw 403 \`ApiError\` when \`!hasSuccessfulRegion && lastScopeError\`. + * **symbolic-wasm: JS callback errors silently swallowed via .ok()? — must propagate as JsError**: Trap: using \`.ok()?\` on \`call1\` (JS function invocation) and \`dyn\_into::\()\` looks like idiomatic Rust error-to-Option conversion. Fix: both failures must propagate as \`JsError\` to the caller — thrown JS exceptions yield partial bundles with no feedback; non-\`Uint8Array\` returns (ArrayBuffer, plain arrays) silently skip files. Pattern: capture callback error in \`Option\\` outside closure, set it on failure, check after closure returns. Make \`with\_object\` generic over \`E: From\\` so both error paths unify. Flagged by Cursor Bugbot (Medium) and Sentry Seer (Medium) on PR #991. @@ -352,6 +403,9 @@ * **atomicWriteFile in agent-skills.ts: same-dir temp + rename guarantees no partial reads**: \`atomicWriteFile(destPath, content)\` at \`src/lib/agent-skills.ts:72\`: writes to \`.\.\.\.tmp\` in the same directory as \`destPath\`, then calls \`rename()\` into place. Same-directory placement guarantees same filesystem → POSIX atomic rename. Concurrent readers never observe a truncated or partially-written file. Temp file is cleaned up on error. Used by \`writeSkillFiles()\` (replacing in-place \`writeFile\`). Skills are written on every version — write-if-changed optimization was explicitly rejected as unnecessary. + +* **bundle-sources exit-code convention: manual exitCode=1 vs OutputError for no-sources path**: In \`src/commands/debug-files/bundle-sources.ts\`, the no-sources-found path uses \`this.process.exitCode = 1\` (not \`OutputError\`). This is a known Medium deviation from the framework-blessed pattern: \`OutputError\` (exit 60) is robust against framework finalization resetting exitCode; manual assignment is fragile. The \`-o\` flag also does NOT create parent directories (unlike \`bundle-jvm\`), so \`writeFile\` throws raw ENOENT if the parent doesn't exist. Both are accepted as-is in PR #1126 — do not 'fix' them without a follow-up PR discussion. Exit code map: ValidationError→21, success→0, no-sources→1. + * **CI Node version pinning: centralized env block per workflow file, ternary for matrix jobs**: Node CVE-2026-48931 fix: \`NODE\_VERSION\_22="22.23.1"\`, \`NODE\_VERSION\_24="24.18.0"\` (22.23.0 had the vulnerability; fix landed in 22.23.1 via nodejs/node#64004). Pattern: add top-level \`env:\` block to each workflow file (ci.yml, release.yml, sentry-release.yml, docs-preview.yml) with both constants + rationale comment. Reference via \`${{ env.NODE\_VERSION\_22 }}\`. Matrix jobs (build-npm) use ternary: \`${{ matrix.node == '24' && env.NODE\_VERSION\_24 || env.NODE\_VERSION\_22 }}\` — matrix labels stay as bare majors (\`\["22","24"]\`) for job naming. Gotcha: \`eval-skill-fork.yml\` has no \`setup-node\` step at all — must add one explicitly \[\[019f03bb-f9cf-7208-a183-d4f0074480f9]]. @@ -400,6 +454,9 @@ * **Node.js version matrix testing pattern for npm package**: Build npm package on development Node floor (22.15+), smoke-test on matrix Node versions. CI env vars: NODE\_VERSION\_20: "20.20.2" (WASM-SQLite floor), NODE\_VERSION\_22: "22.23.1", NODE\_VERSION\_24: "24.18.0". Build job: setup-node uses env.NODE\_VERSION\_22. Smoke-test job: setup-node uses matrix.node with fallback to env vars. Ensures fallback path is exercised in CI. + +* **parseIssueArg multi-line handling: first non-blank line wins (CLI-1G1)**: Issue identifiers are always single-line atomic tokens. \`parseIssueArg\` in \`src/lib/arg-parsing.ts\` uses \`LINE\_SPLIT\_PATTERN = /\r?\n/\` to split input, trims each line, and takes the first non-empty line (PR #1148, CLI-1G1). Rationale: \`.trim()\` only strips leading/trailing whitespace — embedded newlines from command substitution or agent note-appending survive and reach \`validateResourceId\`. Joining lines (like the \`api.ts\` LINE\_BREAK\_PATTERN approach) is wrong for atomic tokens because \`CLI-ABC\n\\` would produce garbage. Splitting on \`\n\` is safe because newlines are control characters already rejected by \`validateResourceId\` — splitting never breaks project display names with spaces. + * **Preserve ApiError type so classifySilenced can silence 4xx errors**: Preserve ApiError type for classifySilenced: \`classifySilenced\` (src/lib/error-reporting.ts) only silences \`ApiError\` with status 401-499 — wrapping in generic \`CliError\` loses \`status\` and causes 403s to be captured. Re-throw via \`new ApiError(msg, error.status, error.detail, error.endpoint)\` with terse message (\`ApiError.format()\` appends detail/endpoint). \`ValidationError\` without \`field\` collapses unfielded errors into one fingerprint; always pass \`field\`. Fingerprint rule changes don't retroactively re-fingerprint — manually merge new groups into canonical old parents. \`ApiError\` rule keys by \`api\_status + command\`. @@ -444,15 +501,39 @@ ### Preference + +* **Always add new check scripts to both package.json and CI workflow**: When introducing a new check or validation script, the user expects it to be registered in two places simultaneously: (1) as a named script in \`package.json\` alongside other \`check:\*\` scripts, and (2) as a \`- run: pnpm run \\` step in \`.github/workflows/ci.yml\`. Never add to only one location. This applies to any new linting, validation, or verification script added to the project. + + +* **Always check CI/PR status after opening or updating a pull request**: After creating or pushing changes to a pull request, the user consistently checks the CI check status (e.g., via 'gh pr checks' or similar tooling) to monitor pass/fail/pending state of automated checks such as lint, typecheck, unit tests, security scans, and bot code reviews (Cursor Bugbot, Seer Code Review). When assisting, proactively run or offer to run PR status checks after PR creation/updates, summarize pass/pending/fail counts, and flag any pending or failing checks that need attention before considering the PR ready to merge. + + +* **Always clarify that the repo uses plain git (not jj) when jj commands fail**: When a jj command fails with 'no jj repo in .', the user consistently clarifies that the repo is a plain git repo and that jj's 'never fails on conflict' behavior is being referenced conceptually — meaning conflicts should be recorded/resolved rather than aborting operations. The agent should: (1) fall back to git commands immediately without retrying jj, (2) handle merge conflicts by stashing, pulling, and resolving (e.g., \`git checkout --theirs\` for files like \`.lore.md\`), and (3) not attempt \`jj git init\` or any jj initialization. This pattern appears at the start of every build session. + + +* **Always compare PR branch against main before reviewing changes**: When reviewing a PR, the user consistently wants to understand exactly what changed in the PR branch versus main before diving into the content. This means fetching the remote branch if not available locally, running \`git log main..origin/\\` to see commits, and \`git diff\` (with stat) to understand the scope of changes. The user explicitly frames this as needing to know 'what changes were made vs what actually exists on main.' Always establish this baseline diff context first before analyzing or discussing PR content. + + +* **Always conduct thorough PR reviews with severity-classified findings**: PR review standards: (1) Compare branch vs main first (\`git log main..origin/\\`, \`git diff --stat\`). (2) Verify every PR description claim against actual source files at specific line numbers — never trust PR metadata. (3) Classify findings as BLOCKING vs NON-BLOCKING with file paths and line numbers. (4) Flag LLM-generated planning artifacts (e.g., DOCS-AUDIT.md) as blocking violations of repo conventions. (5) Investigate root causes — check bundle output, trace esbuild variable renaming, identify silent regressions. (6) Run relevant check scripts and grep codebase directly rather than reasoning from PR metadata. + + +* **Always create a dedicated branch when updating fossilize versions**: When a new version of fossilize is released, always create a branch named \`chore/fossilize-{version}\` tracking origin/main, update the dependency, remove any functionality now handled natively by fossilize (e.g., \`stripCachedNodeBinaries()\` removed in 0.7.0), verify the build succeeds, then commit with \`chore: update fossilize to X.Y.Z\`. Follow this exact pattern: branch → update dep → remove superseded code → build verify → commit → PR. + * **Always Directs to Resolve Merge Conflicts and Ensure Compatibility**: The user consistently directs the assistant to resolve merge conflicts, ensure compatibility, and verify code changes before merging. This includes rebasing branches, resolving conflicts, and verifying code changes. The user also emphasizes the importance of backwards and forwards compatibility during transitions and releases. * **Always ensures merge readiness before merging**: The user consistently seeks to ensure that all prerequisites are met before merging, including assessing the impact of changes, verifying CI checks, evaluating test coverage, and confirming the correctness of the code and its documentation. The user also tends to consider the user-facing aspects and potential issues that may arise after merging. + +* **Always explore e2e test infrastructure thoroughly before debugging or modifying tests**: When approaching e2e test work, always explore the full infrastructure before making changes: \`test/e2e/\` (14 files: api, auth, bundle, completion, delta-upgrade, event, issue, library, log, multiregion, project, skill-eval, telemetry-exit, trace), \`test/fixture.ts\` (getCliCommand, runCli, createE2EContext), \`test/helpers.ts\` (useTestConfigDir, useEnvSandbox, resetHostScopingState, mintSntrysToken, extractFetchUrl), \`test/mocks/\` (server.ts, routes.js, multiregion.ts), \`src/bin.ts\`, \`src/cli.ts\`. Key: \`getCliCommand()\` returns \`\[SENTRY\_CLI\_BINARY]\` if set, else \`\[process.execPath, 'run', 'src/bin.ts']\`. \`createE2EContext.run()\` sets \`SENTRY\_AUTH\_TOKEN: ''\`, \`SENTRY\_TOKEN: ''\`, \`SENTRY\_CLI\_NO\_TELEMETRY: '1'\`. \`test:e2e\` runs without \`--isolate --parallel\`. Map full infrastructure before proposing fixes. + * **Always fetchable from the base repo with github**: User stated always fetchable from the base repo with github. + +* **Always flag import framework mismatches as blocking CI issues in PR reviews**: When reviewing PRs, the user consistently identifies test files using the wrong import framework (e.g., \`bun:test\` instead of \`vitest\`) as a BLOCKING issue, not a non-blocking suggestion. This applies when the project has migrated frameworks and all other test files use the new one. The user expects the reviewer/assistant to explicitly label it as blocking (B1, B2, etc.) and distinguish it from non-blocking issues (N1, N2, etc.), using a clear severity classification system in PR review feedback. + * **Always follow a standard workflow for PR creation and merging**: The user consistently enforces a standard workflow for creating and merging Pull Requests (PRs). This workflow includes creating a branch with a specific naming convention (e.g., \`fix/\-\\`), committing changes with a \`.lore.md\` file, creating a PR, and waiting for CI checks and bot reviews to complete before merging. The user also emphasizes the importance of proper issue tracking, cross-linking tasks, and regenerating patches when necessary. @@ -468,6 +549,9 @@ * **Always investigate build configurations and dependencies when researching Node version compatibility**: The user consistently researches build configurations (esbuild, bundle scripts) and dependency management when evaluating Node version compatibility. They specifically examine how external dependencies like SQLite modules are handled, including import patterns, externalization in bundlers, and fallback mechanisms. The user wants to understand the complete dependency chain and build pipeline implications when supporting different Node versions. + +* **Always investigate root cause by tracing through multiple specific code layers before accepting a fix**: When facing a runtime bug (especially undefined values from framework internals), the user consistently demands thorough investigation across multiple layers — framework source code (node\_modules), wrapper utilities, bundler config, and call sites — before accepting any fix. The user explicitly rejects surface-level explanations and pushes for tracing the exact code path that produces the unexpected value. Only after exhausting the investigation does the user accept a defensive fix strategy. When directing investigation, the user specifies concrete areas to search (e.g., 4 specific code locations). Always read and analyze the relevant framework internals, not just application code. + * **Always maintain zero runtime dependencies with bundled WASM fallback**: User consistently requires that the CLI maintain zero runtime dependencies. For features requiring native modules (like SQLite), they prefer bundling a WASM fallback driver in the npm package for older Node versions, while using native modules on newer Node versions. The standalone SEA binary must always use native modules and never bundle WASM. All dependencies must be devDependencies, bundled at build time via esbuild, with CI enforcing zero runtime dependencies. @@ -477,12 +561,24 @@ * **Always Monitor CI Status**: The user consistently checks and verifies the status of CI checks, including Validate generated files, CodeQL, and other workflows. They also investigate and address failures, often by identifying root causes and applying fixes. Additionally, the user monitors and confirms the resolution of transient issues and ensures that all required checks pass before proceeding with the PR. + +* **Always monitor PR CI checks until fully green before proceeding**: After opening or updating a PR, the user consistently wants the assistant to poll and report GitHub Actions CI status repeatedly (build jobs, unit tests, E2E tests, lint, security scans, etc.) until all checks pass. When a check is pending, keep polling rather than stopping early. When a check fails, investigate the specific failing job/step (fetch run ID, job ID, logs) to determine if it's a genuine issue or flaky test before deciding next steps. Only consider the PR ready (e.g., for merge) once mergeStateStatus is CLEAN and all required checks are pass/skipping. Report status updates with concrete details: check names, pass/fail/pending state, durations, job IDs, and run URLs. + * **Always perform comprehensive adversarial code reviews before merging**: The user consistently requests and performs detailed adversarial code reviews before merging significant changes. This includes: 1) Providing complete code context and test results, 2) Analyzing edge cases and failure scenarios, 3) Identifying security and reliability issues across multiple categories (BLOCKING, SHOULD-FIX, NIT), 4) Verifying fixes through systematic testing, 5) Ensuring CI passes across all configurations. The review covers both implementation details and broader architectural implications, with particular focus on error handling, resource management, and cross-process interactions. * **Always perform rigorous, read-only code reviews with specific focus areas**: The user consistently conducts critical, adversarial code reviews in a read-only manner, focusing on specific technical areas. They provide detailed context about the repository, branch, and changes under review, and specify exact focus areas like path correctness, dependency management, build configurations, and security implications. The user maintains strict read-only discipline, prohibiting any modifications to source files, and often works within isolated worktrees. They expect thorough verification of technical changes against documented requirements and prior decisions. + +* **Always perform thorough codebase exploration before designing or implementing fixes**: When investigating a bug or feature, the user consistently requests comprehensive upfront exploration across multiple files before any code changes. This includes: reading relevant command and API files completely, searching for all references to key terms/parameters, checking type definitions in SDK/node\_modules, and understanding the full data flow from flags to API calls. The user expects the assistant to map out the entire call chain, identify misleading comments, and surface all related code paths before proposing a solution. Do not jump to fixes — first read all relevant files thoroughly and report findings. + + +* **Always perform thorough quality reviews of PRs distinguishing blocking vs non-blocking issues**: When reviewing PRs, the user expects a structured quality review that: (1) categorizes issues as BLOCKING vs non-blocking/low-priority, (2) verifies each claimed change against the actual codebase, (3) flags LLM-generated planning artifacts (e.g., DOCS-AUDIT.md) that violate repo conventions as blocking issues, (4) checks for missed/inconsistent changes across all affected files, and (5) confirms correct changes are working as intended. The user wants specific file paths and line numbers cited for each issue. Non-blocking issues should still be reported but clearly distinguished from blockers. + + +* **Always plan systemic fixes with structured multi-problem breakdowns before implementation**: When the user identifies documentation or tooling issues, they consistently organize them as numbered problems with precise file locations, line numbers, and root causes before any code is written. They expect the assistant to engage at the planning level first — proposing detection strategies, fix approaches, and tradeoffs — and to consolidate related problems (e.g., merging overlapping tasks) rather than treating each in isolation. Plans are written to files and iterated on. Implementation only follows after the plan is agreed upon. The user prefers systemic/automated fixes (e.g., derive patterns from package.json) over one-off patches. + * **Always plans for testing or verification of tasks**: The user consistently implies a need for testing or verification of tasks, as seen in multiple instances where they either directly request tests or imply the necessity for verification. This pattern is observed across various sessions where the user is planning and executing tasks, indicating a preference for ensuring that tasks are validated or tested. @@ -528,6 +624,9 @@ * **Always research distribution architecture before implementation**: The user consistently performs deep architectural research on distribution mechanisms before making implementation decisions. This includes examining package.json (bin, files, exports, engines), build scripts, polyfills, runtime detection, CI/CD workflows, and documented policies. The research is read-only and focuses on understanding how the software is built, bundled, and distributed across different platforms and environments. + +* **Always research technical approaches thoroughly before implementation**: When facing a significant technical decision or migration, the user consistently requests deep research into multiple approaches before writing any code. This includes: fetching specific upstream documentation/source files (e.g., BUILDING.md, configure.py), identifying concrete flags/options, estimating build times, and evaluating cross-compilation feasibility. The user wants tradeoffs between paths laid out explicitly. Only after research is complete does implementation begin. When presenting research, include specific flags, URLs, estimated costs (time/size), and platform constraints. + * **Always resolve a string (or change the type definition)**: User stated always resolve a string (or change the type definition). @@ -540,9 +639,18 @@ * **Always specify exact version requirements and constraints**: The user consistently provides precise version requirements and technical constraints when discussing dependencies, platform support, and compatibility. This includes specifying exact Node.js version floors (e.g., '>=18.0'), defining version ranges for conditional logic (e.g., 'Node 18–22.14'), and setting strict version pins in CI configurations. The user expects these constraints to be accurately implemented and documented across all relevant files. + +* **Always stage all modified files before committing, not just already-staged ones**: When preparing to commit, the user reviews git status and expects ALL modified files to be staged together — not just files already in the index. If unstaged modified files exist alongside staged ones, the user treats this as an incomplete commit state that needs to be resolved before proceeding. The user reviews the full list of changed files (staged + unstaged) as a checklist against completed tasks, and expects the commit to encompass all related changes from the session as a single coherent unit. + + +* **Always store plans as markdown files in the \`.opencode/plans\` directory with timestamp-prefixed filenames**: When working in plan mode, the user expects plans to be written to \`.opencode/plans/\` as markdown files. Filenames follow the pattern \`{timestamp}-{slug}.md\` (e.g., \`1779289703678-sentryclirc-migration.md\`). Some plans use descriptive slugs without timestamps (e.g., \`require-conventional-pr-title.md\`). Plans are created before implementation begins, and the assistant should call \`plan\_exit\` when done planning. Plans may be edited iteratively during the planning phase before switching to build mode. + * **Always switch from plan mode to build mode before executing changes**: The user consistently uses a two-phase workflow: first planning (read-only exploration, writing a plan file), then explicitly approving a switch to build/agent mode before any changes are executed. When the user approves the mode switch, the assistant should immediately begin executing the existing plan file — typically by re-reading the key files to be modified. Never execute changes while still in plan mode, even if the plan is complete and approved. Wait for the explicit mode-switch approval before acting. + +* **Always track migration progress with explicit completion criteria and remaining blockers**: The Bun→Node migration is complete only when \`Bun.build({ compile: true })\` is replaced by fossilize in \`script/build.ts\`. As of the current session, \`script/build.ts\` already uses fossilize (\`--no-bundle\`, \`--out-dir dist-bin\`, \`--node-version lts\`) with esbuild for bundling — the migration is complete. NODE\_VERSION='lts' in build.ts. The user expects the assistant to track this state across sessions and confirm the migration is done. When resuming sessions, verify \`script/build.ts\` does not contain \`Bun.build({ compile: true })\` before declaring migration complete. + * **Always track pre-existing failures separately from introduced regressions**: When running tests, the user consistently distinguishes between failures that existed before their changes and failures caused by their changes. They verify pre-existing failures by checking out main/stashing changes and confirming the same failures reproduce. Only new failures introduced by the current branch are treated as actionable. When reporting test results, always clarify which failures are pre-existing (with evidence) versus newly introduced, and never treat pre-existing failures as blockers for the current fix. @@ -579,38 +687,110 @@ * **Always verify PR claims against actual codebase before accepting changes**: When reviewing a PR, the user consistently directs the assistant to check each stated claim against the real source files on the main branch rather than trusting the PR description or commit messages. This applies especially to documentation PRs: the user wants specific file paths, line numbers, and code excerpts cited as evidence. The user also cross-checks automated tooling (scripts, CI configs) against what they actually produce. When a PR introduces fixes, the user wants confirmation that the underlying problem genuinely existed and that the fix is correct — not just that the PR author says so. Always run the relevant check scripts and grep the codebase directly rather than reasoning from PR metadata alone. + +* **Always work around the worktree conflict error when merging to main**: When merging PRs locally, the user consistently encounters \`fatal: 'main' is already used by worktree at ...\` and expects a workaround to be applied automatically rather than treating it as a blocking error. The merge is always completed successfully despite this error (e.g., using \`gh pr merge\` via CLI or other workaround). Never stop or report failure when this specific worktree conflict appears — proceed with the merge using an alternative method and confirm the PR was merged successfully. + + +* **Always work from a structured plan file before executing multi-step tasks**: When tackling multi-step or multi-file changes, the user consistently creates a formal plan file (e.g., \`.opencode/plans/\-\.md\`) during a planning phase before any edits are made. The plan enumerates discrete numbered tasks with priorities and target files. Execution only begins after the user explicitly approves the plan. During execution, tasks are marked in\_progress and completed sequentially. The user expects this plan-then-execute workflow to be followed strictly — no file edits during planning, and tasks tracked against the approved plan. + * **Always write tests alongside implementation**: Behavioral pattern detected across 8 sessions (action: requested-tests). The user consistently demonstrates this behavior. * **Call plan\_exit to indicate planning done**: Always call plan\_exit to indicate that planning is done. + +* **Designer Steven Lewis directs Dammit Sans for headings, Rubik for body**: Steven Lewis is the designer for the sentry-cli docs site. His direction: use Dammit Sans for headers, Rubik for body. Dammit Sans will eventually be scoped mainly to larger headings (h1 + some h2s). Dammit Sans missing glyphs: \`/ \* \ | ^ \_ \\\`\` plus \`#\` and \`~\` — fall back to Rubik Variable. + + +* **Enforce internal wrapper conventions over direct Stricli imports**: When implementing or reviewing CLI commands in this codebase, always use the project's internal wrapper modules instead of importing directly from '@stricli/core'. Specifically: import \`buildRouteMap\` from \`../../lib/route-map.js\` (which auto-injects standard aliases: list→ls, view→show, delete→remove/rm, create→new — do not add these manually), and use \`buildCommand\` from \`../../lib/command.js\` for all commands (which injects hidden flags like --log-level, --verbose, --org, --project, --fields, and handles auth/skipRcUrlCheck logic). When adding a new route/command, always update \`src/app.ts\` in two places: the alphabetical import block and the top-level \`routes\` object (plus \`hideRoute\` only if needed). Before implementing new features, research existing similar commands/patterns in the codebase (e.g., mirror \`build upload\` for \`build download\`, reuse streaming logic from \`upgrade.ts\`) rather than writing from scratch. + + +* **Enforce read-only, verification-first workflow for code reviews and asset/config work in getsentry/cli**: When the user requests a code review, PR audit, or investigation in the getsentry/cli repo (or similar), they consistently mandate a strict read-only discipline: never edit, write, or 'fix' files during review; record sha256 checksums (or diffs) of all files that will be touched before running any commands; restore files byte-identically if anything gets mutated; and confirm git status is clean afterward. They also expect rigorous, adversarial verification of concrete claims (e.g., exact character/column widths, banner never wraps, PR description matches actual diff) rather than taking descriptions at face value. When exploring history (PR commits, branch state, prior related PRs/issues), the user wants tool-based evidence (commit SHAs, diffs, metadata) cited rather than assumptions. Apply this pattern whenever asked to review, audit, or verify code/PRs/assets: default to read-only, checksum before/after, and independently verify specific technical assertions. + + +* **Enforce strict read-only adversarial code review protocol for PR reviews**: When asked to review a PR or commit in the getsentry/cli repo, treat it as a critical/adversarial, READ-ONLY review: never modify, write, or fix source files. Before running any commands, record checksums (sha256sum) of files expected to change; if any mutation occurs, restore files byte-identically and confirm \`git status --short\` is clean afterward. Builds/tests are allowed only if output is isolated (e.g., to dist/) and don't touch tracked source. Verify claims empirically rather than trusting the PR description — actually measure/compute things like column widths, row/array lengths, hash equality between duplicated files, and test boundary conditions. Explicitly confirm the scoped set of changed files matches expectations, and flag any invariant (e.g., 'never wraps', behavior parity) that isn't verifiably guaranteed across all consumers/code paths. + + +* **Ensure banner-related file changes stay synchronized across duplicate implementations**: When modifying the CLI banner (BANNER\_ROWS, BANNER\_GRADIENT, or related quadrant-block art/colors), the user expects perfect consistency between all files that duplicate this data, especially src/lib/banner.ts and src/lib/init/ui/ink-ui.ts. Always verify row counts, gradient stops, and byte-for-byte content match (e.g., via sha256 checksums) across duplicated definitions. When requesting reviews, treat this synchronization as a key correctness criterion. Also expect the user to favor incremental, tiered solutions (e.g., full/wordmark/text fallback) for responsive design problems, deferring more complex approaches (like sixel graphics) for later. When given recommended options in prompts, the user typically accepts the assistant's suggested/recommended choice rather than customizing further. + * **Follow consistent code style conventions**: Behavioral pattern detected across 3 sessions (action: corrected-style). The user consistently demonstrates this behavior. + +* **Follow the established git workflow (branch, PR, review)**: Behavioral pattern detected across 6 sessions (action: enforced-workflow). The user consistently demonstrates this behavior. + * **Ink import behavior**: User stated code should 'never calls \`import("ink")\` at runtime —', indicating a preference against runtime imports of Ink library. + +* **Iterate on brand/design assets with review checkpoints and strict read-only verification**: User is actively managing a documentation site rebrand (logos, OG images, accent colors, wordmarks) across multiple sessions, iterating incrementally: choosing among assistant-recommended options for colors/design (preferring the 'recommended' choice), deferring some items to later commits, then circling back to complete them. User also engages in a separate strict adversarial review pass of the same PR, mandating read-only discipline (sha256 checksums before/after, byte-identical restoration, clean git status verification) and expects the assistant to catch discrepancies between PR descriptions and actual diffs. When resuming design work, expect the user to ask to 'proceed with' previously deferred/planned items rather than starting fresh. When reviewing, never modify files—always checksum before touching, verify after, and flag stale/inaccurate PR descriptions relative to the real commit diff. + * **Monorepo setup for toolkit**: Always resolve merge conflicts manually in .lore.md — applies to CLI and MCP. This ensures that changes to the changelog are reviewed and intentional. * **Never throws - errors are caught and reported to Sentry**: Never throws - errors are caught and reported to Sentry. This ensures that the application remains stable and provides useful error information. + +* **Never treat incomplete operations as successful — always surface silent failures**: When reviewing code, the user explicitly asserts that incomplete operations must never report success. Examples from \`debug-files upload\`: \`not\_found\` after deadline is a failure (exit 1), not success (exit 0). Symlink cycles must not hang silently. Missing requested IDs must be surfaced. Any failure path that silently exits 0 or produces no diagnostic is a blocker. + * **Never use node\_modules/**: User stated never to use 'node\_modules/.'. + +* **Never uses form-data at runtime — only dev transitive dependency via @types/node-fetch**: User stated never uses form-data at runtime — only dev transitive dependency via @types/node-fetch. + + +* **Perform rigorous code-only reviews cross-checked against legacy Rust CLI**: When reviewing ported TypeScript Sentry CLI features (e.g., 'build upload', VCS metadata), the user requests a critical, objective code review without writing any code. Always: (1) fetch and read the corresponding legacy Rust implementation fully to cross-check behavior/parity, (2) read all relevant TS source and test files in full, (3) run \`pnpm exec tsc --noEmit\` and \`pnpm exec vitest run\` on affected test paths and report exit codes/results, (4) produce findings categorized strictly by severity (Critical/High/Medium/Low/Nit), each with exact file:line references and a concrete, specific fix suggestion, (5) be skeptical and find real functional bugs or behavioral divergences from Rust, not style nits, (6) explicitly flag any deviations from documented CLI behavior or use cases as blockers if they break primary workflows. Do not modify code during these review sessions—only report findings and let the user decide on fixes. + * **Prefers Bun-native APIs over Node**: prefer Bun-native APIs over Node. - + +* **Prefers freshly-created location over existing**: \`installAgentSkills()\` in \`src/lib/agent-skills.ts\` returns \`results.find(location => location.created) ?? results\[0] ?? null\` — prefers freshly-created location over existing. Installs to \`~/.agents/skills/sentry-cli/\` and \`~/.claude/skills/sentry-cli/\` only. Detection: \`detectClaudeCode()\` checks \`existsSync(join(homeDir, '.claude'))\`; installer never creates top-level agent roots — presence of root dir is the detection signal. OpenCode is detected via \`OPENCODE\_CLIENT\` env var in \`detect-agent.ts\` for telemetry only — NOT for skill installation. No OpenCode skill install path exists anywhere in the repo. + + +* **Refine ASCII/block-art CLI banner rendering with iterative visual verification**: When working on the Sentry CLI's ASCII/Unicode block-art banner (src/lib/banner.ts), the user is meticulous about pixel-accurate, legible wordmark reproduction. They provide reference images (e.g., sentry-ref.webp), scrutinize letterform legibility (e.g., flagged the 'E' being unreadable), and expect the assistant to: (1) verify image dimensions/scale, (2) analyze font/duty-cycle characteristics, (3) test multiple sampling/rendering strategies (threshold-downsample, monospace grid mapping, block-glyph density), (4) compare aspect ratios and column/row counts against source, and (5) generate multiple candidate options with tradeoffs (legibility vs. scanline texture) for user selection. When reviewing related PRs, the user also enforces strict read-only discipline (sha256sum verification, no edits, clean git status). Always iterate empirically on rendering parameters and present concrete side-by-side comparisons rather than a single guess. + + +* **Request read-only critical code reviews with severity-tagged findings**: When user asks for a code review of a PR/feature (often ports of legacy Rust sentry-cli functionality into the TypeScript CLI), they explicitly forbid writing or editing code — only produce findings. Provide output organized by severity levels (Critical/High/Medium/Low/Nit), with each finding including a concrete file:line reference and a specific suggested fix. User expects a rigorous, skeptical, objective review that surfaces real bugs and correctness/security issues rather than style nits. User typically specifies exact files/functions to read in full and provides context like repo path, branch, PR number, and that the code is a port from the legacy Rust implementation for cross-checking behavioral parity. Assistant should read all specified files fully, compare against the Rust reference when applicable, and compile a structured severity-ranked report without modifying any code. + + +* **Request rigorous port-fidelity code reviews against legacy Rust implementation**: When reviewing TypeScript ports of legacy Rust sentry-cli functionality (e.g., snapshots diff, build VCS metadata), the user expects a critical, objective, findings-only code review (no code changes) that: (1) reads all relevant new files fully, (2) cross-checks logic and semantics line-by-line against the original Rust source and any third-party libraries/binaries it wrapped (e.g., odiff, pixelmatch), (3) verifies wire-format/field names, default option values, and edge-case behavior (e.g., threshold scaling, antialiasing inversion, decoder output formats) match exactly, (4) runs tsc --noEmit and relevant vitest suites as verification, and (5) organizes findings by severity (Critical/High/Medium/Low/Nit) with file:line references and concrete fixes. Assistant should proactively investigate subtle divergences from Rust behavior (e.g., missing event-payload parsing, gitignore handling differences) rather than assuming the port is equivalent. + + +* **Require adversarial read-only subagent review for merged dependency/patch-bump PRs**: When a PR bumps patched dependencies or regenerates patches (e.g., @sentry/core, @sentry/node-core, @stricli/core version bumps with custom tree-shaking patches), after it's merged the user wants a separate, critical, adversarial, read-only review performed in an isolated git worktree checked out at the merged commit with a fresh install. The review must: (1) never modify source, patch, or lockfile files—builds/tests only writing to dist/; (2) verify checksums/git status to prove read-only discipline; (3) check for dangling references in both CJS and ESM builds after export stripping; (4) verify completeness of stripped exports vs new version's additions; (5) confirm no unintended lockfile/dependency changes; (6) validate PR description's numeric claims; (7) run check:patches/tsc and assess safety-net gaps. Use a subagent (or dedicated review pass) with a detailed, prioritized checklist and deliver a clear verdict (e.g., PASS / FOLLOW-UP NEEDED / BLOCKER) at the end. + + * **Respect explicitly rejected approaches**: Behavioral pattern detected across 13 sessions (action: rejected-approach). The user consistently demonstrates this behavior. * **Review code before committing**: Behavioral pattern detected across 9 sessions (action: requested-review). The user consistently demonstrates this behavior. + +* **Review code before committing**: Behavioral pattern detected across 7 sessions (action: requested-review). The user consistently demonstrates this behavior. + + +* **Rigorously verify pnpm patch files after dependency version bumps**: When updating pinned dependencies (e.g., @sentry/core, @sentry/node-core, @stricli/core) that have corresponding pnpm patchedDependencies, the user requires thorough verification of the patch files: (1) confirm all originally stripped exports/imports are still stripped in the new version, plus any new-in-version exports that reference stripped modules are also stripped, (2) verify no dangling references remain to stripped code across all build targets (cjs/esm, index/light variants), (3) check patch hygiene — no build artifacts, no unintended sourceMappingURL edits, no whitespace-only churn, (4) enumerate all file targets touched by each patch with line numbers, and (5) verify package.json patchedDependencies key format includes the version pin. When assisting with dependency/patch updates, proactively run these completeness and hygiene checks and report exact counts/diffs rather than assuming the patch still applies correctly. + * **SQLite usage research for Node 20 support**: User is researching Node 18+ support for Sentry CLI (getsentry/cli) and needs to understand how SQLite is used. Specifically investigating the lack of built-in node:sqlite module in Node 18-22.14 and exploring alternatives like node-sqlite3-wasm fallback. The CLI is distributed both as an npm package and as standalone SEA binaries. The standalone binary always embeds modern LTS Node and uses node:sqlite. The npm bundle MUST inline the WASM driver (it's a devDependency, not shipped as a runtime dep). The project has zero runtime dependencies (all deps are devDependencies, bundled at build time via esbuild). CI enforces zero runtime dependencies with bun run check:deps / pnpm run check:deps. * **Understanding SQLite usage patterns**: User repeatedly asks to understand HOW SQLite is used across multiple sessions, indicating a strong preference for deep technical understanding of database usage patterns. + + +* **Verify patch strip-sets with empirical cross-checks before trusting them**: When maintaining patches that strip exports/modules from vendored packages (e.g., @sentry/core, @sentry/node-core) across version upgrades, the user expects rigorous empirical verification rather than assumption-based patching. This includes: reconstructing pristine pre-patch source to diff against new upstream versions; checking both CJS and ESM builds for strip parity (same names removed in both formats); verifying no dangling references (exports pointing to stripped modules that themselves weren't stripped); confirming CJS re-exports don't resolve to undefined and ESM re-exports don't throw SyntaxErrors; identifying newly-added upstream exports and deciding whether to keep or strip them; and running actual runtime checks (node --check, dynamic import) as proof rather than static review alone. When updating a patch for a new package version, always cross-verify strip-set completeness and consistency across module formats before finalizing. + + +* **Verify pnpm lockfile dependency trees and versions before finalizing dependency changes**: When updating or auditing dependencies (e.g., pnpm-lock.yaml), the user expects thorough verification of the resulting lockfile: checking transitive dependency entries (like @spotlightjs/spotlight's nested @sentry/core, @sentry/node, hono), confirming exact resolved versions, cross-referencing multiple lockfile entries for the same package (patched vs unpatched, different peer contexts), and grepping for security-relevant packages to confirm no vulnerable versions remain. When a grep or script doesn't produce expected confirmation output, re-check by inspecting the raw lockfile snapshot directly rather than trusting a single query. Always confirm both package.json version ranges and pnpm-lock.yaml resolved versions match expectations after any install/update, especially around security patches or CVE fixes. + + +* **Verify TypeScript CLI ports against both legacy Rust source and live server implementation**: When reviewing or implementing a TypeScript port of a legacy Rust CLI feature (e.g., sentry-cli snapshots download), the user expects the assistant to cross-check three sources: (1) the legacy Rust implementation being ported from, (2) the actual live Sentry server-side API endpoint source code (permissions, rate limits, error responses, side effects), and (3) the new TypeScript client code under review. The user wants a rigorous, objective comparison — not just style review — that surfaces real behavioral discrepancies (e.g., streaming-to-disk vs buffering-in-memory, missing rate-limit handling, mismatched error codes, auth token leakage risks). When asked for a review, do not write code; produce findings organized by severity with file:line references and concrete fixes, grounded in actual source inspection rather than assumptions. + + +* **Verify TypeScript port matches legacy Rust sentry-cli behavior exactly**: When porting sentry-cli functionality from Rust to TypeScript, always cross-reference the legacy Rust implementation (e.g., collect\_git\_metadata, find\_head\_sha, find\_base\_sha, VcsInfo struct, CI/GitHub Actions env var handling, clap flag semantics like conflicts\_with) against the new TS code and tests. Actively look for behavioral discrepancies — such as flag conflict handling, error vs. silent-override behavior, and missing env var reads (e.g., GITHUB\_EVENT\_PATH) — and flag them as bugs/blockers rather than assuming the port is correct. Use probe tests to empirically confirm flag-parsing edge cases (single flag, combined flags, malformed flags) and compare results against Rust's documented behavior. Prioritize fidelity to legacy behavior unless an intentional deviation is explicitly decided upon. + + +* **Verify visual/terminal output changes across all render surfaces with rigorous validation**: When making changes to CLI banner/visual rendering (colors, ASCII/block art, responsive layout), the user consistently: (1) requires the assistant to check ALL rendering call sites (help.ts, ink-app.tsx, ink-ui.ts, wizard-runner.ts) since banner code is duplicated/must stay in sync across multiple files; (2) cares deeply about pixel/character-level legibility and exact visual fidelity to source art (e.g., verifying individual letterforms aren't distorted); (3) expects careful tradeoff analysis (aspect ratio, duty cycle, column width) with multiple candidate options presented before deciding; (4) sometimes requests strict read-only adversarial review workflows requiring sha256 verification of files before/after and clean git status confirmation; (5) expects existing tests to be updated in sync with visual changes. When editing shared visual assets, always search for all consumers, verify byte-identical duplication where files must mirror each other, and present tiered/graduated solutions for terminal-width responsiveness. diff --git a/src/lib/init/preflight.ts b/src/lib/init/preflight.ts index 9111725bb1..347174ab70 100644 --- a/src/lib/init/preflight.ts +++ b/src/lib/init/preflight.ts @@ -359,8 +359,28 @@ function canCreateProjectInTeam(team: SentryTeam): boolean { return Array.isArray(team.access) && team.access.includes("team:admin"); } -function hasOrgWriteAccess(access: unknown): boolean { - return Array.isArray(access) && access.includes("org:write"); +/** + * Whether the user's access scopes indicate they can create projects + * regardless of the org's `allowMemberProjectCreation` flag. + * + * Sentry's role hierarchy (from server.py SENTRY_ROLES): + * - member: project:read only — blocked when flag is disabled + * - admin: project:write, project:admin, team:admin — CAN create projects + * - manager: org:write, project:admin, is_global — CAN create projects + * - owner: org:write, org:admin, is_global — CAN create projects + * + * The previous check only looked for `org:write`, which excluded org admins + * who have `project:write` / `project:admin` but not `org:write`. + */ +function canBypassMemberCreationRestriction(access: unknown): boolean { + if (!Array.isArray(access)) { + return false; + } + return ( + access.includes("org:write") || + access.includes("project:admin") || + access.includes("project:write") + ); } async function assertOrgScopedCreationCanProceed(org: string): Promise { @@ -375,7 +395,7 @@ async function assertOrgScopedCreationCanProceed(org: string): Promise { if ( organization.allowMemberProjectCreation === false && - !hasOrgWriteAccess(organization.access) + !canBypassMemberCreationRestriction(organization.access) ) { throw new WizardError(formatMemberProjectCreationDisabledError(org)); } diff --git a/test/lib/init/preflight.test.ts b/test/lib/init/preflight.test.ts index e48f0901e3..8d82c3734e 100644 --- a/test/lib/init/preflight.test.ts +++ b/test/lib/init/preflight.test.ts @@ -712,4 +712,54 @@ describe("resolveInitContext", () => { expect(context?.team).toBeUndefined(); }); + + test("allows org-scoped creation when member creation is disabled but user is an admin (project:admin scope)", async () => { + listTeamsSpy.mockResolvedValueOnce([]); + getOrganizationSpy.mockResolvedValueOnce({ + id: "1", + slug: "acme", + name: "Acme", + access: ["project:read", "project:write", "project:admin", "team:admin"], + allowMemberProjectCreation: false, + } as any); + + const { ui } = createMockUI(); + const context = await resolveInitContext(makeOptions(), ui); + + expect(context?.team).toBeUndefined(); + }); + + test("allows org-scoped creation when member creation is disabled but user has project:write scope", async () => { + listTeamsSpy.mockResolvedValueOnce([]); + getOrganizationSpy.mockResolvedValueOnce({ + id: "1", + slug: "acme", + name: "Acme", + access: ["project:read", "project:write"], + allowMemberProjectCreation: false, + } as any); + + const { ui } = createMockUI(); + const context = await resolveInitContext(makeOptions(), ui); + + expect(context?.team).toBeUndefined(); + }); + + test("allows org-scoped creation when listTeams returns 403 and user has project:admin scope", async () => { + listTeamsSpy.mockRejectedValueOnce( + new ApiError("Forbidden", 403, "No team:read access") + ); + getOrganizationSpy.mockResolvedValueOnce({ + id: "1", + slug: "acme", + name: "Acme", + access: ["project:read", "project:write", "project:admin"], + allowMemberProjectCreation: false, + } as any); + + const { ui } = createMockUI(); + const context = await resolveInitContext(makeOptions(), ui); + + expect(context?.team).toBeUndefined(); + }); });