TypeScript
refactor(source-control): forges handle their own listing and SSH host quirks (#24288)
Julius Marminge6e7921174366
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 8b6aebfa4d3..cf55c2b304a 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -51,6 +51,7 @@"@t3tools/source-control-azure-devops": "workspace:*","@t3tools/source-control-bitbucket": "workspace:*","@t3tools/source-control-core": "workspace:*",+ "@t3tools/source-control-definitions": "workspace:*","@t3tools/source-control-forgejo": "workspace:*","@t3tools/source-control-gitcafe": "workspace:*","@t3tools/source-control-github": "workspace:*",diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 6f4367f7c4b..429132731ef 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -27,6 +27,8 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";+import type { SourceControlProvider } from "@t3tools/source-control-core/server/SourceControlProvider";+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";import { fakePullRequestProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver";import {@@ -170,6 +172,26 @@ const keyedByCanonicalKey = {repositoryKey: ({ canonicalKey }: { readonly canonicalKey: string }) => canonicalKey,};+/** A host whose SSH remotes name an alias, so discovery says which server serves them. */+const sshAliasHost = {+ resolveRemoteWebHost: ({ cwd, context, resolveContext }) =>+ isSshRemoteUrl(context.remoteUrl)+ ? resolveContext({+ cwd,+ context: {+ ...context,+ provider: { kind: SourceControlProviderKind.make("unknown"), name: "", baseUrl: "" },+ },+ }).pipe(+ Effect.map((resolved) =>+ resolved === null || resolved.provider.kind === "unknown"+ ? null+ : new URL(resolved.provider.baseUrl).host,+ ),+ )+ : Effect.succeed(null),+} as SourceControlProvider["Service"];+function makeService(input: {readonly settings?: ServerSettings;readonly projects: ReadonlyArray<OrchestrationProjectShell>;@@ -193,6 +215,10 @@ function makeService(input: {resolveLink: () => undefined,resolveHandle:input.resolveHandle ?? (() => Effect.die("Unexpected provider refinement")),+ get: (kind) =>+ Effect.succeed(+ kind === "forgejo" ? sshAliasHost : ({} as SourceControlProvider["Service"]),+ ),}),Layer.mock(ProjectService.ProjectService)({listShells: (options) =>@@ -1526,6 +1552,52 @@ it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after}),);+it.effect("names an SSH remote's web host from a later checkout when the first cannot", () =>+ Effect.gen(function* () {+ const hosts: Array<string> = [];+ const service = yield* makeService({+ projects: ["/first", "/second"].map((workspaceRoot, index) =>+ project({+ id: `p${index}`,+ title: `checkout ${index}`,+ workspaceRoot,+ repository: "team/repo",+ provider: SourceControlProviderKind.make("forgejo"),+ host: "ssh.code.example",+ remoteUrl: "[email protected]:team/repo.git",+ }),+ ),+ providers: [+ fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), {+ listChangeRequests: (input) => {+ hosts.push(input.host);+ return Effect.succeed({ items: [], truncated: false, continues: true });+ },+ }),+ ],+ resolveHandle: ({ cwd, context }) =>+ Effect.succeed({+ context:+ cwd === "/first"+ ? context!+ : {+ ...context!,+ provider: {+ kind: SourceControlProviderKind.make("forgejo"),+ name: "Forgejo",+ baseUrl: "http://code.example:3000",+ },+ },+ provider: undefined as never,+ }),+ });++ yield* service.list({ state: "open" });++ assert.deepStrictEqual(hosts, ["code.example:3000"]);+ }),+);+it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () =>Effect.gen(function* () {const service = yield* makeService({@@ -2191,7 +2263,6 @@ it.effect("carries every repository of a slice on from the oldest row in it", ()],providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"), {- listsAcrossMayOmitRepositories: true,listChangeRequestsAcross: () =>Effect.succeed({items: [@@ -2200,6 +2271,7 @@ it.effect("carries every repository of a slice on from the oldest row in it", ()batchedChangeRequest(3, "acme/web", "2026-07-02T00:00:00Z"),],truncated: true,+ unresolved: ["acme/docs"],}),}),],@@ -2283,51 +2355,49 @@ it.effect("reads a workspace larger than one search in chunks, and merges them",assert.strictEqual(result.entries.length, 101);}),);-it.effect(- "asks on its own for a repository a search answered nothing for, where searches can omit one",- () =>- Effect.gen(function* () {- const separately: string[] = [];- const service = yield* makeService({- projects: [- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),- project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),- ],- providers: [- fakePullRequestProvider(SourceControlProviderKind.make("github"), {- listsAcrossMayOmitRepositories: true,- listChangeRequests: ({ repository }) => {- separately.push(repository);- return repository === "acme/docs"- ? Effect.fail(requestFailed)- : Effect.succeed({ items: [], truncated: false, continues: true });- },- listChangeRequestsAcross: () =>- Effect.succeed({- items: [batchedChangeRequest(1, "acme/web", "2026-07-03T00:00:00Z")],- truncated: false,- }),- }),- ],- });+it.effect("asks on its own for a repository a search could not vouch for", () =>+ Effect.gen(function* () {+ const separately: string[] = [];+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),+ project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),+ ],+ providers: [+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {+ listChangeRequests: ({ repository }) => {+ separately.push(repository);+ return repository === "acme/docs"+ ? Effect.fail(requestFailed)+ : Effect.succeed({ items: [], truncated: false, continues: true });+ },+ listChangeRequestsAcross: () =>+ Effect.succeed({+ items: [batchedChangeRequest(1, "acme/web", "2026-07-03T00:00:00Z")],+ truncated: false,+ unresolved: ["acme/docs"],+ }),+ }),+ ],+ });- const result = yield* service.list({ state: "open" });+ const result = yield* service.list({ state: "open" });- assert.deepStrictEqual(separately, ["acme/docs"]);- assert.deepStrictEqual(result.errors, [- {- projectId: "p2" as ProjectId,- projectTitle: "docs",- message: "acme/docs could not be read.",- },- ]);- assert.deepStrictEqual(- result.entries.map((entry) => entry.number),- [1],- );- }),+ assert.deepStrictEqual(separately, ["acme/docs"]);+ assert.deepStrictEqual(result.errors, [+ {+ projectId: "p2" as ProjectId,+ projectTitle: "docs",+ message: "acme/docs could not be read.",+ },+ ]);+ assert.deepStrictEqual(+ result.entries.map((entry) => entry.number),+ [1],+ );+ }),);-it.effect("believes a search's silence about a repository where searches cover every one", () =>+it.effect("believes a search's silence about a repository it vouches for", () =>Effect.gen(function* () {const separately: string[] = [];const service = yield* makeService({diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 2a81959e9e7..54d9620b4c3 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -82,6 +82,7 @@ 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,@@ -142,7 +143,6 @@ 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 SEARCH_VISIBILITY_TTL = Duration.minutes(10);const STALE_DETAIL_WINDOW = Duration.minutes(10);const isPullRequestProviderError = Schema.is(PullRequestProviderError);const LIST_CACHE_CAPACITY = 64;@@ -506,9 +506,6 @@ function withRateLimitBackoff(...(api.unavailableRequirement === undefined? {}: { unavailableRequirement: api.unavailableRequirement }),- ...(api.listsAcrossMayOmitRepositories === undefined- ? {}- : { listsAcrossMayOmitRepositories: api.listsAcrossMayOmitRepositories }),...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),...(api.readsPublicHostWithoutCheckout === undefined? {}@@ -661,16 +658,8 @@ function rankFilterOptions<A>(};}-/** Whether the project's remote is SSH on a host whose SSH remotes do not name its web host. */-function sshRemoteHidesWebHost(- identity: NonNullable<OrchestrationProjectShell["repositoryIdentity"]>,-) {- return (- identity.provider !== undefined &&- sourceControlDefinitions.find(identity.provider)?.sshRemoteHidesWebHost === true &&- isSshRemoteUrl(identity.locator.remoteUrl)- );-}+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 {@@ -706,25 +695,36 @@ export const make = Effect.gen(function* () {const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;const readCache = yield* PullRequestReadCache.PullRequestReadCache;- const refineUnknownProjectKinds = (+ /**+ * 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 RefinementCandidate = {+ ) {+ type Candidate = {readonly project: OrchestrationProjectShell;- readonly provider: SourceControlProviderInfo;- readonly remoteName: string;- readonly remoteUrl: string;+ readonly context: SourceControlProviderContext;};- const refinements = new Map<string, RefinementCandidate[]>();+ 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?.provider !== "unknown" && !(identity && sshRemoteHidesWebHost(identity))) ||- sourceControlDefinitions.repositorySelector(project.repositoryIdentity) === null+ !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 &&@@ -736,50 +736,90 @@ export const make = Effect.gen(function* () {continue;}const { remoteName, remoteUrl } = identity.locator;- const provider = sourceControlDefinitions.recognizeRemote(remoteUrl);- if (provider !== null) {- const candidates = refinements.get(provider.baseUrl);- const candidate = { project, provider, remoteName, remoteUrl };- if (candidates === undefined) refinements.set(provider.baseUrl, [candidate]);- else candidates.push(candidate);- }+ 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);}- return Effect.forEach(- refinements,- ([baseUrl, candidates]) =>- Effect.firstSuccessOf(- candidates.map(({ project, provider, remoteName, remoteUrl }) =>- Effect.suspend(() =>- sourceControlProviders.resolveHandle({- cwd: project.workspaceRoot,- context: {- provider: sourceControlDefinitions.find(provider.kind)?.sshRemoteHidesWebHost- ? { ...provider, kind: SourceControlProviderKind.make("unknown") }- : provider,- remoteName,- remoteUrl,- ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)- ? { requestedHost: filter.host }- : {}),- },- }),- ).pipe(- Effect.flatMap((handle) => {- const refined = handle.context?.provider;- return refined === undefined || refined.kind === "unknown"- ? Effect.fail(undefined)- : Effect.succeed(refined);- }),+ 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 },),- ),- ).pipe(- Effect.map((provider) => [baseUrl, provider] as const),- Effect.orElseSucceed(() => [baseUrl, null] as const),+ )+ : 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">,@@ -811,11 +851,11 @@ export const make = Effect.gen(function* () {),),Effect.flatMap((projects) =>- refineUnknownProjectKinds(projects, filter).pipe(- Effect.map((refinedProviders) => ({ refinedProviders, projects })),+ resolveRemoteHosts(projects, filter).pipe(+ Effect.map((remoteHosts) => ({ remoteHosts, projects })),),),- Effect.map(({ refinedProviders, projects }) => {+ Effect.map(({ remoteHosts, projects }) => {const supported: SupportedProject[] = [];const unimplemented = new Map<string,@@ -832,17 +872,13 @@ export const make = Effect.gen(function* () {project.repositoryIdentity,);if (!identity || kind === undefined || repository === null) continue;- let refinedProvider: SourceControlProviderInfo | null | undefined;- if (kind === "unknown" || sshRemoteHidesWebHost(identity)) {- const provider = sourceControlDefinitions.recognizeRemote(identity.locator.remoteUrl);- refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl);- kind = refinedProvider?.kind ?? kind;- }- const host =- refinedProvider &&- sourceControlDefinitions.find(refinedProvider.kind)?.sshRemoteHidesWebHost- ? new URL(refinedProvider.baseUrl).host.toLowerCase()- : sourceControlDefinitions.changeRequestHost(identity, kind);+ 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;}@@ -1193,13 +1229,6 @@ export const make = Effect.gen(function* () {};};- // On a host whose read across repositories may omit some, a repository that has appeared in- // one is known to be covered. Empty reads for that same repository are therefore real empty- // answers, not a reason to read it on its own again.- const searchVisibleAt = new Map<string, number>();- const searchVisibilityKey = (host: string, repository: string) =>- `${host}\n${repository.trim().toLowerCase()}`;-const listUncached: PullRequestService["Service"]["list"] = Effect.fn("PullRequestService.listUncached",)(function* (input) {@@ -1409,75 +1438,53 @@ export const make = Effect.gen(function* () {: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),}).pipe(observeRead,- Effect.flatMap(({ value: page, observedAt }) =>- Effect.flatMap(Clock.currentTimeMillis, (now) => {- const rows = new Map<string, Array<ProviderChangeRequest>>();- for (const [key, visibleAt] of searchVisibleAt) {- if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) {- searchVisibleAt.delete(key);- }- }- 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);- searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now);- }- 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 fetched = rows.get(project.repository.trim().toLowerCase()) ?? [];- // A repository the read said nothing at all about, on a host whose read can omit- // one, is read on its own, once, before it is believed. Only on its first slice:- // after that it has a boundary to carry on from, and silence past one means the- // rows are older rather than absent.- const lastVisible = searchVisibleAt.get(- searchVisibilityKey(project.host, project.repository),- );- const searchIsKnownVisible =- first.api.listsAcrossMayOmitRepositories !== true ||- (!page.truncated &&- lastVisible !== undefined &&- now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL));- if (- fetched.length === 0 &&- cursorOf(project) === undefined &&- !searchIsKnownVisible- ) {- 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.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),);};diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.test.ts b/apps/server/src/sourceControl/sourceControlDefinitions.test.tsnew file mode 100644index 00000000000..e21efd8173a--- /dev/null+++ b/apps/server/src/sourceControl/sourceControlDefinitions.test.ts@@ -0,0 +1,12 @@+import { expect, it } from "@effect/vitest";++import {+ BUILT_IN_SOURCE_CONTROL_DRIVER_LIST,+ sourceControlDefinitions,+} from "./sourceControlDefinitions.ts";++it("runs a driver for every host the server and clients read, in their order", () => {+ expect(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition)).toEqual(+ sourceControlDefinitions.definitions,+ );+});diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.tsindex 590fdd2cfb9..eaeb8dd55f1 100644--- a/apps/server/src/sourceControl/sourceControlDefinitions.ts+++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts@@ -1,18 +1,12 @@import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";-import { makeSourceControlDefinitionRegistry } from "@t3tools/source-control-core/shared/definition";+import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry";import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";import * as GitHubDriver from "@t3tools/source-control-github/server/driver";import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";-/**- * The same order as the clients' registry in `@t3tools/client-runtime/source-control-clients`.- * A change request URL goes to the first host whose shape it has, so GitCafe, which claims- * `/pull/` and `/pulls/` only on its own hostnames, claims before GitHub and Forgejo, which- * claim them everywhere. A remote goes to the first host that recognises it, and a hostname can- * carry more than one host's label (`gitea.github.example`), so recognition has its own order.- */+/** In the shared registry's order, which is the order hosts are listed and probed in. */export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [GitHubDriver.driver,GitLabDriver.driver,@@ -22,17 +16,4 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [AzureDevOpsDriver.driver,] as const;-export const sourceControlDefinitions = makeSourceControlDefinitionRegistry(- BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition),- {- claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind],- recognizeRemotesIn: [- GitCafeDriver.driver.kind,- ForgejoDriver.driver.kind,- GitHubDriver.driver.kind,- GitLabDriver.driver.kind,- AzureDevOpsDriver.driver.kind,- BitbucketDriver.driver.kind,- ],- },-);+export const sourceControlDefinitions = builtInSourceControlDefinitions;diff --git a/package.json b/package.jsonindex bce3d1c34fc..4012a03c20d 100644--- a/package.json+++ b/package.json@@ -29,7 +29,7 @@"check:changed": "node scripts/check-changed.ts","lint": "vp lint --report-unused-disable-directives","knip": "knip --preprocessor ./scripts/knip-schemas.ts",- "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",+ "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints","knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts","lint:mobile": "node scripts/mobile-native-static-check.ts","test": "vp run -r test",diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 81a91d6057a..712ea05bdcb 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -464,13 +464,8 @@"@pierre/diffs": "catalog:","@t3tools/contracts": "workspace:*","@t3tools/shared": "workspace:*",- "@t3tools/source-control-azure-devops": "workspace:*",- "@t3tools/source-control-bitbucket": "workspace:*","@t3tools/source-control-core": "workspace:*",- "@t3tools/source-control-forgejo": "workspace:*",- "@t3tools/source-control-gitcafe": "workspace:*",- "@t3tools/source-control-github": "workspace:*",- "@t3tools/source-control-gitlab": "workspace:*",+ "@t3tools/source-control-definitions": "workspace:*","effect": "catalog:","three": "0.180.0"},diff --git a/packages/client-runtime/src/sourceControlClients.ts b/packages/client-runtime/src/sourceControlClients.tsindex e7ca2816091..c7db3db4afc 100644--- a/packages/client-runtime/src/sourceControlClients.ts+++ b/packages/client-runtime/src/sourceControlClients.ts@@ -1,8 +1,6 @@-import * as AzureDevOps from "@t3tools/source-control-azure-devops/shared/definition";-import * as Bitbucket from "@t3tools/source-control-bitbucket/shared/definition";+import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry";import {HostCredentialSettings,- makeSourceControlDefinitionRegistry,readSourceControlHostSettings,} from "@t3tools/source-control-core/shared/definition";import type { ServerSettings } from "@t3tools/contracts";@@ -20,42 +18,8 @@ export {type SourceControlHostCredentials,type SourceControlIcon,} from "@t3tools/source-control-core/shared/definition";-import * as Forgejo from "@t3tools/source-control-forgejo/shared/definition";-import * as GitCafe from "@t3tools/source-control-gitcafe/shared/definition";-import * as GitHub from "@t3tools/source-control-github/shared/definition";-import * as GitLab from "@t3tools/source-control-gitlab/shared/definition";-/**- * GitHub comes first because a repository that has not reported its host yet reads as GitHub,- * which is what clients have always shown there. A change request URL goes to the first host- * whose shape it has, so GitCafe, which claims `/pull/` and `/pulls/` only on its own hostnames,- * claims before GitHub and Forgejo, which claim them everywhere. A hostname can carry more than- * one host's label (`gitea.github.example`), so remote recognition has its own order. The server's- * `sourceControl/sourceControlClients.ts` keeps the same order.- */-const BUILT_IN_SOURCE_CONTROL_CLIENTS = [- GitHub.definition,- GitLab.definition,- GitCafe.definition,- Forgejo.definition,- Bitbucket.definition,- AzureDevOps.definition,-];--export const sourceControlClients = makeSourceControlDefinitionRegistry(- BUILT_IN_SOURCE_CONTROL_CLIENTS,- {- claimChangeRequestUrlsFirst: [GitCafe.definition.kind],- recognizeRemotesIn: [- GitCafe.definition.kind,- Forgejo.definition.kind,- GitHub.definition.kind,- GitLab.definition.kind,- AzureDevOps.definition.kind,- Bitbucket.definition.kind,- ],- },-);+export const sourceControlClients = builtInSourceControlDefinitions;/** The saved per-hostname accounts and tokens of a host whose definition has `credentials`. */export function readHostCredentialSettings(diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex bd6b9ea1cef..53913406175 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -176,6 +176,11 @@ export interface ProviderBatchedChangeRequest extends ProviderChangeRequest {export interface ProviderBatchedChangeRequestPage {readonly items: ReadonlyArray<ProviderBatchedChangeRequest>;readonly truncated: boolean;+ /**+ * Repositories asked about that the page cannot vouch for: its silence about them may be an+ * omission rather than an empty answer, so the caller reads each on its own.+ */+ readonly unresolved?: ReadonlyArray<string>;}export interface ProviderChangeRequestStat {@@ -343,12 +348,6 @@ export interface PullRequestProviderApi {* rows a page ordered by update shows. `cursor` is one boundary for all of them, so a caller* with repositories standing at different boundaries asks in groups rather than in one call.*/- /**- * Set when `listChangeRequestsAcross` can answer with silence for a repository it does not- * cover rather than with an error, so a repository the read said nothing about is read on its- * own before it is believed empty.- */- readonly listsAcrossMayOmitRepositories?: boolean;readonly listChangeRequestsAcross?: (input: {readonly cwd: string;readonly host: string;diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.tsindex 90e9acfcb25..f5f2c2d786b 100644--- a/packages/source-control-core/src/server/SourceControlProvider.ts+++ b/packages/source-control-core/src/server/SourceControlProvider.ts@@ -141,6 +141,19 @@ export class SourceControlProvider extends Context.Service<readonly context: SourceControlProviderContext;}) => Effect.Effect<SourceControlProviderContext | null, SourceControlProviderError>;}) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;+ /**+ * The web host serving a remote, for a host whose remote URL may not name it (an SSH alias+ * for one of several servers). It answers for the context's `requestedHost` when the caller+ * narrows to one. Absent, or null, means the remote's own host is the web host.+ */+ readonly resolveRemoteWebHost?: (input: {+ readonly cwd: string;+ readonly context: SourceControlProviderContext;+ readonly resolveContext: (input: {+ readonly cwd: string;+ readonly context: SourceControlProviderContext;+ }) => Effect.Effect<SourceControlProviderContext | null, SourceControlProviderError>;+ }) => Effect.Effect<string | null, SourceControlProviderError>;readonly resolveLink?: ResolveSourceControlLink;/*** Whether `createChangeRequest` from `cwd` targets `repository`, the `owner/name` of thediff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.tsindex e3390d844b0..8d25856e5dc 100644--- a/packages/source-control-core/src/shared/definition.ts+++ b/packages/source-control-core/src/shared/definition.ts@@ -295,11 +295,6 @@ export interface SourceControlDefinition {* equal under. Null when the key is not this host's.*/readonly canonicalRepositoryKey?: (key: string) => string | null;- /**- * An SSH remote names the SSH server only, so the web host, and its port, come from resolving- * the provider rather than from the remote.- */- readonly sshRemoteHidesWebHost?: boolean;/*** Null when `url` is not media this host keeps behind a credential. A client cannot load such* media itself, so it asks the server, whose driver for this host fetches it.diff --git a/packages/source-control-definitions/package.json b/packages/source-control-definitions/package.jsonnew file mode 100644index 00000000000..c845de40b8b--- /dev/null+++ b/packages/source-control-definitions/package.json@@ -0,0 +1,23 @@+{+ "name": "@t3tools/source-control-definitions",+ "private": true,+ "type": "module",+ "exports": {+ "./registry": {+ "types": "./src/registry.ts",+ "import": "./src/registry.ts"+ }+ },+ "scripts": {+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@t3tools/source-control-azure-devops": "workspace:*",+ "@t3tools/source-control-bitbucket": "workspace:*",+ "@t3tools/source-control-core": "workspace:*",+ "@t3tools/source-control-forgejo": "workspace:*",+ "@t3tools/source-control-gitcafe": "workspace:*",+ "@t3tools/source-control-github": "workspace:*",+ "@t3tools/source-control-gitlab": "workspace:*"+ }+}diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.tsnew file mode 100644index 00000000000..0f213ab67a9--- /dev/null+++ b/packages/source-control-definitions/src/registry.ts@@ -0,0 +1,38 @@+import * as AzureDevOps from "@t3tools/source-control-azure-devops/shared/definition";+import * as Bitbucket from "@t3tools/source-control-bitbucket/shared/definition";+import { makeSourceControlDefinitionRegistry } from "@t3tools/source-control-core/shared/definition";+import * as Forgejo from "@t3tools/source-control-forgejo/shared/definition";+import * as GitCafe from "@t3tools/source-control-gitcafe/shared/definition";+import * as GitHub from "@t3tools/source-control-github/shared/definition";+import * as GitLab from "@t3tools/source-control-gitlab/shared/definition";++/**+ * The server and every client read hosts through this one registry, so they agree on which host+ * owns a URL or remote. GitHub comes first because a repository that has not reported its host+ * yet reads as GitHub, which is what clients have always shown there. A change request URL goes+ * to the first host whose shape it has, so GitCafe, which claims `/pull/` and `/pulls/` only on+ * its own hostnames, claims before GitHub and Forgejo, which claim them everywhere. A hostname can+ * carry more than one host's label (`gitea.github.example`), so remote recognition has its own+ * order.+ */+export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry(+ [+ GitHub.definition,+ GitLab.definition,+ GitCafe.definition,+ Forgejo.definition,+ Bitbucket.definition,+ AzureDevOps.definition,+ ],+ {+ claimChangeRequestUrlsFirst: [GitCafe.definition.kind],+ recognizeRemotesIn: [+ GitCafe.definition.kind,+ Forgejo.definition.kind,+ GitHub.definition.kind,+ GitLab.definition.kind,+ AzureDevOps.definition.kind,+ Bitbucket.definition.kind,+ ],+ },+);diff --git a/packages/source-control-definitions/tsconfig.json b/packages/source-control-definitions/tsconfig.jsonnew file mode 100644index 00000000000..564a5990051--- /dev/null+++ b/packages/source-control-definitions/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "../../tsconfig.base.json",+ "include": ["src"]+}diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.tsindex 5b4d92418e0..e24f44f73eb 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts@@ -649,6 +649,74 @@ it.effect("gives Forgejo identities the browser URL of the login that serves the),);+it.effect("names the web server behind an SSH alias from the login that serves it", () =>+ Effect.gen(function* () {+ const provider = yield* ForgejoSourceControlProvider.make;+ const resolveWebHost = provider.resolveRemoteWebHost!;+ const asked: Array<string | undefined> = [];+ const context = (remoteUrl: string) => ({+ provider: {+ kind: SourceControlProviderKind.make("forgejo"),+ name: "Forgejo",+ baseUrl: "https://ssh.forge.test",+ },+ remoteName: "origin",+ remoteUrl,+ requestedHost: "forge.test:3000",+ });+ const served = (input: {+ readonly context: { readonly requestedHost?: string; readonly provider: { kind: string } };+ }) =>+ Effect.sync(() => {+ asked.push(input.context.requestedHost);+ assert.strictEqual(input.context.provider.kind, "unknown");+ return {+ provider: {+ kind: SourceControlProviderKind.make("forgejo"),+ name: "Forgejo / Gitea",+ baseUrl: "http://forge.test:3000/git",+ },+ remoteName: "origin",+ remoteUrl: "",+ };+ });++ assert.strictEqual(+ yield* resolveWebHost({+ cwd: "/repo",+ context: context("[email protected]:team/repo.git"),+ resolveContext: served,+ }),+ "forge.test:3000",+ );+ assert.deepStrictEqual(asked, ["forge.test:3000"]);+ assert.strictEqual(+ yield* resolveWebHost({+ cwd: "/repo",+ context: context("https://forge.test:3000/team/repo.git"),+ resolveContext: () => Effect.die("an HTTP remote names its own web host"),+ }),+ null,+ );+ assert.strictEqual(+ yield* resolveWebHost({+ cwd: "/repo",+ context: context("[email protected]:team/repo.git"),+ resolveContext: () => Effect.succeed(null),+ }),+ null,+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),+ TestSourceControlHost.layer(),+ Layer.mock(ForgejoCli.ForgejoCli)({}),+ ),+ ),+ ),+);+it.effect("loads Forgejo pull request references from files and commits views", () =>Effect.gen(function* () {const provider = yield* ForgejoSourceControlProvider.make;diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.tsindex ba8465e9cc7..e44e41b8801 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts@@ -234,6 +234,27 @@ const refineRepositoryIdentity: NonNullable<};});+// An SSH remote names an alias rather than the web server, so the login that serves it says which.+const resolveRemoteWebHost: NonNullable<+ SourceControlProvider.SourceControlProvider["Service"]["resolveRemoteWebHost"]+> = Effect.fn("ForgejoSourceControlProvider.resolveRemoteWebHost")(function* ({+ cwd,+ context,+ resolveContext,+}) {+ if (!ForgejoCli.parseForgejoRemote(context.remoteUrl)?.ssh) return null;+ const resolved = yield* resolveContext({+ cwd,+ context: {+ ...context,+ provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },+ },+ });+ return resolved?.provider.kind === "forgejo"+ ? new URL(resolved.provider.baseUrl).host.toLowerCase()+ : null;+});+const RepositorySchema = Schema.Struct({full_name: Schema.String,clone_url: Schema.String,@@ -306,6 +327,7 @@ export const make = Effect.gen(function* () {kind: SourceControlProviderKind.make("forgejo"),repositoryNameFromRemoteUrl,refineRepositoryIdentity,+ resolveRemoteWebHost,listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")(function* (input) {const repo = yield* cli.resolveRepository(input);diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.tsindex 8be55644ef9..c303ac80a46 100644--- a/packages/source-control-forgejo/src/shared/definition.ts+++ b/packages/source-control-forgejo/src/shared/definition.ts@@ -107,7 +107,6 @@ export const definition = defineSourceControl({}: null,changeRequestHost,- sshRemoteHidesWebHost: true,isChangeRequestInRepository: (identity, link) => {if (!isChangeRequestAuthorityOfProject(identity, link)) return false;const web = resolvedWebUrl(identity);diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.tsindex 28b83ed3d32..1263f07f753 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts@@ -2,12 +2,16 @@ import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";+import * as TestClock from "effect/testing/TestClock";import type { PullRequestReaction } from "@t3tools/contracts";import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";-import type { GitHubPullRequestCore } from "./gitHubPullRequestJson.ts";+import type {+ GitHubPullRequestCore,+ GitHubPullRequestSearchItem,+} from "./gitHubPullRequestJson.ts";import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";@@ -770,3 +774,167 @@ describe("loginAvatarUrl", () => {}});});++describe("listChangeRequestsAcross", () => {+ const searched = (repository: string): GitHubPullRequestSearchItem => ({+ repository,+ number: 1,+ title: "Change",+ url: `https://github.com/${repository}/pull/1`,+ author: null,+ authorId: null,+ headBranch: "feature",+ baseBranch: "main",+ state: "open" as const,+ isDraft: false,+ mergeability: "mergeable" as const,+ additions: 0,+ deletions: 0,+ createdAt: "2026-07-01T00:00:00Z",+ updatedAt: "2026-07-02T00:00:00Z",+ reviewRequestLogins: [],+ hasTeamReviewRequest: false,+ labels: [],+ reviewDecision: null,+ checksState: null,+ });+ const across = {+ cwd: "/w",+ host: "github.com",+ repositories: ["acme/web", "acme/docs"],+ state: "open" as const,+ involvement: "all" as const,+ viewer: "viewer",+ limit: 50,+ };+ type Search = Parameters<+ GitHubPullRequestApi.GitHubPullRequestApi["Service"]["searchPullRequests"]+ >[0];+ // Pages answer in turn; a one-repository check for any pull request answers from `covered`.+ const providerAnswering = (input: {+ readonly pages: Array<GitHubPullRequestApi.GitHubPullRequestSearchBatch>;+ readonly covered?: (repository: string) => boolean;+ readonly checks?: Array<string>;+ }) =>+ make.pipe(+ Effect.provide(+ Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({+ searchPullRequests: (search: Search) => {+ if (search.state !== "all") return Effect.succeed(input.pages.shift()!);+ const repository = search.repositories[0]!;+ input.checks?.push(repository);+ return input.covered === undefined+ ? Effect.fail(+ new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({ cwd: search.cwd }),+ )+ : Effect.succeed({+ items: input.covered(repository) ? [searched(repository)] : [],+ truncated: false,+ });+ },+ }),+ ),+ Effect.map((provider) => provider.listChangeRequestsAcross!),+ );++ it.effect("believes silence about a repository search covers, and checks it once", () =>+ Effect.gen(function* () {+ const checks: Array<string> = [];+ const read = yield* providerAnswering({+ pages: [+ { items: [searched("acme/web")], truncated: false },+ { items: [searched("acme/web")], truncated: false },+ ],+ covered: () => true,+ checks,+ });+ expect((yield* read(across)).unresolved).toEqual([]);+ expect((yield* read(across)).unresolved).toEqual([]);+ expect(checks).toEqual(["acme/docs"]);+ }),+ );++ it.effect("leaves a repository search does not cover to be read on its own", () =>+ Effect.gen(function* () {+ const read = yield* providerAnswering({+ pages: [{ items: [searched("acme/web")], truncated: false }],+ covered: (repository) => repository !== "acme/docs",+ });+ expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);+ }),+ );++ it.effect("does not check a repository a page had rows for", () =>+ Effect.gen(function* () {+ const checks: Array<string> = [];+ const read = yield* providerAnswering({+ pages: [+ { items: [searched("acme/web"), searched("acme/docs")], truncated: false },+ { items: [searched("acme/web")], truncated: false },+ ],+ covered: () => true,+ checks,+ });+ yield* read(across);+ expect((yield* read(across)).unresolved).toEqual([]);+ expect(checks).toEqual([]);+ }),+ );++ it.effect("vouches for no silent repository in a truncated first slice", () =>+ Effect.gen(function* () {+ const read = yield* providerAnswering({+ pages: [{ items: [searched("acme/web")], truncated: true }],+ covered: () => true,+ });+ expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);+ }),+ );++ it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>+ Effect.gen(function* () {+ const read = yield* providerAnswering({+ pages: [+ { items: [searched("acme/web")], truncated: true },+ { items: [searched("acme/web")], truncated: true },+ ],+ covered: (repository) => repository !== "acme/renamed",+ });+ const later = { ...across, cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 } };+ expect((yield* read(later)).unresolved).toEqual([]);+ expect(+ (yield* read({ ...later, repositories: ["acme/web", "acme/renamed"] })).unresolved,+ ).toEqual(["acme/renamed"]);+ }),+ );++ it.effect("asks again after a failed check, and after coverage has had time to change", () =>+ Effect.gen(function* () {+ const checks: Array<string> = [];+ const failing = yield* providerAnswering({+ pages: [+ { items: [searched("acme/web")], truncated: false },+ { items: [searched("acme/web")], truncated: false },+ ],+ checks,+ });+ expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);+ expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);+ expect(checks).toEqual(["acme/docs", "acme/docs"]);++ checks.length = 0;+ const read = yield* providerAnswering({+ pages: [+ { items: [searched("acme/web")], truncated: false },+ { items: [searched("acme/web")], truncated: false },+ ],+ covered: () => true,+ checks,+ });+ yield* read(across);+ yield* TestClock.adjust("61 minutes");+ yield* read(across);+ expect(checks).toEqual(["acme/docs", "acme/docs"]);+ }),+ );+});diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex fa660d77af4..17bf91e8377 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -1,5 +1,10 @@import { SourceControlProviderKind } from "@t3tools/contracts";import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";+import * as Cache from "effect/Cache";+import * as Duration from "effect/Duration";+import * as Equal from "effect/Equal";+import * as Exit from "effect/Exit";+import * as Hash from "effect/Hash";import * as Effect from "effect/Effect";import type {PullRequestActor,@@ -185,12 +190,98 @@ export function loginAvatarUrl(login: string, host: string): string | null {return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;}+// Whether search covers a repository changes only when the repository is renamed or moved.+const SEARCH_COVERAGE_TTL = Duration.hours(1);+const SEARCH_COVERAGE_CAPACITY = 4096;+const SEARCH_COVERAGE_CONCURRENCY = 4;++/**+ * Whether GitHub search covers a repository. `cwd` only says where to ask, so equality ignores+ * it and `lookup`, and every checkout of a repository shares one answer.+ */+class SearchCoverage {+ readonly key: string;+ readonly lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>;++ constructor(+ host: string,+ repository: string,+ lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>,+ ) {+ this.key = `${host.toLowerCase()}\n${repository.trim().toLowerCase()}`;+ this.lookup = lookup;+ }++ [Equal.symbol](that: unknown): boolean {+ return that instanceof SearchCoverage && that.key === this.key;+ }+ [Hash.symbol](): number {+ return Hash.string(this.key);+ }+}+const rendersEmpty = (body: string): boolean =>body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;export const make = Effect.gen(function* () {const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;+ // GitHub does not index every repository for search: a renamed one answers for its old name+ // with silence rather than with an error. Where search has any pull request for a repository it+ // covers it, so its silence on a page is a real empty answer; any other the caller reads on its+ // own. A failed check is not kept.+ const searchCoverage = yield* Cache.makeWith((request: SearchCoverage) => request.lookup, {+ capacity: SEARCH_COVERAGE_CAPACITY,+ timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero),+ });+ const coverageOf = (+ input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],+ repository: string,+ ) =>+ new SearchCoverage(+ input.host,+ repository,+ Effect.suspend(() =>+ cli.searchPullRequests({+ cwd: input.cwd,+ host: input.host,+ repositories: [repository],+ state: "all",+ involvement: "all",+ viewer: input.viewer,+ limit: 1,+ }),+ ).pipe(Effect.map((batch) => batch.items.length > 0)),+ );+ const unresolvedBySearch = Effect.fn("GitHubPullRequestProvider.unresolvedBySearch")(function* (+ input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],+ batch: GitHubPullRequestApi.GitHubPullRequestSearchBatch,+ ) {+ // A repository a page has rows for is covered without asking.+ yield* Effect.forEach(+ batch.items,+ (item) => Cache.set(searchCoverage, coverageOf(input, item.repository), true),+ { discard: true },+ );+ const answered = new Set(batch.items.map((item) => item.repository.trim().toLowerCase()));+ const silent = input.repositories.filter(+ (repository) => !answered.has(repository.trim().toLowerCase()),+ );+ // A truncated first slice can be silent about a covered repository whose rows are just+ // older than the cut, so it vouches for none. Past the first slice silence from a covered+ // repository means its rows are older rather than absent.+ if (input.cursor === undefined && batch.truncated) return silent;+ return yield* Effect.filter(+ silent,+ (repository) =>+ Cache.get(searchCoverage, coverageOf(input, repository)).pipe(+ Effect.map((covered) => !covered),+ Effect.orElseSucceed(() => true),+ ),+ { concurrency: SEARCH_COVERAGE_CONCURRENCY },+ );+ });+const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>new PullRequestProviderError({provider: SourceControlProviderKind.make("github"),@@ -306,9 +397,6 @@ export const make = Effect.gen(function* () {),),- // GitHub does not index every repository for search: a renamed one answers for its old name- // with silence rather than with an error.- listsAcrossMayOmitRepositories: true,listChangeRequestsAcross: (input) =>cli.searchPullRequests({@@ -325,13 +413,16 @@ export const make = Effect.gen(function* () {}).pipe(Effect.mapError(fail("listChangeRequestsAcross")),- Effect.map((batch) => ({- truncated: batch.truncated,- items: batch.items.map((item) => ({- ...item,- author: withAvatar(item.author, new Map<string, string>(), input.host),+ Effect.flatMap((batch) =>+ Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({+ truncated: batch.truncated,+ items: batch.items.map((item) => ({+ ...item,+ author: withAvatar(item.author, new Map<string, string>(), input.host),+ })),+ unresolved,})),- })),+ ),),listChangeRequestStats: (input) =>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e39d07057f9..bc46b03b9f8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -891,6 +891,9 @@ importers:'@t3tools/source-control-core':specifier: workspace:*version: link:../../packages/source-control-core+ '@t3tools/source-control-definitions':+ specifier: workspace:*+ version: link:../../packages/source-control-definitions'@t3tools/source-control-forgejo':specifier: workspace:*version: link:../../packages/source-control-forgejo@@ -1339,27 +1342,12 @@ importers:'@t3tools/shared':specifier: workspace:*version: link:../shared- '@t3tools/source-control-azure-devops':- specifier: workspace:*- version: link:../source-control-azure-devops- '@t3tools/source-control-bitbucket':- specifier: workspace:*- version: link:../source-control-bitbucket'@t3tools/source-control-core':specifier: workspace:*version: link:../source-control-core- '@t3tools/source-control-forgejo':- specifier: workspace:*- version: link:../source-control-forgejo- '@t3tools/source-control-gitcafe':+ '@t3tools/source-control-definitions':specifier: workspace:*- version: link:../source-control-gitcafe- '@t3tools/source-control-github':- specifier: workspace:*- version: link:../source-control-github- '@t3tools/source-control-gitlab':- specifier: workspace:*- version: link:../source-control-gitlab+ version: link:../source-control-definitionseffect:specifier: 4.0.5version: 4.0.5@@ -1906,6 +1894,30 @@ importers:specifier: 1.3.0version: 1.3.0(@astrojs/[email protected])(@tsc-rs/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@volar/[email protected](@tsc-rs/[email protected]))([email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ packages/source-control-definitions:+ dependencies:+ '@t3tools/source-control-azure-devops':+ specifier: workspace:*+ version: link:../source-control-azure-devops+ '@t3tools/source-control-bitbucket':+ specifier: workspace:*+ version: link:../source-control-bitbucket+ '@t3tools/source-control-core':+ specifier: workspace:*+ version: link:../source-control-core+ '@t3tools/source-control-forgejo':+ specifier: workspace:*+ version: link:../source-control-forgejo+ '@t3tools/source-control-gitcafe':+ specifier: workspace:*+ version: link:../source-control-gitcafe+ '@t3tools/source-control-github':+ specifier: workspace:*+ version: link:../source-control-github+ '@t3tools/source-control-gitlab':+ specifier: workspace:*+ version: link:../source-control-gitlab+packages/source-control-forgejo:dependencies:'@t3tools/contracts':diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.tsindex cceda337422..fc82d4e20d6 100644--- a/scripts/release-smoke.ts+++ b/scripts/release-smoke.ts@@ -40,6 +40,7 @@ const workspaceFiles = ["packages/source-control-azure-devops/package.json","packages/source-control-bitbucket/package.json","packages/source-control-core/package.json",+ "packages/source-control-definitions/package.json","packages/source-control-forgejo/package.json","packages/source-control-gitcafe/package.json","packages/source-control-github/package.json",