All files / src/commands/issue list.ts

86.49% Statements 301/348
69.32% Branches 174/251
91.8% Functions 56/61
86.13% Lines 292/339

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526                                                                                                                                                                                                            12x                                                                               12x     12x                                             25x 13x   12x             12x                                       25x           25x     5x 25x                               19x     19x       58x 50x       8x                     6x                 1x   1x                                                           8x 13x 23x 23x 23x                                 245x 245x 245x                       174x   50x 47x   48x 46x   35x 43x     40x   1x 1x                                                                   20x 20x                     14x     20x   6x     6x   14x                               1x 1x 1x 1x       1x   1x       1x       1x 1x         1x 1x               1x   1x 1x 1x 1x 1x 1x 1x                                                                                           12x 12x         12x   19x               12x 12x 19x 13x     12x   12x 12x 2x   2x         10x 10x 13x 13x         1x       10x 9x   11x       1x   1x 1x 2x 2x     1x   1x   2x                       308x     167x             26x 26x     26x     26x 26x       13x       13x                                   13x 13x 13x     13x 2x 2x                 2x       11x                 11x                                       14x   14x         14x             14x 14x           13x                     13x   13x   13x 13x   13x 1x           1x     1x         12x                   12x           12x 12x 2x   10x   12x 2x     12x                                         12x                                   2x   2x 2x     2x   2x           2x 2x     2x         2x 2x   2x 2x 4x         2x                                                                                           12x                                                                                                                                                     16x     16x             13x 1x               1x         12x               19x 12x 12x 12x         12x 3x 3x 3x   3x 3x 3x                   12x       16x   16x       16x   16x     12x                       13x             12x 12x   12x   19x 19x 13x     6x       12x   4x 4x           4x 4x 4x 2x 2x         4x                       8x 8x 8x   16x       16x 3x 3x   5x     8x           8x 16x       8x       8x     8x   15x     15x 24x 2x   22x   15x   13x           2x   11x 8x 16x 16x     16x           16x   22x     16x   2x                     16x 2x 2x   2x         8x 1x 1x       7x       16x 16x 3x 4x 4x       7x 2x 2x 2x 2x 2x   2x 1x     2x 2x     7x           7x                             12x                   12x                                                 6x 6x   6x     6x 6x                   8x   8x   2x 2x   2x       6x 6x       6x 6x       6x 1x     6x                                 13x     13x         13x 13x 13x       13x       12x                   12x                                                                                                                                                   30x 30x   30x       30x                                                                           30x     30x               30x     30x 16x           30x                                 14x                     21x 19x 19x 2x   19x 5x   19x     21x 21x      
/**
 * sentry issue list
 *
 * List issues from Sentry projects.
 * Supports monorepos with multiple detected projects.
 */
 
import type { SentryContext } from "../../context.js";
import { buildProjectAliasMap } from "../../lib/alias.js";
import {
  API_MAX_PER_PAGE,
  buildIssueListCollapse,
  type IssueCollapseField,
  type IssuesPage,
  listIssuesAllPages,
  listIssuesPaginated,
} from "../../lib/api-client.js";
import { extractRequiredScopes } from "../../lib/api-scope.js";
import {
  looksLikeIssueShortId,
  parseOrgProjectArg,
} from "../../lib/arg-parsing.js";
 
import { getActiveEnvVarName, isEnvTokenActive } from "../../lib/db/auth.js";
import {
  advancePaginationState,
  buildMultiTargetContextKey,
  buildPaginationContextKey,
  CURSOR_SEP,
  decodeCompoundCursor,
  encodeCompoundCursor,
  hasPreviousPage,
  resolveCursor,
} from "../../lib/db/pagination.js";
import {
  clearProjectAliases,
  setProjectAliases,
} from "../../lib/db/project-aliases.js";
import { createDsnFingerprint } from "../../lib/dsn/index.js";
import {
  ApiError,
  ContextError,
  ValidationError,
  withAuthGuard,
} from "../../lib/errors.js";
import {
  type IssueTableRow,
  shouldAutoCompact,
  willShowTrend,
  writeIssueTable,
} from "../../lib/formatters/index.js";
import {
  CommandOutput,
  type OutputConfig,
} from "../../lib/formatters/output.js";
import {
  buildListCommand,
  buildListLimitFlag,
  LIST_BASE_ALIASES,
  LIST_MAX_LIMIT,
  LIST_TARGET_POSITIONAL,
  paginationHint,
  parseCursorFlag,
  targetPatternExplanation,
} from "../../lib/list-command.js";
import { logger } from "../../lib/logger.js";
import {
  dispatchOrgScopedList,
  distributeFetchBudget,
  type FetchResult as FetchResultOf,
  jsonTransformListResult,
  type ListCommandMeta,
  type ListResult,
  type ModeHandler,
  trimWithGroupGuarantee,
} from "../../lib/org-list.js";
import { withProgress } from "../../lib/polling.js";
import {
  type ResolvedTarget,
  resolveTargetsFromParsedArg,
} from "../../lib/resolve-target.js";
import {
  SEARCH_SYNTAX_REFERENCE,
  sanitizeQuery,
} from "../../lib/search-query.js";
import {
  appendPeriodHint,
  formatTimeRangeFlag,
  PERIOD_BRIEF,
  parsePeriod,
  serializeTimeRange,
  type TimeRange,
  timeRangeToApiParams,
} from "../../lib/time-range.js";
import {
  type SentryIssue,
  SentryIssueSchema,
  type Writer,
} from "../../types/index.js";
import { resolveIssue } from "./utils.js";
 
/** Command key for pagination cursor storage */
export const PAGINATION_KEY = "issue-list";
 
type ListFlags = {
  readonly query?: string;
  readonly limit: number;
  readonly sort: "date" | "new" | "freq" | "user";
  readonly period: TimeRange;
  readonly json: boolean;
  readonly cursor?: string;
  readonly fresh: boolean;
  readonly compact?: boolean;
  readonly fields?: string[];
};
 
/**
 * Extended result type for issue list with display context.
 *
 * Extends {@link ListResult} with rendering metadata needed by the human
 * formatter (pre-built display rows, table options) and by the JSON
 * transform (raw issue data for serialization).
 *
 * Handlers return this type; the `OutputConfig` decides how to render it.
 */
export type IssueListResult = ListResult<SentryIssue> & {
  /** Pre-formatted display rows for the human issue table */
  displayRows?: IssueTableRow[];
  /** Title shown above the table in human output (e.g. "Issues in sentry/cli") */
  title?: string;
  /** Footer mode controlling which usage tip to show after the table */
  footerMode?: "single" | "multi" | "none";
  /** Whether to use compact (single-line) table rendering */
  compact?: boolean;
  /** "More issues available" hint with actionable flags */
  moreHint?: string;
  /** DSN detection or multi-project summary footer */
  footer?: string;
};
 
