sailfork / t3code-github / apps/ server/ src/ pullRequest/ PullRequestService.ts

import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import {
  PullRequestOperationError,
  PullRequestUnavailableError,
  resolvePullRequestAuthorFilter,
  type OrchestrationProjectShell,
  type ProjectId,
  type PullRequestAction,
  type PullRequestActionInput,
  type PullRequestActivity,
  type PullRequestCommentInput,
  type PullRequestCommentUpdateInput,
  type PullRequestDetail,
  type PullRequestPreview,
  type PullRequestChecks,
  type PullRequestDiffFileContentsInput,
  type PullRequestDiffFileContentsResult,
  type PullRequestDiffStat,
  type PullRequestDiffInput,
  type PullRequestChangeBreakdown,
  type PullRequestFilesViewedResult,
  type PullRequestDiffResult,
  type PullRequestInvalidateInput,
  type PullRequestReportStateInput,
  type PullRequestListEntry,
  type PullRequestListFilters,
  type PullRequestListInput,
  type PullRequestListProjectError,
  type PullRequestListResult,
  type PullRequestListStatsInput,
  type PullRequestFilterOptions,
  type PullRequestFilterOptionsInput,
  type PullRequestActor,
  type PullRequestReferenceCandidate,
  type PullRequestLabel,
  type PullRequestListStatsResult,
  type PullRequestProviderSummary,
  type PullRequestReactionInput,
  type PullRequestRef,
  type PullRequestRoutingResult,
  type PullRequestRoutingIdentityInput,
  type PullRequestRoutingIdentityResult,
  type PullRequestReviewVerdict,
  type PullRequestReviewerCandidateList,
  type PullRequestReviewerCandidatesInput,
  type PullRequestReviewerRequestInput,
  type PullRequestLabelCandidateList,
  type PullRequestLabelChangeInput,
  type PullRequestSetFilesViewedInput,
  type PullRequestState,
  type PullRequestSubmitReviewInput,
  PullRequestStack,
  PullRequestSummary,
  type PullRequestThreadReplyInput,
  type PullRequestThreadResolutionInput,
  type PullRequestThreadCommentsInput,
  type PullRequestThreadCommentsResult,
  type PullRequestUpdateInput,
  type SourceControlProviderInfo,
  SourceControlProviderKind,
  type ThreadPullRequestKey,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";

import * as ProjectService from "../project/ProjectService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
  type ProviderChangeRequest,
  type ProviderChangeRequestDetail,
  type ProviderDiffFilePaths,
  type ProviderFilterOptionPage,
  type ProviderListCursor,
  type ProviderChangeRequestSummary,
  type ProviderChangeRequestWatchFingerprint,
  type PullRequestProviderApi,
  PullRequestProviderError,
} from "@t3tools/source-control-core/server/PullRequestProvider";
import * as PullRequestReadCache from "./PullRequestReadCache.ts";
import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts";
import * as ViewedFiles from "./pullRequestViewedFiles.ts";
import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts";

export interface PullRequestMergeEvent extends PullRequestRef {
  readonly mergedAt: string;
}

type PullRequestReading = Pick<
  PullRequestSummary,
  "state" | "isDraft" | "updatedAt" | "observedAt"
>;

function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) {
  if (current === undefined) return true;
  if (current.state === "merged" && next.state !== "merged") return false;
  if (next.updatedAt !== current.updatedAt) return next.updatedAt > current.updatedAt;
  return (next.observedAt ?? -Infinity) >= (current.observedAt ?? -Infinity);
}

// Providers request one extra row; 99 stays within GitHub/GitLab's 100-row API limit.
const DEFAULT_REPOSITORY_LIST_LIMIT = 99;
const REPOSITORY_CONCURRENCY = 12;
const REPOSITORY_SEARCH_CHUNK = 100;
const FILTERED_LIST_READS = 5;

// Host reads spawn CLIs and hit low quotas; briefly share results and identical in-flight reads.
const LIST_CACHE_TTL = Duration.seconds(30);
const DETAIL_CACHE_TTL = Duration.seconds(60);
const MERGED_DETAIL_CACHE_TTL = Duration.minutes(10);
const detailTimeToLive = (state: PullRequestState | undefined) =>
  state === "merged" ? MERGED_DETAIL_CACHE_TTL : DETAIL_CACHE_TTL;
const CHECKS_CACHE_TTL = Duration.seconds(15);
const REPORTED_STATE_DEDUPE_MS = 5 * 60 * 1_000;
const DIFF_CACHE_TTL = Duration.seconds(60);
const COMMIT_DIFF_CACHE_TTL = Duration.minutes(10);
const LIST_STATS_CACHE_TTL = Duration.seconds(60);
const FILES_VIEWED_CACHE_TTL = Duration.seconds(15);
const DIFF_STALE_WINDOW = Duration.minutes(10);
const DIFF_SWEEP_INTERVAL = Duration.minutes(1);
const VIEWER_CACHE_TTL = Duration.minutes(10);
const STALE_DETAIL_WINDOW = Duration.minutes(10);
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
const LIST_CACHE_CAPACITY = 64;
const LIST_STATS_CACHE_CAPACITY = 32;
const DETAIL_CACHE_CAPACITY = 128;
const DIFF_CACHE_CAPACITY = 128;
// Each holder stays within this UTF-16 patch budget as well as its entry-count bound.
const DIFF_CACHE_PATCH_BUDGET_BYTES = 32 * 1024 * 1024;
const canCacheDiff = (value: PullRequestDiffResult) =>
  value.patch.length * 2 <= DIFF_CACHE_PATCH_BUDGET_BYTES;
const diffCacheEvictions = (entries: Iterable<readonly [string, PullRequestDiffResult]>) => {
  let bytes = 0;
  const evictions: string[] = [];
  for (const [key, value] of Array.from(entries).toReversed()) {
    const size = value.patch.length * 2;
    if (bytes + size > DIFF_CACHE_PATCH_BUDGET_BYTES) {
      evictions.push(key);
    } else {
      bytes += size;
    }
  }
  return evictions;
};
const FILES_VIEWED_CACHE_CAPACITY = 128;
const VIEWER_CACHE_CAPACITY = 32;

export type PullRequestError = PullRequestUnavailableError | PullRequestOperationError;

const routingCredential = Context.Reference<{
  readonly credentialFingerprint: string;
  readonly viewer: string;
} | null>("t3/PullRequestService/routingCredential", { defaultValue: () => null });
const credentialNamespace = Symbol("pullRequestCredentialNamespace");
type CredentialRef = PullRequestRef & { readonly [credentialNamespace]?: string };

