-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhuman.ts
More file actions
2407 lines (2123 loc) · 70 KB
/
human.ts
File metadata and controls
2407 lines (2123 loc) · 70 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Human-readable output formatters
*
* Centralized formatting utilities for consistent CLI output.
* Detail views (issue, event, org, project) are built as markdown and rendered
* via renderMarkdown(). List rows still use lightweight inline formatting for
* performance, while list tables are rendered via writeTable() → renderMarkdown().
*/
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import prettyMs from "pretty-ms";
import type {
DashboardDetail,
DashboardWidget,
} from "../../types/dashboard.js";
import type {
BreadcrumbsEntry,
ExceptionEntry,
ExceptionValue,
IssueStatus,
RequestEntry,
SentryEvent,
SentryIssue,
SentryOrganization,
SentryProject,
StackFrame,
TraceSpan,
Writer,
} from "../../types/index.js";
import { withSerializeSpan } from "../telemetry.js";
import { type FixabilityTier, muted } from "./colors.js";
import {
colorTag,
escapeMarkdownCell,
escapeMarkdownInline,
isPlainOutput,
mdKvTable,
mdRow,
mdTableHeader,
renderMarkdown,
safeCodeSpan,
} from "./markdown.js";
import { sparkline } from "./sparkline.js";
import { colorizeSql, isDbSpanOp } from "./sql.js";
import { type Column, writeTable } from "./table.js";
import { computeSpanDurationMs, formatRelativeTime } from "./time-utils.js";
// Color tag maps
/** Markdown color tags for Seer fixability tiers */
const FIXABILITY_TAGS: Record<FixabilityTier, Parameters<typeof colorTag>[0]> =
{
high: "green",
med: "yellow",
low: "red",
};
// Status Formatting
const STATUS_ICONS: Record<IssueStatus, string> = {
resolved: colorTag("green", "✓"),
unresolved: colorTag("yellow", "●"),
ignored: colorTag("muted", "−"),
};
const STATUS_LABELS: Record<IssueStatus, string> = {
resolved: `${colorTag("green", "✓")} Resolved`,
unresolved: `${colorTag("yellow", "●")} Unresolved`,
ignored: `${colorTag("muted", "−")} Ignored`,
};
/** Maximum features to display before truncating with "... and N more" */
const MAX_DISPLAY_FEATURES = 10;
/**
* Capitalize the first letter of a string
*/
function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Convert Seer fixability score to a tier label.
*
* Thresholds are simplified from Sentry core (sentry/seer/autofix/constants.py)
* into 3 tiers for CLI display.
*
* @param score - Numeric fixability score (0-1)
* @returns `"high"` | `"med"` | `"low"`
*/
export function getSeerFixabilityLabel(score: number): FixabilityTier {
if (score > 0.66) {
return "high";
}
if (score > 0.33) {
return "med";
}
return "low";
}
/**
* Format fixability score as "label(pct%)" for compact list display.
*
* @param score - Numeric fixability score, or null/undefined if unavailable
* @returns Formatted string like `"med(50%)"`, or `""` when score is unavailable
*/
export function formatFixability(score: number | null | undefined): string {
if (score === null || score === undefined) {
return "";
}
const label = getSeerFixabilityLabel(score);
const pct = Math.round(score * 100);
return `${label}(${pct}%)`;
}
/**
* Format fixability score for detail view: "Label (pct%)".
*
* Uses capitalized label with space before parens for readability
* in the single-issue detail display.
*
* @param score - Numeric fixability score, or null/undefined if unavailable
* @returns Formatted string like `"Med (50%)"`, or `""` when score is unavailable
*/
export function formatFixabilityDetail(
score: number | null | undefined
): string {
if (score === null || score === undefined) {
return "";
}
const label = getSeerFixabilityLabel(score);
const pct = Math.round(score * 100);
return `${capitalize(label)} (${pct}%)`;
}
/** Map of entry type strings to their TypeScript types */
type EntryTypeMap = {
exception: ExceptionEntry;
breadcrumbs: BreadcrumbsEntry;
request: RequestEntry;
};
/**
* Extract a typed entry from event entries by type
* @returns The entry if found, null otherwise
*/
function extractEntry<T extends keyof EntryTypeMap>(
event: SentryEvent,
type: T
): EntryTypeMap[T] | null {
if (!event.entries) {
return null;
}
for (const entry of event.entries) {
if (
entry &&
typeof entry === "object" &&
"type" in entry &&
entry.type === type
) {
return entry as EntryTypeMap[T];
}
}
return null;
}
/** Regex to extract base URL from a permalink */
const BASE_URL_REGEX = /^(https?:\/\/[^/]+)/;
/**
* Format a features list as a markdown bullet list.
*
* @param features - Array of feature names (may be undefined)
* @returns Markdown string, or empty string if no features
*/
function formatFeaturesMarkdown(features: string[] | undefined): string {
if (!features || features.length === 0) {
return "";
}
const displayFeatures = features.slice(0, MAX_DISPLAY_FEATURES);
const items = displayFeatures.map((f) => `- ${f}`).join("\n");
const more =
features.length > MAX_DISPLAY_FEATURES
? `\n*... and ${features.length - MAX_DISPLAY_FEATURES} more*`
: "";
return `\n**Features** (${features.length}):\n\n${items}${more}`;
}
/**
* Get status icon for an issue status
*/
export function formatStatusIcon(status: string | undefined): string {
return STATUS_ICONS[status as IssueStatus] ?? colorTag("yellow", "●");
}
/**
* Get full status label for an issue status
*/
export function formatStatusLabel(status: string | undefined): string {
return (
STATUS_LABELS[status as IssueStatus] ?? `${colorTag("yellow", "●")} Unknown`
);
}
// Issue Formatting
/** Quantifier suffixes indexed by groups of 3 digits (K=10^3, M=10^6, …, E=10^18) */
const QUANTIFIERS = ["", "K", "M", "B", "T", "P", "E"];
/**
* Abbreviate large numbers with K/M/B/T/P/E suffixes (up to 10^18).
*
* The decimal is only shown when the rounded value is < 100 (e.g. "12.3K",
* "1.5M" but not "100M").
*
* @param raw - Stringified count
* @returns Abbreviated string without padding
*/
function abbreviateCount(raw: string): string {
const n = Number(raw);
if (Number.isNaN(n)) {
Sentry.logger.warn(`Unexpected non-numeric issue count: ${raw}`);
return "?";
}
if (n < 1000) {
return raw;
}
const tier = Math.min(Math.floor(Math.log10(n) / 3), QUANTIFIERS.length - 1);
const suffix = QUANTIFIERS[tier] ?? "";
const scaled = n / 10 ** (tier * 3);
const rounded1dp = Number(scaled.toFixed(1));
if (rounded1dp < 100) {
return `${rounded1dp.toFixed(1)}${suffix}`;
}
const rounded = Math.round(scaled);
if (rounded >= 1000 && tier < QUANTIFIERS.length - 1) {
const nextSuffix = QUANTIFIERS[tier + 1] ?? "";
return `${(rounded / 1000).toFixed(1)}${nextSuffix}`;
}
return `${Math.min(rounded, 999)}${suffix}`;
}
/**
* Options for formatting short IDs with alias highlighting.
*/
export type FormatShortIdOptions = {
/** Project slug to determine the prefix for suffix highlighting */
projectSlug?: string;
/** Project alias (e.g., "e", "w", "o1:d") for multi-project display */
projectAlias?: string;
/** Whether in multi-project mode (highlights alias chars in short ID) */
isMultiProject?: boolean;
};
/**
* Format short ID for multi-project mode by highlighting the alias characters.
* Only highlights the specific characters that form the alias:
* - CLI-25 with alias "c" → **C**LI-**25**
*
* @returns Formatted string with ANSI highlights, or null if no match found
*/
function formatShortIdWithAlias(
shortId: string,
projectAlias: string
): string | null {
// Extract the project part of the alias — cross-org collision aliases use
// the format "o1/d" where only "d" should match against the short ID parts.
const aliasPart = projectAlias.includes("/")
? (projectAlias.split("/").pop() ?? projectAlias)
: projectAlias;
const aliasUpper = aliasPart.toUpperCase();
const aliasLen = aliasUpper.length;
const parts = shortId.split("-");
const issueSuffix = parts.pop() ?? "";
const projectParts = parts;
if (!aliasUpper.includes("-")) {
for (let i = projectParts.length - 1; i >= 0; i--) {
const part = projectParts[i];
if (part?.startsWith(aliasUpper)) {
const result = projectParts.map((p, idx) => {
if (idx === i) {
return `${colorTag("bu", p.slice(0, aliasLen))}${p.slice(aliasLen)}`;
}
return p;
});
return `${result.join("-")}-${colorTag("bu", issueSuffix)}`;
}
}
}
const projectPortion = projectParts.join("-");
if (projectPortion.startsWith(aliasUpper)) {
const highlighted = colorTag("bu", projectPortion.slice(0, aliasLen));
const rest = projectPortion.slice(aliasLen);
return `${highlighted}${rest}-${colorTag("bu", issueSuffix)}`;
}
return null;
}
/**
* Format a short ID with highlighting to show what the user can type as shorthand.
*
* - Single project: CLI-25 → CLI-**25** (suffix highlighted)
* - Multi-project: CLI-WEBSITE-4 with alias "w" → CLI-**W**EBSITE-**4** (alias chars highlighted)
*
* @param shortId - Full short ID (e.g., "CLI-25", "CLI-WEBSITE-4")
* @param options - Formatting options (projectSlug and/or projectAlias)
* @returns Formatted short ID with highlights
*/
export function formatShortId(
shortId: string,
options?: FormatShortIdOptions | string
): string {
const opts: FormatShortIdOptions =
typeof options === "string" ? { projectSlug: options } : (options ?? {});
const { projectSlug, projectAlias, isMultiProject } = opts;
const upperShortId = shortId.toUpperCase();
if (isMultiProject && projectAlias) {
const formatted = formatShortIdWithAlias(upperShortId, projectAlias);
if (formatted) {
return formatted;
}
}
if (projectSlug) {
const prefix = `${projectSlug.toUpperCase()}-`;
if (upperShortId.startsWith(prefix)) {
const suffix = shortId.slice(prefix.length);
return `${prefix}${colorTag("bu", suffix.toUpperCase())}`;
}
}
return upperShortId;
}
/**
* Compute the alias shorthand for an issue (e.g., "o1:d-a3", "w-2a").
* This is what users type to reference the issue.
*
* @param shortId - Full short ID (e.g., "DASHBOARD-A3")
* @param projectAlias - Project alias (e.g., "o1:d", "w")
* @returns Alias shorthand (e.g., "o1:d-a3", "w-2a") or empty string if no alias
*/
function computeAliasShorthand(shortId: string, projectAlias?: string): string {
if (!projectAlias) {
return "";
}
const suffix = shortId.split("-").pop()?.toLowerCase() ?? "";
return `${projectAlias}-${suffix}`;
}
// Issue Table Helpers
/** Minimum terminal width to show the TREND sparkline column. */
export const TREND_MIN_TERM_WIDTH = 100;
/**
* Whether the TREND sparkline column will be rendered in the issue table.
*
* Returns `true` when the terminal is wide enough (≥ {@link TREND_MIN_TERM_WIDTH}).
* Non-TTY output defaults to 80 columns, which is below the threshold.
*
* Used by the issue list command to decide whether to request stats data
* from the API — when TREND won't be shown, stats can be collapsed to
* save 200-500ms per request.
*/
export function willShowTrend(): boolean {
const termWidth = process.stdout.columns || 80;
return termWidth >= TREND_MIN_TERM_WIDTH;
}
/** Lines per issue row in non-compact mode (2-line content + separator). */
const LINES_PER_DEFAULT_ROW = 3;
/**
* Fixed line overhead for the rendered table.
*
* Top border (1) + header row (1) + header separator (1) + bottom border (1) = 4,
* minus 1 because the last data row has no trailing separator (row separators
* are drawn between data rows only: `r > 0 && r < allRows.length - 1`).
* Net overhead = 3.
*/
const TABLE_LINE_OVERHEAD = 3;
/**
* Determine whether auto-compact should activate based on terminal height.
*
* Returns `true` when the estimated non-compact table height exceeds the
* terminal's row count, meaning compact mode would keep output on-screen.
*
* Returns `false` when terminal height is unknown (non-TTY/piped output)
* to prefer full output for downstream parsing.
*
* @param rowCount - Number of issue rows to render
* @returns Whether compact mode should be used
*/
export function shouldAutoCompact(rowCount: number): boolean {
const termHeight = process.stdout.rows;
if (!termHeight) {
return false;
}
const estimatedHeight =
rowCount * LINES_PER_DEFAULT_ROW + TABLE_LINE_OVERHEAD;
return estimatedHeight > termHeight;
}
/**
* Substatus label for the TREND column's second line.
* Matches Sentry web UI visual indicators.
*/
export function substatusLabel(substatus?: string | null): string {
switch (substatus) {
case "regressed":
return colorTag("red", "Regressed");
case "escalating":
return colorTag("yellow", "Escalating");
case "new":
return colorTag("green", "New");
case "ongoing":
return colorTag("muted", "Ongoing");
default:
return "";
}
}
/**
* Build issue subtitle from metadata for the ISSUE column.
*
* Prefers `metadata.value` (error message), falling back to
* `metadata.type` + `metadata.function` for structured metadata.
*
* The result is a single line — truncation to the available column
* width is handled by the table renderer's word-wrapping/truncation.
*
* @param metadata - Issue metadata from the API
* @returns Subtitle string, or empty string if no relevant metadata
*/
export function formatIssueSubtitle(
metadata?: SentryIssue["metadata"]
): string {
if (!metadata) {
return "";
}
if (metadata.value) {
return collapseWhitespace(metadata.value);
}
const parts: string[] = [];
if (metadata.type) {
parts.push(metadata.type);
}
if (metadata.function) {
parts.push(`in ${metadata.function}`);
}
return parts.join(" ");
}
/**
* Collapse runs of whitespace (including newlines) into single spaces
* and trim the result. Prevents multi-line metadata values from blowing
* up the ISSUE cell height.
*/
function collapseWhitespace(s: string): string {
return s.replace(/\s+/g, " ").trim();
}
/**
* Extract sparkline data points from the issue stats object.
*
* Stats keys depend on `groupStatsPeriod` ("24h", "14d", "auto", etc.).
* Each entry in the time-series is `[timestamp, count]`.
* Takes the first available key since the API returns one key matching
* the requested period.
*
* @param stats - Issue stats object from the API
* @returns Array of numeric counts for each time bucket
*/
export function extractStatsPoints(stats?: Record<string, unknown>): number[] {
if (!stats) {
return [];
}
const key = Object.keys(stats)[0];
if (!key) {
return [];
}
const buckets = stats[key];
if (!Array.isArray(buckets)) {
return [];
}
return buckets.map((b: unknown) =>
Array.isArray(b) && b.length >= 2 ? Number(b[1]) || 0 : 0
);
}
/** Row data prepared for the issue table */
export type IssueTableRow = {
issue: SentryIssue;
/** Org slug — used as project key in trimWithProjectGuarantee and similar utilities. */
orgSlug: string;
formatOptions: FormatShortIdOptions;
};
/**
* Format the SHORT ID cell with optional alias.
*
* Default (2-line): linked short ID on line 1, muted alias on line 2.
* Compact (single-line): alias appended as a suffix on the same line.
*
* @param issue - The Sentry issue
* @param formatOptions - Formatting options with alias info
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatIdCell(
issue: SentryIssue,
formatOptions: FormatShortIdOptions,
compact = false
): string {
const formatted = formatShortId(issue.shortId, formatOptions);
const linked = issue.permalink
? `[${formatted}](${issue.permalink})`
: formatted;
const alias = computeAliasShorthand(
issue.shortId,
formatOptions.projectAlias
);
if (alias) {
const sep = compact ? " " : "\n";
return `${linked}${sep}${colorTag("muted", alias)}`;
}
return linked;
}
/**
* Format the ISSUE cell.
*
* Default (2-line): bold title on line 1, muted subtitle on line 2.
* Compact (single-line): bold title only — truncated with "…" by the renderer.
*
* @param issue - The Sentry issue
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatIssueCell(issue: SentryIssue, compact = false): string {
const title = `**${escapeMarkdownInline(issue.title)}**`;
if (compact) {
return title;
}
const subtitle = formatIssueSubtitle(issue.metadata);
if (subtitle) {
return `${title}\n${colorTag("muted", escapeMarkdownInline(subtitle))}`;
}
return title;
}
/**
* Format the TREND cell with sparkline and substatus label.
*
* Default (2-line): sparkline on line 1, substatus label on line 2.
* Compact (single-line): sparkline + substatus on the same line.
*
* @param issue - The Sentry issue
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatTrendCell(issue: SentryIssue, compact = false): string {
const points = extractStatsPoints(
issue.stats as Record<string, unknown> | undefined
);
const graph = points.length > 0 ? colorTag("muted", sparkline(points)) : "";
const status = substatusLabel(issue.substatus);
const parts = [graph, status].filter(Boolean);
const sep = compact ? " " : "\n";
return parts.join(sep);
}
/**
* Write an issue list as a Unicode-bordered markdown table.
*
* Columns match the Sentry web UI issue stream layout:
*
* | SHORT ID (+ alias) | ISSUE | SEEN | AGE | TREND | EVENTS | USERS | TRIAGE |
*
* Default mode: 2-line rows (title + subtitle, sparkline + substatus, etc.)
* for maximum information density. Row separators drawn between rows.
*
* Compact mode (`--compact`): single-line rows for quick scanning. All cells
* collapsed to one line, long titles truncated with "…".
*
* Callers should resolve auto-compact (via {@link shouldAutoCompact}) before
* passing `compact` — this function treats `undefined` as `false`.
*
* @param stdout - Output writer
* @param rows - Issues with formatting options
* @param options - Display options
*/
export function writeIssueTable(
stdout: Writer,
rows: IssueTableRow[],
options?: { compact?: boolean }
): void {
const compact = options?.compact ?? false;
const showTrend = willShowTrend();
const columns: Column<IssueTableRow>[] = [
// SHORT ID — primary identifier (+ alias), never shrink
{
header: "SHORT ID",
shrinkable: false,
value: ({ issue, formatOptions }) =>
formatIdCell(issue, formatOptions, compact),
},
// ISSUE — title (+ subtitle in default mode)
{
header: "ISSUE",
value: ({ issue }) => formatIssueCell(issue, compact),
},
// SEEN — lastSeen
{
header: "SEEN",
value: ({ issue }) => formatRelativeTime(issue.lastSeen),
},
// AGE — firstSeen
{
header: "AGE",
value: ({ issue }) => formatRelativeTime(issue.firstSeen),
},
];
// TREND — sparkline + substatus (2-line), auto-hidden on narrow terminals
if (showTrend) {
columns.push({
header: "TREND",
value: ({ issue }) => formatTrendCell(issue, compact),
shrinkable: false,
});
}
columns.push(
// EVENTS — period-scoped count
{
header: "EVENTS",
value: ({ issue }) => abbreviateCount(`${issue.count}`),
align: "right",
},
// USERS — affected user count
{
header: "USERS",
value: ({ issue }) => abbreviateCount(`${issue.userCount ?? 0}`),
align: "right",
},
// TRIAGE — combined priority + fixability for actionability
{
header: "TRIAGE",
value: ({ issue }) =>
formatTriageCell(issue.priority, issue.seerFixabilityScore),
}
);
// Row separators colored with the muted palette color (#898294 → RGB 137,130,148)
// so they're lighter than the solid outer borders.
const mutedAnsi = "\x1b[38;2;137;130;148m";
writeTable(stdout, rows, columns, {
rowSeparator: mutedAnsi,
truncate: true,
});
}
/** Weight assigned to each priority level for composite triage scoring. */
const PRIORITY_WEIGHTS: Record<string, number> = {
critical: 1.0,
high: 0.75,
medium: 0.5,
low: 0.25,
};
/** Default impact weight when priority is unknown. */
const DEFAULT_IMPACT_WEIGHT = 0.5;
/** How much impact (priority) contributes to the composite score. */
const IMPACT_RATIO = 0.6;
/**
* Compute composite triage score from priority and fixability.
*
* The score blends impact (from priority) and fixability (from Seer)
* using a weighted average: `impact × 0.6 + fixability × 0.4`.
* Higher scores mean "fix this first" — high impact AND easy to fix.
*
* @param priority - Priority string from the API
* @param fixabilityScore - Seer fixability score (0–1)
* @returns Composite score (0–1), or null if neither dimension is available
*/
function computeTriageScore(
priority?: string | null,
fixabilityScore?: number | null
): number | null {
const hasPriority = Boolean(priority);
const hasFix = fixabilityScore !== null && fixabilityScore !== undefined;
if (!(hasPriority || hasFix)) {
return null;
}
const impact = hasPriority
? (PRIORITY_WEIGHTS[priority?.toLowerCase() ?? ""] ?? DEFAULT_IMPACT_WEIGHT)
: DEFAULT_IMPACT_WEIGHT;
const fix = hasFix ? fixabilityScore : DEFAULT_IMPACT_WEIGHT;
return impact * IMPACT_RATIO + fix * (1 - IMPACT_RATIO);
}
/**
* Format the TRIAGE cell as a single-line composite score.
*
* Combines priority (impact) and Seer fixability into a single percentage
* that answers "should I fix this now?". The score is colored by tier:
* green (≥67%), yellow (34–66%), red (≤33%).
*
* Displays:
* - Both available: `"High 82%"` — priority label + composite score
* - Priority only: `"High"` — just the label (no score without fixability)
* - Fixability only: `"78%"` — composite score alone
* - Neither: empty
*
* @param priority - Priority string from the API
* @param fixabilityScore - Seer AI fixability score (0–1)
* @returns Single-line cell string
*/
function formatTriageCell(
priority?: string | null,
fixabilityScore?: number | null
): string {
const hasFix = fixabilityScore !== null && fixabilityScore !== undefined;
const label = formatPriorityLabel(priority);
const score = computeTriageScore(priority, fixabilityScore);
// No data at all
if (score === null) {
return "";
}
// Priority without fixability — show label only (no fake %)
if (!hasFix) {
return label;
}
// Format the composite percentage
const pct = Math.round(score * 100);
const tier = getSeerFixabilityLabel(score);
const tag = FIXABILITY_TAGS[tier];
const pctStr = colorTag(tag, `${pct}%`);
return label ? `${label} ${pctStr}` : pctStr;
}
/**
* Format priority as a colored label.
*
* @param priority - Priority string from the API
* @returns Colored label or empty string
*/
function formatPriorityLabel(priority?: string | null): string {
if (!priority) {
return "";
}
switch (priority.toLowerCase()) {
case "critical":
return colorTag("red", "Critical");
case "high":
return colorTag("red", "High");
case "medium":
return colorTag("yellow", "Med ");
case "low":
return colorTag("muted", "Low ");
default:
return priority;
}
}
/**
* Format detailed issue information as rendered markdown.
*
* @param issue - The Sentry issue to format
* @returns Rendered terminal string
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: issue formatting logic
export function formatIssueDetails(issue: SentryIssue): string {
const lines: string[] = [];
lines.push(`## ${issue.shortId}: ${escapeMarkdownInline(issue.title ?? "")}`);
lines.push("");
// Key-value details as a table
const kvRows: [string, string][] = [];
kvRows.push([
"Status",
`${formatStatusLabel(issue.status)}${issue.substatus ? ` (${capitalize(issue.substatus)})` : ""}`,
]);
if (issue.priority) {
kvRows.push(["Priority", capitalize(issue.priority)]);
}
if (
issue.seerFixabilityScore !== null &&
issue.seerFixabilityScore !== undefined
) {
const tier = getSeerFixabilityLabel(issue.seerFixabilityScore);
const fixDetail = formatFixabilityDetail(issue.seerFixabilityScore);
kvRows.push(["Fixability", colorTag(FIXABILITY_TAGS[tier], fixDetail)]);
}
let levelLine = issue.level ?? "unknown";
if (issue.isUnhandled) {
levelLine += " (unhandled)";
}
kvRows.push(["Level", levelLine]);
kvRows.push(["Platform", issue.platform ?? "unknown"]);
kvRows.push(["Type", issue.type ?? "unknown"]);
kvRows.push([
"Assignee",
escapeMarkdownInline(String(issue.assignedTo?.name ?? "Unassigned")),
]);
if (issue.project) {
kvRows.push([
"Project",
`${escapeMarkdownInline(issue.project.name ?? "(unknown)")} (${safeCodeSpan(issue.project.slug ?? "")})`,
]);
}
const firstReleaseVersion = issue.firstRelease?.shortVersion;
const lastReleaseVersion = issue.lastRelease?.shortVersion;
if (firstReleaseVersion || lastReleaseVersion) {
const first = escapeMarkdownInline(String(firstReleaseVersion ?? ""));
const last = escapeMarkdownInline(String(lastReleaseVersion ?? ""));
if (firstReleaseVersion && lastReleaseVersion) {
if (firstReleaseVersion === lastReleaseVersion) {
kvRows.push(["Release", first]);
} else {
kvRows.push(["Releases", `${first} → ${last}`]);
}
} else if (lastReleaseVersion) {
kvRows.push(["Release", last]);
} else if (firstReleaseVersion) {
kvRows.push(["Release", first]);
}
}
kvRows.push(["Events", String(issue.count ?? 0)]);
kvRows.push(["Users", String(issue.userCount ?? 0)]);
if (issue.firstSeen) {
let firstSeenLine = new Date(issue.firstSeen).toLocaleString();
if (firstReleaseVersion) {
firstSeenLine += ` (in ${escapeMarkdownCell(String(firstReleaseVersion))})`;
}
kvRows.push(["First seen", firstSeenLine]);
}
if (issue.lastSeen) {
let lastSeenLine = new Date(issue.lastSeen).toLocaleString();
if (lastReleaseVersion && lastReleaseVersion !== firstReleaseVersion) {
lastSeenLine += ` (in ${escapeMarkdownCell(String(lastReleaseVersion))})`;
}
kvRows.push(["Last seen", lastSeenLine]);
}
if (issue.culprit) {
kvRows.push(["Culprit", safeCodeSpan(issue.culprit)]);
}
kvRows.push(["Link", issue.permalink ?? ""]);
lines.push(mdKvTable(kvRows));
if (issue.metadata?.value) {
lines.push("");
lines.push("**Message:**");
lines.push("");
lines.push(
`> ${escapeMarkdownInline(issue.metadata.value).replace(/\n/g, "\n> ")}`
);
}
if (issue.metadata?.filename) {
lines.push("");
lines.push(`**File:** \`${issue.metadata.filename}\``);
}
if (issue.metadata?.function) {
lines.push(`**Function:** \`${issue.metadata.function}\``);
}
return renderMarkdown(lines.join("\n"));
}
// Stack Trace Formatting
/**
* Format a single stack frame as markdown.
*/
function formatStackFrameMarkdown(frame: StackFrame): string {
const lines: string[] = [];
const fn = frame.function || "<anonymous>";
const file = frame.filename || frame.absPath || "<unknown>";
const line = frame.lineNo ?? "?";
const col = frame.colNo ?? "?";
const inAppTag = frame.inApp ? " `[in-app]`" : "";
lines.push(`${safeCodeSpan(`at ${fn} (${file}:${line}:${col})`)}${inAppTag}`);
if (frame.context && frame.context.length > 0) {
lines.push("");
lines.push("```");
for (const [lineNo, code] of frame.context) {
const isCurrentLine = lineNo === frame.lineNo;
const prefix = isCurrentLine ? ">" : " ";
lines.push(`${prefix} ${String(lineNo).padStart(6)} | ${code}`);
}
lines.push("```");
lines.push("");
}
return lines.join("\n");
}
/**
* Format an exception value (type, message, stack trace) as markdown.
*/
function formatExceptionValueMarkdown(exception: ExceptionValue): string {
const lines: string[] = [];
const type = exception.type || "Error";
const value = exception.value || "";
lines.push(`**${safeCodeSpan(`${type}: ${value}`)}**`);
if (exception.mechanism) {
const handled = exception.mechanism.handled ? "handled" : "unhandled";
const mechType = exception.mechanism.type || "unknown";
lines.push(`*mechanism: ${mechType} (${handled})*`);
}
lines.push("");
const frames = exception.stacktrace?.frames ?? [];
const reversedFrames = [...frames].reverse();
for (const frame of reversedFrames) {
lines.push(formatStackFrameMarkdown(frame));
}
return lines.join("\n");
}
/**
* Build the stack trace section as markdown.
*/
function buildStackTraceMarkdown(exceptionEntry: ExceptionEntry): string {
const lines: string[] = [];
lines.push("### Stack Trace");
lines.push("");
const values = exceptionEntry.data.values ?? [];
for (const exception of values) {
lines.push(formatExceptionValueMarkdown(exception));
}
return lines.join("\n");
}
// Breadcrumbs Formatting
/**
* Build the breadcrumbs section as a markdown table.
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: breadcrumb formatting logic
function buildBreadcrumbsMarkdown(breadcrumbsEntry: BreadcrumbsEntry): string {
const breadcrumbs = breadcrumbsEntry.data.values ?? [];
if (breadcrumbs.length === 0) {
return "";
}
const lines: string[] = [];
lines.push("### Breadcrumbs");
lines.push("");
lines.push(mdTableHeader(["Time", "Level", "Category", "Message"]).trimEnd());
for (const breadcrumb of breadcrumbs) {
const timestamp = breadcrumb.timestamp
? new Date(breadcrumb.timestamp).toLocaleTimeString()
: "??:??:??";