/** @internal */ export type SortValue = "date" | "new" | "freq" | "user";
 
const VALID_SORT_VALUES: SortValue[] = ["date", "new", "freq", "user"];
 
/** Usage hint for ContextError messages */
const USAGE_HINT = "sentry issue list <org>/<project>";
 
/** Options returned by {@link buildListApiOptions}. */
type ListApiOptions = {
  /** Fields to collapse (omit) from the API response for performance. */
  collapse: IssueCollapseField[];
  /** Stats period resolution — undefined when stats are collapsed. */
  groupStatsPeriod: "" | "14d" | "24h" | "auto" | undefined;
};
 
/**
 * Determine whether stats data should be collapsed (skipped) in the API request.
 *
 * Stats power the TREND sparkline column, which is only shown when:
 * 1. Output is human (not `--json`) — JSON consumers don't render sparklines
 * 2. Terminal is wide enough — narrow terminals and non-TTY hide TREND
 *
 * Collapsing stats avoids expensive Snuba/ClickHouse aggregation queries,
 * saving 200-500ms per API request.
 *
 * @see {@link willShowTrend} for the terminal width threshold logic
 */
function shouldCollapseStats(json: boolean): boolean {
  if (json) {
    return true;
  }
  return !willShowTrend();
}
 
/**
 * Fields that depend on the `lifetime` API data. When `collapse=lifetime`
 * is sent, the server omits these from the list response. See #969.
 */
const LIFETIME_FIELDS = new Set([
  "count",
  "userCount",
  "firstSeen",
  "lastSeen",
]);
 
/**
 * Build the collapse and groupStatsPeriod options for issue list API calls.
 *
 * When stats are collapsed, groupStatsPeriod is omitted (undefined) since
 * the server won't compute stats anyway. This avoids wasted server-side
 * processing and makes the request intent explicit.
 *
 * Lifetime is only collapsed in JSON mode when explicit `--fields` are
 * provided and none of them are lifetime-dependent (`count`, `userCount`,
 * `firstSeen`, `lastSeen`). Human output always needs these for the
 * EVENTS, USERS, SEEN, and AGE columns.
 */
function buildListApiOptions(json: boolean, fields?: string[]): ListApiOptions {
  const collapseStats = shouldCollapseStats(json);
  // Collapse lifetime only when in JSON mode with explicit --fields that
  // don't include any lifetime-dependent field. Human output always needs
  // these (EVENTS, USERS, SEEN, AGE columns), and JSON without --fields
  // returns all fields.
  const collapseLifetime =
    json &&
    fields !== undefined &&
    fields.length > 0 &&
    !fields.some((f) => LIFETIME_FIELDS.has(f));
  return {
    collapse: buildIssueListCollapse({
      shouldCollapseStats: collapseStats,
      shouldCollapseLifetime: collapseLifetime,
    }),
    groupStatsPeriod: collapseStats ? undefined : "auto",
  };
}
 
/**
 * Resolve the effective compact mode from the flag tri-state and issue count.
 *
 * - `true` / `false` — explicit user override, returned as-is
 * - `undefined` — auto-detect based on terminal height vs estimated table height
 */
function resolveCompact(flag: boolean | undefined, rowCount: number): boolean {
  Iif (flag !== undefined) {
    return flag;
  }
  return shouldAutoCompact(rowCount);
}
 
function parseSort(value: string): SortValue {
  if (!VALID_SORT_VALUES.includes(value as SortValue)) {
    throw new Error(
      `Invalid sort value. Must be one of: ${VALID_SORT_VALUES.join(", ")}`
    );
  }
  return value as SortValue;
}
 
// Query sanitization (AND/OR handling) is in src/lib/search-query.ts
 
/**
 * Format the issue list header with column titles.
 *
 * @param title - Section title
 */
function formatListHeader(title: string): string {
  return `${title}:\n\n`;
}
 
/**
 * Format footer with usage tip.
 *
 * @param mode - Display mode: 'single' (one project), 'multi' (multiple projects), or 'none'
 */
function formatListFooter(mode: "single" | "multi" | "none"): string {
  switch (mode) {
    case "single":
      return "\nTip: Use 'sentry issue view <ID>' to view details (bold part works as shorthand).";
    case "multi":
      return "\nTip: Use 'sentry issue view <ALIAS>' to view details (see ALIAS column).";
    default:
      return "\nTip: Use 'sentry issue view <SHORT_ID>' to view issue details.";
  }
}
 
/** Issue list with target context */
/** @internal */ export type IssueListFetchResult = {
  target: ResolvedTarget;
  issues: SentryIssue[];
  /** Whether the project has more issues beyond what was fetched. */
  hasMore?: boolean;
  /** Cursor to resume fetching from this project (for Phase 2 / next page). */
  nextCursor?: string;
};
 
/**
 * Attach formatting options to each issue based on alias map.
 *
 * @param results - Issue list results with targets
 * @param aliasMap - Map from "org:project" to alias
 * @param isMultiProject - Whether in multi-project mode (shows ALIAS column)
 */
function attachFormatOptions(
  results: IssueListFetchResult[],
  aliasMap: Map<string, string>,
  isMultiProject: boolean
): IssueTableRow[] {
  return results.flatMap((result) =>
    result.issues.map((issue) => {
      const key = `${result.target.org}/${result.target.project}`;
      const alias = aliasMap.get(key);
      return {
        issue,
        orgSlug: result.target.org,
        formatOptions: {
          projectSlug: result.target.project,
          projectAlias: alias,
          isMultiProject,
        },
      };
    })
  );
}
 
/**
 * Compare two optional date strings (most recent first).
 */
function compareDates(a: string | undefined, b: string | undefined): number {
  const dateA = a ? new Date(a).getTime() : 0;
  const dateB = b ? new Date(b).getTime() : 0;
  return dateB - dateA;
}
 
/**
 * Get comparator function for the specified sort option.
 *
 * @param sort - Sort option from CLI flags
 * @returns Comparator function for Array.sort()
 */
function getComparator(
  sort: SortValue
): (a: SentryIssue, b: SentryIssue) => number {
  switch (sort) {
    case "date":
      return (a, b) =>
        compareDates(a.lastSeen ?? undefined, b.lastSeen ?? undefined);
    case "new":
      return (a, b) =>
        compareDates(a.firstSeen ?? undefined, b.firstSeen ?? undefined);
    case "freq":
      return (a, b) =>
        Number.parseInt(b.count ?? "0", 10) -
        Number.parseInt(a.count ?? "0", 10);
    case "user":
      return (a, b) => (b.userCount ?? 0) - (a.userCount ?? 0);
    default:
      return (a, b) =>
        compareDates(a.lastSeen ?? undefined, b.lastSeen ?? undefined);
  }
}
 