export class PullRequestService extends Context.Service<
  PullRequestService,
  {
    readonly list: (
      input: PullRequestListInput,
    ) => Effect.Effect<PullRequestListResult, PullRequestError>;
    readonly listStats: (
      input: PullRequestListStatsInput,
    ) => Effect.Effect<PullRequestListStatsResult, PullRequestError>;
    readonly filterOptions: (
      input: PullRequestFilterOptionsInput,
    ) => Effect.Effect<PullRequestFilterOptions, PullRequestError>;
    readonly routing: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestRoutingResult, PullRequestError>;
    readonly routingIdentity: (
      input: PullRequestRoutingIdentityInput,
    ) => Effect.Effect<PullRequestRoutingIdentityResult, PullRequestError>;
    readonly withRoutingCredential: <A, E, R>(
      input: PullRequestRef,
      operation: Effect.Effect<A, E, R>,
    ) => Effect.Effect<A, E | PullRequestError, R>;
    readonly summary: (
      input: PullRequestRef,
      options?: { readonly recoverTransientFailure?: boolean },
    ) => Effect.Effect<PullRequestSummary, PullRequestError>;
    readonly stack: (
      input: PullRequestRef,
      options?: { readonly includeDetails?: boolean },
    ) => Effect.Effect<PullRequestStack | null, PullRequestError>;
    readonly subscribeMerges: Effect.Effect<
      Stream.Stream<PullRequestMergeEvent>,
      never,
      Scope.Scope
    >;
    readonly subscribeStateChanges: Effect.Effect<
      Stream.Stream<ThreadPullRequestKey>,
      never,
      Scope.Scope
    >;
    readonly reportState: (
      input: PullRequestReportStateInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly subscribeRefreshes: Stream.Stream<number>;
    readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect<void>;
    /** Project and remote lookups inside `effect` read once per filter, e.g. across one sync sweep. */
    readonly withSharedProjectReads: <A, E, R>(
      effect: Effect.Effect<A, E, R>,
    ) => Effect.Effect<A, E, R>;
    readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>;
    readonly preview: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestPreview, PullRequestError>;
    readonly checks: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestChecks | null, PullRequestError>;
    readonly watchFingerprint: (
      input: PullRequestRef,
    ) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, PullRequestError>;
    readonly activity: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestActivity, PullRequestError>;
    readonly threadComments: (
      input: PullRequestThreadCommentsInput,
    ) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestError>;
    readonly diff: (
      input: PullRequestDiffInput,
    ) => Effect.Effect<PullRequestDiffResult, PullRequestError>;
    readonly diffFileContents: (
      input: PullRequestDiffFileContentsInput,
    ) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;
    readonly filesViewed: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestFilesViewedResult, PullRequestError>;
    readonly setFilesViewed: (
      input: PullRequestSetFilesViewedInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly changeBreakdown: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;
    readonly runAction: (
      input: PullRequestActionInput,
    ) => Effect.Effect<PullRequestSummary | undefined, PullRequestError>;
    readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
    readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
    readonly updateComment: (
      input: PullRequestCommentUpdateInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly submitReview: (
      input: PullRequestSubmitReviewInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly replyToThread: (
      input: PullRequestThreadReplyInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly setThreadResolution: (
      input: PullRequestThreadResolutionInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly setReaction: (
      input: PullRequestReactionInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly reviewerCandidates: (
      input: PullRequestReviewerCandidatesInput,
    ) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;
    readonly requestReviewers: (
      input: PullRequestReviewerRequestInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly labelCandidates: (
      input: PullRequestRef,
    ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestError>;
    readonly setLabels: (
      input: PullRequestLabelChangeInput,
    ) => Effect.Effect<void, PullRequestError>;
    readonly invalidate: (
      input: PullRequestInvalidateInput,
      options?: { readonly notifyReaders?: boolean },
    ) => Effect.Effect<void>;
  }
>()("t3/pullRequest/PullRequestService") {}

const VERDICT_LABELS: Record<PullRequestReviewVerdict, string> = {
  comment: "review",
  approve: "approve",
  "request-changes": "request changes on",
};

const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
  merge: "You need write access on this repository to merge.",
  ready:
    "You need write access on this repository, or to have opened this change request, to mark it ready for review.",
  draft:
    "You need write access on this repository, or to have opened this change request, to return it to a draft.",
  close:
    "You need write access on this repository, or to have opened this change request, to close it.",
  "update-branch":
    "You need write access on this repository, or to have opened this change request, to update its branch.",
  reopen:
    "You need write access on this repository, or to have opened this change request, to reopen it.",
  "enable-auto-merge":
    "Auto-merge needs write access on this repository, and the repository has to allow it.",
  "disable-auto-merge":
    "You need write access on this repository to stop it being merged for you once it is ready.",
  revert: "You need write access on this repository to open a revert pull request.",
  "delete-branch": "You need write access on the source repository to delete its branch.",
  "approve-workflows":
    "You need write access on this repository to approve workflows from a fork pull request.",
};

const REVIEWER_REQUEST_REFUSAL = "You need write access on this repository to ask for a review.";
const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to change its labels.";

export interface SupportedProject {
  readonly cursorKey: string;
  readonly project: OrchestrationProjectShell;
  readonly api: PullRequestProviderApi;
  readonly repository: string;
  readonly host: string;
  /** Unlike Azure repository names, remotes are unique across an organization. */
  readonly remote: string;
  readonly repositoryKey: string | null;
}

interface WorkspaceProjects {
  readonly supported: ReadonlyArray<SupportedProject>;
  readonly unimplemented: ReadonlyMap<
    string,
    { readonly kind: SourceControlProviderKind; readonly projectCount: number }
  >;
  readonly viewerRoots: ReadonlyMap<string, ReadonlyArray<string>>;
}

// Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends.
const sharedProjectReads = Context.Reference<{
  open: boolean;
  readonly reads: Map<string, Effect.Effect<WorkspaceProjects, PullRequestError>>;
} | null>("t3/PullRequestService/sharedProjectReads", { defaultValue: () => null });

interface RepositoryBatch {
  readonly key: string;
  readonly entries: ReadonlyArray<PullRequestListEntry>;
  readonly errors: ReadonlyArray<PullRequestListProjectError>;
  readonly truncated: boolean;
  readonly nextCursor: string | null;
}

interface ListCursor extends ProviderListCursor {
  readonly seenAt: ReadonlyArray<number>;
}

const LIST_CURSOR_PATTERN =
  /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?(?:\|([\w.:~+-]{1,128}))?$/;

function parseListCursor(raw: string): ListCursor | null {
  const match = LIST_CURSOR_PATTERN.exec(raw);
  if (match === null) return null;
  const seenAt = match[3];
  return {
    updatedBefore: match[1]!,
    delivered: Number(match[2]),
    seenAt: seenAt === undefined ? [] : seenAt.split(",").map(Number),
    ...(match[4] === undefined ? {} : { resumeAfter: match[4] }),
  };
}

function listCursorKey(host: string, repository: string): string {
  return `${host} ${repository.toLowerCase()}`;
}

// Preserve exclusions across slices sharing a timestamp to avoid redelivery.
function nextListCursor(
  previous: ListCursor | undefined,
  fetched: ReadonlyArray<ProviderChangeRequest>,
  delivered: ReadonlyArray<ProviderChangeRequest>,
  /** A provider may consume malformed offset-paged rows that never appear in `delivered`. */
  cursorAdvance = delivered.length,
  resumeAfter?: string,
): string | null {
  if (fetched.length === 0) return null;
  // Use all fetched rows: a slice containing only duplicates must still advance to older rows.
  const oldest = fetched.reduce((left, right) => (right.updatedAt < left.updatedAt ? right : left));
  return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance, resumeAfter);
}

function listCursorAt(
  previous: ListCursor | undefined,
  boundary: string,
  fetched: ReadonlyArray<ProviderChangeRequest>,
  deliveredCount: number,
  resumeAfter?: string,
): string {
  const seenAt = new Set([
    ...(previous?.updatedBefore === boundary ? previous.seenAt : []),
    ...fetched.filter((item) => item.updatedAt === boundary).map((item) => item.number),
  ]);
  const cursor = `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`;
  return resumeAfter === undefined ? cursor : `${cursor}|${resumeAfter}`;
}

function isProviderUnusable(error: PullRequestProviderError): boolean {
  return error.reason === "missing-tool" || error.reason === "unauthenticated";
}

type UnavailableRequirementOf = (
  kind: SourceControlProviderKind,
) => PullRequestProviderApi["unavailableRequirement"];

function unavailableRequirement(
  requirementOf: UnavailableRequirementOf,
  error: PullRequestProviderError,
): string | undefined {
  const requirement = requirementOf(error.provider);
  if (requirement === undefined) return undefined;
  return error.reason === "missing-tool" ? requirement.missing : requirement.unauthenticated;
}

function providerDetail(
  requirementOf: UnavailableRequirementOf,
  error: PullRequestProviderError,
): string {
  if (!isProviderUnusable(error)) return error.detail;
  return unavailableRequirement(requirementOf, error) ?? error.detail;
}

function toPullRequestErrorWith(
  requirementOf: UnavailableRequirementOf,
): (operation: string) => (error: PullRequestProviderError) => PullRequestError {
  return (operation) => (error) => {
    if (isProviderUnusable(error)) {
      const requirement = unavailableRequirement(requirementOf, error);
      return new PullRequestUnavailableError({
        reason: error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated",
        provider: error.provider,
        ...(requirement === undefined ? {} : { requirement }),
        cause: error,
      });
    }
    return new PullRequestOperationError({
      operation,
      detail: error.detail,
      ...(error.reason === "not-found" ? { reason: "not-found" as const } : {}),
      cause: error,
    });
  };
}

function withRateLimitBackoff(
  api: PullRequestProviderApi,
  host: string,
  limits: SourceControlRateLimit.SourceControlRateLimit["Service"],
  options?: { readonly viewerAllowsPause: boolean },
): PullRequestProviderApi {
  const key = { provider: api.kind, host };
  const protect = <A>(
    operation: string,
    effect: Effect.Effect<A, PullRequestProviderError>,
    allowPaused: boolean,
  ) =>
    limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe(
      Effect.mapError(
        (error) =>
          new PullRequestProviderError({
            provider: api.kind,
            operation,
            reason: "rate-limited",
            detail: error.detail,
            retryAt: error.retryAt,
            cause: error,
          }),
      ),
      Effect.flatMap((lease) =>
        effect.pipe(
          Effect.provideService(SourceControlRateLimit.Interactive, allowPaused),
          Effect.tap(() => limits.recordSuccess({ ...key, lease })),
          Effect.tapError((error) =>
            error.reason === "rate-limited"
              ? limits.recordRateLimit({
                  ...key,
                  lease,
                  ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
                })
              : Effect.void,
          ),
        ),
      ),
    );
  const wrap =
    <Args extends ReadonlyArray<unknown>, A>(
      operation: string,
      call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
      allowPaused = false,
    ) =>
    (...args: Args) =>
      protect(operation, call(...args), allowPaused);
  const interactive = <Args extends ReadonlyArray<unknown>, A>(
    operation: string,
    call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
  ) => wrap(operation, call, true);

  const wrapped = {
    kind: api.kind,
    capabilities: api.capabilities,
    ...(api.mergeMessageRewrite === undefined
      ? {}
      : { mergeMessageRewrite: api.mergeMessageRewrite }),
    ...(api.unavailableRequirement === undefined
      ? {}
      : { unavailableRequirement: api.unavailableRequirement }),
    ...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),
    ...(api.servesHost === undefined ? {} : { servesHost: api.servesHost }),
    ...(api.readsPublicHostWithoutCheckout === undefined
      ? {}
      : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),
    getViewer:
      options?.viewerAllowsPause === true
        ? interactive("getViewer", api.getViewer)
        : wrap("getViewer", api.getViewer),
    ...(api.getRoutingIdentity === undefined ? {} : { getRoutingIdentity: api.getRoutingIdentity }),
    ...(api.withVerifiedCredential === undefined
      ? {}
      : { withVerifiedCredential: api.withVerifiedCredential }),
    listChangeRequests: wrap("listChangeRequests", api.listChangeRequests),
    ...(api.listChangeRequestsAcross === undefined
      ? {}
      : {
          listChangeRequestsAcross: wrap("listChangeRequestsAcross", api.listChangeRequestsAcross),
        }),
    ...(api.listChangeRequestStats === undefined
      ? {}
      : {
          listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats),
        }),
    getChangeRequest: wrap("getChangeRequest", api.getChangeRequest),
    ...(api.forgetChangeRequestReads === undefined
      ? {}
      : { forgetChangeRequestReads: api.forgetChangeRequestReads }),
    ...(api.getChangeRequestPreview === undefined
      ? {}
      : { getChangeRequestPreview: wrap("getChangeRequestPreview", api.getChangeRequestPreview) }),
    ...(api.getChangeRequestChecks === undefined
      ? {}
      : { getChangeRequestChecks: wrap("getChangeRequestChecks", api.getChangeRequestChecks) }),
    ...(api.getChangeRequestSummary === undefined
      ? {}
      : {
          getChangeRequestSummary: wrap("getChangeRequestSummary", api.getChangeRequestSummary),
        }),
    ...(api.getChangeRequestStack === undefined
      ? {}
      : { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }),
    ...(api.getChangeRequestWatchFingerprint === undefined
      ? {}
      : {
          getChangeRequestWatchFingerprint: wrap(
            "getChangeRequestWatchFingerprint",
            api.getChangeRequestWatchFingerprint,
          ),
        }),
    getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),
    ...(api.getReviewThreadComments === undefined
      ? {}
      : {
          getReviewThreadComments: wrap("getReviewThreadComments", api.getReviewThreadComments),
        }),
    getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions),
    getDiff: wrap("getDiff", api.getDiff),
    ...(api.getDiffFilePaths === undefined
      ? {}
      : { getDiffFilePaths: wrap("getDiffFilePaths", api.getDiffFilePaths) }),
    ...(api.getDiffFileContents === undefined
      ? {}
      : { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }),
    ...(api.getFilesViewed === undefined
      ? {}
      : { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }),
    ...(api.getFileStats === undefined
      ? {}
      : { getFileStats: wrap("getFileStats", api.getFileStats) }),
    ...(api.setFilesViewed === undefined
      ? {}
      : { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }),
    ...(api.getFileRevisions === undefined
      ? {}
      : { getFileRevisions: wrap("getFileRevisions", api.getFileRevisions) }),
    runAction: interactive("runAction", api.runAction),
    ...(api.updateChangeRequest === undefined
      ? {}
      : {
          updateChangeRequest: interactive("updateChangeRequest", api.updateChangeRequest),
        }),
    comment: interactive("comment", api.comment),
    ...(api.updateComment === undefined
      ? {}
      : { updateComment: interactive("updateComment", api.updateComment) }),
    submitReview: interactive("submitReview", api.submitReview),
    listReviewerCandidates: interactive("listReviewerCandidates", api.listReviewerCandidates),
    setReviewerRequest: interactive("setReviewerRequest", api.setReviewerRequest),
    ...(api.listLabelCandidates === undefined
      ? {}
      : { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }),
    ...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }),
    ...(api.listRepositoryLabels === undefined
      ? {}
      : { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }),
    ...(api.searchRepositoryAuthors === undefined
      ? {}
      : {
          searchRepositoryAuthors: interactive(
            "searchRepositoryAuthors",
            api.searchRepositoryAuthors,
          ),
        }),
    ...(api.searchRepositoryReferences === undefined
      ? {}
      : {
          searchRepositoryReferences: interactive(
            "searchRepositoryReferences",
            api.searchRepositoryReferences,
          ),
        }),
    replyToThread: interactive("replyToThread", api.replyToThread),
    setReaction: interactive("setReaction", api.setReaction),
    setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
  };
  // Optional provider methods must be forwarded too; returning the interface alone permits omissions.
  return wrapped satisfies PullRequestProviderApi &
    Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;
}

const FILTER_OPTIONS_LIMIT = 100;

/**
 * Exact matches first, then names that begin with the query, then the rest, so a short query
 * still puts the obvious answer at the top of a long list.
 */
function rankFilterOptions<A>(
  pages: ReadonlyArray<ProviderFilterOptionPage<A>>,
  input: {
    readonly query: string | undefined;
    readonly keyOf: (item: A) => string;
    readonly textsOf: (item: A) => ReadonlyArray<string | null>;
    /** Ties keep the hosts' order instead of sorting by key. */
    readonly hostOrder?: boolean;
  },
): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {
  const query = input.query?.trim().toLowerCase() ?? "";
  const unique = new Map<string, A>();
  for (const page of pages) {
    for (const item of page.items) {
      const key = input.keyOf(item).toLowerCase();
      if (!unique.has(key)) unique.set(key, item);
    }
  }
  const rank = (item: A) => {
    const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : []));
    if (query.length === 0) return 0;
    if (texts.includes(query)) return 0;
    if (texts.some((text) => text.startsWith(query))) return 1;
    if (texts.some((text) => text.includes(query))) return 2;
    return null;
  };
  const ranked = [...unique.values()]
    .flatMap((item) => {
      const score = rank(item);
      return score === null ? [] : [{ item, score, key: input.keyOf(item) }];
    })
    .toSorted(
      (left, right) =>
        left.score - right.score ||
        (input.hostOrder === true
          ? 0
          : left.key.localeCompare(right.key, undefined, { sensitivity: "base" })),
    );
  return {
    items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),
    truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated),
  };
}

