sailfork / t3code-github / apps/ server/ src/ git/ GitManager.ts

import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as ByteSize from "effect/ByteSize";
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 FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import {
  GitActionProgressEvent,
  GitActionProgressPhase,
  GitCommandError,
  GitPreparePullRequestThreadInput,
  GitPreparePullRequestThreadResult,
  GitPullRequestRefInput,
  GitResolvePullRequestResult,
  GitRunStackedActionInput,
  GitRunStackedActionResult,
  GitStackedAction,
  VcsStatusInput,
  type VcsStatusLocalResult,
  type VcsStatusRemoteResult,
  VcsStatusResult,
  ModelSelection,
  type OrchestrationV2TurnItem,
  type ProjectId,
  SourceControlProviderError,
  type SourceControlWritingStyleSettings,
  type ThreadId,
  type ThreadPullRequestKey,
  type VcsCreateWorktreeInput,
  type VcsCreateWorktreeResult,
} from "@t3tools/contracts";
import {
  hasProjectSettingsOverrides,
  resolveProjectSettings,
} from "@t3tools/shared/projectSettings";
import {
  mergeGitStatusParts,
  resolveAutoFeatureBranchName,
  sanitizeBranchFragment,
  sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import {
  type ChangeRequestTerminology,
  UNKNOWN_SOURCE_CONTROL_CLIENT,
} from "@t3tools/source-control-core/shared/definition";
import {
  normalizeThreadPullRequestKey,
  threadPullRequestKeyOf,
} from "../sourceControl/threadPullRequests.ts";
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";

import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
import {
  historicalMessage,
  renderHistory,
  selectHistory,
} from "@t3tools/provider-core/server/handoffBudget";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import {
  conventionalCommitsTextGenerationPolicy,
  customTextGenerationPolicy,
  repositoryConventionsTextGenerationPolicy,
} from "../textGeneration/TextGenerationPresets.ts";
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { detachStackFrame } from "./detachStackFrame.ts";
import * as ServerSettings from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import type { ChangeRequest } from "@t3tools/contracts";

export interface GitActionProgressReporter {
  readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}

export interface GitRunStackedActionOptions {
  readonly actionId?: string;
  readonly progressReporter?: GitActionProgressReporter;
}

export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions {
  readonly refreshMissingPullRequest?: boolean;
}

export type GitBranchPullRequest = NonNullable<VcsStatusResult["pr"]> & {
  readonly repositoryKey: string | null;
  readonly updatedAt: string | null;
  readonly closedAt?: string | null;
  readonly mergedAt?: string | null;
  readonly headSha?: string | null;
};

interface SourceControlTextGenerationSettings {
  readonly modelSelection: ModelSelection;
  readonly style: SourceControlWritingStyleSettings;
}

export class GitManager extends Context.Service<
  GitManager,
  {
    readonly createWorktree: (
      input: VcsCreateWorktreeInput,
      options?: GitVcsDriver.CreateWorktreeOptions,
    ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
    readonly status: (
      input: VcsStatusInput,
    ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
    readonly localStatus: (
      input: VcsStatusInput,
    ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
    readonly remoteStatus: (
      input: VcsStatusInput,
      options?: GitRemoteStatusOptions,
    ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
    /** refresh queries the host; freshGitState rereads only git state and is required before persisting. */
    readonly branchPullRequest: (
      input: { readonly cwd: string; readonly branch: string },
      options?: { readonly refresh?: boolean; readonly freshGitState?: boolean },
    ) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
    readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
    readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
    readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
    readonly resolvePullRequest: (
      input: GitPullRequestRefInput,
    ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
    readonly preparePullRequestThread: (
      input: GitPreparePullRequestThreadInput,
    ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
    readonly runStackedAction: (
      input: GitRunStackedActionInput,
      options?: GitRunStackedActionOptions,
    ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
    readonly subscribePullRequestStateChanges: Effect.Effect<
      Stream.Stream<ThreadPullRequestKey>,
      never,
      Scope.Scope
    >;
  }
>()("t3/git/GitManager") {}

const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
const PR_LOOKUP_CACHE_TTL = Duration.seconds(60);
const PR_LOOKUP_NO_OPEN_PR_CACHE_TTL = Duration.minutes(5);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5);
const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15);
const PR_THREAD_CONTEXT_BYTES = 16_000;
const PR_THREAD_COMMAND_OUTPUT_CHARS = 2_000;
const isSourceControlProviderError = Schema.is(SourceControlProviderError);

/**
 * Throttled lookups fail fast, so a flat failure TTL would retry faster than a healthy
 * lookup refreshes. Backing off per branch keeps a 429 from becoming sustained pressure.
 */
function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration {
  const exponent = Math.max(0, consecutiveFailures - 1);
  const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent);
  return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL);
}
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;

function isNotGitRepositoryError(error: GitCommandError): boolean {
  return error.message.toLowerCase().includes("not a git repository");
}

interface OpenPrInfo {
  number: number;
  title: string;
  url: string;
  baseRefName: string;
  headRefName: string;
}

interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
  state: "open" | "closed" | "merged";
  isDraft?: boolean;
  closedAt?: string | null;
  mergedAt?: string | null;
  updatedAt: Option.Option<DateTime.Utc>;
  headSha?: string | undefined;
}

const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
  Order.flip(Option.makeOrder(DateTime.Order)),
  (pullRequest) => pullRequest.updatedAt,
);

interface ResolvedPullRequest {
  number: number;
  title: string;
  url: string;
  baseBranch: string;
  headBranch: string;
  state: "open" | "closed" | "merged";
}

interface PullRequestHeadRemoteInfo {
  isCrossRepository?: boolean | undefined;
  headRepositoryNameWithOwner?: string | null | undefined;
  headRepositoryOwnerLogin?: string | null | undefined;
}

interface BranchHeadContext {
  localBranch: string;
  headBranch: string;
  headSelectors: ReadonlyArray<string>;
  preferredHeadSelector: string;
  remoteName: string | null;
  headRemoteUrlKey: string | null;
  targetRemoteUrlKey: string | null;
  headRepositoryNameWithOwner: string | null;
  headRepositoryOwnerLogin: string | null;
  isCrossRepository: boolean;
}

export function pullRequestRepositoryKey(value: string): string | null {
  const repositoryUrl = sourceControlDefinitions.parseChangeRequestUrl(value)?.link.repositoryUrl;
  return repositoryUrl === undefined
    ? null
    : sourceControlDefinitions.repositoryKeyFromRemote(repositoryUrl);
}

/** Null when the host did not name the repository the head lives in. */
function resolveHeadRepositoryNameWithOwner(pullRequest: PullRequestHeadRemoteInfo): string | null {
  return normalizeOptionalString(pullRequest.headRepositoryNameWithOwner);
}

function resolvePullRequestWorktreeLocalBranchName(
  pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
): string {
  if (!pullRequest.isCrossRepository) {
    return pullRequest.headBranch;
  }

  const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();
  const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head";
  return `t3code/pr-${pullRequest.number}/${suffix}`;
}

export function parseRepositoryNameWithOwnerFromRemoteUrl(
  url: string | null,
  provider?: Pick<
    SourceControlProvider.SourceControlProvider["Service"],
    "repositoryNameFromRemoteUrl"
  >,
): string | null {
  const trimmed = url?.trim() ?? "";
  if (trimmed.length === 0) return null;
  return (
    provider?.repositoryNameFromRemoteUrl?.(trimmed) ??
    SourceControlProvider.repositoryPathFromRemoteUrl(trimmed)
  );
}

function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
  const trimmed = nameWithOwner?.trim() ?? "";
  if (trimmed.length === 0) {
    return null;
  }
  // The first segment only: a nested path's owner is its top-level group. The full path
  // distinguishes subgroups.
  const [ownerLogin] = trimmed.split("/");
  const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
  return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
}

function normalizeOptionalString(value: string | null | undefined): string | null {
  const trimmed = value?.trim() ?? "";
  return trimmed.length > 0 ? trimmed : null;
}

function normalizeOptionalRepositoryNameWithOwner(value: string | null | undefined): string | null {
  const normalized = normalizeOptionalString(value);
  return normalized ? normalized.toLowerCase() : null;
}

function normalizeOptionalOwnerLogin(value: string | null | undefined): string | null {
  const normalized = normalizeOptionalString(value);
  return normalized ? normalized.toLowerCase() : null;
}

interface PullRequestHeadIdentity {
  readonly repositoryNameWithOwner: string | null;
  readonly ownerLogin: string | null;
}

function resolveExpectedHeadIdentity(
  headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
): PullRequestHeadIdentity {
  const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
    headContext.headRepositoryNameWithOwner,
  );
  return {
    repositoryNameWithOwner,
    ownerLogin:
      normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
      parseRepositoryOwnerLogin(repositoryNameWithOwner),
  };
}