type FetchResult = FetchResultOf<IssueListFetchResult>;
 
/**
 * Fetch issues for a single target project.
 *
 * @param target - Resolved org/project target
 * @param options - Query options (query, limit, sort, optional resume cursor)
 * @returns Success with issues + pagination state, or failure with error preserved
 * @throws {AuthError} When user is not authenticated
 */
async function fetchIssuesForTarget(
  target: ResolvedTarget,
  options: {
    query?: string;
    limit: number;
    sort: SortValue;
    statsPeriod?: string;
    /** Absolute start datetime (ISO-8601). Mutually exclusive with statsPeriod. */
    start?: string;
    /** Absolute end datetime (ISO-8601). Mutually exclusive with statsPeriod. */
    end?: string;
    /** Resume from this cursor (Phase 2 redistribution or next-page resume). */
    startCursor?: string;
    onPage?: (fetched: number, limit: number) => void;
    /** Pre-computed API performance options. @see {@link buildListApiOptions} */
    collapse?: IssueCollapseField[];
    /** Stats period resolution — undefined when stats are collapsed. */
    groupStatsPeriod?: "" | "14d" | "24h" | "auto";
  }
): Promise<FetchResult> {
  const result = await withAuthGuard(async () => {
    const { issues, nextCursor } = await listIssuesAllPages(
      target.org,
      target.project,
      {
        ...options,
        projectId: target.projectId,
        groupStatsPeriod: options.groupStatsPeriod,
        start: options.start,
        end: options.end,
      }
    );
    return { target, issues, hasMore: !!nextCursor, nextCursor };
  });
 
  if (!result.ok) {
    const error =
      result.error instanceof Error
        ? result.error
        : new Error(String(result.error));
    return { success: false, error };
  }
  return { success: true, data: result.value };
}
 
/**
 * Execute Phase 2 of the budget fetch: redistribute surplus to expandable targets
 * and merge the additional results back into `phase1` in place.
 */
async function runPhase2(
  targets: ResolvedTarget[],
  phase1: FetchResult[],
  expandableIndices: number[],
  context: {
    surplus: number;
    options: Omit<BudgetFetchOptions, "limit" | "startCursors">;
  }
): Promise<void> {
  const { surplus, options } = context;
  const extraQuotas = distributeFetchBudget(surplus, expandableIndices.length);
  const requests = expandableIndices
    .map((targetIndex, allocationIndex) => ({
      targetIndex,
      limit: extraQuotas[allocationIndex] ?? 0,
    }))
    .filter((request) => request.limit > 0);
 
  Iif (requests.length === 0) {
    return;
  }
 
  const phase2 = await Promise.all(
    requests.map(({ targetIndex, limit }) => {
      // expandableIndices only contains indices where r.success && r.data.nextCursor
      // biome-ignore lint/style/noNonNullAssertion: guaranteed by expandableIndices filter
      const target = targets[targetIndex]!;
      const r = phase1[targetIndex] as {
        success: true;
        data: IssueListFetchResult;
      };
      // biome-ignore lint/style/noNonNullAssertion: same guarantee
      const cursor = r.data.nextCursor!;
      return fetchIssuesForTarget(target, {
        ...options,
        limit,
        startCursor: cursor,
      });
    })
  );
 
  for (let j = 0; j < requests.length; j++) {
    // biome-ignore lint/style/noNonNullAssertion: j is within requests bounds
    const i = requests[j]!.targetIndex;
    const p2 = phase2[j];
    const p1 = phase1[i];
    Eif (p1?.success && p2?.success) {
      p1.data.issues.push(...p2.data.issues);
      p1.data.hasMore = p2.data.hasMore;
      p1.data.nextCursor = p2.data.nextCursor;
    }
  }
}
 
/**
 * Options for {@link fetchWithBudget}.
 */
type BudgetFetchOptions = {
  query?: string;
  limit: number;
  sort: SortValue;
  statsPeriod?: string;
  /** Absolute start datetime (ISO-8601). Mutually exclusive with statsPeriod. */
  start?: string;
  /** Absolute end datetime (ISO-8601). Mutually exclusive with statsPeriod. */
  end?: string;
  /** Per-target cursors from a previous page (compound cursor resume). */
  startCursors?: Map<string, string>;
  /** Pre-computed collapse fields for API performance. @see {@link buildListApiOptions} */
  collapse?: IssueCollapseField[];
  /** Stats period resolution — undefined when stats are collapsed. */
  groupStatsPeriod?: "" | "14d" | "24h" | "auto";
};
 
/**
 * Fetch issues from multiple targets within a global limit budget.
 *
 * Uses a two-phase strategy:
 * 1. Phase 1: distribute the global limit across targets and fetch in parallel.
 * 2. Phase 2: if total fetched < limit and some targets have more, redistribute
 *    the surplus among those expandable targets and fetch one more page each.
 *
 * Targets with a `startCursor` in `options.startCursors` resume from that cursor
 * instead of starting fresh — used for compound cursor pagination (−c next / −c prev).
 *
 * @param targets - Resolved org/project targets to fetch from
 * @param options - Query + budget options
 * @param onProgress - Called after Phase 1 and Phase 2 with total fetched so far
 * @returns Merged fetch results and whether any target has further pages
 */
async function fetchWithBudget(
  targets: ResolvedTarget[],
  options: BudgetFetchOptions,
  onProgress: (fetched: number) => void
): Promise<{ results: FetchResult[]; hasMore: boolean }> {
  const { limit, startCursors } = options;
  const quotas = distributeFetchBudget(limit, targets.length, {
    minimumPerGroup: true,
  });
 
  // Phase 1: fetch quota from each target in parallel
  const phase1 = await Promise.all(
    targets.map((t, i) =>
      fetchIssuesForTarget(t, {
        ...options,
        limit: quotas[i] ?? 1,
        startCursor: startCursors?.get(`${t.org}/${t.project}`),
      })
    )
  );
 
  let totalFetched = 0;
  for (const r of phase1) {
    if (r.success) {
      totalFetched += r.data.issues.length;
    }
  }
  onProgress(totalFetched);
 
  const surplus = limit - totalFetched;
  if (surplus <= 0) {
    return {
      results: phase1,
      hasMore: phase1.some((r) => r.success && r.data.hasMore),
    };
  }
 
  // Identify targets that hit their quota and have a cursor to continue
  const expandableIndices: number[] = [];
  for (let i = 0; i < phase1.length; i++) {
    const r = phase1[i];
    if (
      r?.success &&
      r.data.issues.length >= (quotas[i] ?? 1) &&
      r.data.nextCursor
    ) {
      expandableIndices.push(i);
    }
  }
 
  if (expandableIndices.length === 0) {
    return {
      results: phase1,
      hasMore: phase1.some((r) => r.success && r.data.hasMore),
    };
  }
 
  await runPhase2(targets, phase1, expandableIndices, { surplus, options });
 
  totalFetched = 0;
  for (const r of phase1) {
    Eif (r.success) {
      totalFetched += r.data.issues.length;
    }
  }
  onProgress(totalFetched);
 
  return {
    results: phase1,
    hasMore: phase1.some((r) => r.success && r.data.hasMore),
  };
}
 