const remoteHostKey = (recognized: SourceControlProviderInfo, remoteUrl: string) =>
  `${recognized.baseUrl}\n${isSshRemoteUrl(remoteUrl) ? "ssh" : "web"}`;

/** An HTTP remote names its server's web host, port included. */
function httpRemoteHost(remoteUrl: string): string | null {
  try {
    const remote = new URL(remoteUrl);
    return remote.protocol === "http:" || remote.protocol === "https:"
      ? remote.host.toLowerCase()
      : null;
  } catch {
    return null;
  }
}

// Capture before the provider read so a slow response keeps its original freshness through caches.
const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {
  const observedAt = yield* Clock.currentTimeMillis;
  return { value: yield* read, observedAt };
});

export const make = Effect.gen(function* () {
  const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);
  const stateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
  const pullRequestRefreshes = yield* SubscriptionRef.make(0);
  const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry;
  const requirementOf: UnavailableRequirementOf = (kind) =>
    registry.get(kind)?.unavailableRequirement;
  const toPullRequestError = toPullRequestErrorWith(requirementOf);
  const serverSettings = yield* ServerSettings.ServerSettingsService;
  const projects = yield* ProjectService.ProjectService;
  const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
  const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
  const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;
  const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;
  const readCache = yield* PullRequestReadCache.PullRequestReadCache;
  const clock = yield* Clock.Clock;

  /**
   * Where each project's remote is served from, by the remote's recognised base URL: a remote no
   * definition placed is identified by the hosting CLIs, and a host whose remotes may not name
   * its web server says which one does. One project per base URL and transport answers for all
   * of them.
   */
  const resolveRemoteHosts = Effect.fn("PullRequestService.resolveRemoteHosts")(function* (
    projects: ReadonlyArray<OrchestrationProjectShell>,
    filter: Pick<PullRequestListInput, "projectId" | "host">,
  ) {
    type Candidate = {
      readonly project: OrchestrationProjectShell;
      readonly context: SourceControlProviderContext;
    };
    const candidatesByKey = new Map<string, Candidate[]>();
    for (const project of projects) {
      if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
      const identity = project.repositoryIdentity;
      if (
        !identity ||
        identity.provider === undefined ||
        sourceControlDefinitions.repositorySelector(identity) === null
      )
        continue;
      if (identity.provider !== "unknown") {
        const provider = yield* sourceControlProviders
          .get(identity.provider)
          .pipe(Effect.orElseSucceed(() => null));
        if (provider?.resolveRemoteWebHost === undefined) continue;
      }
      const host = sourceControlDefinitions.changeRequestHost(identity, "unknown");
      if (
        filter.host !== undefined &&
        host !== "unknown" &&
        host !== filter.host.toLowerCase() &&
        httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() &&
        !isSshRemoteUrl(identity.locator.remoteUrl)
      ) {
        continue;
      }
      const { remoteName, remoteUrl } = identity.locator;
      const recognized = sourceControlDefinitions.recognizeRemote(remoteUrl);
      if (recognized === null) continue;
      const candidate = {
        project,
        context: {
          provider:
            identity.provider === "unknown"
              ? recognized
              : { ...recognized, kind: identity.provider },
          remoteName,
          remoteUrl,
          ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)
            ? { requestedHost: filter.host }
            : {}),
        },
      };
      const key = remoteHostKey(recognized, remoteUrl);
      const candidates = candidatesByKey.get(key);
      if (candidates === undefined) candidatesByKey.set(key, [candidate]);
      else candidates.push(candidate);
    }

    const resolveContext = (input: {
      readonly cwd: string;
      readonly context: SourceControlProviderContext;
    }) => sourceControlProviders.resolveHandle(input).pipe(Effect.map((handle) => handle.context));
    type RemoteHost = { readonly kind: SourceControlProviderKind; readonly host: string | null };
    const resolveCandidate = ({ project, context }: Candidate) =>
      (context.provider.kind === "unknown"
        ? resolveContext({ cwd: project.workspaceRoot, context }).pipe(
            Effect.map((resolved) =>
              resolved === null || resolved.provider.kind === "unknown"
                ? null
                : { context: resolved, discovered: true },
            ),
          )
        : Effect.succeed({ context, discovered: false })
      ).pipe(
        Effect.flatMap((found) =>
          found === null
            ? Effect.succeed(null)
            : sourceControlProviders.get(found.context.provider.kind).pipe(
                Effect.flatMap(
                  (provider) =>
                    provider.resolveRemoteWebHost?.({
                      cwd: project.workspaceRoot,
                      context: found.context,
                      // A remote discovery just placed is not looked up a second time.
                      resolveContext: found.discovered
                        ? () => Effect.succeed(found.context)
                        : resolveContext,
                    }) ?? Effect.succeed(null),
                ),
                Effect.orElseSucceed(() => null),
                Effect.map((host): RemoteHost => ({ kind: found.context.provider.kind, host })),
              ),
        ),
        Effect.orElseSucceed(() => null),
      );

    // An SSH remote whose web host one checkout could not name may be named by the next; a
    // kind found without a host still stands if none can.
    const resolveKey = Effect.fn("PullRequestService.resolveRemoteHost")(function* (
      candidates: ReadonlyArray<Candidate>,
    ) {
      let fallback: RemoteHost | null = null;
      for (const candidate of candidates) {
        const resolved = yield* resolveCandidate(candidate);
        if (resolved === null) continue;
        if (resolved.host !== null || !isSshRemoteUrl(candidate.context.remoteUrl)) {
          return resolved;
        }
        fallback ??= resolved;
      }
      return fallback;
    });

    return yield* Effect.forEach(
      candidatesByKey,
      ([key, candidates]) =>
        resolveKey(candidates).pipe(Effect.map((resolved) => [key, resolved] as const)),
      { concurrency: REPOSITORY_CONCURRENCY },
    ).pipe(Effect.map((resolved) => new Map(resolved)));
  });

  const listWorkspaceProjects = (
    filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
  ): Effect.Effect<WorkspaceProjects, PullRequestError> =>
    Effect.flatMap(sharedProjectReads, (shared) => {
      if (shared === null || !shared.open) return readWorkspaceProjects(filter);
      const key = JSON.stringify([filter.projectId, filter.projectIds, filter.host]);
      const existing = shared.reads.get(key);
      if (existing !== undefined) return existing;
      return Effect.cached(readWorkspaceProjects(filter)).pipe(
        Effect.tap((read) => Effect.sync(() => shared.reads.set(key, read))),
        Effect.flatten,
      );
    });

  const withSharedProjectReads = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
    Effect.suspend(() => {
      const shared = { open: true, reads: new Map() };
      return effect.pipe(
        Effect.provideService(sharedProjectReads, shared),
        Effect.ensuring(
          Effect.sync(() => {
            shared.open = false;
            shared.reads.clear();
          }),
        ),
      );
    });

  const readWorkspaceProjects = (
    filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
  ): Effect.Effect<WorkspaceProjects, PullRequestError> =>
    (filter.projectId === undefined
      ? projects.listShells(
          filter.projectIds === undefined ? undefined : { projectIds: filter.projectIds },
        )
      : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
    ).pipe(
      Effect.mapError(
        (error) =>
          new PullRequestOperationError({
            operation: "listProjects",
            detail: "The project list could not be read.",
            cause: error,
          }),
      ),
      Effect.flatMap((projects) =>
        Effect.forEach(
          projects,
          (project) =>
            project.repositoryIdentity != null
              ? Effect.succeed(project)
              : repositoryIdentities
                  .resolve(project.workspaceRoot)
                  .pipe(Effect.map((repositoryIdentity) => ({ ...project, repositoryIdentity }))),
          { concurrency: REPOSITORY_CONCURRENCY },
        ),
      ),
      Effect.flatMap((projects) =>
        resolveRemoteHosts(projects, filter).pipe(
          Effect.map((remoteHosts) => ({ remoteHosts, projects })),
        ),
      ),
      Effect.map(({ remoteHosts, projects }) => {
        const supported: SupportedProject[] = [];
        const unimplemented = new Map<
          string,
          { kind: SourceControlProviderKind; projectCount: number }
        >();
        const viewerRoots = new Map<string, string[]>();
        const seen = new Set<string>();
        for (const project of projects) {
          if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
          if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
          const identity = project.repositoryIdentity;
          let kind = identity?.provider;
          const repository = sourceControlDefinitions.repositorySelector(
            project.repositoryIdentity,
          );
          if (!identity || kind === undefined || repository === null) continue;
          const recognized = sourceControlDefinitions.recognizeRemote(identity.locator.remoteUrl);
          const remote =
            recognized === null
              ? undefined
              : remoteHosts.get(remoteHostKey(recognized, identity.locator.remoteUrl));
          kind = remote?.kind ?? kind;
          const host = remote?.host ?? sourceControlDefinitions.changeRequestHost(identity, kind);
          if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
            continue;
          }
          const registered = registry.get(kind);
          const api = registered?.servesHost?.(host) === false ? null : registered;
          if (api !== null) {
            const roots = viewerRoots.get(host);
            if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);
            else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot);
          }
          const repositoryKey =
            api?.repositoryKey?.({ canonicalKey: identity.canonicalKey }) ?? null;
          const key = listCursorKey(host, repositoryKey ?? repository);
          if (seen.has(key)) continue;
          seen.add(key);
          if (api === null) {
            const counted = unimplemented.get(host);
            if (counted === undefined) unimplemented.set(host, { kind, projectCount: 1 });
            else counted.projectCount += 1;
            continue;
          }
          supported.push({
            cursorKey: key,
            project,
            api: withRateLimitBackoff(api, host, rateLimits),
            repository,
            host,
            remote:
              repositoryKey ??
              sourceControlDefinitions.repositoryKeyFromRemote(`https://${host}/${repository}`),
            repositoryKey:
              repositoryKey === null
                ? null
                : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()),
          });
        }
        return { supported, unimplemented, viewerRoots };
      }),
    );

  // Azure derives organization from the checkout; require the matching repository.
  const requireProject = (ref: PullRequestRef): Effect.Effect<SupportedProject, PullRequestError> =>
    listWorkspaceProjects({ projectId: ref.projectId }).pipe(
      Effect.flatMap(({ supported }): Effect.Effect<SupportedProject, PullRequestError> => {
        const own = supported[0];
        const repository = ref.repository.trim();
        const host = ref.host?.trim().toLowerCase();
        if (own !== undefined && own.repository.toLowerCase() === repository.toLowerCase()) {
          if (host === undefined || host === own.host) return Effect.succeed(own);
        }
        if (host === undefined) {
          if (own === undefined) {
            return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" }));
          }
          return Effect.fail(
            new PullRequestOperationError({
              operation: "resolveRepository",
              detail: "The change request does not belong to the selected project.",
            }),
          );
        }
        const referenceKey = `${host}/${repository}`.toLowerCase();
        const repositoryKey = sourceControlDefinitions.canonicalRepositoryKey(referenceKey);
        // A host that spells one repository several ways (Azure's SSH and legacy clone hosts)
        // can differ from the browser URL's host. Compare the complete repository identity
        // before narrowing those checkouts by host.
        return listWorkspaceProjects(
          sourceControlDefinitions.findByRepositoryKey(referenceKey) ? {} : { host },
        ).pipe(
          Effect.flatMap(({ supported }) => {
            const onHost = supported.filter((candidate) => candidate.host === host);
            const route =
              supported.find(
                (candidate) =>
                  candidate.repositoryKey !== null && candidate.repositoryKey === repositoryKey,
              ) ??
              onHost.find(
                (candidate) =>
                  candidate.repositoryKey === null &&
                  candidate.repository.toLowerCase() === repository.toLowerCase(),
              ) ??
              onHost.find((candidate) => candidate.repositoryKey === null);
            if (route === undefined) {
              return Effect.gen(function* () {
                const publicHost = sourceControlDefinitions.findByPublicHost(host);
                const api = publicHost === undefined ? null : registry.get(publicHost.kind);
                if (api?.readsPublicHostWithoutCheckout) {
                  const selected = yield* projects.getShell(ref.projectId).pipe(
                    Effect.mapError(
                      (cause) =>
                        new PullRequestOperationError({
                          operation: "resolveRepository",
                          detail: "The selected project could not be read.",
                          cause,
                        }),
                    ),
                  );
                  if (Option.isSome(selected)) {
                    return {
                      cursorKey: listCursorKey(host, repository),
                      project: selected.value,
                      api: withRateLimitBackoff(api, host, rateLimits),
                      repository,
                      host,
                      remote: sourceControlDefinitions.repositoryKeyFromRemote(
                        `https://${host}/${repository}`,
                      ),
                      repositoryKey: null,
                    };
                  }
                }
                return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" });
              });
            }
            return Effect.succeed(
              route.repositoryKey !== null ||
                route.repository.toLowerCase() === repository.toLowerCase()
                ? route
                : {
                    ...route,
                    repository,
                    remote: sourceControlDefinitions.repositoryKeyFromRemote(
                      `https://${host}/${repository}`,
                    ),
                  },
            );
          }),
        );
      }),
    );

  const canonicalRef = Effect.fn("PullRequestService.canonicalRef")(function* <
    I extends PullRequestRef,
  >(input: I) {
    const project = yield* requireProject(input);
    return {
      ...input,
      projectId: project.project.id,
      host: project.host,
      repository: project.repository,
    };
  });

  // Access can change after page load; recheck every write.
  const viewerPermissionsOf = (
    project: SupportedProject,
    ref: PullRequestRef,
    operation: string,
    includeUpdateBranch = false,
  ) =>
    project.api
      .getViewerPermissions({
        cwd: project.project.workspaceRoot,
        repository: project.repository,
        host: project.host,
        number: ref.number,
        includeUpdateBranch,
      })
      .pipe(Effect.mapError(toPullRequestError(operation)));

  const decodeCursors = (
    cursors: PullRequestListInput["cursors"],
  ): Effect.Effect<ReadonlyMap<string, ListCursor> | null, PullRequestError> => {
    if (cursors === undefined) return Effect.succeed(null);
    const decoded = new Map<string, ListCursor>();
    for (const [key, raw] of Object.entries(cursors)) {
      const cursor = parseListCursor(raw);
      if (cursor === null) {
        return Effect.fail(
          new PullRequestOperationError({
            operation: "list",
            detail: "The list could not be carried on from where it left off.",
          }),
        );
      }
      decoded.set(key, cursor);
    }
    return Effect.succeed(decoded);
  };

  type ResolvedViewer = {
    readonly host: string;
    readonly kind: SourceControlProviderKind;
    readonly viewer: string | null;
    readonly error: PullRequestProviderError | null;
  };
  const viewersByHost = new Map<string, { readonly at: number; readonly result: ResolvedViewer }>();
  const viewerFlights = yield* Cache.makeWith(
    (key: string): Effect.Effect<ResolvedViewer> => {
      const [host, kind, roots] = JSON.parse(key) as [
        string,
        SourceControlProviderKind,
        ReadonlyArray<string>,
      ];
      const registered = registry.get(kind);
      if (registered === null) {
        return Effect.die(new Error(`Missing pull request provider: ${kind}`));
      }
      const api = withRateLimitBackoff(registered, host, rateLimits, { viewerAllowsPause: true });
      return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd, host }))).pipe(
        Effect.map((viewer) => ({
          host,
          kind,
          viewer: viewer as string | null,
          error: null as PullRequestProviderError | null,
        })),
        Effect.tap((result) =>
          Effect.map(Clock.currentTimeMillis, (at) => viewersByHost.set(host, { at, result })),
        ),
        Effect.catch((error) =>
          Effect.succeed({
            host,
            kind,
            viewer: null,
            error,
          }),
        ),
      );
    },
    {
      capacity: VIEWER_CACHE_CAPACITY,
      // Share cold-page lookups briefly; keep failures retryable.
      timeToLive: (exit) =>
        Exit.isSuccess(exit) && exit.value.error === null ? Duration.seconds(1) : Duration.zero,
    },
  );

  const resolveViewers = (
    projects: ReadonlyArray<SupportedProject>,
    viewerRoots: WorkspaceProjects["viewerRoots"],
    options?: { readonly allowPaused: boolean },
  ) =>
    Effect.forEach(
      [...new Set(projects.map(({ host }) => host))],
      (host) =>
        Effect.flatMap(Clock.currentTimeMillis, (now): Effect.Effect<ResolvedViewer> => {
          const held = viewersByHost.get(host);
          if (held !== undefined && now - held.at <= Duration.toMillis(VIEWER_CACHE_TTL)) {
            return Effect.succeed(held.result);
          }
          const forHost = projects.filter((project) => project.host === host);
          const api = forHost[0]!.api;
          // Include deduplicated checkouts too; one unreadable worktree must not mark the whole host signed out.
          const roots =
            viewerRoots.get(host) ?? forHost.map(({ project }) => project.workspaceRoot);
          const key = JSON.stringify([host, api.kind, [...new Set(roots)].sort()]);
          if (options?.allowPaused === true) return Cache.get(viewerFlights, key);
          // Check pauses outside the shared lookup so background reads cannot spawn repeated failing CLIs and extend the pause.
          return rateLimits.check({ provider: api.kind, host }).pipe(
            Effect.flatMap(() => Cache.get(viewerFlights, key)),
            Effect.catch((error) =>
              Effect.succeed<ResolvedViewer>({
                host,
                kind: api.kind,
                viewer: null,
                error: new PullRequestProviderError({
                  provider: api.kind,
                  operation: "getViewer",
                  reason: "rate-limited",
                  detail: error.detail,
                  retryAt: error.retryAt,
                  cause: error,
                }),
              }),
            ),
          );
        }),
      { concurrency: REPOSITORY_CONCURRENCY },
    );

  const matchesRowFilters = (
    item: ProviderChangeRequest,
    filters: PullRequestListFilters | undefined,
    viewer: string,
  ): boolean => {
    if (filters === undefined) return true;
    const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
    const holds = (label: string) => labels.has(label.trim().toLowerCase());
    return (
      (filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
      (filters.review === undefined ||
        item.reviewDecision === undefined ||
        (filters.review === "none"
          ? item.reviewDecision === null
          : item.reviewDecision === filters.review)) &&
      (filters.checks === undefined ||
        item.checksState === undefined ||
        item.checksState === filters.checks) &&
      (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
      (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
      (filters.author === undefined ||
        item.author?.login.toLowerCase() ===
          resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
    );
  };

  const toEntry = (input: {
    readonly project: SupportedProject;
    readonly item: ProviderChangeRequest;
    readonly viewer: string;
    readonly observedAt: number;
  }): PullRequestListEntry => {
    const viewer = input.viewer.toLowerCase();
    return {
      ...(input.item.stack === undefined ? {} : { stack: input.item.stack }),
      provider: input.project.api.kind,
      host: input.project.host,
      projectId: input.project.project.id,
      projectTitle: input.project.project.title,
      repository: input.project.repository,
      number: input.item.number,
      title: input.item.title,
      url: input.item.url,
      author: input.item.author,
      headBranch: input.item.headBranch,
      baseBranch: input.item.baseBranch,
      state: input.item.state,
      isDraft: input.item.isDraft,
      mergeability: input.item.mergeability,
      additions: input.item.additions,
      deletions: input.item.deletions,
      createdAt: input.item.createdAt,
      updatedAt: input.item.updatedAt,
      observedAt: input.observedAt,
      ...(input.item.checksState === undefined || input.item.checksState === null
        ? {}
        : { checksState: input.item.checksState }),
      viewerReviewRequested:
        input.item.author?.login.toLowerCase() !== viewer &&
        input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer),
      labels: input.item.labels,
      ...(input.item.reviewDecision === undefined || input.item.reviewDecision === null
        ? {}
        : { reviewDecision: input.item.reviewDecision }),
    };
  };

  const listUncached: PullRequestService["Service"]["list"] = Effect.fn(
    "PullRequestService.listUncached",
  )(function* (input) {
    const involvement = input.involvement ?? "all";
    const epochAtStart = epochCounter;
    const continuation = yield* decodeCursors(input.cursors);
    const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input);
    const projectCounts = new Map<string, number>();
    for (const { host } of projects) {
      projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);
    }

    const viewerResults = yield* resolveViewers(projects, viewerRoots);
    const viewers: Record<string, string> = {};
    for (const result of viewerResults) {
      if (result.viewer !== null) viewers[result.host] = result.viewer;
    }

    const providers: ReadonlyArray<PullRequestProviderSummary> = [
      ...viewerResults.map((result) => {
        const capabilities = projects.find((project) => project.host === result.host)?.api
          .capabilities;
        return {
          host: result.host,
          kind: result.kind,
          searchesOnHost: capabilities?.search ?? false,
          actions: capabilities?.actions ?? [],
          projectCount: projectCounts.get(result.host) ?? 1,
          configured: result.viewer !== null,
          detail: result.error === null ? null : providerDetail(requirementOf, result.error),
        };
      }),
      ...[...unimplemented].map(([host, { kind, projectCount }]) => ({
        host,
        kind,
        searchesOnHost: false,
        actions: [],
        projectCount,
        configured: false,
        detail: "This host cannot be browsed here yet.",
      })),
    ];

    const selected =
      continuation === null
        ? projects
        : projects.filter(({ cursorKey }) => continuation.has(cursorKey));
    const readable = selected.filter(({ host }) => viewers[host] !== undefined);
    const unreadable = selected
      .filter(({ host }) => viewers[host] === undefined)
      .map(({ project, repository }) => ({
        projectId: project.id,
        projectTitle: project.title,
        message: `${repository} could not be read.`,
      }));
    if (readable.length === 0) {
      const errors = viewerResults.flatMap((result) =>
        result.error === null || !selected.some(({ host }) => host === result.host)
          ? []
          : [result.error],
      );
      const blocking = errors.find(isProviderUnusable) ?? errors[0];
      if (blocking) {
        return yield* toPullRequestError("list")(blocking);
      }

      return {
        viewers: viewers as PullRequestListResult["viewers"],
        providers,
        entries: [],
        errors: [],
        truncated: false,
        nextCursors: {},
      };
    }

    const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
    const cursorOf = (project: SupportedProject): ListCursor | undefined =>
      continuation?.get(project.cursorKey);

    const readSlice = (
      project: SupportedProject,
      cursor: ListCursor | undefined,
    ): Effect.Effect<RepositoryBatch> => {
      {
        const viewer = viewers[project.host]!;
        const key = project.cursorKey;
        return project.api
          .listChangeRequests({
            cwd: project.project.workspaceRoot,
            repository: project.repository,
            host: project.host,
            state: input.state,
            involvement,
            viewer,
            limit,
            query: input.query,
            filters: input.filters,
            ...(cursor === undefined
              ? {}
              : {
                  cursor: {
                    updatedBefore: cursor.updatedBefore,
                    delivered: cursor.delivered,
                    seenAt: cursor.seenAt,
                    resumeAfter: cursor.resumeAfter,
                  },
                }),
          })
          .pipe(
            observeRead,
            Effect.map(({ value: page, observedAt }): RepositoryBatch => {
              // The boundary instant was asked for inclusively, so the rows already sent at it
              // come back with the slice. Dropping them here rather than asking for strictly
              // older is what keeps their neighbours at the same instant from being skipped.
              const items =
                cursor === undefined
                  ? page.items
                  : page.items.filter(
                      (item) =>
                        item.updatedAt !== cursor.updatedBefore ||
                        !cursor.seenAt.includes(item.number),
                    );
              return {
                key,
                entries: items
                  .filter((item) => matchesRowFilters(item, input.filters, viewer))
                  .map((item) => toEntry({ project, item, viewer, observedAt })),
                errors: [],
                truncated: page.truncated,
                nextCursor:
                  page.continues && page.truncated
                    ? nextListCursor(
                        cursor,
                        page.items,
                        items,
                        page.cursorAdvance,
                        page.resumeAfter,
                      )
                    : null,
              };
            }),
            Effect.catch((error): Effect.Effect<RepositoryBatch> =>
              Effect.succeed({
                key,
                entries: [],
                errors: [
                  {
                    projectId: project.project.id,
                    projectTitle: project.project.title,
                    message:
                      error.accessHint === undefined
                        ? `${project.repository} could not be read.`
                        : `${project.repository} could not be read. ${error.accessHint}`,
                  },
                ],
                truncated: false,
                nextCursor: null,
              }),
            ),
          );
      }
    };

    // Filters a host cannot apply thin out the slices it hands over, so a repository keeps
    // reading until it has a page's worth or runs out. The reads are bounded: a filter that
    // matches nothing would otherwise walk the repository's whole history in one request.
    const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {
      const fill = (batch: RepositoryBatch, reads: number): Effect.Effect<RepositoryBatch> => {
        const cursor = batch.nextCursor === null ? null : parseListCursor(batch.nextCursor);
        if (
          input.filters === undefined ||
          cursor === null ||
          batch.entries.length >= limit ||
          reads >= FILTERED_LIST_READS
        ) {
          return Effect.succeed(batch);
        }
        return readSlice(project, cursor).pipe(
          Effect.flatMap((next) =>
            // A slice that failed keeps the cursor before it, so the reader can try again.
            next.errors.length > 0
              ? Effect.succeed(batch)
              : fill({ ...next, entries: [...batch.entries, ...next.entries] }, reads + 1),
          ),
        );
      };
      return readSlice(project, cursorOf(project)).pipe(Effect.flatMap((batch) => fill(batch, 1)));
    };

    const readTogether = (
      chunk: ReadonlyArray<SupportedProject>,
    ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {
      const first = chunk[0]!;
      const readAcross = first.api.listChangeRequestsAcross;
      const separately = () =>
        Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });
      if (readAcross === undefined) return separately();
      const viewer = viewers[first.host]!;
      const cursor = cursorOf(first);
      return readAcross({
        cwd: first.project.workspaceRoot,
        host: first.host,
        repositories: chunk.map((project) => project.repository),
        state: input.state,
        involvement,
        viewer,
        limit,
        query: input.query,
        filters: input.filters,
        ...(cursor === undefined
          ? {}
          : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
      }).pipe(
        observeRead,
        Effect.flatMap(({ value: page, observedAt }) => {
          const rows = new Map<string, Array<ProviderChangeRequest>>();
          for (const item of page.items) {
            const key = item.repository.trim().toLowerCase();
            const held = rows.get(key);
            if (held === undefined) rows.set(key, [item]);
            else held.push(item);
          }
          const unresolved = new Set(
            (page.unresolved ?? []).map((repository) => repository.trim().toLowerCase()),
          );
          const boundary = page.items.reduce<string | null>(
            (oldest, item) =>
              oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,
            null,
          );
          return Effect.forEach(
            chunk,
            (project): Effect.Effect<RepositoryBatch> => {
              const key = project.repository.trim().toLowerCase();
              const fetched = rows.get(key) ?? [];
              if (fetched.length === 0 && unresolved.has(key)) return readRepository(project);
              const cursorHere = cursorOf(project);
              const items =
                cursorHere === undefined
                  ? fetched
                  : fetched.filter(
                      (item) =>
                        item.updatedAt !== cursorHere.updatedBefore ||
                        !cursorHere.seenAt.includes(item.number),
                    );
              return Effect.succeed({
                key: project.cursorKey,
                entries: items
                  .filter((item) => matchesRowFilters(item, input.filters, viewer))
                  .map((item) => toEntry({ project, item, viewer, observedAt })),
                errors: [],
                truncated: page.truncated,
                nextCursor:
                  page.truncated && boundary !== null
                    ? listCursorAt(cursorHere, boundary, fetched, items.length)
                    : null,
              });
            },
            { concurrency: REPOSITORY_CONCURRENCY },
          );
        }),
        Effect.catch(separately),
      );
    };

    const together = new Map<string, Array<SupportedProject>>();
    const separate: Array<SupportedProject> = [];
    for (const project of readable) {
      if (project.api.listChangeRequestsAcross === undefined) {
        separate.push(project);
        continue;
      }
      const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`;
      const group = together.get(key);
      if (group === undefined) together.set(key, [project]);
      else group.push(project);
    }
    const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) =>
      readRepository(project).pipe(Effect.map((batch) => [batch])),
    );
    for (const group of together.values()) {
      for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) {
        reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK)));
      }
    }
    const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat();

    const nextCursors: Record<string, string> = {};
    for (const batch of batches) {
      if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;
    }
    const entries = batches
      .flatMap((batch) => batch.entries)
      .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
    // Hover cards on listed rows read from here. A pinned account or a mid-read refresh is another
    // scope; half the cache stays free for previews read directly.
    if ((yield* routingCredential) === null && epochCounter === epochAtStart) {
      const seeds = entries
        .slice(0, DETAIL_CACHE_CAPACITY / 2)
        .map((entry) => [refCacheKey(entry), previewFields(entry)] as const)
        .toReversed();
      for (const [key, value] of seeds) {
        if (!(yield* Cache.has(previewCache, key))) yield* Cache.set(previewCache, key, value);
      }
    }

    return {
      viewers: viewers as PullRequestListResult["viewers"],
      providers,
      entries,
      errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],
      truncated: batches.some((batch) => batch.truncated),
      nextCursors,
    };
  });

  const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>
    routingCredential.pipe(
      Effect.flatMap((credential) =>
        credential !== null
          ? Effect.succeed(credential.viewer)
          : resolveViewers([project], new Map()).pipe(