function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
  const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
    resolveHeadRepositoryNameWithOwner(pr),
  );
  return {
    repositoryNameWithOwner,
    ownerLogin:
      normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
      parseRepositoryOwnerLogin(repositoryNameWithOwner),
  };
}

export function matchesBranchHeadContext(
  pr: PullRequestInfo,
  headContext: Pick<
    BranchHeadContext,
    "headBranch" | "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin" | "isCrossRepository"
  >,
): boolean {
  if (pr.headRefName !== headContext.headBranch) {
    return false;
  }

  const expectedHead = resolveExpectedHeadIdentity(headContext);
  const pullRequestHead = resolvePullRequestHeadIdentity(pr);

  if (expectedHead.repositoryNameWithOwner) {
    if (pullRequestHead.repositoryNameWithOwner) {
      if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
        return false;
      }
    }
    if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
      if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
        return false;
      }
    }
  }

  if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
    if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
      return false;
    }
  }

  if (headContext.isCrossRepository) {
    if (pr.isCrossRepository === false) {
      return false;
    }
    if (
      (expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
      !pullRequestHead.repositoryNameWithOwner &&
      !pullRequestHead.ownerLogin
    ) {
      return false;
    }
    return true;
  }

  if (pr.isCrossRepository === true) {
    if (
      (!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
      (!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
    ) {
      return false;
    }
  }

  return true;
}

function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
  return {
    number: summary.number,
    title: summary.title,
    url: summary.url,
    baseRefName: summary.baseRefName,
    headRefName: summary.headRefName,
    ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
    state: summary.state ?? "open",
    ...(summary.isDraft === true ? { isDraft: true } : {}),
    closedAt: summary.closedAt ?? null,
    mergedAt: summary.mergedAt ?? null,
    updatedAt: summary.updatedAt,
    ...(summary.isCrossRepository !== undefined
      ? { isCrossRepository: summary.isCrossRepository }
      : {}),
    ...(summary.headRepositoryNameWithOwner !== undefined
      ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
      : {}),
    ...(summary.headRepositoryOwnerLogin !== undefined
      ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
      : {}),
  };
}

function limitContext(value: string, maxChars: number): string {
  if (value.length <= maxChars) return value;
  return `${value.slice(0, maxChars)}\n\n[truncated]`;
}

// Preserve command evidence when selectHistory drops oversized items; test verdicts are at the tail.
function limitCommandOutput(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
  if (item.type !== "command_execution" || item.output === undefined) return item;
  if (item.output.length <= PR_THREAD_COMMAND_OUTPUT_CHARS) return item;
  return { ...item, output: `[truncated]\n${item.output.slice(-PR_THREAD_COMMAND_OUTPUT_CHARS)}` };
}

function shortenSha(sha: string | undefined): string | null {
  if (!sha) return null;
  return sha.slice(0, SHORT_SHA_LENGTH);
}

function truncateText(
  value: string | undefined,
  maxLength = TOAST_DESCRIPTION_MAX,
): string | undefined {
  if (!value) return undefined;
  if (value.length <= maxLength) return value;
  if (maxLength <= 3) return "...".slice(0, maxLength);
  return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
}

function withDescription(title: string, description: string | undefined) {
  return description ? { title, description } : { title };
}

function summarizeGitActionResult(
  result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
  terms: ChangeRequestTerminology,
): {
  title: string;
  description?: string;
} {
  if (result.pr.status === "created" || result.pr.status === "opened_existing") {
    const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
    const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
    return withDescription(title, truncateText(result.pr.title));
  }

  if (result.push.status === "pushed") {
    const shortSha = shortenSha(result.commit.commitSha);
    const branch = result.push.upstreamBranch ?? result.push.branch;
    const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
    const branchPart = branch ? ` to ${branch}` : "";
    return withDescription(
      `Pushed${pushedCommitPart}${branchPart}`,
      truncateText(result.commit.subject),
    );
  }

  if (result.commit.status === "created") {
    const shortSha = shortenSha(result.commit.commitSha);
    const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
    return withDescription(title, truncateText(result.commit.subject));
  }

  return { title: "Done" };
}

function sanitizeCommitMessage(generated: {
  subject: string;
  body: string;
  branch?: string | undefined;
}): {
  subject: string;
  body: string;
  branch?: string | undefined;
} {
  const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
  const subject = rawSubject.replace(/[.]+$/g, "").trim();
  const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
  return {
    subject: safeSubject,
    body: generated.body.trim(),
    ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
  };
}

function sanitizeProgressText(value: string): string | null {
  const trimmed = value.trim();
  if (trimmed.length === 0) {
    return null;
  }
  if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
    return trimmed;
  }
  return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
}