/**
 * Trim issues to the global limit while guaranteeing at least one issue per
 * project. Thin wrapper around {@link trimWithGroupGuarantee} for `IssueTableRow`.
 */
function trimWithProjectGuarantee(
  issues: IssueTableRow[],
  limit: number
): IssueTableRow[] {
  return trimWithGroupGuarantee(
    issues,
    limit,
    (r) => `${r.orgSlug}/${r.formatOptions.projectSlug ?? ""}`
  );
}
 
/** Build the CLI hint for fetching the next page, preserving active flags. */
/** Append active non-default issue list flags to a base command string. */
function appendIssueFlags(base: string, flags: ListFlags): string {
  const parts: string[] = [];
  Iif (flags.sort !== "date") {
    parts.push(`--sort ${flags.sort}`);
  }
  Iif (flags.query) {
    parts.push(`-q "${flags.query}"`);
  }
  appendPeriodHint(parts, flags.period, DEFAULT_PERIOD, "-t");
  return parts.length > 0 ? `${base} ${parts.join(" ")}` : base;
}
 
function nextPageHint(org: string, flags: ListFlags): string {
  return appendIssueFlags(`sentry issue list ${org}/ -c next`, flags);
}
 
function prevPageHint(org: string, flags: ListFlags): string {
  return appendIssueFlags(`sentry issue list ${org}/ -c prev`, flags);
}
 
/**
 * Fetch org-wide issues, auto-paginating from the start or resuming from a cursor.
 *
 * When `cursor` is provided (--cursor resume), fetches a single page to keep the
 * cursor chain intact. Otherwise auto-paginates up to the requested limit.
 */
async function fetchOrgAllIssues(
  org: string,
  flags: Pick<ListFlags, "query" | "limit" | "sort" | "json" | "fields">,
  timeRange: TimeRange,
  options: {
    cursor?: string;
    onPage?: (fetched: number, limit: number) => void;
  }
): Promise<IssuesPage> {
  const apiOpts = buildListApiOptions(flags.json, flags.fields);
  const timeParams = timeRangeToApiParams(timeRange);
  const { cursor, onPage } = options;
 
  // When resuming with --cursor, fetch a single page so the cursor chain stays intact.
  if (cursor) {
    const perPage = Math.min(flags.limit, API_MAX_PER_PAGE);
    const response = await listIssuesPaginated(org, "", {
      query: flags.query,
      cursor,
      perPage,
      sort: flags.sort,
      ...timeParams,
      groupStatsPeriod: apiOpts.groupStatsPeriod,
      collapse: apiOpts.collapse,
    });
    return { issues: response.data, nextCursor: response.nextCursor };
  }
 
  // No cursor — auto-paginate from the beginning via the shared helper.
  const { issues, nextCursor } = await listIssuesAllPages(org, "", {
    query: flags.query,
    limit: flags.limit,
    sort: flags.sort,
    ...timeParams,
    groupStatsPeriod: apiOpts.groupStatsPeriod,
    collapse: apiOpts.collapse,
    onPage,
  });
  return { issues, nextCursor };
}
 
/** Options for {@link handleOrgAllIssues}. */
type OrgAllIssuesOptions = {
  org: string;
  flags: ListFlags;
  timeRange: TimeRange;
};
 
/**
 * Handle org-all mode for issues: cursor-paginated listing of all issues in an org.
 *
 * Uses a sort+query-aware context key so cursors from different searches are
 * never accidentally reused. Returns an {@link IssueListResult} — the caller
 * is responsible for rendering (JSON or human output).
 */
async function handleOrgAllIssues(
  options: OrgAllIssuesOptions
): Promise<IssueListResult> {
  const { org, flags, timeRange } = options;
  // Encode sort + query in context key so cursors from different searches don't collide.
  const contextKey = buildPaginationContextKey("org", org, {
    sort: flags.sort,
    period: serializeTimeRange(timeRange),
    q: flags.query,
  });
  const { cursor, direction } = resolveCursor(
    flags.cursor,
    PAGINATION_KEY,
    contextKey
  );
 
  let issuesResult: IssuesPage;
  try {
    issuesResult = await withProgress(
      {
        message: `Fetching issues (up to ${flags.limit})...`,
        json: flags.json,
      },
      (setMessage) =>
        fetchOrgAllIssues(org, flags, timeRange, {
          cursor,
          onPage: (fetched, limit) =>
            setMessage(
              `Fetching issues, ${fetched} and counting (up to ${limit})...`
            ),
        })
    );
  } catch (error) {
    throw enrichIssueListError(error, flags);
  }
  const { issues, nextCursor } = issuesResult;
 
  advancePaginationState(PAGINATION_KEY, contextKey, direction, nextCursor);
 
  const hasMore = !!nextCursor;
  const hasPrev = hasPreviousPage(PAGINATION_KEY, contextKey);
 
  if (issues.length === 0) {
    const nav = paginationHint({
      hasPrev,
      hasMore,
      prevHint: prevPageHint(org, flags),
      nextHint: nextPageHint(org, flags),
    });
    const hint = nav
      ? `No issues on this page. ${nav}`
      : `No issues found in organization '${org}'.`;
    return { items: [], hasMore, hasPrev, nextCursor, hint };
  }
 
  // isMultiProject=true: org-all shows issues from every project, so the ALIAS
  // column is needed to identify which project each issue belongs to.
  const displayRows: IssueTableRow[] = issues.map((issue) => ({
    issue,
    // org-all: org context comes from the `org` param; issue.organization may be absent
    orgSlug: org,
    formatOptions: {
      projectSlug: issue.project?.slug ?? "",
      isMultiProject: true,
    },
  }));
 
  const nav = paginationHint({
    hasPrev,
    hasMore,
    prevHint: prevPageHint(org, flags),
    nextHint: nextPageHint(org, flags),
  });
  const hintParts: string[] = [];
  if (hasMore) {
    hintParts.push(`Showing ${issues.length} issues (more available)`);
  } else {
    hintParts.push(`Showing ${issues.length} issues`);
  }
  if (nav) {
    hintParts.push(nav);
  }
 
  return {
    items: issues,
    hasMore,
    hasPrev,
    nextCursor,
    hint: hintParts.join("\n"),
    displayRows,
    title: `Issues in ${org}`,
    compact: resolveCompact(flags.compact, displayRows.length),
  };
}
 
