Skip to content

Commit 145b002

Browse files
committed
fix: unescape backslash escapes in plain mode, deduplicate plainSafeMuted
- stripMarkdownInline() now unescapes markdown backslash escapes (\|, \<, \>, \, \_, \*, \[, \]) so plain output shows literal characters instead of escaped ones. Addresses Seer review. - mdRow() replaces literal | with box-drawing │ after stripping to prevent breaking pipe-delimited table format. - Export plainSafeMuted() from human.ts and reuse in output.ts instead of duplicating. Addresses BugBot review.
1 parent 9c37339 commit 145b002

File tree

6 files changed

+85
-12
lines changed

6 files changed

+85
-12
lines changed

AGENTS.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -782,4 +782,73 @@ mock.module("./some-module", () => ({
782782
| Add documentation | `docs/src/content/docs/` |
783783
784784
<!-- This section is maintained by the coding agent via lore (https://github.com/BYK/opencode-lore) -->
785+
## Long-term Knowledge
786+
787+
### Architecture
788+
789+
<!-- lore:019ce2be-39f1-7ad9-a4c5-4506b62f689c -->
790+
* **api-client.ts split into domain modules under src/lib/api/**: The original monolithic \`src/lib/api-client.ts\` (1,977 lines) was split into 12 focused domain modules under \`src/lib/api/\`: infrastructure.ts (shared helpers, types, raw requests), organizations.ts, projects.ts, teams.ts, repositories.ts, issues.ts, events.ts, traces.ts, logs.ts, seer.ts, trials.ts, users.ts. The original \`api-client.ts\` was converted to a ~100-line barrel re-export file preserving all existing import paths. The \`biome.jsonc\` override for \`noBarrelFile\` already includes \`api-client.ts\`. When adding new API functions, place them in the appropriate domain module under \`src/lib/api/\`, not in the barrel file.
791+
792+
<!-- lore:019cb8ea-c6f0-75d8-bda7-e32b4e217f92 -->
793+
* **CLI telemetry DSN is public write-only — safe to embed in install script**: The CLI's Sentry DSN (\`SENTRY\_CLI\_DSN\` in \`src/lib/constants.ts\`) is a public write-only ingest key already baked into every binary. Safe to hardcode in install scripts. Opt-out: \`SENTRY\_CLI\_NO\_TELEMETRY=1\`.
794+
795+
<!-- lore:019c978a-18b5-7a0d-a55f-b72f7789bdac -->
796+
* **cli.sentry.dev is served from gh-pages branch via GitHub Pages**: \`cli.sentry.dev\` is served from gh-pages branch via GitHub Pages. Craft's gh-pages target runs \`git rm -r -f .\` before extracting docs — persist extra files via \`postReleaseCommand\` in \`.craft.yml\`. Install script supports \`--channel nightly\`, downloading from the \`nightly\` release tag directly. version.json is only used by upgrade/version-check flow.
797+
798+
<!-- lore:019cbe93-19b8-7776-9705-20bbde226599 -->
799+
* **Nightly delta upgrade buildNightlyPatchGraph fetches ALL patch tags — O(N) HTTP calls**: Delta upgrade in \`src/lib/delta-upgrade.ts\` supports stable (GitHub Releases) and nightly (GHCR) channels. \`filterAndSortChainTags\` filters \`patch-\*\` tags by version range using \`Bun.semver.order()\`. GHCR uses \`fetchWithRetry\` (10s timeout + 1 retry; blobs 30s) with optional \`signal?: AbortSignal\` combined via \`AbortSignal.any()\`. \`isExternalAbort(error, signal)\` skips retries for external aborts — critical for background prefetch. Patches cached to \`~/.sentry/patch-cache/\` (file-based, 7-day TTL). \`loadCachedChain\` stitches patches for multi-hop offline upgrades.
800+
801+
<!-- lore:2c3eb7ab-1341-4392-89fd-d81095cfe9c4 -->
802+
* **npm bundle requires Node.js >= 22 due to node:sqlite polyfill**: The npm package (dist/bin.cjs) requires Node.js >= 22 because the bun:sqlite polyfill uses \`node:sqlite\`. A runtime version guard in the esbuild banner catches this early. When writing esbuild banner strings in TS template literals, double-escape: \`\\\\\\\n\` in TS → \`\\\n\` in output → newline at runtime. Single \`\\\n\` produces a literal newline inside a JS string, causing SyntaxError.
803+
804+
<!-- lore:019c972c-9f0f-75cd-9e24-9bdbb1ac03d6 -->
805+
* **Numeric issue ID resolution returns org:undefined despite API success**: Numeric issue ID resolution in \`resolveNumericIssue()\`: (1) try DSN/env/config for org, (2) if found use \`getIssueInOrg(org, id)\` with region routing, (3) else fall back to unscoped \`getIssue(id)\`, (4) extract org from \`issue.permalink\` via \`parseSentryUrl\` as final fallback. \`parseSentryUrl\` handles path-based (\`/organizations/{org}/...\`) and subdomain-style URLs. \`matchSubdomainOrg()\` filters region subdomains by requiring slug length > 2. Self-hosted uses path-based only.
806+
807+
<!-- lore:019ce0bb-f35d-7380-b661-8dc56f9938cf -->
808+
* **Seer trial prompt uses middleware layering in bin.ts error handling chain**: The CLI's error recovery middlewares in \`bin.ts\` are layered: \`main() → executeWithAutoAuth() → executeWithSeerTrialPrompt() → runCommand()\`. Seer trial prompts (for \`no\_budget\`/\`not\_enabled\` errors) are caught by the inner wrapper; auth errors bubble up to the outer wrapper. After successful auth login retry, the retry also goes through \`executeWithSeerTrialPrompt\` (not \`runCommand\` directly) so the full middleware chain applies. Trial check API: \`GET /api/0/customers/{org}/\`\`productTrials\[]\` (prefer \`seerUsers\`, fallback \`seerAutofix\`). Start trial: \`PUT /api/0/customers/{org}/product-trial/\`. The \`/customers/\` endpoint is getsentry SaaS-only; self-hosted 404s gracefully. \`ai\_disabled\` errors are excluded (admin's explicit choice). \`startSeerTrial\` accepts \`category\` from the trial object — don't hardcode it.
809+
810+
### Decision
811+
812+
<!-- lore:019c99d5-69f2-74eb-8c86-411f8512801d -->
813+
* **Raw markdown output for non-interactive terminals, rendered for TTY**: Markdown-first output pipeline: custom renderer in \`src/lib/formatters/markdown.ts\` walks \`marked\` tokens to produce ANSI-styled output. Commands build CommonMark using helpers (\`mdKvTable()\`, \`mdRow()\`, \`colorTag()\`, \`escapeMarkdownCell()\`, \`safeCodeSpan()\`) and pass through \`renderMarkdown()\`. \`isPlainOutput()\` precedence: \`SENTRY\_PLAIN\_OUTPUT\` > \`NO\_COLOR\` > \`FORCE\_COLOR\` > \`!isTTY\`. \`--json\` always outputs JSON. Colors defined in \`COLORS\` object in \`colors.ts\`. Tests run non-TTY so assertions match raw CommonMark; use \`stripAnsi()\` helper for rendered-mode assertions.
814+
815+
<!-- lore:00166785-609d-4ab5-911e-ee205d17b90c -->
816+
* **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.
817+
818+
### Gotcha
819+
820+
<!-- lore:019c8ab6-d119-7365-9359-98ecf464b704 -->
821+
* **@sentry/api SDK passes Request object to custom fetch — headers lost on Node.js**: @sentry/api SDK calls \`\_fetch(request)\` with no init object. In \`authenticatedFetch\`, \`init\` is undefined so \`prepareHeaders\` creates empty headers — on Node.js this strips Content-Type (HTTP 415). Fix: fall back to \`input.headers\` when \`init\` is undefined. Use \`unwrapPaginatedResult\` (not \`unwrapResult\`) to access the Response's Link header for pagination. \`per\_page\` is not in SDK types; cast query to pass it at runtime.
822+
823+
<!-- lore:019c9e98-7af4-7e25-95f4-fc06f7abf564 -->
824+
* **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.\`
825+
826+
<!-- lore:019c9776-e3dd-7632-88b8-358a19506218 -->
827+
* **GitHub immutable releases prevent rolling nightly tag pattern**: getsentry/cli has immutable GitHub releases — assets can't be modified and tags can NEVER be reused. Nightly builds publish to GHCR with versioned tags like \`nightly-0.14.0-dev.1772661724\`, not GitHub Releases or npm. \`fetchManifest()\` throws \`UpgradeError("network\_error")\` for both network failures and non-200 — callers must check message for HTTP 404/403. Craft with no \`preReleaseCommand\` silently skips \`bump-version.sh\` if only target is \`github\`.
828+
829+
<!-- lore:019cb8c2-d7b5-780c-8a9f-d20001bc198f -->
830+
* **Install script: BSD sed and awk JSON parsing breaks OCI digest extraction**: The install script parses OCI manifests with awk (no jq). Key trap: BSD sed \`\n\` is literal, not newline. Fix: single awk pass tracking last-seen \`"digest"\`, printing when \`"org.opencontainers.image.title"\` matches target. The config digest (\`sha256:44136fa...\`) is a 2-byte \`{}\` blob — downloading it instead of the real binary causes \`gunzip: unexpected end of file\`.
831+
832+
<!-- lore:019c969a-1c90-7041-88a8-4e4d9a51ebed -->
833+
* **Multiple mockFetch calls replace each other — use unified mocks for multi-endpoint tests**: Bun test mocking gotchas: (1) \`mockFetch()\` replaces \`globalThis.fetch\` — calling it twice replaces the first mock. Use a single unified fetch mock dispatching by URL pattern. (2) \`mock.module()\` pollutes the module registry for ALL subsequent test files. Tests using it must live in \`test/isolated/\` and run via \`test:isolated\`. This also causes \`delta-upgrade.test.ts\` to fail when run alongside \`test/isolated/delta-upgrade.test.ts\` — the isolated test's \`mock.module()\` replaces \`CLI\_VERSION\` for all subsequent files. (3) For \`Bun.spawn\`, use direct property assignment in \`beforeEach\`/\`afterEach\`.
834+
835+
<!-- lore:019c9741-d78e-73b1-87c2-e360ef6c7475 -->
836+
* **useTestConfigDir without isolateProjectRoot causes DSN scanning of repo tree**: \`useTestConfigDir()\` creates temp dirs under \`.test-tmp/\` in the repo tree. Without \`{ isolateProjectRoot: true }\`, \`findProjectRoot\` walks up and finds the repo's \`.git\`, causing DSN detection to scan real source code and trigger network calls against test mocks (timeouts). Always pass \`isolateProjectRoot: true\` when tests exercise \`resolveOrg\`, \`detectDsn\`, or \`findProjectRoot\`.
837+
838+
### Pattern
839+
840+
<!-- lore:019c972c-9f11-7c0d-96ce-3f8cc2641175 -->
841+
* **Org-scoped SDK calls follow getOrgSdkConfig + unwrapResult pattern**: All org-scoped API calls in src/lib/api-client.ts: (1) call \`getOrgSdkConfig(orgSlug)\` for regional URL + SDK config, (2) spread into SDK function: \`{ ...config, path: { organization\_id\_or\_slug: orgSlug, ... } }\`, (3) pass to \`unwrapResult(result, errorContext)\`. Shared helpers \`resolveAllTargets\`/\`resolveOrgAndProject\` must NOT call \`fetchProjectId\` — commands that need it enrich targets themselves.
842+
843+
<!-- lore:5ac4e219-ea1f-41cb-8e97-7e946f5848c0 -->
844+
* **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 advisory checks. Both typically take 2-3 minutes but may not trigger on draft PRs — only ready-for-review PRs reliably get bot reviews. 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 \<PR> --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\`.
845+
846+
<!-- lore:019cb162-d3ad-7b05-ab4f-f87892d517a6 -->
847+
* **Shared pagination infrastructure: buildPaginationContextKey and parseCursorFlag**: List commands with cursor pagination use \`buildPaginationContextKey(type, identifier, flags)\` for composite context keys and \`parseCursorFlag(value)\` accepting \`"last"\` magic value. Critical: \`resolveCursor()\` must be called inside the \`org-all\` override closure, not before \`dispatchOrgScopedList\` — otherwise cursor validation errors fire before the correct mode-specific error.
848+
849+
<!-- lore:019cbd5f-ec35-7e2d-8386-6d3a67adf0cf -->
850+
* **Telemetry instrumentation pattern: withTracingSpan + captureException for handled errors**: For graceful-fallback operations, use \`withTracingSpan\` from \`src/lib/telemetry.ts\` for child spans and \`captureException\` from \`@sentry/bun\` (named import — Biome forbids namespace imports) with \`level: 'warning'\` for non-fatal errors. \`withTracingSpan\` uses \`onlyIfParent: true\` — no-op without active transaction. User-visible fallbacks use \`log.warn()\` not \`log.debug()\`. Several commands bypass telemetry by importing \`buildCommand\` from \`@stricli/core\` directly instead of \`../../lib/command.js\` (trace/list, trace/view, log/view, api.ts, help.ts).
851+
852+
<!-- lore:019cc43d-e651-7154-a88e-1309c4a2a2b6 -->
853+
* **Testing Stricli command func() bodies via spyOn mocking**: To unit-test a Stricli command's \`func()\` body: (1) \`const func = await cmd.loader()\`, (2) \`func.call(mockContext, flags, ...args)\` with mock \`stdout\`, \`stderr\`, \`cwd\`, \`setContext\`. (3) \`spyOn\` namespace imports to mock dependencies (e.g., \`spyOn(apiClient, 'getLogs')\`). The \`loader()\` return type union causes \`.call()\` LSP errors — these are false positives that pass \`tsc --noEmit\`. When API functions are renamed (e.g., \`getLog\`\`getLogs\`), update both spy target name AND mock return shape (single → array). Slug normalization (\`normalizeSlug\`) replaces underscores with dashes but does NOT lowercase — test assertions must match original casing (e.g., \`'CAM-82X'\` not \`'cam-82x'\`).
785854
<!-- End lore-managed section -->

src/lib/formatters/human.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1048,7 +1048,7 @@ function buildRequestMarkdown(requestEntry: RequestEntry): string {
10481048
* through full `renderMarkdown()`. This helper ensures no raw ANSI escapes
10491049
* leak when `NO_COLOR` is set, output is piped, or `isPlainOutput()` is true.
10501050
*/
1051-
function plainSafeMuted(text: string): string {
1051+
export function plainSafeMuted(text: string): string {
10521052
return isPlainOutput() ? text : muted(text);
10531053
}
10541054

src/lib/formatters/markdown.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,12 @@ export function mdTableHeader(cols: readonly string[]): string {
9595
*/
9696
export function mdRow(cells: readonly string[]): string {
9797
if (isPlainOutput()) {
98-
return `| ${cells.map(stripMarkdownInline).join(" | ")} |\n`;
98+
// Strip markdown syntax, then replace literal pipes with box-drawing │
99+
// to prevent them from breaking the pipe-delimited table format.
100+
const stripped = cells.map((c) =>
101+
stripMarkdownInline(c).replace(/\|/g, "\u2502")
102+
);
103+
return `| ${stripped.join(" | ")} |\n`;
99104
}
100105
const out = cells.map((c) =>
101106
renderInline(marked.lexer(c).flatMap(flattenInline)).replace(
@@ -227,6 +232,10 @@ export function stripMarkdownInline(md: string): string {
227232
text = text.replace(/_{1,2}([^_]+)_{1,2}/g, "$1");
228233
// Code spans: `text` → text
229234
text = text.replace(/`([^`]+)`/g, "$1");
235+
// Backslash escapes: \| \< \> \\ \_ \* \[ \] \` → literal character.
236+
// escapeMarkdownCell/escapeMarkdownInline add these for the markdown parser;
237+
// the TTY path unescapes via marked.lexer(), but plain mode must do it here.
238+
text = text.replace(/\\([|<>\\*_`[\]])/g, "$1");
230239
return text;
231240
}
232241

src/lib/formatters/output.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,8 @@
2727
*/
2828

2929
import type { Writer } from "../../types/index.js";
30-
import { muted } from "./colors.js";
30+
import { plainSafeMuted } from "./human.js";
3131
import { formatJson, writeJson } from "./json.js";
32-
import { isPlainOutput } from "./plain-detect.js";
3332

3433
// ---------------------------------------------------------------------------
3534
// Shared option types
@@ -335,11 +334,6 @@ export function writeOutput<T>(
335334
}
336335
}
337336

338-
/** Apply muted styling only in TTY mode; return plain text when piped. */
339-
function plainSafeMuted(text: string): string {
340-
return isPlainOutput() ? text : muted(text);
341-
}
342-
343337
/** Format footer text (muted in TTY, plain when piped, with surrounding newlines). */
344338
export function formatFooter(text: string): string {
345339
return `\n${plainSafeMuted(text)}\n`;

test/lib/formatters/log.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ describe("formatLogRow (plain mode)", () => {
227227
test("escapes pipe characters in message", () => {
228228
const log = createTestLog({ message: "a|b" });
229229
const result = formatLogRow(log);
230-
// Raw pipe in message must be escaped so it doesn't break the table
231-
expect(result).toContain("a\\|b");
230+
// Pipe in message replaced with box-drawing │ so it doesn't break the table
231+
expect(result).toContain("a\u2502b");
232232
});
233233

234234
test("ends with newline", () => {

test/lib/formatters/trace.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,8 @@ describe("formatTraceRow (plain mode)", () => {
222222

223223
test("escapes pipe characters in transaction name", () => {
224224
const row = formatTraceRow(makeTransaction({ transaction: "GET /a|b" }));
225-
expect(row).toContain("GET /a\\|b");
225+
// Pipe replaced with box-drawing │ so it doesn't break the table
226+
expect(row).toContain("GET /a\u2502b");
226227
});
227228

228229
test("shows 'unknown' for empty transaction", () => {

0 commit comments

Comments
 (0)