interface CommitAndBranchSuggestion {
  subject: string;
  body: string;
  branch?: string | undefined;
  commitMessage: string;
}

function isCommitAction(
  action: GitStackedAction,
): action is "commit" | "commit_push" | "commit_push_pr" {
  return action === "commit" || action === "commit_push" || action === "commit_push_pr";
}

function formatCommitMessage(subject: string, body: string): string {
  const trimmedBody = body.trim();
  if (trimmedBody.length === 0) {
    return subject;
  }
  return `${subject}\n\n${trimmedBody}`;
}

function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
  const normalized = raw.replace(/\r\n/g, "\n").trim();
  if (normalized.length === 0) {
    return null;
  }

  const [firstLine, ...rest] = normalized.split("\n");
  const subject = firstLine?.trim() ?? "";
  if (subject.length === 0) {
    return null;
  }

  return {
    subject,
    body: rest.join("\n").trim(),
  };
}

// A branch remote of "." tracks another local branch, which no change request can have as its head.
function publishedRemoteName(branchRemote: string | null): string | null {
  return branchRemote === "." ? null : branchRemote;
}

function headBranchProbe(
  provider: SourceControlProvider.SourceControlProvider["Service"],
  headSelectors: ReadonlyArray<string>,
  state: "open" | "all",
) {
  return (
    provider.headBranchProbe?.({ headSelectors, state }) ?? {
      headSelectors,
      limit: state === "open" ? 1 : 20,
    }
  );
}

function appendUnique(values: string[], next: string | null | undefined): void {
  const trimmed = next?.trim() ?? "";
  if (trimmed.length === 0 || values.includes(trimmed)) {
    return;
  }
  values.push(trimmed);
}

function toStatusPr(pr: PullRequestInfo): {
  number: number;
  title: string;
  url: string;
  baseRef: string;
  headRef: string;
  state: "open" | "closed" | "merged";
  isDraft?: boolean;
  updatedAt: string | null;
} {
  return {
    number: pr.number,
    title: pr.title,
    url: pr.url,
    baseRef: pr.baseRefName,
    headRef: pr.headRefName,
    state: pr.state,
    ...(pr.isDraft === true ? { isDraft: true } : {}),
    updatedAt: Option.match(pr.updatedAt, {
      onNone: () => null,
      onSome: (updatedAt) => DateTime.formatIso(updatedAt),
    }),
  };
}

function normalizePullRequestReference(reference: string): string {
  const trimmed = reference.trim();
  const hashNumber = /^#(\d+)$/.exec(trimmed);
  return hashNumber?.[1] ?? trimmed;
}

function toResolvedPullRequest(pr: {
  number: number;
  title: string;
  url: string;
  baseRefName: string;
  headRefName: string;
  state?: "open" | "closed" | "merged";
}): ResolvedPullRequest {
  return {
    number: pr.number,
    title: pr.title,
    url: pr.url,
    baseBranch: pr.baseRefName,
    headBranch: pr.headRefName,
    state: pr.state ?? "open",
  };
}

function shouldPreferSshRemote(url: string | null): boolean {
  if (!url) return false;
  return isSshRemoteUrl(url);
}

function toPullRequestHeadRemoteInfo(pr: {
  isCrossRepository?: boolean | undefined;
  headRepositoryNameWithOwner?: string | null | undefined;
  headRepositoryOwnerLogin?: string | null | undefined;
}): PullRequestHeadRemoteInfo {
  return {
    ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
    ...(pr.headRepositoryNameWithOwner !== undefined
      ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
      : {}),
    ...(pr.headRepositoryOwnerLogin !== undefined
      ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
      : {}),
  };
}