/** Options for {@link handleResolvedTargets}. */
type ResolvedTargetsOptions = {
  parsed: ReturnType<typeof parseOrgProjectArg>;
  flags: ListFlags;
  cwd: string;
  timeRange: TimeRange;
};
 
/** Default --period value (used to detect user-implicit vs explicit). */
const DEFAULT_PERIOD = "90d";
 
/**
 * Build an enriched error detail for 400 Bad Request responses.
 *
 * Appends actionable suggestions so users know what to try next. This is the
 * most common class of API error in `issue list` (CLI-BM, CLI-7B) — the Sentry
 * API rejects the request due to query syntax or parameter issues, but the raw
 * "400 Bad Request" message alone doesn't guide the user to a fix.
 *
 * @param originalDetail - The API response detail (may be undefined)
 * @param flags - Current command flags for context-aware hints
 * @returns Enhanced detail string with suggestions
 */
function build400Detail(
  originalDetail: string | undefined,
  flags: Pick<ListFlags, "query" | "period">
): string {
  const lines: string[] = [];
 
  Eif (originalDetail) {
    lines.push(originalDetail);
  }
 
  const suggestions: string[] = [];
 
  Iif (flags.query) {
    suggestions.push(
      "Check your --query syntax (Sentry search reference: https://docs.sentry.io/concepts/search/)"
    );
  }
 
  Eif (formatTimeRangeFlag(flags.period) === DEFAULT_PERIOD) {
    suggestions.push("Try a shorter time range: --period 14d or --period 24h");
  }
 
  suggestions.push(
    "Verify you have access to the target project: sentry project list <org>/"
  );
 
  // Only add the separator when there's a detail line preceding the suggestions
  Eif (lines.length > 0) {
    lines.push("");
  }
  lines.push("Suggestions:");
  for (const s of suggestions) {
    lines.push(`  • ${s}`);
  }
 
  // ApiError.format() prepends "\n  " only before the first line of detail.
  // Indent continuation lines to maintain alignment with the first line.
  return lines.join("\n  ");
}
 
/**
 * Enrich an API error from issue listing with actionable suggestions.
 *
 * Handles both 400 (query/parameter) and 403 (permission) errors.
 * Re-throws non-ApiError and unhandled statuses unchanged.
 */
function enrichIssueListError(
  error: unknown,
  flags: Pick<ListFlags, "query" | "period">
): never {
  if (error instanceof ApiError) {
    if (error.status === 400) {
      throw new ApiError(
        error.message,
        error.status,
        build400Detail(error.detail, flags),
        error.endpoint
      );
    }
    if (error.status === 403) {
      // Centralized 403 enrichment (infrastructure.ts) already added
      // scope/token hints. Only append the project-membership hint.
      const detail = error.enriched403
        ? appendProjectMembershipHint(error.detail)
        : build403Detail(error.detail);
      throw new ApiError(
        error.message,
        error.status,
        detail,
        error.endpoint,
        true
      );
    }
  }
  throw error;
}
 
/**
 * Default scopes mentioned when the API response doesn't tell us which
 * scope is missing. These are the minimum the issue-list endpoint needs
 * — surfaced verbatim from the previous hardcoded message so the
 * fallback behavior matches the pre-fix UX.
 */
const DEFAULT_ISSUE_LIST_SCOPES = "org:read, project:read";
 
/**
 * Build an enriched error detail for 403 Forbidden responses.
 *
 * Only mentions token scopes when using a custom env-var token
 * (SENTRY_AUTH_TOKEN / SENTRY_TOKEN) since the regular `sentry auth login`
 * OAuth flow always grants the required scopes.
 *
 * When the API's detail payload names the required scope(s) explicitly
 * (see {@link extractRequiredScopes}) we surface that list instead of
 * the hardcoded default — this is the fix for getsentry/cli#785 item #9
 * where a token missing `event:read` was told it might be missing
 * `org:read, project:read` (which it actually had).
 *
 * @param originalDetail - The API response detail (may be undefined)
 * @returns Enhanced detail string with suggestions
 */
function build403Detail(originalDetail: unknown): string {
  const lines: string[] = [];
 
  if (typeof originalDetail === "string" && originalDetail) {
    lines.push(originalDetail, "");
  }
 
  lines.push("Suggestions:");
 
  if (isEnvTokenActive()) {
    const scopes = extractRequiredScopes(originalDetail);
    const scopeList =
      scopes.length > 0 ? scopes.join(", ") : DEFAULT_ISSUE_LIST_SCOPES;
    // When the API was explicit about what's missing, frame the hint
    // as a definite statement ("is missing") rather than a hedged
    // "may lack" — this is the user-visible payoff of parsing the
    // response.
    const leader =
      scopes.length > 0
        ? `Your ${getActiveEnvVarName()} token is missing the required scope(s)`
        : `Your ${getActiveEnvVarName()} token may lack the required scopes`;
    lines.push(
      `  • ${leader} (${scopeList})`,
      "  • Check token scopes at: https://sentry.io/settings/account/api/auth-tokens/"
    );
  } else {
    lines.push("  • Re-authenticate with: sentry auth login");
  }
 
  lines.push("  • Verify project membership: sentry project list <org>/");
 
  return lines.join("\n  ");
}
 
/**
 * Append a project membership verification hint to an already-enriched
 * 403 detail string. Used when centralized enrichment (infrastructure.ts)
 * has already added scope/token hints and we only need the issue-list-specific
 * suggestion.
 */
function appendProjectMembershipHint(detail: string | undefined): string {
  const base = detail ?? "You do not have permission to perform this action.";
  return `${base}\n  Verify project membership: sentry project list <org>/`;
}
 
/**
 * Handle auto-detect, explicit, and project-search modes.
 *
 * All three share the same flow: resolve targets → fetch issues within the
 * global limit budget → merge → trim with project guarantee → display.
 * Cursor pagination uses a compound cursor (one cursor per project, encoded
 * as a pipe-separated string) so `-c next` / `-c prev` works across multi-target results.
 */
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: inherent multi-target resolution, compound cursor, error handling, and display logic
async function handleResolvedTargets(
  options: ResolvedTargetsOptions
): Promise<IssueListResult> {
  const { parsed, flags, cwd, timeRange } = options;
 
  const { targets, footer, skippedSelfHosted, detectedDsns } =
    await resolveTargetsFromParsedArg(parsed, {
      cwd,
      usageHint: USAGE_HINT,
      enrichProjectIds: true,
      checkIssueShortId: true,
    });
 
  if (targets.length === 0) {
    Iif (skippedSelfHosted) {
      throw new ContextError(
        "Organization and project",
        USAGE_HINT,
        undefined,
        `Found ${skippedSelfHosted} DSN(s) that could not be resolved — you may not have access to these projects`
      );
    }
    throw new ContextError("Organization and project", USAGE_HINT);
  }
 
  // Build a compound cursor context key that encodes the full target set +
  // search parameters so a cursor from one search is never reused for another.
  const contextKey = buildMultiTargetContextKey(targets, {
    sort: flags.sort,
    query: flags.query,
    period: serializeTimeRange(timeRange),
  });
 
  // Resolve per-target start cursors from the stored compound cursor (--cursor resume).
  // Sorted target keys must match the order used in buildMultiTargetContextKey.
  const sortedTargetKeys = targets.map((t) => `${t.org}/${t.project}`).sort();
  const startCursors = new Map<string, string>();
  const exhaustedTargets = new Set<string>();
  const { cursor: rawCursor, direction } = resolveCursor(
    flags.cursor,
    PAGINATION_KEY,
    contextKey
  );
  if (rawCursor) {
    const decoded = decodeCompoundCursor(rawCursor);
    for (let i = 0; i < decoded.length && i < sortedTargetKeys.length; i++) {
      const cursor = decoded[i];
      // biome-ignore lint/style/noNonNullAssertion: i is within bounds
      const key = sortedTargetKeys[i]!;
      if (cursor) {
        startCursors.set(key, cursor);
      } else E{
        // null = project was exhausted on previous page — skip it entirely
        exhaustedTargets.add(key);
      }
    }
  }
 
  // Filter out exhausted targets so they are not re-fetched from scratch (Comment 2 fix).
  const activeTargets =
    exhaustedTargets.size > 0
      ? targets.filter((t) => !exhaustedTargets.has(`${t.org}/${t.project}`))
      : targets;
 
  const targetCount = activeTargets.length;
  const baseMessage =
    targetCount > 1
      ? `Fetching issues from ${targetCount} projects`
      : "Fetching issues";
 
  const apiOpts = buildListApiOptions(flags.json, flags.fields);
 
  const { results, hasMore } = await withProgress(
    { message: `${baseMessage} (up to ${flags.limit})...`, json: flags.json },
    (setMessage) =>
      fetchWithBudget(
        activeTargets,
        {
          query: flags.query,
          limit: flags.limit,
          sort: flags.sort,
          ...timeRangeToApiParams(timeRange),
          startCursors,
          collapse: apiOpts.collapse,
          groupStatsPeriod: apiOpts.groupStatsPeriod,
        },
        (fetched) => {
          setMessage(
            `${baseMessage}, ${fetched} and counting (up to ${flags.limit})...`
          );
        }
      )
  );
 
  const validResults: IssueListFetchResult[] = [];
  const failures: { target: ResolvedTarget; error: Error }[] = [];
 
  for (let i = 0; i < results.length; i++) {
    // biome-ignore lint/style/noNonNullAssertion: index within bounds
    const result = results[i]!;
    if (result.success) {
      validResults.push(result.data);
    } else {
      // biome-ignore lint/style/noNonNullAssertion: index within bounds
      failures.push({ target: activeTargets[i]!, error: result.error });
    }
  }
 
  if (validResults.length === 0 && failures.length > 0) {
    // biome-ignore lint/style/noNonNullAssertion: guarded by failures.length > 0
    const { error: first } = failures[0]!;
    const prefix = `Failed to fetch issues from ${targets.length} project(s)`;
 
    // Propagate ApiError so telemetry sees the original status code.
    // For 400 errors, append actionable suggestions since the user's query
    // or parameters are likely malformed. Common causes: invalid Sentry
    // search syntax, unsupported period for the org's data retention.
    Eif (first instanceof ApiError) {
      let detail = first.detail;
      if (first.status === 400) {
        detail = build400Detail(first.detail, flags);
      } else Iif (first.status === 403) {
        detail = first.enriched403
          ? appendProjectMembershipHint(first.detail)
          : build403Detail(first.detail);
      }
      throw new ApiError(
        `${prefix}: ${first.message}`,
        first.status,
        detail,
        first.endpoint,
        first.enriched403 || first.status === 403
      );
    }
 
    throw new Error(`${prefix}: ${first.message}`);
  }
 
  const isMultiProject = validResults.length > 1;
  const isSingleProject = validResults.length === 1;
  const firstTarget = validResults[0]?.target;
 
  const { aliasMap, entries } = isMultiProject
    ? buildProjectAliasMap(validResults)
    : { aliasMap: new Map<string, string>(), entries: {} };
 
  if (isMultiProject) {
    const fingerprint = createDsnFingerprint(detectedDsns ?? []);
    setProjectAliases(entries, fingerprint);
  } else {
    clearProjectAliases();
  }
 
  const allIssuesWithOptions = attachFormatOptions(
    validResults,
    aliasMap,
    isMultiProject
  );
 
  allIssuesWithOptions.sort((a, b) =>
    getComparator(flags.sort)(a.issue, b.issue)
  );
 
  // Trim to the global limit with project representation guarantee
  const issuesWithOptions = trimWithProjectGuarantee(
    allIssuesWithOptions,
    flags.limit
  );
  const trimmed = issuesWithOptions.length < allIssuesWithOptions.length;
  // Store compound cursor only after display trimming is known. If rows were
  // fetched but not displayed, a stored next cursor would skip those rows.
  const cursorValues: (string | null)[] = sortedTargetKeys.map((key) => {
    // Exhausted targets from previous page stay exhausted
    Iif (exhaustedTargets.has(key)) {
      return null;
    }
    const result = results.find((r) => {
      if (!r.success) {
        return false;
      }
      return `${r.data.target.org}/${r.data.target.project}` === key;
    });
    if (result?.success) {
      // Successful fetch: null = exhausted (no more pages), string = has more
      return result.data.nextCursor ?? null;
    }
    // Target failed this fetch — preserve the cursor it was given so the next
    // `-c next` retries from the same position rather than skipping it entirely.
    // If no start cursor was given (first-page failure), null means not retried
    // via cursor; the user can run without -c next to restart all projects.
    return startCursors.get(key) ?? null;
  });
  const hasAnyCursor = cursorValues.some((c) => c !== null);
  const hasMoreToShow = hasMore || hasAnyCursor || trimmed;
  const canPaginate = hasAnyCursor && !trimmed;
  const compoundNextCursor = canPaginate
    ? encodeCompoundCursor(cursorValues)
    : undefined;
  advancePaginationState(
    PAGINATION_KEY,
    contextKey,
    direction,
    compoundNextCursor
  );
  const hasPrev = hasPreviousPage(PAGINATION_KEY, contextKey);
 
  const allIssues = issuesWithOptions.map((i) => i.issue);
 
  const errors =
    failures.length > 0
      ? failures.map(({ target: t, error: e }) =>
          e instanceof ApiError
            ? {
                project: `${t.org}/${t.project}`,
                status: e.status,
                message: e.message,
              }
            : { project: `${t.org}/${t.project}`, message: e.message }
        )
      : undefined;
 
  // Write partial-failure note to stderr (side effect for progress/warnings)
  if (failures.length > 0) {
    const failedNames = failures
      .map(({ target: t }) => `${t.org}/${t.project}`)
      .join(", ");
    logger.warn(
      `Failed to fetch issues from ${failedNames}. Showing results from ${validResults.length} project(s).`
    );
  }
 
  if (issuesWithOptions.length === 0) {
    const hint = footer ? `No issues found.\n\n${footer}` : "No issues found.";
    return { items: [], hint, hasMore: false, hasPrev, errors };
  }
 
  const title =
    isSingleProject && firstTarget
      ? `Issues in ${firstTarget.orgDisplay}/${firstTarget.projectDisplay}`
      : `Issues from ${validResults.length} projects`;
 
  let footerMode: "single" | "multi" | "none" = "none";
  if (isMultiProject) {
    footerMode = "multi";
  } else Eif (isSingleProject) {
    footerMode = "single";
  }
 
  let moreHint: string | undefined;
  if (hasMoreToShow) {
    const higherLimit = Math.min(flags.limit * 2, LIST_MAX_LIMIT);
    const canIncreaseLimit = higherLimit > flags.limit;
    const actionParts: string[] = [];
    Eif (canIncreaseLimit) {
      actionParts.push(`-n ${higherLimit}`);
    }
    if (canPaginate) {
      actionParts.push("-c next");
    }
    // Only set the hint when there is at least one actionable option
    Eif (actionParts.length > 0) {
      moreHint = `More issues available — use ${actionParts.join(" or ")} for more.`;
    }
  }
  Iif (hasPrev) {
    // Multi-target mode: no single org to build a full command hint, so use bare flag
    const prevPart = "Prev: -c prev";
    moreHint = moreHint ? `${moreHint}\n${prevPart}` : prevPart;
  }
 
  return {
    items: allIssues,
    hasMore: hasMoreToShow,
    hasPrev,
    errors,
    displayRows: issuesWithOptions,
    title,
    footerMode,
    compact: resolveCompact(flags.compact, issuesWithOptions.length),
    moreHint,
    footer,
  };
}
 