export const make = Effect.gen(function* () {
  const gitCore = yield* GitVcsDriver.GitVcsDriver;
  const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
  const textGeneration = yield* TextGeneration.TextGeneration;
  const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
  const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
  const random = yield* SecureRandom.SecureRandom;
  const fileSystem = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;

  const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
  const changeRequestTermsFor = Effect.fn("GitManager.changeRequestTermsFor")(function* (
    cwd: string,
  ) {
    return yield* sourceControlProvider(cwd).pipe(
      Effect.map((provider) => sourceControlDefinitions.get(provider.kind).changeRequest),
      Effect.orElseSucceed(() => UNKNOWN_SOURCE_CONTROL_CLIENT.changeRequest),
    );
  });
  const serverSettingsService = yield* ServerSettings.ServerSettingsService;
  const threads = yield* ProjectionStore.ProjectionStoreV2;
  const projects = yield* ProjectStore.ProjectStoreV2;
  const projectSettingsFor = Effect.fnUntraced(function* (input: {
    readonly cwd: string;
    readonly threadId?: ThreadId | undefined;
    readonly projectId?: ProjectId | undefined;
  }) {
    const settings = yield* serverSettingsService.getSettings;
    if (!hasProjectSettingsOverrides(settings))
      return { settings, projectId: null as ProjectId | null };
    const threadProjectId =
      input.threadId === undefined
        ? null
        : yield* threads.getThreadShell(input.threadId).pipe(
            Effect.map((thread) => thread?.projectId ?? null),
            Effect.orElseSucceed(() => null),
          );
    const projectId =
      threadProjectId ??
      input.projectId ??
      (yield* projects.findActiveByWorkspaceRoot(input.cwd).pipe(
        Effect.map((project) => Option.getOrNull(project)?.projectId ?? null),
        Effect.orElseSucceed(() => null),
      ));
    return { settings: resolveProjectSettings(settings, projectId).settings, projectId };
  });
  const readThreadContext = Effect.fnUntraced(
    function* (threadId: ThreadId | undefined) {
      if (threadId === undefined) return undefined;
      const { visibleTurnItems } = yield* threads.getThreadProjection(threadId);
      const selected = selectHistory({
        messages: visibleTurnItems.flatMap(
          ({ item }) => historicalMessage(limitCommandOutput(item)) ?? [],
        ),
        coverage: "Digest of the thread that made this change, oldest first.",
        budget: PR_THREAD_CONTEXT_BYTES,
      });
      return selected.messages.length === 0
        ? undefined
        : renderHistory(selected.messages, selected.context);
    },
    (effect, threadId) =>
      effect.pipe(
        Effect.catch((error) =>
          Effect.logWarning("GitManager.readThreadContext failed", {
            threadId,
            errorTag: error._tag,
          }).pipe(Effect.as(undefined)),
        ),
      ),
  );
  // Hands the base T3 recorded for a branch to the host, whose own tools may keep it elsewhere.
  // Best-effort: nothing T3 does reads it back from there.
  const shareBranchBase = Effect.fn("GitManager.shareBranchBase")(function* (
    cwd: string,
    branch: string,
  ) {
    const baseBranch = yield* gitCore
      .readBranchBase(cwd, branch)
      .pipe(Effect.orElseSucceed(() => null));
    if (baseBranch === null) return;
    const provider = yield* sourceControlProvider(cwd).pipe(Effect.orElseSucceed(() => null));
    yield* provider?.recordBranchBase?.({ cwd, branch, baseBranch }) ?? Effect.void;
  });
  // Publishing a branch that tracks its base records that base first, even when the push then
  // fails, so the host hears of it after every successful push rather than the first attempt.
  const pushCurrentBranch = Effect.fn("GitManager.pushCurrentBranch")(function* (
    cwd: string,
    branch: string | null,
  ) {
    const result = yield* gitCore.pushCurrentBranch(cwd, branch);
    if (result.status === "pushed" && result.branch) {
      yield* shareBranchBase(cwd, result.branch);
    }
    return result;
  });
  const readWorktreesDirectory = serverSettingsService.getSettings.pipe(
    Effect.map((settings) => settings.worktreesDirectory),
    Effect.orElseSucceed(() => ""),
  );
  const createWorktree: GitManager["Service"]["createWorktree"] = Effect.fn(
    "GitManager.createWorktree",
  )(function* (input, options) {
    const submodules =
      options?.submodules !== undefined
        ? options.submodules
        : yield* projectSettingsFor(input).pipe(
            Effect.map(({ settings }) => settings.worktreeSubmodules),
            Effect.orElseSucceed(() => null),
          );
    const worktreesDirectory = yield* readWorktreesDirectory;
    const result = yield* gitCore.createWorktree(input, {
      worktreesDirectory,
      ...options,
      submodules,
    });
    if (input.newRefName && input.baseRefName) {
      yield* shareBranchBase(input.cwd, input.newRefName);
    }
    return result;
  });

  const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(
    function* (cwd: string, fileName: string) {
      const root = yield* fileSystem.realPath(cwd);
      const instructionPath = yield* fileSystem.realPath(path.join(root, fileName));
      const relative = path.relative(root, instructionPath);
      if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) {
        return "";
      }
      const info = yield* fileSystem.stat(instructionPath);
      if (info.type !== "File" || info.size > ByteSize.bytes(20_000)) {
        return "";
      }
      return (yield* fileSystem.readFileString(instructionPath)).trim();
    },
    Effect.orElseSucceed(() => ""),
  );

  const readRecentCommitSubjects = (cwd: string) =>
    gitCore
      .execute({
        operation: "GitManager.readRecentCommitSubjects",
        cwd,
        args: ["log", "-n", "20", "--no-merges", "--no-show-signature", "--pretty=format:%s"],
      })
      .pipe(
        Effect.map((result) =>
          result.stdout
            .split("\n")
            .map((line) => line.trim())
            .filter((line) => line.length > 0),
        ),
        Effect.orElseSucceed(() => []),
      );

  const resolveStylePolicy = Effect.fn("GitManager.resolveStylePolicy")(function* (
    cwd: string,
    settings: SourceControlTextGenerationSettings,
  ) {
    switch (settings.style.mode) {
      case "conventional_commits":
        return conventionalCommitsTextGenerationPolicy;
      case "custom":
        return customTextGenerationPolicy(
          settings.style.customInstructions
            ? {
                commitInstructions: settings.style.customInstructions,
                changeRequestInstructions: settings.style.customInstructions,
              }
            : {},
        );
      case "repo_conventions": {
        const subjects = yield* readRecentCommitSubjects(cwd);
        const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");
        const isClaudeWriter =
          settings.modelSelection.instanceId === "claudeAgent" ||
          (yield* providerRegistry.getProviders).some(
            (provider) =>
              provider.instanceId === settings.modelSelection.instanceId &&
              provider.driver === "claudeAgent",
          );
        const claudeInstructions = isClaudeWriter
          ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")
          : "";
        const examples = [
          ...(subjects.length > 0
            ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]
            : []),
          ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),
          // CLAUDE.md is often a symlink or copy of AGENTS.md; skip the duplicate.
          ...(claudeInstructions && claudeInstructions !== agentInstructions
            ? [`Local CLAUDE.md:\n${claudeInstructions}`]
            : []),
        ].join("\n\n");
        if (!examples) {
          return repositoryConventionsTextGenerationPolicy;
        }
        return {
          ...repositoryConventionsTextGenerationPolicy,
          commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
          changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
        };
      }
    }
  });
  const randomUUIDv4 = (cwd: string) =>
    random.uuidV4().pipe(
      Effect.mapError(
        (cause) =>
          new GitManagerError({
            operation: "randomUUIDv4",
            cwd,
            detail: "Failed to generate Git operation identifier.",
            cause,
          }),
      ),
    );

  const createProgressEmitter = (
    input: { cwd: string; action: GitStackedAction },
    options?: GitRunStackedActionOptions,
  ) =>
    (options?.actionId === undefined
      ? randomUUIDv4(input.cwd)
      : Effect.succeed(options.actionId)
    ).pipe(
      Effect.map((actionId) => {
        const reporter = options?.progressReporter;
        const emit = (event: GitActionProgressPayload) =>
          reporter
            ? reporter.publish({
                actionId,
                cwd: input.cwd,
                action: input.action,
                ...event,
              } as GitActionProgressEvent)
            : Effect.void;

        return {
          actionId,
          emit,
        };
      }),
    );

  const pullRequestHostOptions = (url: string) => {
    const host = URL.parse(url)?.host;
    return host ? { host } : {};
  };

  const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
    function* (
      cwd: string,
      pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
      localBranch = pullRequest.headBranch,
    ) {
      const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
      if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
        const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
        yield* gitCore.fetchRemoteTrackingBranch({
          cwd,
          remoteName,
          remoteBranch: pullRequest.headBranch,
        });
        yield* gitCore.setBranchUpstream({
          cwd,
          branch: localBranch,
          remoteName,
          remoteBranch: pullRequest.headBranch,
        });
        return;
      }

      if (repositoryNameWithOwner.length === 0) {
        return;
      }

      const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
        cwd,
        repository: repositoryNameWithOwner,
        ...pullRequestHostOptions(pullRequest.url),
      });
      const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
      const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
      const preferredRemoteName =
        pullRequest.headRepositoryOwnerLogin?.trim() ||
        repositoryNameWithOwner.split("/")[0]?.trim() ||
        "fork";
      const remoteName = yield* gitCore.ensureRemote({
        cwd,
        preferredName: preferredRemoteName,
        url: remoteUrl,
      });

      yield* gitCore.fetchRemoteTrackingBranch({
        cwd,
        remoteName,
        remoteBranch: pullRequest.headBranch,
      });
      yield* gitCore.setBranchUpstream({
        cwd,
        branch: localBranch,
        remoteName,
        remoteBranch: pullRequest.headBranch,
      });
    },
  );

  const configurePullRequestHeadUpstream = (
    cwd: string,
    pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
    localBranch = pullRequest.headBranch,
  ) =>
    configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe(
      Effect.catch((error) =>
        Effect.logWarning("GitManager.configurePullRequestHeadUpstream failed", {
          cwd,
          localBranch,
          headBranch: pullRequest.headBranch,
          cause: error,
        }).pipe(Effect.asVoid),
      ),
    );

  // The kind comes from the provider, not the remote alone: an unrecognised remote can resolve
  // to a known host.
  const changeRequestHeadRef = Effect.fn("GitManager.changeRequestHeadRef")(function* (
    cwd: string,
    number: number,
  ) {
    const provider = yield* sourceControlProvider(cwd);
    const ref = sourceControlDefinitions.get(provider.kind).changeRequestHeadRef?.(number);
    if (ref === undefined) {
      return yield* new GitManagerError({
        operation: "changeRequestHeadRef",
        cwd,
        detail: "This host publishes no ref for a change request's head.",
      });
    }
    return ref;
  });

  const fetchChangeRequestHeadIntoBranch = Effect.fn("GitManager.fetchChangeRequestHeadIntoBranch")(
    function* (cwd: string, number: number, branch: string) {
      const ref = yield* changeRequestHeadRef(cwd, number);
      yield* gitCore.fetchRefIntoBranch({ cwd, ref, branch });
    },
  );

  const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")(
    function* (
      cwd: string,
      pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
      localBranch = pullRequest.headBranch,
    ) {
      const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";

      if (repositoryNameWithOwner.length === 0) {
        yield* fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
          // Fall back to a branch fetch only for an open PR in the primary remote's repository.
          // A host can resolve a PR number from another repository, so verify the repository first.
          // Closed PR branches may have moved past the head recorded at closure.
          Effect.catch((cause) =>
            pullRequest.isCrossRepository === true || pullRequest.state !== "open"
              ? Effect.fail(cause)
              : Effect.gen(function* () {
                  const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
                  const remoteUrl = yield* gitCore.readConfigValue(cwd, `remote.${remoteName}.url`);
                  const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
                  if (
                    remoteUrl === null ||
                    pullRequestKey === null ||
                    sourceControlDefinitions.canonicalRepositoryKey(pullRequestKey) !==
                      sourceControlDefinitions.canonicalRepositoryKey(
                        sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl),
                      )
                  ) {
                    return yield* cause;
                  }
                  yield* gitCore.fetchRemoteBranch({
                    cwd,
                    remoteName,
                    remoteBranch: pullRequest.headBranch,
                    localBranch,
                  });
                }),
          ),
        );
        return;
      }

      const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
        cwd,
        repository: repositoryNameWithOwner,
        ...pullRequestHostOptions(pullRequest.url),
      });
      const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
      const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
      const preferredRemoteName =
        pullRequest.headRepositoryOwnerLogin?.trim() ||
        repositoryNameWithOwner.split("/")[0]?.trim() ||
        "fork";
      const remoteName = yield* gitCore.ensureRemote({
        cwd,
        preferredName: preferredRemoteName,
        url: remoteUrl,
      });

      yield* gitCore.fetchRemoteBranch({
        cwd,
        remoteName,
        remoteBranch: pullRequest.headBranch,
        localBranch,
      });
      yield* gitCore.setBranchUpstream({
        cwd,
        branch: localBranch,
        remoteName,
        remoteBranch: pullRequest.headBranch,
      });
    },
  );

  const materializePullRequestHeadBranch = (
    cwd: string,
    pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
    localBranch = pullRequest.headBranch,
  ) =>
    materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
      Effect.catch((primaryCause) =>
        fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
          Effect.mapError(
            (fallbackCause) =>
              new GitPullRequestMaterializationError({
                cwd,
                pullRequestNumber: pullRequest.number,
                headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
                headBranch: pullRequest.headBranch,
                localBranch,
                cause: new AggregateError(
                  [primaryCause, fallbackCause],
                  `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
                  { cause: primaryCause },
                ),
              }),
          ),
        ),
      ),
    );
  const tempDir = yield* Config.String("TMPDIR").pipe(
    Config.orElse(() => Config.String("TEMP")),
    Config.orElse(() => Config.String("TMP")),
    Config.withDefault("/tmp"),
  );
  const canonicalizeExistingPath = (value: string) =>
    fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
  const normalizeStatusCacheKey = canonicalizeExistingPath;
  const nonRepositoryStatusDetails: GitVcsDriver.GitStatusDetails = {
    isRepo: false,
    hasOriginRemote: false,
    isDefaultBranch: false,
    branch: null,
    upstreamRef: null,
    hasWorkingTreeChanges: false,
    workingTree: { files: [], insertions: 0, deletions: 0 },
    hasUpstream: false,
    aheadCount: 0,
    behindCount: 0,
    aheadOfDefaultCount: 0,
  };
  const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
    const details = yield* gitCore
      .statusDetailsLocal(cwd, { includeDivergence: false, includeBranchChanges: true })
      .pipe(
        Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
      );
    const hostingProvider = details.isRepo
      ? yield* resolveHostingProvider(cwd, details.branch)
      : null;

    return {
      isRepo: details.isRepo,
      ...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
      hasPrimaryRemote: details.hasOriginRemote,
      isDefaultRef: details.isDefaultBranch,
      refName: details.branch,
      hasWorkingTreeChanges: details.hasWorkingTreeChanges,
      workingTree: details.workingTree,
      ...(details.branchChanges ? { branchChanges: details.branchChanges } : {}),
    } satisfies VcsStatusLocalResult;
  });
  const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
    capacity: STATUS_RESULT_CACHE_CAPACITY,
    timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
  });
  const invalidateLocalStatusResultCache = (cwd: string) =>
    normalizeStatusCacheKey(cwd).pipe(
      Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
    );
  const prLookupEpochByCwd = new Map<string, number>();
  const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
  const bumpPrLookupEpoch = (cwd: string) =>
    normalizeStatusCacheKey(cwd).pipe(
      Effect.map((cacheKey) => {
        prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
      }),
    );
  const prLookupCacheKey = (
    cwd: string,
    details: {
      branch: string;
      upstreamRef: string | null;
      defaultBranch: string | null;
      localBranchExists?: boolean;
      remoteName?: string | null;
    },
  ) =>
    [
      cwd,
      details.branch,
      details.upstreamRef ?? "",
      details.defaultBranch ?? "",
      details.localBranchExists === false ? "0" : "1",
      details.remoteName ?? "",
      String(prLookupEpoch(cwd)),
    ].join("\u0000");
  const prLookupFailureStreakByKey = new Map<string, number>();
  const nextPrLookupFailureTtl = (key: string) => {
    if (
      !prLookupFailureStreakByKey.has(key) &&
      prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY
    ) {
      const oldestKey = prLookupFailureStreakByKey.keys().next().value;
      if (oldestKey !== undefined) {
        prLookupFailureStreakByKey.delete(oldestKey);
      }
    }
    const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1;
    prLookupFailureStreakByKey.set(key, streak);
    return prLookupFailureTtl(streak);
  };
  const pullRequestStateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
  const lookupStates = new Map<
    string,
    { readonly state: PullRequestInfo["state"]; readonly isDraft: boolean }
  >();
  const noteLookupState = (pr: PullRequestInfo) =>
    Effect.suspend(() => {
      const parsed = sourceControlDefinitions.parseChangeRequestUrl(pr.url)?.link;
      if (parsed === undefined || parsed.number !== pr.number) return Effect.void;
      const key = normalizeThreadPullRequestKey(parsed);
      const id = threadPullRequestKeyOf(key);
      const previous = lookupStates.get(id);
      lookupStates.delete(id);
      if (lookupStates.size >= PR_LOOKUP_CACHE_CAPACITY) {
        const oldest = lookupStates.keys().next().value;
        if (oldest !== undefined) lookupStates.delete(oldest);
      }
      lookupStates.set(id, { state: pr.state, isDraft: pr.isDraft === true });
      return (previous?.state ?? "open") === pr.state &&
        (previous?.isDraft === true) === (pr.isDraft === true)
        ? Effect.void
        : PubSub.publish(pullRequestStateChanges, key);
    });
  const prLookupCache = yield* Cache.makeWith(
    (key: string) => {
      const [
        cwd = "",
        branch = "",
        upstreamRef = "",
        defaultBranch = "",
        branchExists = "1",
        remoteName = "",
      ] = key.split("\u0000");
      const details = {
        branch,
        upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
        defaultBranch: defaultBranch.length > 0 ? defaultBranch : null,
        localBranchExists: branchExists !== "0",
        ...(remoteName.length > 0 ? { remoteName } : {}),
      };
      return Effect.gen(function* () {
        const { headContext, lookup } = yield* resolveLookupHeadContext(cwd, details);
        if (!lookup) {
          return { latest: null, headContext };
        }
        if (
          details.localBranchExists &&
          (details.upstreamRef === null || headContext.remoteName === null) &&
          (yield* isUnpublishedBranch(cwd, headContext))
        ) {
          return { latest: null, headContext };
        }
        const latest = yield* findLatestPrForHeadContext(cwd, headContext);
        if (latest !== null) yield* noteLookupState(latest);
        return { latest, headContext };
      });
    },
    {
      capacity: PR_LOOKUP_CACHE_CAPACITY,
      timeToLive: (exit, key) => {
        if (Exit.isSuccess(exit)) {
          prLookupFailureStreakByKey.delete(key);
          return exit.value.latest?.state === "open"
            ? PR_LOOKUP_CACHE_TTL
            : PR_LOOKUP_NO_OPEN_PR_CACHE_TTL;
        }
        return nextPrLookupFailureTtl(key);
      },
    },
  );
  const getPrLookup = (key: string) => detachStackFrame(Cache.get(prLookupCache, key));
  interface LastKnownPr {
    readonly pr: ReturnType<typeof toStatusPr> | null;
    readonly headSha: string | null;
    readonly upstreamRef: string | null;
    readonly headBranch: string;
    readonly remoteName: string | null;
    readonly headRemoteUrlKey: string | null;
  }
  const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
  const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
    if (
      !lastKnownPrByBranchKey.has(branchKey) &&
      lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
    ) {
      const oldestKey = lastKnownPrByBranchKey.keys().next().value;
      if (oldestKey !== undefined) {
        lastKnownPrByBranchKey.delete(oldestKey);
      }
    }
    lastKnownPrByBranchKey.set(branchKey, entry);
  };
  const resolveLastKnownPr = (
    branchKey: string,
    current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
  ): LastKnownPr | null => {
    const lastKnown = lastKnownPrByBranchKey.get(branchKey);
    if (!lastKnown) return null;
    if (lastKnown.headBranch !== current.headBranch) {
      return null;
    }

    // Config read failures become null; require both remote URLs before treating a mismatch as real.
    if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
      return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown : null;
    }

    if (
      lastKnown.upstreamRef !== null &&
      current.upstreamRef !== null &&
      lastKnown.remoteName !== null &&
      current.remoteName !== null
    ) {
      return lastKnown.remoteName === current.remoteName ? lastKnown : null;
    }
    return lastKnown;
  };
  const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
    cwd: string,
    details: {
      branch: string;
      upstreamRef: string | null;
      defaultBranch: string | null;
      isDefaultBranch: boolean;
    },
    refreshMissingPullRequest = false,
  ) {
    // Upstream changes must not orphan the same branch's fallback value.
    const branchKey = `${cwd}\u0000${details.branch}`;
    const cacheKey = prLookupCacheKey(cwd, details);
    if (refreshMissingPullRequest) {
      const cached = yield* Cache.getOption(prLookupCache, cacheKey).pipe(
        Effect.orElseSucceed(() => Option.none()),
      );
      if (Option.isSome(cached) && cached.value.latest === null) {
        yield* Cache.invalidate(prLookupCache, cacheKey);
      }
    }
    return yield* getPrLookup(cacheKey).pipe(
      Effect.map(({ latest, headContext }) => {
        if (!latest) return { pr: null, headSha: null, headContext };
        // Merged/closed matches are usually reverse-merge history, not the thread's PR context.
        if (details.isDefaultBranch && latest.state !== "open") {
          return { pr: null, headSha: null, headContext };
        }
        return { pr: toStatusPr(latest), headSha: latest.headSha ?? null, headContext };
      }),
      Effect.tap(({ pr, headSha, headContext }) =>
        Effect.sync(() =>
          rememberLastKnownPr(branchKey, {
            pr,
            headSha,
            upstreamRef: details.upstreamRef,
            headBranch: headContext.headBranch,
            remoteName: headContext.remoteName,
            headRemoteUrlKey: headContext.headRemoteUrlKey,
          }),
        ),
      ),
      Effect.map(({ pr, headSha }) => ({ pr, headSha })),
      Effect.catch((error) => {
        const fallback = lastKnownPrByBranchKey.get(branchKey)?.pr
          ? resolveLookupHeadContext(cwd, details).pipe(
              Effect.map(({ headContext }) =>
                resolveLastKnownPr(branchKey, {
                  upstreamRef: details.upstreamRef,
                  headBranch: headContext.headBranch,
                  remoteName: headContext.remoteName,
                  headRemoteUrlKey: headContext.headRemoteUrlKey,
                }),
              ),
            )
          : Effect.succeed(null);
        return Effect.logWarning("PR lookup failed.").pipe(
          Effect.annotateLogs({
            operation: "lookupStatusPr",
            branch: details.branch,
            errorTag:
              typeof error === "object" && error !== null && "_tag" in error
                ? String(error._tag)
                : typeof error,
            ...(isSourceControlProviderError(error)
              ? {
                  provider: error.provider,
                  providerOperation: error.operation,
                  ...(error.command === undefined ? {} : { providerCommand: error.command }),
                  errorDetail: error.detail,
                }
              : {}),
          }),
          Effect.andThen(fallback),
          Effect.map((lastKnown) => ({
            pr: lastKnown?.pr ?? null,
            headSha: lastKnown?.headSha ?? null,
          })),
        );
      }),
    );
  });
  const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
    cwd: string,
    options?: GitRemoteStatusOptions,
  ) {
    const details = yield* gitCore
      .statusDetailsRemote(cwd, options)
      .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
    if (details === null || !details.isRepo) {
      return null;
    }

    const { pr, headSha } =
      details.branch !== null
        ? yield* lookupStatusPr(
            cwd,
            {
              branch: details.branch,
              upstreamRef: details.upstreamRef,
              defaultBranch: details.defaultBranch,
              isDefaultBranch: details.isDefaultBranch,
            },
            options?.refreshMissingPullRequest,
          )
        : { pr: null, headSha: null };
    // Squash and rebase merges land new commits, so HEAD never becomes reachable from the base.
    const shippedByMergedPr =
      pr?.state === "merged" &&
      headSha !== null &&
      (yield* Effect.gen(function* () {
        const defaultBranch =
          details.defaultBranch ??
          (yield* gitCore.resolvePrimaryRemoteName(cwd).pipe(
            Effect.flatMap((remoteName) => gitCore.resolveDefaultBranchName(cwd, remoteName)),
            Effect.orElseSucceed(() => null),
          ));
        const mergedIntoDefault =
          defaultBranch === null
            ? pr.baseRef === "main" || pr.baseRef === "master"
            : pr.baseRef === defaultBranch;
        if (!mergedIntoDefault) return false;
        return yield* gitCore.resolveCommit({ cwd, revision: "HEAD" }).pipe(
          Effect.map(({ commitSha }) => commitSha === headSha),
          Effect.orElseSucceed(() => false),
        );
      }));

    return {
      hasUpstream: details.hasUpstream,
      // A real upstream delta stays; only the no-upstream fallback counts against the base.
      aheadCount: shippedByMergedPr && !details.hasUpstream ? 0 : details.aheadCount,
      behindCount: details.behindCount,
      aheadOfDefaultCount: shippedByMergedPr ? 0 : details.aheadOfDefaultCount,
      pr,
    } satisfies VcsStatusRemoteResult;
  });
  const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {
    capacity: STATUS_RESULT_CACHE_CAPACITY,
    timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
  });
  const invalidateRemoteStatusResultCache = (cwd: string) =>
    normalizeStatusCacheKey(cwd).pipe(
      Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
    );

  const readConfigValueNullable = (cwd: string, key: string) =>
    gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));

  // Whether the remote's host creates change requests in the only remote. A host's tools can let
  // configuration outside the remotes name another repository; the remote itself otherwise.
  const targetsOnlyRemote = Effect.fn("targetsOnlyRemote")(function* (
    cwd: string,
    remoteName: string,
    remote: { readonly remoteUrl: string | null; readonly repositoryNameWithOwner: string | null },
  ) {
    const provider =
      remote.remoteUrl === null ? null : sourceControlDefinitions.recognizeRemote(remote.remoteUrl);
    if (remote.remoteUrl === null || provider === null) return true;
    const context = { provider, remoteName, remoteUrl: remote.remoteUrl };
    const handle = yield* sourceControlProviders
      .resolveHandle({ cwd, context })
      .pipe(Effect.orElseSucceed(() => null));
    const createsChangeRequestsIn = handle?.provider.createsChangeRequestsIn;
    if (createsChangeRequestsIn === undefined) return true;
    return yield* createsChangeRequestsIn({
      cwd,
      context: handle?.context ?? context,
      repository: remote.repositoryNameWithOwner,
    });
  });

  const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
    cwd: string,
    branch: string | null,
  ) {
    const preferredRemoteName =
      branch === null
        ? "origin"
        : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
    const remoteUrl =
      (yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
      (yield* readConfigValueNullable(cwd, "remote.origin.url"));

    const provider = remoteUrl ? sourceControlDefinitions.recognizeRemote(remoteUrl) : null;
    if (!remoteUrl || provider?.kind !== "unknown") return provider;
    const handle = yield* sourceControlProviders
      .resolveHandle({
        cwd,
        context: { provider, remoteName: preferredRemoteName, remoteUrl },
      })
      .pipe(Effect.orElseSucceed(() => null));
    return handle?.context?.provider ?? provider;
  });

  const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
    cwd: string,
    remoteName: string | null,
  ) {
    if (!remoteName) {
      return {
        remoteUrl: null,
        remoteUrlKey: null,
        repositoryNameWithOwner: null,
        ownerLogin: null,
      };
    }

    const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
    let repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
    if (
      remoteUrl !== null &&
      /^https?:\/\//iu.test(remoteUrl) &&
      (repositoryNameWithOwner?.split("/").length ?? 0) > 2
    ) {
      const kind = sourceControlDefinitions.recognizeRemote(remoteUrl)?.kind;
      const provider =
        kind === undefined
          ? undefined
          : yield* (
              kind === "unknown" ? sourceControlProvider(cwd) : sourceControlProviders.get(kind)
            ).pipe(Effect.orElseSucceed(() => undefined));
      repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, provider);
    }
    return {
      remoteUrl,
      remoteUrlKey: remoteUrl ? sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) : null,
      repositoryNameWithOwner,
      ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
    };
  });

  const resolveHeadAndOriginContexts = (cwd: string, remoteName: string | null) =>
    remoteName === "origin"
      ? resolveRemoteRepositoryContext(cwd, "origin").pipe(
          Effect.map((origin) => [origin, origin] as const),
        )
      : Effect.all(
          [
            resolveRemoteRepositoryContext(cwd, remoteName),
            resolveRemoteRepositoryContext(cwd, "origin"),
          ],
          { concurrency: "unbounded" },
        );

  const resolveBranchHeadContext = Effect.fn("resolveBranchHeadContext")(function* (
    cwd: string,
    details: { branch: string; upstreamRef: string | null; remoteName?: string },
  ) {
    const branchRemote =
      details.remoteName ??
      (yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`));
    const remoteName = publishedRemoteName(branchRemote);
    const headBranchFromUpstream =
      details.upstreamRef && branchRemote !== "."
        ? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName })
        : "";
    const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
    const shouldProbeLocalBranchSelector =
      headBranchFromUpstream.length === 0 || headBranch === details.branch;

    const [remoteRepository, originRepository] = yield* resolveHeadAndOriginContexts(
      cwd,
      remoteName,
    );

    // With no origin to compare against, the only remote is the repository change requests
    // are created in unless the host's own configuration names another, so a branch on it is
    // not a fork. With several remotes, or with that other target, it may still be a fork.
    const isOnlyRemote =
      remoteName !== null &&
      remoteName !== "origin" &&
      originRepository.remoteUrlKey === null &&
      (yield* gitCore
        .execute({
          operation: "GitManager.resolveBranchHeadContext.remotes",
          cwd,
          args: ["remote"],
          timeoutMs: 5_000,
        })
        .pipe(
          Effect.map(
            (result) => result.stdout.split("\n").filter((name) => name.trim().length > 0).length,
          ),
          Effect.orElseSucceed(() => 0),
        )) === 1 &&
      (yield* targetsOnlyRemote(cwd, remoteName, remoteRepository));
    const isForeignRemote = remoteName !== null && remoteName !== "origin" && !isOnlyRemote;

    const isCrossRepository =
      remoteRepository.repositoryNameWithOwner !== null &&
      originRepository.repositoryNameWithOwner !== null
        ? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
          originRepository.repositoryNameWithOwner.toLowerCase()
        : isForeignRemote && remoteRepository.repositoryNameWithOwner !== null;

    const ownerHeadSelector =
      remoteRepository.ownerLogin && headBranch.length > 0
        ? `${remoteRepository.ownerLogin}:${headBranch}`
        : null;
    const remoteAliasHeadSelector =
      remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
    const shouldProbeRemoteOwnedSelectors = isCrossRepository || isForeignRemote;

    const headSelectors: string[] = [];
    if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
      appendUnique(headSelectors, ownerHeadSelector);
      appendUnique(
        headSelectors,
        remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
      );
    }
    if (shouldProbeLocalBranchSelector) {
      appendUnique(headSelectors, details.branch);
    }
    appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
    if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
      appendUnique(headSelectors, ownerHeadSelector);
      appendUnique(
        headSelectors,
        remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
      );
    }

    return {
      localBranch: details.branch,
      headBranch,
      headSelectors,
      preferredHeadSelector:
        ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
      remoteName,
      headRemoteUrlKey:
        remoteRepository.remoteUrlKey ??
        (remoteName === null ? originRepository.remoteUrlKey : null),
      targetRemoteUrlKey: originRepository.remoteUrlKey,
      headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
      headRepositoryOwnerLogin: remoteRepository.ownerLogin,
      isCrossRepository,
    } satisfies BranchHeadContext;
  });

  // Remote names can contain slashes; match refs literally.
  const findRemoteTrackingRemote = Effect.fn("findRemoteTrackingRemote")(function* (
    cwd: string,
    branch: string,
    preferredRemoteName: string | null,
  ) {
    if (branch.length === 0) return null;
    return yield* Effect.gen(function* () {
      const remoteNames = (yield* gitCore.execute({
        operation: "GitManager.findRemoteTrackingRemote.remotes",
        cwd,
        args: ["remote"],
        timeoutMs: 5_000,
      })).stdout
        .split("\n")
        .map((name) => name.trim())
        .filter((name) => name.length > 0);
      if (remoteNames.length === 0) return null;
      const refs = new Set(
        (yield* gitCore.execute({
          operation: "GitManager.findRemoteTrackingRemote.refs",
          cwd,
          args: [
            "for-each-ref",
            "--format=%(refname)",
            ...remoteNames.map((name) => `refs/remotes/${name}/${branch}`),
          ],
          timeoutMs: 5_000,
        })).stdout
          .split("\n")
          .map((ref) => ref.trim())
          .filter((ref) => ref.length > 0),
      );
      const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`));
      if (preferredRemoteName !== null && matching.includes(preferredRemoteName)) {
        return preferredRemoteName;
      }
      if (matching.includes("origin")) return "origin";
      return matching[0] ?? null;
    });
  });

  const findPublishedBranchRemote = Effect.fn("findPublishedBranchRemote")(function* (
    cwd: string,
    branch: string,
  ) {
    const localRef = `refs/heads/${branch}`;
    const remoteNames = (yield* gitCore.execute({
      operation: "GitManager.findPublishedBranchRemote.remotes",
      cwd,
      args: ["remote"],
      timeoutMs: 5_000,
    })).stdout
      .split("\n")
      .map((name) => name.trim())
      .filter((name) => name.length > 0);
    if (remoteNames.length === 0) return null;

    const refs = yield* gitCore.execute({
      operation: "GitManager.findPublishedBranchRemote",
      cwd,
      args: [
        "for-each-ref",
        "--format=%(refname)%00%(objectname)",
        localRef,
        ...remoteNames.map((name) => `refs/remotes/${name}/${branch}`),
      ],
      timeoutMs: 5_000,
    });
    const oidByRef = new Map(
      refs.stdout
        .split("\n")
        .map((line) => line.trim().split("\u0000"))
        .filter((entry): entry is [string, string] => entry.length === 2),
    );
    const localOid = oidByRef.get(localRef);
    if (!localOid) return null;

    const remoteRefs = remoteNames.flatMap((name) => {
      const oid = oidByRef.get(`refs/remotes/${name}/${branch}`);
      return oid ? [{ name, oid }] : [];
    });
    const exactRemotes = remoteRefs.filter((remote) => remote.oid === localOid);
    if (exactRemotes.length > 1) return null;
    let remoteName = exactRemotes[0]?.name;
    if (remoteName === undefined) {
      const ancestorRemotes = yield* Effect.forEach(
        remoteRefs,
        (remote) =>
          gitCore
            .execute({
              operation: "GitManager.findPublishedBranchRemote.ancestor",
              cwd,
              args: ["merge-base", "--is-ancestor", remote.oid, localOid],
              allowNonZeroExit: true,
              timeoutMs: 5_000,
            })
            .pipe(
              Effect.flatMap((result) => {
                // Exit 1 means non-ancestor; other failures must reject inference rather than pick another fork.
                if (result.exitCode === 0) return Effect.succeed(remote.name);
                if (result.exitCode === 1) return Effect.succeed(null);
                return new GitCommandError({
                  operation: "GitManager.findPublishedBranchRemote.ancestor",
                  command: "git merge-base --is-ancestor",
                  cwd,
                  exitCode: result.exitCode,
                  detail: "Ancestry probe failed; rejecting ancestry inference.",
                });
              }),
            ),
        { concurrency: "unbounded" },
      );
      const matches = ancestorRemotes.filter((name) => name !== null);
      if (matches.length !== 1) return null;
      remoteName = matches[0];
    }
    if (remoteName === undefined) return null;
    const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);