/** Metadata for the shared dispatch infrastructure. */
const issueListMeta: ListCommandMeta = {
  paginationKey: PAGINATION_KEY,
  entityName: "issue",
  entityPlural: "issues",
  commandPrefix: "sentry issue list",
};
 
/**
 * @internal Exported for testing only. Not part of the public API.
 */
export const __testing = {
  trimWithProjectGuarantee,
  encodeCompoundCursor,
  decodeCompoundCursor,
  buildMultiTargetContextKey,
  buildProjectAliasMap,
  getComparator,
  compareDates,
  parseSort,
  CURSOR_SEP,
  MAX_LIMIT: LIST_MAX_LIMIT,
  VALID_SORT_VALUES,
};
 
// ---------------------------------------------------------------------------
// Output rendering
// ---------------------------------------------------------------------------
 
/**
 * Render an issue table to a string by buffering `writeIssueTable` output.
 *
 * This bridges the existing `writeIssueTable` (Writer-based) API to the
 * return-based `OutputConfig` pattern without duplicating the table logic.
 */
function renderIssueTable(rows: IssueTableRow[], compact: boolean): string {
  const parts: string[] = [];
  const buffer: Writer = {
    write: (s: string) => {
      parts.push(s);
    },
  };
  writeIssueTable(buffer, rows, { compact });
  return parts.join("");
}
 
/**
 * Format an {@link IssueListResult} as human-readable terminal output.
 *
 * Renders the title, issue table (via {@link writeIssueTable}), footer tip,
 * and "more available" hint. Empty results show the hint message only.
 */
function formatIssueListHuman(result: IssueListResult): string {
  const parts: string[] = [];
 
  if (result.items.length === 0) {
    // Empty result — hint contains "No issues found" or similar
    Eif (result.hint) {
      parts.push(result.hint);
    }
    return parts.join("\n");
  }
 
  // Title above the table (e.g. "Issues in sentry/cli:")
  Eif (result.title) {
    parts.push(formatListHeader(result.title));
  }
 
  // Render the issue table
  Eif (result.displayRows && result.displayRows.length > 0) {
    parts.push(renderIssueTable(result.displayRows, result.compact ?? false));
  }
 
  // Footer tip (e.g. "Tip: Use 'sentry issue view <ID>' ...")
  if (result.footerMode) {
    parts.push(formatListFooter(result.footerMode));
  }
 
  return parts.join("");
}
 
// Search syntax reference lives in src/lib/search-query.ts
 
/**
 * JSON transform for issue list that conditionally injects search syntax.
 *
 * Delegates to shared `jsonTransformListResult` for envelope handling.
 * Adds `_searchSyntax` only when the result set is empty — that's when
 * users/agents most likely need query help (bad query, wrong syntax).
 * Avoids bloating every successful response with static metadata.
 */
function jsonTransformIssueList(
  result: IssueListResult,
  fields?: string[]
): unknown {
  const transformed = jsonTransformListResult(result, fields);
  // Only inject into empty paginated envelopes — helps agents discover
  // query syntax when their search returned nothing.
  Eif (
    transformed &&
    typeof transformed === "object" &&
    !Array.isArray(transformed)
  ) {
    const envelope = transformed as Record<string, unknown>;
    const data = envelope.data;
    Iif (Array.isArray(data) && data.length === 0) {
      envelope._searchSyntax = SEARCH_SYNTAX_REFERENCE;
    }
  }
  return transformed;
}
 
/** Output configuration for the issue list command. */
const issueListOutput: OutputConfig<IssueListResult> = {
  human: formatIssueListHuman,
  jsonTransform: jsonTransformIssueList,
  schema: SentryIssueSchema,
};
 
// ---------------------------------------------------------------------------
// Command definition
// ---------------------------------------------------------------------------
 
export const listCommand = buildListCommand("issue", {
  docs: {
    brief: "List issues in a project",
    fullDescription:
      "List issues from Sentry projects.\n\n" +
      "Target patterns:\n" +
      "  sentry issue list               # auto-detect from DSN or config\n" +
      "  sentry issue list <org>/<proj>  # explicit org and project\n" +
      "  sentry issue list <org>/        # all projects in org (trailing / required)\n" +
      "  sentry issue list <project>     # find project across all orgs\n\n" +
      `${targetPatternExplanation()}\n\n` +
      "In monorepos with multiple Sentry projects, shows issues from all detected projects.\n\n" +
      "The --limit flag specifies the total number of issues to display (max 1000). " +
      "When multiple projects are detected, the limit is distributed evenly across them. " +
      "Projects with fewer issues than their share give their surplus to others. " +
      "Use --cursor / -c next / -c prev to paginate through larger result sets.\n\n" +
      "By default, only issues with activity in the last 90 days are shown. " +
      "Use --period to adjust (e.g. --period 24h, --period 14d).\n\n" +
      "Query syntax (--query flag):\n" +
      "  Terms are space-separated and implicitly ANDed together.\n" +
      "  AND/OR operators are NOT supported. Use alternatives:\n" +
      "    key:[val1,val2]   # in-list: matches val1 OR val2 for one key\n" +
      "    *term*            # wildcard matching\n" +
      "  Filters:  key:value, !key:value (negation), key:>N, key:<N\n" +
      '  Quoted:   message:"exact phrase with spaces"\n' +
      "  Built-in: is:unresolved, is:resolved, assigned:me, has:user\n" +
      "  Dates:    age:-24h (last 24h), firstSeen:+7d (older than 7d)\n" +
      "  Docs:     https://docs.sentry.io/concepts/search/\n\n" +
      "Alias: `sentry issues` → `sentry issue list`",
  },
  output: issueListOutput,
  parameters: {
    positional: LIST_TARGET_POSITIONAL,
    flags: {
      query: {
        kind: "parsed",
        parse: sanitizeQuery,
        brief: "Search query (Sentry syntax, implicit AND, no OR operator)",
        optional: true,
      },
      limit: buildListLimitFlag("issues"),
      sort: {
        kind: "parsed",
        parse: parseSort,
        brief: "Sort by: date, new, freq, user",
        default: "date" as const,
      },
      period: {
        kind: "parsed",
        parse: parsePeriod,
        brief: PERIOD_BRIEF,
        default: "90d",
      },
      cursor: {
        kind: "parsed",
        parse: parseCursorFlag,
        brief:
          'Pagination cursor (use "next" for next page, "prev" for previous)',
        optional: true,
      },
      compact: {
        kind: "boolean",
        brief: "Single-line rows for compact output (auto-detects if omitted)",
        optional: true,
      },
    },
    aliases: {
      ...LIST_BASE_ALIASES,
      q: "query",
      s: "sort",
      t: "period",
    },
  },
  async *func(this: SentryContext, flags: ListFlags, target?: string) {
    const { cwd } = this;
    const log = logger.withTag("issue.list");
 
    const parsed = parseOrgProjectArg(target);
 
    // Auto-recover: user passed an issue short ID (e.g., "ARMAX-3E") instead
    // of a project slug. Their intent is unambiguous — resolve and show it.
    Iif (
      parsed.type === "project-search" &&
      looksLikeIssueShortId(parsed.projectSlug)
    ) {
      const shortId = parsed.projectSlug;
      log.warn(
        `'${shortId}' is an issue short ID, not a project slug. Showing the issue.`
      );
      const { org, issue } = await resolveIssue({
        issueArg: shortId,
        cwd,
        command: "view",
      });
      const displayRows: IssueTableRow[] = [
        {
          issue,
          orgSlug: org ?? "",
          formatOptions: {
            projectSlug: issue.project?.slug ?? "",
            isMultiProject: false,
          },
        },
      ];
      yield new CommandOutput({
        items: [issue],
        displayRows,
        title: `Issue ${issue.shortId}`,
        footerMode: "none",
        compact: true,
      } satisfies IssueListResult);
      return {
        hint: `Tip: Use 'sentry issue view ${shortId}' for full details`,
      };
    }
 
    // Validate --limit range. Auto-pagination handles the API's 100-per-page
    // cap transparently, but we cap the total at MAX_LIMIT for practical CLI
    // response times. Use --cursor for paginating through larger result sets.
    Iif (flags.limit < 1) {
      throw new ValidationError("--limit must be at least 1.", "limit");
    }
    Iif (flags.limit > LIST_MAX_LIMIT) {
      throw new ValidationError(
        `--limit cannot exceed ${LIST_MAX_LIMIT}. ` +
          "Use --cursor to paginate through larger result sets.",
        "limit"
      );
    }
 
    const timeRange = flags.period;
 
    // biome-ignore lint/suspicious/noExplicitAny: shared handler accepts any mode variant
    const resolveAndHandle: ModeHandler<any> = (ctx) =>
      handleResolvedTargets({
        ...ctx,
        flags,
        timeRange,
      });
 
    const result = (await dispatchOrgScopedList({
      config: issueListMeta,
      cwd,
      flags,
      parsed,
      // When a bare slug matches a cached org, silently redirect to org-all
      // mode instead of erroring (CLI-MC, 17 users). The user typed an org
      // slug — their intent is clear, and org-all handles it correctly.
      orgSlugMatchBehavior: "redirect",
      // Multi-target modes (auto-detect, explicit, project-search) handle
      // compound cursor pagination themselves via handleResolvedTargets.
      allowCursorInModes: ["auto-detect", "explicit", "project-search"],
      overrides: {
        "auto-detect": resolveAndHandle,
        explicit: resolveAndHandle,
        "project-search": resolveAndHandle,
        "org-all": (ctx) =>
          handleOrgAllIssues({
            org: ctx.parsed.org,
            flags,
            timeRange,
          }),
      },
    })) as IssueListResult;
 
    // Only forward hints to the framework footer when items exist — empty
    // results already render hint text inside formatIssueListHuman.
    let combinedHint: string | undefined;
    if (result.items.length > 0) {
      const hintParts: string[] = [];
      if (result.moreHint) {
        hintParts.push(result.moreHint);
      }
      if (result.footer) {
        hintParts.push(result.footer);
      }
      combinedHint = hintParts.length > 0 ? hintParts.join("\n") : result.hint;
    }
 
    yield new CommandOutput(result);
    return { hint: combinedHint };
  },
});