@devries-cameron20 / t3code-1 / commits / 4d87110c5e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

test(source-control): forge behaviour is tested in its own package (#24000)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 24, 2026 at 04:24 UTC 4d87110c5e99f5c16f974fb568264447bb2cfc1a
45 files changed +2672 -2530
apps/server/src/assets/AssetAccess.test.ts
+3 -5
@@ -34,7 +34,7 @@ import { assetFileResponse } from "../http.ts";
34 import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
35 import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
36 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
37 -import type { SourceControlDriverInstance } from "@t3tools/source-control-core/server/driver";
37 +import { fakeSourceControlDriverInstance } from "@t3tools/source-control-testing/fakeSourceControlDriver";
38 import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
39 import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
40 import { sourceControlMediaResponse } from "./sourceControlMediaResponse.ts";
@@ -957,9 +957,7 @@ describe("AssetAccess", () => {
957 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
958 {
959 driver: { kind: media.definition.kind, definition: media.definition },
960 - instance: {
961 - sourceControl: {} as SourceControlDriverInstance["sourceControl"],
962 - discovery: {} as SourceControlDriverInstance["discovery"],
960 + instance: fakeSourceControlDriverInstance(media.definition.kind, {
961 pullRequests: null,
962 fetchMedia: (request) =>
963 Effect.sync(() => {
@@ -969,7 +967,7 @@ describe("AssetAccess", () => {
967 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
968 );
969 }),
972 - },
970 + }),
971 },
972 ]);
973 return Effect.gen(function* () {
apps/server/src/git/GitManager.test.ts
+640 -920
@@ -15,7 +15,6 @@ import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as PlatformError from "effect/PlatformError";
17 import * as Result from "effect/Result";
18 -import * as Schema from "effect/Schema";
18 import * as Scope from "effect/Scope";
19 import * as Stream from "effect/Stream";
20 import { ChildProcessSpawner } from "effect/process";
@@ -42,12 +41,6 @@ import {
41 TurnItemId,
42 } from "@t3tools/contracts";
43 import * as DateTime from "effect/DateTime";
45 -import { decodeGitHubPullRequestListJson } from "@t3tools/source-control-github/server/gitHubPullRequests";
46 -import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
47 -import * as HostProcess from "@t3tools/shared/HostProcess";
48 -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
49 -import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
50 -import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
44 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
45 import {
46 fromRunner,
@@ -58,12 +51,6 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
51 import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
52 import * as VcsProjectConfig from "../vcs/VcsProjectConfig.ts";
53 import * as GitWorkflowService from "./GitWorkflowService.ts";
61 -import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
62 -import * as GitLabSourceControlProvider from "@t3tools/source-control-gitlab/server/GitLabSourceControlProvider";
63 -import {
64 - ForgejoPullRequestSchema,
65 - toForgejoChangeRequest,
66 -} from "@t3tools/source-control-forgejo/server/forgejoPullRequests";
54 import type { SourceControlProvider } from "@t3tools/source-control-core/server/SourceControlProvider";
55 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
56 import * as ServerConfig from "../config.ts";
@@ -75,124 +62,74 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
62 import * as ServerSettings from "../serverSettings.ts";
63 import * as GitManager from "./GitManager.ts";
64
78 -const encodeCliJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
79 -const decodeForgejoPullRequest = Schema.decodeEffect(ForgejoPullRequestSchema);
65 +/** A change request the fake host reports. Omitted fields read as an open, undated request. */
66 +type FakeChangeRequest = Omit<ChangeRequest, "provider" | "state" | "updatedAt"> & {
67 + readonly state?: ChangeRequest["state"];
68 + readonly updatedAt?: string;
69 +};
70
81 -interface FakeGhScenario {
82 - prListSequence?: string[];
83 - prListByHeadSelector?: Record<string, string>;
84 - prListSequenceByHeadSelector?: Record<string, string[]>;
85 - createdPrUrl?: string;
71 +interface FakeProviderScenario {
72 + /** The kind the fake host reports itself as. */
73 + kind?: string;
74 + /** Answers to successive change request listings, whatever their head selector. */
75 + prListSequence?: ReadonlyArray<ReadonlyArray<FakeChangeRequest>>;
76 + prListByHeadSelector?: Record<string, ReadonlyArray<FakeChangeRequest>>;
77 + prListSequenceByHeadSelector?: Record<string, ReadonlyArray<ReadonlyArray<FakeChangeRequest>>>;
78 + /** The answer to every listing the other lists leave unanswered. */
79 + prListOtherwise?: ReadonlyArray<FakeChangeRequest>;
80 defaultBranch?: string;
87 - pullRequest?: {
88 - number: number;
89 - title: string;
90 - url: string;
91 - baseRefName: string;
92 - headRefName: string;
93 - state?: "open" | "closed" | "merged";
94 - isDraft?: boolean;
95 - isCrossRepository?: boolean;
96 - headRepositoryNameWithOwner?: string | null;
97 - headRepositoryOwnerLogin?: string | null;
98 - headSha?: string;
99 - };
81 + pullRequest?: FakeChangeRequest;
82 repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
83 failWith?: string;
84 failCause?: unknown;
85 failAfterCalls?: number;
104 - /** Check out the pull request head the way gh does: fast-forward only unless forced. */
86 + /** Check out the pull request head from its pull ref: fast-forward only unless forced. */
87 syncCheckoutWithPullHead?: boolean;
88 + /**
89 + * The host's `headBranchProbe`. By default the fake probes only bare branch names, a hundred
90 + * at a time, so tests see GitManager defer to the hook; null leaves the probe to GitManager.
91 + */
92 + headBranchProbe?: SourceControlProvider["Service"]["headBranchProbe"] | null;
93 }
94
108 -function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
109 - return {
110 - exitCode: ChildProcessSpawner.ExitCode(0),
111 - stdout,
112 - stderr: "",
113 - stdoutTruncated: false,
114 - stderrTruncated: false,
115 - };
116 -}
117 -
118 -type FakeGitTextGeneration = TextGeneration.TextGeneration["Service"];
119 -
120 -type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
121 -
122 -type FakePullRequestSummary = Omit<ChangeRequest, "provider" | "state" | "updatedAt"> & {
123 - readonly state?: ChangeRequest["state"];
124 - readonly updatedAt?: string;
125 -};
95 +type FakeProviderCall =
96 + | {
97 + readonly operation: "listChangeRequests";
98 + readonly headSelector: string;
99 + readonly state: string;
100 + readonly limit: number | undefined;
101 + }
102 + | {
103 + readonly operation: "createChangeRequest";
104 + readonly baseRefName: string;
105 + readonly headSelector: string;
106 + readonly title: string;
107 + }
108 + | { readonly operation: "getChangeRequest"; readonly reference: string }
109 + | {
110 + readonly operation: "checkoutChangeRequest";
111 + readonly reference: string;
112 + readonly force: boolean;
113 + }
114 + | { readonly operation: "getRepositoryCloneUrls"; readonly repository: string }
115 + | { readonly operation: "getDefaultBranch" };
116
127 -function normalizeFakePullRequestSummary(raw: unknown): FakePullRequestSummary | null {
128 - if (!raw || typeof raw !== "object") {
129 - return null;
130 - }
117 +const listed = (calls: ReadonlyArray<FakeProviderCall>) =>
118 + calls.flatMap((call) => (call.operation === "listChangeRequests" ? [call] : []));
119
132 - const record = raw as Record<string, unknown>;
133 - const number = record.number;
134 - const title = record.title;
135 - const url = record.url;
136 - const baseRefName = record.baseRefName;
137 - const headRefName = record.headRefName;
138 - const headRepository =
139 - typeof record.headRepository === "object" && record.headRepository !== null
140 - ? (record.headRepository as Record<string, unknown>)
141 - : null;
142 - const headRepositoryOwner =
143 - typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
144 - ? (record.headRepositoryOwner as Record<string, unknown>)
145 - : null;
146 -
147 - if (
148 - typeof number !== "number" ||
149 - typeof title !== "string" ||
150 - typeof url !== "string" ||
151 - typeof baseRefName !== "string" ||
152 - typeof headRefName !== "string"
153 - ) {
154 - return null;
155 - }
120 +const listedSelectors = (calls: ReadonlyArray<FakeProviderCall>) =>
121 + listed(calls).map((call) => call.headSelector);
122
157 - const state =
158 - typeof record.state === "string"
159 - ? record.state === "OPEN" || record.state === "open"
160 - ? "open"
161 - : record.state === "CLOSED" || record.state === "closed"
162 - ? "closed"
163 - : "merged"
164 - : undefined;
165 - const isDraft = typeof record.isDraft === "boolean" ? record.isDraft : undefined;
166 - const isCrossRepository =
167 - typeof record.isCrossRepository === "boolean" ? record.isCrossRepository : undefined;
168 - const headRepositoryNameWithOwner =
169 - typeof record.headRepositoryNameWithOwner === "string"
170 - ? record.headRepositoryNameWithOwner
171 - : typeof headRepository?.nameWithOwner === "string"
172 - ? headRepository.nameWithOwner
173 - : undefined;
174 - const headRepositoryOwnerLogin =
175 - typeof record.headRepositoryOwnerLogin === "string"
176 - ? record.headRepositoryOwnerLogin
177 - : typeof headRepositoryOwner?.login === "string"
178 - ? headRepositoryOwner.login
179 - : undefined;
123 +const created = (calls: ReadonlyArray<FakeProviderCall>) =>
124 + calls.flatMap((call) =>
125 + call.operation === "createChangeRequest"
126 + ? [{ baseRefName: call.baseRefName, headSelector: call.headSelector }]
127 + : [],
128 + );
129
181 - return {
182 - number,
183 - title,
184 - url,
185 - baseRefName,
186 - headRefName,
187 - ...(state ? { state } : {}),
188 - ...(isDraft === true ? { isDraft: true } : {}),
189 - ...(isCrossRepository !== undefined ? { isCrossRepository } : {}),
190 - ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
191 - ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
192 - };
193 -}
130 +type FakeGitTextGeneration = TextGeneration.TextGeneration["Service"];
131
195 -function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
132 +function runGitSyncForFakeCheckout(cwd: string, args: readonly string[]): void {
133 const result = NodeChildProcess.spawnSync("git", args, {
134 cwd,
135 encoding: "utf8",
@@ -201,10 +138,9 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
138 return;
139 }
140 throw new Error(
204 - `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
141 + `Failed to simulate a host checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
142 );
143 }
207 -
144 function makeTempDir(
145 prefix: string,
146 ): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
@@ -284,18 +220,6 @@ function initRepo(
220 });
221 }
222
287 -const makeGitLabTemplateProvider = Effect.fnUntraced(function* () {
288 - const git = yield* GitVcsDriver.GitVcsDriver;
289 - return yield* GitLabSourceControlProvider.make.pipe(
290 - Effect.provide(
291 - Layer.mergeAll(
292 - Layer.mock(GitLabCli.GitLabCli)({}),
293 - TestSourceControlHost.layer({ git: { execute: git.execute } }),
294 - ),
295 - ),
296 - );
297 -});
298 -
223 function createBareRemote(): Effect.Effect<
224 string,
225 PlatformError.PlatformError | GitCommandError,
@@ -413,10 +337,15 @@ function createTextGeneration(
337 };
338 }
339
416 -function createGitHubProviderWithFakeGh(scenario: FakeGhScenario = {}): {
340 +/**
341 + * A host that answers from the scenario and records what it was asked, so tests assert on the
342 + * selectors GitManager chose rather than on any host's wire format.
343 + */
344 +function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): {
345 service: SourceControlProvider["Service"];
418 - ghCalls: string[];
346 + calls: FakeProviderCall[];
347 } {
348 + const kind = SourceControlProviderKind.make(scenario.kind ?? "github");
349 const prListQueue = [...(scenario.prListSequence ?? [])];
350 const prListQueueByHeadSelector = new Map(
351 Object.entries(scenario.prListSequenceByHeadSelector ?? {}).map(([headSelector, values]) => [
@@ -424,160 +353,27 @@ function createGitHubProviderWithFakeGh(scenario: FakeGhScenario = {}): {
353 [...values],
354 ]),
355 );
427 - const ghCalls: string[] = [];
428 -
429 - const fail = (cwd: string, detail: string, cause?: unknown, operation = "fakeGh") =>
430 - new SourceControlProviderFailure({
431 - provider: SourceControlProviderKind.make("github"),
432 - operation,
433 - cwd,
434 - detail,
435 - cause,
356 + const calls: FakeProviderCall[] = [];
357 +
358 + const record = (cwd: string, call: FakeProviderCall) =>
359 + Effect.suspend(() => {
360 + calls.push(call);
361 + return scenario.failWith && calls.length > (scenario.failAfterCalls ?? 0)
362 + ? Effect.fail(
363 + new SourceControlProviderFailure({
364 + provider: kind,
365 + operation: call.operation,
366 + cwd,
367 + detail: scenario.failWith,
368 + cause: scenario.failCause,
369 + }),
370 + )
371 + : Effect.void;
372 });
373
438 - const execute = (input: {
439 - readonly cwd: string;
440 - readonly args: ReadonlyArray<string>;
441 - readonly operation: string;
442 - }): Effect.Effect<VcsProcess.VcsProcessOutput, SourceControlProviderFailure> => {
443 - const args = [...input.args];
444 - ghCalls.push(args.join(" "));
445 -
446 - if (scenario.failWith && ghCalls.length > (scenario.failAfterCalls ?? 0)) {
447 - return Effect.fail(fail(input.cwd, scenario.failWith, scenario.failCause, input.operation));
448 - }
449 -
450 - if (args[0] === "pr" && args[1] === "list") {
451 - const headSelectorIndex = args.findIndex((value) => value === "--head");
452 - const headSelector =
453 - headSelectorIndex >= 0 && headSelectorIndex < args.length - 1
454 - ? args[headSelectorIndex + 1]
455 - : undefined;
456 - const mappedQueue =
457 - typeof headSelector === "string"
458 - ? prListQueueByHeadSelector.get(headSelector)?.shift()
459 - : undefined;
460 - const mappedStdout =
461 - typeof headSelector === "string"
462 - ? scenario.prListByHeadSelector?.[headSelector]
463 - : undefined;
464 - const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
465 - return Effect.succeed(fakeGhOutput(stdout));
466 - }
467 -
468 - if (args[0] === "pr" && args[1] === "create") {
469 - return Effect.succeed(
470 - fakeGhOutput(
471 - (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
472 - ),
473 - );
474 - }
475 -
476 - if (args[0] === "pr" && args[1] === "view") {
477 - const pullRequest: FakePullRequest = scenario.pullRequest ?? {
478 - number: 101,
479 - title: "Pull request",
480 - url: "https://github.com/pingdotgg/codething-mvp/pull/101",
481 - baseRefName: "main",
482 - headRefName: "feature/pull-request",
483 - state: "open",
484 - };
485 - return Effect.succeed(
486 - fakeGhOutput(
487 - JSON.stringify({
488 - ...pullRequest,
489 - ...(pullRequest.headRepositoryNameWithOwner
490 - ? {
491 - headRepository: {
492 - nameWithOwner: pullRequest.headRepositoryNameWithOwner,
493 - },
494 - }
495 - : {}),
496 - ...(pullRequest.headRepositoryOwnerLogin
497 - ? {
498 - headRepositoryOwner: {
499 - login: pullRequest.headRepositoryOwnerLogin,
500 - },
501 - }
502 - : {}),
503 - }) + "\n",
504 - ),
505 - );
506 - }
507 -
508 - if (args[0] === "pr" && args[1] === "checkout") {
509 - return Effect.try({
510 - try: () => {
511 - const headBranch = scenario.pullRequest?.headRefName;
512 - if (headBranch && scenario.syncCheckoutWithPullHead) {
513 - runGitSyncForFakeGh(input.cwd, [
514 - "fetch",
515 - "origin",
516 - `refs/pull/${scenario.pullRequest?.number}/head`,
517 - ]);
518 - const existingBranch = NodeChildProcess.spawnSync(
519 - "git",
520 - ["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`],
521 - { cwd: input.cwd },
522 - );
523 - if (existingBranch.status === 0) {
524 - runGitSyncForFakeGh(input.cwd, ["checkout", headBranch]);
525 - runGitSyncForFakeGh(
526 - input.cwd,
527 - args.includes("--force")
528 - ? ["reset", "--hard", "FETCH_HEAD"]
529 - : ["merge", "--ff-only", "FETCH_HEAD"],
530 - );
531 - } else {
532 - runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch, "FETCH_HEAD"]);
533 - }
534 - } else if (headBranch) {
535 - const existingBranch = NodeChildProcess.spawnSync(
536 - "git",
537 - ["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`],
538 - {
539 - cwd: input.cwd,
540 - encoding: "utf8",
541 - },
542 - );
543 - if (existingBranch.status === 0) {
544 - runGitSyncForFakeGh(input.cwd, ["checkout", headBranch]);
545 - } else {
546 - runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
547 - }
548 - }
549 - return fakeGhOutput("");
550 - },
551 - catch: (error) => fail(input.cwd, "GitHub request failed.", error),
552 - });
553 - }
554 -
555 - if (args[0] === "repo" && args[1] === "view") {
556 - const repository = args[2];
557 - if (typeof repository === "string" && args.includes("nameWithOwner,url,sshUrl")) {
558 - const cloneUrls = scenario.repositoryCloneUrls?.[repository];
559 - if (!cloneUrls) {
560 - return Effect.fail(fail(input.cwd, `Unexpected repository lookup: ${repository}`));
561 - }
562 - return Effect.succeed(
563 - fakeGhOutput(
564 - JSON.stringify({
565 - nameWithOwner: repository,
566 - url: cloneUrls.url,
567 - sshUrl: cloneUrls.sshUrl,
568 - }) + "\n",
569 - ),
570 - );
571 - }
572 - return Effect.succeed(fakeGhOutput(`${scenario.defaultBranch ?? "main"}\n`));
573 - }
574 -
575 - return Effect.fail(fail(input.cwd, `Unexpected gh command: ${args.join(" ")}`));
576 - };
577 -
578 - const toChangeRequest = (summary: FakePullRequestSummary): ChangeRequest => ({
374 + const toChangeRequest = (summary: FakeChangeRequest): ChangeRequest => ({
375 ...summary,
580 - provider: SourceControlProviderKind.make("github"),
376 + provider: kind,
377 state: summary.state ?? "open",
378 closedAt: summary.closedAt ?? null,
379 mergedAt: summary.mergedAt ?? null,
@@ -587,131 +383,170 @@ function createGitHubProviderWithFakeGh(scenario: FakeGhScenario = {}): {
383 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
384 });
385
386 + const pullRequest = (): FakeChangeRequest =>
387 + scenario.pullRequest ?? {
388 + number: 101,
389 + title: "Pull request",
390 + url: "https://github.com/pingdotgg/codething-mvp/pull/101",
391 + baseRefName: "main",
392 + headRefName: "feature/pull-request",
393 + state: "open",
394 + };
395 +
396 + const checkout = (cwd: string, force: boolean) => {
397 + const headBranch = scenario.pullRequest?.headRefName;
398 + if (!headBranch) return;
399 + const existingBranch = NodeChildProcess.spawnSync(
400 + "git",
401 + ["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`],
402 + { cwd },
403 + );
404 + if (scenario.syncCheckoutWithPullHead) {
405 + runGitSyncForFakeCheckout(cwd, [
406 + "fetch",
407 + "origin",
408 + `refs/pull/${scenario.pullRequest?.number}/head`,
409 + ]);
410 + if (existingBranch.status === 0) {
411 + runGitSyncForFakeCheckout(cwd, ["checkout", headBranch]);
412 + runGitSyncForFakeCheckout(
413 + cwd,
414 + force ? ["reset", "--hard", "FETCH_HEAD"] : ["merge", "--ff-only", "FETCH_HEAD"],
415 + );
416 + } else {
417 + runGitSyncForFakeCheckout(cwd, ["checkout", "-b", headBranch, "FETCH_HEAD"]);
418 + }
419 + } else if (existingBranch.status === 0) {
420 + runGitSyncForFakeCheckout(cwd, ["checkout", headBranch]);
421 + } else {
422 + runGitSyncForFakeCheckout(cwd, ["checkout", "-b", headBranch]);
423 + }
424 + };
425 +
426 + const headBranchProbe =
427 + scenario.headBranchProbe === null
428 + ? {}
429 + : {
430 + headBranchProbe:
431 + scenario.headBranchProbe ??
432 + (({ headSelectors }: { readonly headSelectors: ReadonlyArray<string> }) => ({
433 + headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
434 + limit: 100,
435 + })),
436 + };
437 +
438 return {
439 service: {
592 - kind: SourceControlProviderKind.make("github"),
593 - headBranchProbe: ({ headSelectors }) => ({
594 - headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
595 - limit: 100,
596 - }),
597 -
440 + kind,
441 + ...headBranchProbe,
442 listChangeRequests: (input) =>
599 - input.state === "open"
600 - ? execute({
601 - operation: "listChangeRequests",
602 - cwd: input.cwd,
603 - args: [
604 - "pr",
605 - "list",
606 - "--head",
607 - input.headSelector,
608 - "--state",
609 - "open",
610 - "--limit",
611 - String(input.limit ?? 1),
612 - "--json",
613 - "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
614 - ],
615 - }).pipe(
616 - Effect.map((result) => JSON.parse(result.stdout) as unknown[]),
617 - Effect.map((raw) =>
618 - raw
619 - .map((entry) => normalizeFakePullRequestSummary(entry))
620 - .filter((entry): entry is FakePullRequestSummary => entry !== null)
621 - .map(toChangeRequest),
622 - ),
623 - )
624 - : execute({
625 - operation: "listChangeRequests",
626 - cwd: input.cwd,
627 - args: [
628 - "pr",
629 - "list",
630 - "--head",
631 - input.headSelector,
632 - "--state",
633 - input.state,
634 - "--limit",
635 - String(input.limit ?? 20),
636 - "--json",
637 - "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
638 - ],
639 - }).pipe(
640 - Effect.map((result) => {
641 - const raw = result.stdout.trim();
642 - if (raw.length === 0) return [];
643 - const decoded = decodeGitHubPullRequestListJson(raw);
644 - return Result.isSuccess(decoded)
645 - ? decoded.success.map((record) => ({
646 - provider: SourceControlProviderKind.make("github"),
647 - ...record,
648 - }))
649 - : [];
650 - }),
651 - ),
443 + record(input.cwd, {
444 + operation: "listChangeRequests",
445 + headSelector: input.headSelector,
446 + state: input.state,
447 + limit: input.limit,
448 + }).pipe(
449 + Effect.map(() =>
450 + (
451 + prListQueueByHeadSelector.get(input.headSelector)?.shift() ??
452 + scenario.prListByHeadSelector?.[input.headSelector] ??
453 + prListQueue.shift() ??
454 + scenario.prListOtherwise ??
455 + []
456 + ).map(toChangeRequest),
457 + ),
458 + ),
459 createChangeRequest: (input) =>
653 - execute({
460 + record(input.cwd, {
461 operation: "createChangeRequest",
655 - cwd: input.cwd,
656 - args: [
657 - "pr",
658 - "create",
659 - "--base",
660 - input.baseRefName,
661 - "--head",
662 - input.headSelector,
663 - "--title",
664 - input.title,
665 - "--body-file",
666 - input.bodyFile,
667 - ],
668 - }).pipe(Effect.asVoid),
462 + baseRefName: input.baseRefName,
463 + headSelector: input.headSelector,
464 + title: input.title,
465 + }),
466 getDefaultBranch: (input) =>
670 - execute({
671 - operation: "getDefaultBranch",
672 - cwd: input.cwd,
673 - args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
674 - }).pipe(
675 - Effect.map((result) => {
676 - const value = result.stdout.trim();
467 + record(input.cwd, { operation: "getDefaultBranch" }).pipe(
468 + Effect.map(() => {
469 + const value = (scenario.defaultBranch ?? "main").trim();
470 return value.length > 0 ? value : null;
471 }),
472 ),
473 getChangeRequest: (input) =>
681 - execute({
682 - operation: "getChangeRequest",
683 - cwd: input.cwd,
684 - args: [
685 - "pr",
686 - "view",
687 - input.reference,
688 - "--json",
689 - "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
690 - ],
691 - }).pipe(
692 - Effect.map((result) =>
693 - toChangeRequest(JSON.parse(result.stdout) as FakePullRequestSummary),
694 - ),
474 + record(input.cwd, { operation: "getChangeRequest", reference: input.reference }).pipe(
475 + Effect.map(() => toChangeRequest(pullRequest())),
476 ),
477 getRepositoryCloneUrls: (input) =>
697 - execute({
478 + record(input.cwd, {
479 operation: "getRepositoryCloneUrls",
699 - cwd: input.cwd,
700 - args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
701 - }).pipe(Effect.map((result) => JSON.parse(result.stdout))),
480 + repository: input.repository,
481 + }).pipe(
482 + Effect.flatMap(() => {
483 + const cloneUrls = scenario.repositoryCloneUrls?.[input.repository];
484 + return cloneUrls
485 + ? Effect.succeed({ nameWithOwner: input.repository, ...cloneUrls })
486 + : Effect.fail(
487 + new SourceControlProviderFailure({
488 + provider: kind,
489 + operation: "getRepositoryCloneUrls",
490 + cwd: input.cwd,
491 + detail: `Unexpected repository lookup: ${input.repository}`,
492 + }),
493 + );
494 + }),
495 + ),
496 createRepository: (input) =>
703 - Effect.fail(fail(input.cwd, `Unexpected repository create: ${input.repository}`)),
497 + Effect.fail(
498 + new SourceControlProviderFailure({
499 + provider: kind,
500 + operation: "createRepository",
501 + cwd: input.cwd,
502 + detail: `Unexpected repository create: ${input.repository}`,
503 + }),
504 + ),
505 checkoutChangeRequest: (input) =>
705 - execute({
506 + record(input.cwd, {
507 operation: "checkoutChangeRequest",
707 - cwd: input.cwd,
708 - args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
709 - }).pipe(Effect.asVoid),
508 + reference: input.reference,
509 + force: input.force ?? false,
510 + }).pipe(
511 + Effect.flatMap(() =>
512 + Effect.try({
513 + try: () => checkout(input.cwd, input.force ?? false),
514 + catch: (cause) =>
515 + new SourceControlProviderFailure({
516 + provider: kind,
517 + operation: "checkoutChangeRequest",
518 + cwd: input.cwd,
519 + detail: "Host checkout failed.",
520 + cause,
521 + }),
522 + }),
523 + ),
524 + ),
525 },
711 - ghCalls,
526 + calls,
527 };
528 }
529
530 +/**
531 + * Reads a template from the base tree the way a host would, without any host's own lookup
532 + * rules, so tests see which tree GitManager reads it from.
533 + */
534 +const readFakeChangeRequestTemplate = Effect.fnUntraced(function* (input: {
535 + readonly cwd: string;
536 + readonly treeish: string;
537 +}) {
538 + const git = yield* GitVcsDriver.GitVcsDriver;
539 + const result = yield* git
540 + .execute({
541 + operation: "GitManager.test.readTemplate",
542 + cwd: input.cwd,
543 + args: ["show", `${input.treeish}:.github/pull_request_template.md`],
544 + allowNonZeroExit: true,
545 + })
546 + .pipe(Effect.orDie);
547 + const template = result.stdout.trim();
548 + return result.exitCode === 0 && template.length > 0 ? Option.some(template) : Option.none();
549 +});
550 function runStackedAction(
551 manager: GitManager.GitManager["Service"],
552 input: {
@@ -741,14 +576,13 @@ function preparePullRequestThread(
576 }
577
578 function makeManager(input?: {
744 - ghScenario?: FakeGhScenario;
579 + providerScenario?: FakeProviderScenario;
580 sourceControlProvider?: SourceControlProvider["Service"];
581 textGeneration?: Partial<FakeGitTextGeneration>;
582 serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
583 setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
584 gitConfigReads?: string[];
585 gitCommands?: string[];
751 - environment?: NodeJS.ProcessEnv;
586 gitSpawnGate?: {
587 readonly matches: (args: ReadonlyArray<string>) => boolean;
588 readonly reached: Deferred.Deferred<void>;
@@ -760,8 +594,8 @@ function makeManager(input?: {
594 ProjectionStore.ProjectionStoreV2 | ProjectStore.ProjectStoreV2
595 >;
596 }) {
763 - const { service: fakeGitHubProvider, ghCalls } = createGitHubProviderWithFakeGh(
764 - input?.ghScenario,
597 + const { service: fakeProvider, calls: providerCalls } = createFakeSourceControlProvider(
598 + input?.providerScenario,
599 );
600 const textGeneration = createTextGeneration(input?.textGeneration);
601 const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
@@ -828,12 +662,12 @@ function makeManager(input?: {
662 const layerSourceControlRegistry = Layer.effect(
663 SourceControlProviderRegistry.SourceControlProviderRegistry,
664 Effect.gen(function* () {
831 - const git = yield* GitVcsDriver.GitVcsDriver;
665 + const context = yield* Effect.context<GitVcsDriver.GitVcsDriver>();
666 return (
667 input?.sourceControlProvider ?? {
834 - ...fakeGitHubProvider,
835 - readChangeRequestTemplate: ({ cwd, treeish }: { cwd: string; treeish: string }) =>
836 - GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
668 + ...fakeProvider,
669 + readChangeRequestTemplate: (template: { cwd: string; treeish: string }) =>
670 + readFakeChangeRequestTemplate(template).pipe(Effect.provideContext(context)),
671 }
672 );
673 }).pipe(
@@ -876,11 +710,10 @@ function makeManager(input?: {
710 yield* input.seed.pipe(Effect.provideContext(stores), Effect.orDie);
711 }
712 const manager = yield* GitManager.make.pipe(
879 - Effect.provideService(HostProcess.Environment, input?.environment ?? {}),
713 Effect.provide(layerManager),
714 Effect.provideContext(stores),
715 );
883 - return { manager, ghCalls };
716 + return { manager, providerCalls };
717 });
718 }
719
@@ -893,7 +726,7 @@ const layerGitManagerTest = GitVcsDriver.layer.pipe(
726 );
727
728 it.layer(layerGitManagerTest)("GitManager", (it) => {
896 - it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
729 + it.effect("status reports the listed PR whose head is the branch", () =>
730 Effect.gen(function* () {
731 const repoDir = yield* makeTempDir("t3code-git-manager-");
732 yield* initRepo(repoDir);
@@ -903,30 +736,24 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
736 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
737
738 const { manager } = yield* makeManager({
906 - ghScenario: {
739 + providerScenario: {
740 prListSequence: [
908 - JSON.stringify([
741 + [
742 {
910 - number: 0,
911 - title: "invalid",
912 - url: "https://github.com/pingdotgg/codething-mvp/pull/0",
743 + number: 14,
744 + title: "Another branch",
745 + url: "https://github.com/pingdotgg/codething-mvp/pull/14",
746 baseRefName: "main",
914 - headRefName: "feature/invalid",
747 + headRefName: "feature/another-branch",
748 },
749 {
750 number: 15,
918 - title: " Valid PR title ",
919 - url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
920 - baseRefName: " main ",
921 - headRefName: "\tfeature/status-valid-pr-entry\t",
922 - headRepository: {
923 - nameWithOwner: " ",
924 - },
925 - headRepositoryOwner: {
926 - login: " ",
927 - },
751 + title: "Valid PR title",
752 + url: "https://github.com/pingdotgg/codething-mvp/pull/15",
753 + baseRefName: "main",
754 + headRefName: "feature/status-valid-pr-entry",
755 },
929 - ]),
756 + ],
757 ],
758 },
759 });
@@ -945,7 +772,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
772 }),
773 );
774
948 - it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
775 + it.effect("status reports the latest of a branch's closed and merged PRs", () =>
776 Effect.gen(function* () {
777 const repoDir = yield* makeTempDir("t3code-git-manager-");
778 yield* initRepo(repoDir);
@@ -955,9 +782,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
782 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
783
784 const { manager } = yield* makeManager({
958 - ghScenario: {
785 + providerScenario: {
786 prListSequence: [
960 - JSON.stringify([
787 + [
788 {
789 number: 16,
790 title: "Closed PR",
@@ -976,7 +803,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
803 state: "merged",
804 updatedAt: "2026-01-02T00:00:00.000Z",
805 },
979 - ]),
806 + ],
807 ],
808 },
809 });
@@ -1034,18 +861,17 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
861 yield* runGit(repoDir, ["checkout", "-b", "feature/racing-upstream"]);
862 yield* runGit(repoDir, ["push", "-u", "origin", "feature/racing-upstream"]);
863 yield* runGit(repoDir, ["push", "origin", "HEAD:refs/heads/feature/raced-head"]);
1037 - const pullRequest = (number: number, headRefName: string) =>
1038 - encodeCliJson([
1039 - {
1040 - number,
1041 - title: headRefName,
1042 - url: `https://github.com/pingdotgg/codething-mvp/pull/${number}`,
1043 - baseRefName: "main",
1044 - headRefName,
1045 - state: "OPEN",
1046 - updatedAt: "2026-04-07T15:00:00Z",
1047 - },
1048 - ]);
864 + const pullRequest = (number: number, headRefName: string): FakeChangeRequest[] => [
865 + {
866 + number,
867 + title: headRefName,
868 + url: `https://github.com/pingdotgg/codething-mvp/pull/${number}`,
869 + baseRefName: "main",
870 + headRefName,
871 + state: "open",
872 + updatedAt: "2026-04-07T15:00:00Z",
873 + },
874 + ];
875 const gate = {
876 matches: (args: ReadonlyArray<string>) =>
877 args[0] === "for-each-ref" && args.at(-1) === "refs/heads/feature/racing-upstream",
@@ -1054,7 +880,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
880 };
881 const { manager } = yield* makeManager({
882 gitSpawnGate: gate,
1057 - ghScenario: {
883 + providerScenario: {
884 prListByHeadSelector: {
885 "feature/racing-upstream": pullRequest(237, "feature/racing-upstream"),
886 "feature/raced-head": pullRequest(238, "feature/raced-head"),
@@ -1086,26 +912,26 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
912 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
913 yield* runGit(repoDir, ["push", "-u", "origin", "feature/draft-status"]);
914 const drafts = [false, true, true, false, false, true];
1089 - const pullRequest = {
915 + const pullRequest: FakeChangeRequest = {
916 number: 1,
917 title: "Draft status",
918 url: "https://github.com/pingdotgg/codething-mvp/pull/1",
919 baseRefName: "main",
920 headRefName: "feature/draft-status",
1095 - state: "OPEN",
921 + state: "open",
922 };
923 const { manager } = yield* makeManager({
1098 - ghScenario: {
924 + providerScenario: {
925 prListSequence: [
1100 - ...drafts.map((isDraft) => encodeCliJson([{ ...pullRequest, isDraft }])),
1101 - encodeCliJson([
926 + ...drafts.map((isDraft) => [{ ...pullRequest, isDraft }]),
927 + [
928 {
929 ...pullRequest,
930 number: 2,
931 url: "https://github.com/pingdotgg/codething-mvp/pull/2",
1106 - state: "MERGED",
932 + state: "merged",
933 },
1108 - ]),
934 + ],
935 ],
936 },
937 });
@@ -1145,20 +971,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
971 yield* runGit(repoDir, ["checkout", "main"]);
972
973 const { manager } = yield* makeManager({
1148 - ghScenario: {
974 + providerScenario: {
975 prListSequence: [
1150 - JSON.stringify([
976 + [
977 {
978 number: 216,
979 title: "Saved branch PR",
980 url: "https://github.com/pingdotgg/t3code/pull/216",
981 baseRefName: "main",
982 headRefName: "feature/saved-branch",
1157 - headRefOid: "a".repeat(40),
1158 - state: "OPEN",
983 + headSha: "a".repeat(40),
984 + state: "open",
985 updatedAt: "2026-04-03T15:00:00Z",
986 },
1161 - ]),
987 + ],
988 ],
989 },
990 });
@@ -1197,20 +1023,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1023 yield* runGit(repoDir, ["remote", "set-head", "upstream", "develop"]);
1024
1025 const { manager } = yield* makeManager({
1200 - ghScenario: {
1026 + providerScenario: {
1027 prListSequence: [
1202 - JSON.stringify([
1028 + [
1029 {
1030 number: 221,
1031 title: "Merged main PR",
1032 url: "https://github.com/pingdotgg/codething-mvp/pull/221",
1033 baseRefName: "develop",
1034 headRefName: "main",
1209 - state: "MERGED",
1035 + state: "merged",
1036 mergedAt: "2026-04-07T15:00:00Z",
1037 updatedAt: "2026-04-08T15:00:00Z",
1038 },
1213 - ]),
1039 + ],
1040 ],
1041 },
1042 });
@@ -1245,20 +1071,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1071 "feature/deleted-local-branch/child",
1072 ]);
1073
1248 - const { manager, ghCalls } = yield* makeManager({
1249 - ghScenario: {
1074 + const { manager, providerCalls } = yield* makeManager({
1075 + providerScenario: {
1076 prListSequence: [
1251 - JSON.stringify([
1077 + [
1078 {
1079 number: 217,
1080 title: "Deleted local branch PR",
1081 url: "https://github.com/pingdotgg/t3code/pull/217",
1082 baseRefName: "main",
1083 headRefName: "feature/deleted-local-branch",
1258 - state: "MERGED",
1084 + state: "merged",
1085 updatedAt: "2026-04-04T15:00:00Z",
1086 },
1261 - ]),
1087 + ],
1088 ],
1089 },
1090 });
@@ -1274,9 +1100,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1100 mergedAt: null,
1101 updatedAt: "2026-04-04T15:00:00.000Z",
1102 });
1277 - expect(ghCalls.some((call) => call.includes("--head feature/deleted-local-branch"))).toBe(
1278 - true,
1279 - );
1103 + expect(listedSelectors(providerCalls).includes("feature/deleted-local-branch")).toBe(true);
1104 }),
1105 );
1106
@@ -1306,23 +1130,23 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1130 forkDir,
1131 );
1132
1309 - const { manager, ghCalls } = yield* makeManager({
1310 - ghScenario: {
1133 + const { manager, providerCalls } = yield* makeManager({
1134 + providerScenario: {
1135 prListByHeadSelector: {
1312 - "feature/deleted-fork-branch": JSON.stringify([
1136 + "feature/deleted-fork-branch": [
1137 {
1138 number: 218,
1139 title: "Deleted fork branch PR",
1140 url: "https://github.com/pingdotgg/codething-mvp/pull/218",
1141 baseRefName: "main",
1142 headRefName: "feature/deleted-fork-branch",
1319 - state: "MERGED",
1143 + state: "merged",
1144 updatedAt: "2026-04-05T15:00:00Z",
1145 isCrossRepository: true,
1322 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
1323 - headRepositoryOwner: { login: "contributor" },
1146 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1147 + headRepositoryOwnerLogin: "contributor",
1148 },
1325 - ]),
1149 + ],
1150 },
1151 },
1152 });
@@ -1339,9 +1163,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1163 updatedAt: "2026-04-05T15:00:00.000Z",
1164 });
1165 expect(
1342 - ghCalls.some((call) => call.includes("--head feature/deleted-fork-branch --state all")),
1166 + listed(providerCalls).some(
1167 + (call) => call.headSelector === "feature/deleted-fork-branch" && call.state === "all",
1168 + ),
1169 ).toBe(true);
1344 - expect(ghCalls.some((call) => call.includes("--head contributor:"))).toBe(false);
1170 + expect(
1171 + listedSelectors(providerCalls).some((selector) => selector.startsWith("contributor:")),
1172 + ).toBe(false);
1173 }),
1174 );
1175
@@ -1358,7 +1186,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1186 yield* runGit(repoDir, ["push", "fork", "feature/ambiguous-remote"]);
1187 yield* runGit(repoDir, ["checkout", "main"]);
1188 yield* runGit(repoDir, ["branch", "-D", "feature/ambiguous-remote"]);
1361 - const { manager, ghCalls } = yield* makeManager();
1189 + const { manager, providerCalls } = yield* makeManager();
1190
1191 const error = yield* manager
1192 .branchPullRequest({ cwd: repoDir, branch: "feature/ambiguous-remote" })
@@ -1368,7 +1196,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1196 _tag: "GitManagerError",
1197 detail: "Multiple remotes track feature/ambiguous-remote. Its pull request is ambiguous.",
1198 });
1371 - expect(ghCalls).toHaveLength(0);
1199 + expect(providerCalls).toHaveLength(0);
1200 }),
1201 );
1202
@@ -1396,19 +1224,19 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1224 forkDir,
1225 );
1226
1399 - const ghScenario = {
1227 + const providerScenario: FakeProviderScenario = {
1228 prListByHeadSelector: {
1401 - "feature/no-upstream-fork": JSON.stringify([
1229 + "feature/no-upstream-fork": [
1230 {
1231 number: 40,
1232 title: "Another fork's PR",
1233 url: "https://github.com/pingdotgg/codething-mvp/pull/40",
1234 baseRefName: "main",
1235 headRefName: "feature/no-upstream-fork",
1408 - state: "OPEN",
1236 + state: "open",
1237 isCrossRepository: true,
1410 - headRepository: { nameWithOwner: "someone-else/codething-mvp" },
1411 - headRepositoryOwner: { login: "someone-else" },
1238 + headRepositoryNameWithOwner: "someone-else/codething-mvp",
1239 + headRepositoryOwnerLogin: "someone-else",
1240 },
1241 {
1242 number: 41,
@@ -1416,15 +1244,15 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1244 url: "https://github.com/pingdotgg/codething-mvp/pull/41",
1245 baseRefName: "main",
1246 headRefName: "feature/no-upstream-fork",
1419 - state: "OPEN",
1247 + state: "open",
1248 isCrossRepository: true,
1421 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
1422 - headRepositoryOwner: { login: "contributor" },
1249 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1250 + headRepositoryOwnerLogin: "contributor",
1251 },
1424 - ]),
1252 + ],
1253 },
1254 };
1427 - const { manager } = yield* makeManager({ ghScenario });
1255 + const { manager } = yield* makeManager({ providerScenario });
1256
1257 const pullRequest = yield* manager.branchPullRequest({
1258 cwd: repoDir,
@@ -1440,7 +1268,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1268 "refs/remotes/fork/feature/no-upstream-fork",
1269 ]);
1270 expect(localHead.stdout.trim()).not.toBe(pushedHead.stdout.trim());
1443 - const { manager: aheadManager } = yield* makeManager({ ghScenario });
1271 + const { manager: aheadManager } = yield* makeManager({ providerScenario });
1272 expect(
1273 (yield* aheadManager.branchPullRequest({
1274 cwd: repoDir,
@@ -1456,7 +1284,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1284 "refs/heads/feature/no-upstream-fork",
1285 ]);
1286 expect(upstream.stdout.trim()).toBe("");
1459 - const { manager: staleRemoteManager } = yield* makeManager({ ghScenario });
1287 + const { manager: staleRemoteManager } = yield* makeManager({ providerScenario });
1288 expect(
1289 (yield* staleRemoteManager.branchPullRequest({
1290 cwd: repoDir,
@@ -1474,7 +1302,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1302 "HEAD:refs/heads/feature/no-upstream-fork",
1303 ]);
1304 yield* runGit(repoDir, ["checkout", "feature/no-upstream-fork"]);
1477 - const { manager: divergedManager } = yield* makeManager({ ghScenario });
1305 + const { manager: divergedManager } = yield* makeManager({ providerScenario });
1306 expect(
1307 yield* divergedManager.branchPullRequest({
1308 cwd: repoDir,
@@ -1516,24 +1344,24 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1344 secondForkDir,
1345 );
1346
1519 - const ghScenario = {
1347 + const providerScenario: FakeProviderScenario = {
1348 prListByHeadSelector: {
1521 - "feature/ambiguous-fork": JSON.stringify([
1349 + "feature/ambiguous-fork": [
1350 {
1351 number: 41,
1352 title: "One fork's PR",
1353 url: "https://github.com/pingdotgg/codething-mvp/pull/41",
1354 baseRefName: "main",
1355 headRefName: "feature/ambiguous-fork",
1528 - state: "OPEN",
1356 + state: "open",
1357 isCrossRepository: true,
1530 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
1531 - headRepositoryOwner: { login: "contributor" },
1358 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1359 + headRepositoryOwnerLogin: "contributor",
1360 },
1533 - ]),
1361 + ],
1362 },
1363 };
1536 - const { manager: singleRemoteManager } = yield* makeManager({ ghScenario });
1364 + const { manager: singleRemoteManager } = yield* makeManager({ providerScenario });
1365 expect(
1366 (yield* singleRemoteManager.branchPullRequest({
1367 cwd: repoDir,
@@ -1542,14 +1370,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1370 ).toBe(41);
1371
1372 yield* runGit(repoDir, ["push", "second-fork", "feature/ambiguous-fork"]);
1545 - const { manager } = yield* makeManager({ ghScenario });
1373 + const { manager } = yield* makeManager({ providerScenario });
1374 expect(
1375 yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature/ambiguous-fork" }),
1376 ).toBeNull();
1377
1378 yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "Continue feature"]);
1379 yield* runGit(repoDir, ["push", "first-fork", "feature/ambiguous-fork"]);
1552 - const { manager: exactManager } = yield* makeManager({ ghScenario });
1380 + const { manager: exactManager } = yield* makeManager({ providerScenario });
1381 expect(
1382 (yield* exactManager.branchPullRequest({
1383 cwd: repoDir,
@@ -1600,24 +1428,24 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1428 forkDir,
1429 );
1430
1603 - const ghScenario = {
1431 + const providerScenario: FakeProviderScenario = {
1432 prListByHeadSelector: {
1605 - "feature/failed-probe": JSON.stringify([
1433 + "feature/failed-probe": [
1434 {
1435 number: 43,
1436 title: "Failed probe PR",
1437 url: "https://github.com/pingdotgg/codething-mvp/pull/43",
1438 baseRefName: "main",
1439 headRefName: "feature/failed-probe",
1612 - state: "OPEN",
1440 + state: "open",
1441 isCrossRepository: true,
1614 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
1615 - headRepositoryOwner: { login: "contributor" },
1442 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1443 + headRepositoryOwnerLogin: "contributor",
1444 },
1617 - ]),
1445 + ],
1446 },
1447 };
1620 - const { manager } = yield* makeManager({ ghScenario });
1448 + const { manager } = yield* makeManager({ providerScenario });
1449 expect(
1450 yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature/failed-probe" }),
1451 ).toBeNull();
@@ -1649,21 +1477,21 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1477 );
1478
1479 const { manager } = yield* makeManager({
1652 - ghScenario: {
1480 + providerScenario: {
1481 prListByHeadSelector: {
1654 - "feature/slash-remote": JSON.stringify([
1482 + "feature/slash-remote": [
1483 {
1484 number: 42,
1485 title: "Slash remote PR",
1486 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
1487 baseRefName: "main",
1488 headRefName: "feature/slash-remote",
1661 - state: "OPEN",
1489 + state: "open",
1490 isCrossRepository: true,
1663 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
1664 - headRepositoryOwner: { login: "contributor" },
1491 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1492 + headRepositoryOwnerLogin: "contributor",
1493 },
1666 - ]),
1494 + ],
1495 },
1496 },
1497 });
@@ -1689,21 +1517,21 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1517 "git@github.com:old-owner/old-repository.git",
1518 originalRemoteDir,
1519 );
1692 - const { manager, ghCalls } = yield* makeManager({
1693 - ghScenario: {
1520 + const { manager, providerCalls } = yield* makeManager({
1521 + providerScenario: {
1522 prListSequence: [
1695 - JSON.stringify([
1523 + [
1524 {
1525 number: 219,
1526 title: "Old repository PR",
1527 url: "https://github.com/old-owner/old-repository/pull/219",
1528 baseRefName: "main",
1529 headRefName: "feature/repointed-lookup",
1702 - state: "MERGED",
1530 + state: "merged",
1531 updatedAt: "2026-04-06T15:00:00Z",
1532 },
1705 - ]),
1706 - "[]",
1533 + ],
1534 + [],
1535 ],
1536 },
1537 });
@@ -1728,7 +1556,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1556 });
1557
1558 expect(second).toBeNull();
1731 - expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
1559 + expect(listed(providerCalls)).toHaveLength(2);
1560 }),
1561 );
1562
@@ -1744,10 +1572,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1572 yield* runGit(repoDir, ["push", "-u", "origin", "feature/lookup-failure"]);
1573 yield* runGit(repoDir, ["checkout", "main"]);
1574
1747 - const { manager, ghCalls } = yield* makeManager({
1748 - ghScenario: {
1749 - failWith:
1750 - "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
1575 + const { manager, providerCalls } = yield* makeManager({
1576 + providerScenario: {
1577 + failWith: "The host is signed out.",
1578 },
1579 });
1580
@@ -1760,7 +1587,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1587 .branchPullRequest({ cwd: repoDir, branch: "feature/lookup-failure" }, { refresh: true })
1588 .pipe(Effect.flip);
1589 expect(refreshError._tag).toBe("SourceControlProviderError");
1763 - expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);
1590 + expect(listed(providerCalls)).toHaveLength(1);
1591 }),
1592 );
1593
@@ -1797,21 +1624,21 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1624 expect(configuredMerge.stdout.trim()).toBe("refs/heads/feature/merged-branch-deleted");
1625 expect(trackingRef.stdout.trim()).toBe("");
1626
1800 - const { manager, ghCalls } = yield* makeManager({
1801 - ghScenario: {
1627 + const { manager, providerCalls } = yield* makeManager({
1628 + providerScenario: {
1629 prListSequence: [
1803 - JSON.stringify([
1630 + [
1631 {
1632 number: 215,
1633 title: "Merged branch was deleted",
1634 url: "https://github.com/pingdotgg/t3code/pull/215",
1635 baseRefName: "main",
1636 headRefName: "feature/merged-branch-deleted",
1810 - state: "MERGED",
1637 + state: "merged",
1638 mergedAt: "2026-04-02T15:00:00Z",
1639 updatedAt: "2026-04-02T15:00:00Z",
1640 },
1814 - ]),
1641 + ],
1642 ],
1643 },
1644 });
@@ -1828,7 +1655,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1655 state: "merged",
1656 updatedAt: "2026-04-02T15:00:00.000Z",
1657 });
1831 - expect(ghCalls.filter((call) => call.startsWith("pr list ")).length).toBeGreaterThan(0);
1658 + expect(listed(providerCalls).length).toBeGreaterThan(0);
1659 }),
1660 );
1661
@@ -1887,18 +1714,18 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1714 "git@github.example.com:alice/repository.git",
1715 forkDir,
1716 );
1890 - const output = encodeCliJson([
1717 + const output: FakeChangeRequest[] = [
1718 {
1719 number: 2,
1720 title: "Another fork",
1721 url: "https://github.example.com/team/repository/pull/2",
1722 baseRefName: "main",
1723 headRefName: "feature",
1897 - state: "OPEN",
1724 + state: "open",
1725 updatedAt: "2026-04-08T15:00:00Z",
1726 isCrossRepository: true,
1900 - headRepository: { nameWithOwner: "bob/repository" },
1901 - headRepositoryOwner: { login: "bob" },
1727 + headRepositoryNameWithOwner: "bob/repository",
1728 + headRepositoryOwnerLogin: "bob",
1729 },
1730 {
1731 number: 1,
@@ -1906,15 +1733,15 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1733 url: "https://github.example.com/team/repository/pull/1",
1734 baseRefName: "main",
1735 headRefName: "feature",
1909 - state: "OPEN",
1736 + state: "open",
1737 updatedAt: "2026-04-07T15:00:00Z",
1738 isCrossRepository: true,
1912 - headRepository: { nameWithOwner: "alice/repository" },
1913 - headRepositoryOwner: { login: "alice" },
1739 + headRepositoryNameWithOwner: "alice/repository",
1740 + headRepositoryOwnerLogin: "alice",
1741 },
1915 - ]);
1742 + ];
1743 const { manager } = yield* makeManager({
1917 - ghScenario: {
1744 + providerScenario: {
1745 prListByHeadSelector: {
1746 feature: output,
1747 },
@@ -1932,97 +1759,74 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1759 { remoteUrl: "git@gitlab.com:Group/Subgroup/Fork.git", setUpstream: false },
1760 { remoteUrl: "https://gitlab.com/Group/Subgroup/Fork.git", setUpstream: true },
1761 { remoteUrl: "https://gitlab.com/Group/Subgroup/Fork.git", setUpstream: false },
1935 - ] as const)("matches GitLab forks for $remoteUrl/$setUpstream", ({ remoteUrl, setUpstream }) =>
1936 - Effect.gen(function* () {
1937 - const repoDir = yield* makeTempDir("t3code-git-manager-");
1938 - yield* initRepo(repoDir);
1939 - const originDir = yield* createBareRemote();
1940 - const forkDir = yield* createBareRemote();
1941 - const branch = "feature/NestedGroups";
1942 - yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
1943 - yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
1944 - yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);
1945 - yield* runGit(repoDir, ["checkout", "-b", branch]);
1946 - yield* runGit(repoDir, ["push", ...(setUpstream ? ["-u"] : []), "fork", branch]);
1947 - const upstream = yield* runGit(repoDir, [
1948 - "for-each-ref",
1949 - "--format=%(upstream:short)",
1950 - `refs/heads/${branch}`,
1951 - ]);
1952 - expect(upstream.stdout.trim()).toBe(setUpstream ? `fork/${branch}` : "");
1953 - yield* configureVisibleRemoteUrlWithLocalRewrite(
1954 - repoDir,
1955 - "origin",
1956 - "git@gitlab.com:Group/Upstream/Repository.git",
1957 - originDir,
1958 - );
1959 - yield* configureVisibleRemoteUrlWithLocalRewrite(repoDir, "fork", remoteUrl, forkDir);
1960 - const output = encodeCliJson([
1961 - {
1962 - iid: 2,
1963 - title: "Another subgroup's fork",
1964 - web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",
1965 - target_branch: "main",
1966 - source_branch: branch,
1967 - state: "opened",
1968 - updated_at: "2026-04-08T15:00:00Z",
1969 - source_project_id: 102,
1970 - target_project_id: 100,
1971 - source_project: { path_with_namespace: "Group/Other/Fork" },
1972 - },
1973 - {
1974 - iid: 1,
1975 - title: "This subgroup's fork",
1976 - web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
1977 - target_branch: "main",
1978 - source_branch: branch,
1979 - state: "opened",
1980 - updated_at: "2026-04-07T15:00:00Z",
1981 - source_project_id: 101,
1982 - target_project_id: 100,
1983 - source_project: { path_with_namespace: "Group/Subgroup/Fork" },
1984 - },
1985 - ]);
1986 - const calls: SourceControlHost.SourceControlProcessInput[] = [];
1987 - const provider = yield* GitLabSourceControlProvider.make.pipe(
1988 - Effect.provide(
1989 - GitLabCli.layer.pipe(
1990 - Layer.provideMerge(
1991 - TestSourceControlHost.layer({
1992 - process: {
1993 - run: (input) =>
1994 - Effect.sync(() => {
1995 - calls.push(input);
1996 - return fakeGhOutput(output);
1997 - }),
1998 - },
1999 - }),
2000 - ),
2001 - ),
2002 - ),
2003 - );
2004 - const { manager } = yield* makeManager({ sourceControlProvider: provider });
2005 -
2006 - expect(yield* manager.branchPullRequest({ cwd: repoDir, branch })).toMatchObject({
2007 - number: 1,
2008 - repositoryKey: "gitlab.com/group/upstream/repository",
2009 - });
2010 - expect(calls.length).toBeGreaterThan(0);
2011 - for (const call of calls) {
2012 - expect(call.command).toBe("glab");
2013 - expect(call.args).toEqual([
2014 - "mr",
2015 - "list",
2016 - "--source-branch",
2017 - branch,
2018 - "--all",
2019 - "--per-page",
2020 - "20",
2021 - "--output",
2022 - "json",
1762 + ] as const)(
1763 + "matches nested-group forks for $remoteUrl/$setUpstream",
1764 + ({ remoteUrl, setUpstream }) =>
1765 + Effect.gen(function* () {
1766 + const repoDir = yield* makeTempDir("t3code-git-manager-");
1767 + yield* initRepo(repoDir);
1768 + const originDir = yield* createBareRemote();
1769 + const forkDir = yield* createBareRemote();
1770 + const branch = "feature/NestedGroups";
1771 + yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
1772 + yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
1773 + yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);
1774 + yield* runGit(repoDir, ["checkout", "-b", branch]);
1775 + yield* runGit(repoDir, ["push", ...(setUpstream ? ["-u"] : []), "fork", branch]);
1776 + const upstream = yield* runGit(repoDir, [
1777 + "for-each-ref",
1778 + "--format=%(upstream:short)",
1779 + `refs/heads/${branch}`,
1780 ]);
2024 - }
2025 - }),
1781 + expect(upstream.stdout.trim()).toBe(setUpstream ? `fork/${branch}` : "");
1782 + yield* configureVisibleRemoteUrlWithLocalRewrite(
1783 + repoDir,
1784 + "origin",
1785 + "git@gitlab.com:Group/Upstream/Repository.git",
1786 + originDir,
1787 + );
1788 + yield* configureVisibleRemoteUrlWithLocalRewrite(repoDir, "fork", remoteUrl, forkDir);
1789 + const { manager, providerCalls } = yield* makeManager({
1790 + providerScenario: {
1791 + kind: "gitlab",
1792 + headBranchProbe: null,
1793 + prListOtherwise: [
1794 + {
1795 + number: 2,
1796 + title: "Another subgroup's fork",
1797 + url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",
1798 + baseRefName: "main",
1799 + headRefName: branch,
1800 + updatedAt: "2026-04-08T15:00:00Z",
1801 + isCrossRepository: true,
1802 + headRepositoryNameWithOwner: "Group/Other/Fork",
1803 + headRepositoryOwnerLogin: "Group",
1804 + },
1805 + {
1806 + number: 1,
1807 + title: "This subgroup's fork",
1808 + url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
1809 + baseRefName: "main",
1810 + headRefName: branch,
1811 + updatedAt: "2026-04-07T15:00:00Z",
1812 + isCrossRepository: true,
1813 + headRepositoryNameWithOwner: "Group/Subgroup/Fork",
1814 + headRepositoryOwnerLogin: "Group",
1815 + },
1816 + ],
1817 + },
1818 + });
1819 +
1820 + expect(yield* manager.branchPullRequest({ cwd: repoDir, branch })).toMatchObject({
1821 + number: 1,
1822 + repositoryKey: "gitlab.com/group/upstream/repository",
1823 + });
1824 + expect(listed(providerCalls).length).toBeGreaterThan(0);
1825 + for (const call of listed(providerCalls)) {
1826 + expect(call.headSelector.endsWith(branch)).toBe(true);
1827 + expect(call.state).toBe("all");
1828 + }
1829 + }),
1830 );
1831
1832 it.effect(
@@ -2036,26 +1840,22 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1840 yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
1841
1842 const { manager } = yield* makeManager({
2039 - ghScenario: {
1843 + providerScenario: {
1844 prListSequence: [
2041 - JSON.stringify([
1845 + [
1846 {
1847 number: 1661,
1848 title: "Fork PR from main",
1849 url: "https://github.com/pingdotgg/t3code/pull/1661",
1850 baseRefName: "main",
1851 headRefName: "main",
2048 - state: "OPEN",
1852 + state: "open",
1853 updatedAt: "2026-04-01T15:00:00Z",
1854 isCrossRepository: true,
2051 - headRepository: {
2052 - nameWithOwner: "lnieuwenhuis/t3code",
2053 - },
2054 - headRepositoryOwner: {
2055 - login: "lnieuwenhuis",
2056 - },
1855 + headRepositoryNameWithOwner: "lnieuwenhuis/t3code",
1856 + headRepositoryOwnerLogin: "lnieuwenhuis",
1857 },
2058 - ]),
1858 + ],
1859 ],
1860 },
1861 });
@@ -2093,27 +1893,23 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1893 forkDir,
1894 );
1895
2096 - const { manager, ghCalls } = yield* makeManager({
2097 - ghScenario: {
1896 + const { manager, providerCalls } = yield* makeManager({
1897 + providerScenario: {
1898 prListSequence: [
2099 - JSON.stringify([
1899 + [
1900 {
1901 number: 488,
1902 title: "Rebase this PR on latest main",
1903 url: "https://github.com/pingdotgg/codething-mvp/pull/488",
1904 baseRefName: "main",
1905 headRefName: "statemachine",
2106 - state: "OPEN",
1906 + state: "open",
1907 updatedAt: "2026-03-10T07:00:00Z",
1908 isCrossRepository: true,
2109 - headRepository: {
2110 - nameWithOwner: "jasonLaster/codething-mvp",
2111 - },
2112 - headRepositoryOwner: {
2113 - login: "jasonLaster",
2114 - },
1909 + headRepositoryNameWithOwner: "jasonLaster/codething-mvp",
1910 + headRepositoryOwnerLogin: "jasonLaster",
1911 },
2116 - ]),
1912 + ],
1913 ],
1914 },
1915 });
@@ -2129,9 +1925,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1925 state: "open",
1926 updatedAt: "2026-03-10T07:00:00.000Z",
1927 });
2132 - expect(ghCalls).toContain(
2133 - "pr list --head statemachine --state all --limit 100 --json number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
2134 - );
1928 + expect(providerCalls).toContainEqual({
1929 + operation: "listChangeRequests",
1930 + headSelector: "statemachine",
1931 + state: "all",
1932 + limit: 100,
1933 + });
1934 }),
1935 );
1936
@@ -2155,27 +1954,23 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1954 forkDir,
1955 );
1956
2158 - const { manager, ghCalls } = yield* makeManager({
2159 - ghScenario: {
1957 + const { manager, providerCalls } = yield* makeManager({
1958 + providerScenario: {
1959 prListByHeadSelector: {
2161 - main: JSON.stringify([
1960 + main: [
1961 {
1962 number: 777,
1963 title: "Fork PR from main",
1964 url: "https://github.com/pingdotgg/codething-mvp/pull/777",
1965 baseRefName: "main",
1966 headRefName: "main",
2168 - state: "OPEN",
1967 + state: "open",
1968 updatedAt: "2026-03-10T07:00:00Z",
1969 isCrossRepository: true,
2171 - headRepository: {
2172 - nameWithOwner: "contributor/codething-mvp",
2173 - },
2174 - headRepositoryOwner: {
2175 - login: "contributor",
2176 - },
1970 + headRepositoryNameWithOwner: "contributor/codething-mvp",
1971 + headRepositoryOwnerLogin: "contributor",
1972 },
2178 - ]),
1973 + ],
1974 },
1975 },
1976 });
@@ -2191,9 +1986,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1986 state: "open",
1987 updatedAt: "2026-03-10T07:00:00.000Z",
1988 });
2194 - expect(ghCalls).toContain(
2195 - "pr list --head main --state all --limit 100 --json number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
2196 - );
1989 + expect(providerCalls).toContainEqual({
1990 + operation: "listChangeRequests",
1991 + headSelector: "main",
1992 + state: "all",
1993 + limit: 100,
1994 + });
1995 }),
1996 );
1997
@@ -2229,31 +2027,31 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2027 yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
2028 yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
2029
2232 - const { manager, ghCalls } = yield* makeManager({
2233 - ghScenario: {
2030 + const { manager, providerCalls } = yield* makeManager({
2031 + providerScenario: {
2032 prListByHeadSelector: {
2235 - "effect-atom": JSON.stringify([
2033 + "effect-atom": [
2034 {
2035 number: 1618,
2036 title: "Correct PR",
2037 url: "https://github.com/pingdotgg/t3code/pull/1618",
2038 baseRefName: "main",
2039 headRefName: "effect-atom",
2242 - state: "OPEN",
2040 + state: "open",
2041 updatedAt: "2026-03-01T10:00:00Z",
2042 },
2245 - ]),
2246 - "upstream/effect-atom": JSON.stringify([
2043 + ],
2044 + "upstream/effect-atom": [
2045 {
2046 number: 1518,
2047 title: "Wrong PR",
2048 url: "https://github.com/pingdotgg/t3code/pull/1518",
2049 baseRefName: "main",
2050 headRefName: "upstream/effect-atom",
2253 - state: "OPEN",
2051 + state: "open",
2052 updatedAt: "2026-04-01T10:00:00Z",
2053 },
2256 - ]),
2054 + ],
2055 },
2056 },
2057 });
@@ -2269,16 +2067,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2067 state: "open",
2068 updatedAt: "2026-03-01T10:00:00.000Z",
2069 });
2272 - expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
2070 + expect(listedSelectors(providerCalls).includes("upstream/effect-atom")).toBe(false);
2071 + expect(listedSelectors(providerCalls).includes("pingdotgg:upstream/effect-atom")).toBe(
2072 false,
2073 );
2074 expect(
2276 - ghCalls.some((call) => call.includes("pr list --head pingdotgg:upstream/effect-atom ")),
2277 - ).toBe(false);
2278 - expect(
2279 - ghCalls.some((call) =>
2280 - call.includes("pr list --head my-org/upstream:upstream/effect-atom "),
2281 - ),
2075 + listedSelectors(providerCalls).includes("my-org/upstream:upstream/effect-atom"),
2076 ).toBe(false);
2077 }),
2078 );
@@ -2289,20 +2083,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2083 yield* initRepo(repoDir);
2084
2085 const { manager } = yield* makeManager({
2292 - ghScenario: {
2086 + providerScenario: {
2087 prListSequence: [
2294 - JSON.stringify([
2088 + [
2089 {
2090 number: 23,
2091 title: "Merged PR",
2092 url: "https://github.com/pingdotgg/codething-mvp/pull/23",
2093 baseRefName: "feature/status-default-branch-target",
2094 headRefName: "main",
2301 - state: "MERGED",
2095 + state: "merged",
2096 mergedAt: "2026-01-30T10:00:00Z",
2097 updatedAt: "2026-01-30T10:00:00Z",
2098 },
2305 - ]),
2099 + ],
2100 ],
2101 },
2102 });
@@ -2323,21 +2117,21 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2117 yield* runGit(repoDir, ["remote", "set-head", "origin", "main"]);
2118 yield* runGit(repoDir, ["checkout", "-b", "feature/from-main", "origin/main"]);
2119
2326 - const { manager, ghCalls } = yield* makeManager({
2327 - ghScenario: {
2120 + const { manager, providerCalls } = yield* makeManager({
2121 + providerScenario: {
2122 prListSequence: [
2329 - JSON.stringify([
2123 + [
2124 {
2125 number: 54,
2126 title: "Reverse merge from main",
2127 url: "https://github.com/pingdotgg/codething-mvp/pull/54",
2128 baseRefName: "je-filter-list",
2129 headRefName: "main",
2336 - state: "MERGED",
2130 + state: "merged",
2131 mergedAt: "2023-09-28T03:21:10Z",
2132 updatedAt: "2023-09-28T03:21:10Z",
2133 },
2340 - ]),
2134 + ],
2135 ],
2136 },
2137 });
@@ -2345,7 +2139,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2139 const status = yield* manager.status({ cwd: repoDir });
2140 expect(status.refName).toBe("feature/from-main");
2141 expect(status.pr).toBeNull();
2348 - expect(ghCalls.some((call) => call.includes("pr list"))).toBe(false);
2142 + expect(listed(providerCalls).length > 0).toBe(false);
2143 }),
2144 );
2145
@@ -2360,20 +2154,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2154 yield* runGit(repoDir, ["checkout", "-b", "feature/pushed-plain", "origin/main"]);
2155 yield* runGit(repoDir, ["push", "origin", "feature/pushed-plain"]);
2156
2363 - const { manager, ghCalls } = yield* makeManager({
2364 - ghScenario: {
2157 + const { manager, providerCalls } = yield* makeManager({
2158 + providerScenario: {
2159 prListByHeadSelector: {
2366 - "feature/pushed-plain": JSON.stringify([
2160 + "feature/pushed-plain": [
2161 {
2162 number: 88,
2163 title: "Pushed without -u",
2164 url: "https://github.com/pingdotgg/codething-mvp/pull/88",
2165 baseRefName: "main",
2166 headRefName: "feature/pushed-plain",
2373 - state: "OPEN",
2167 + state: "open",
2168 updatedAt: "2026-05-01T10:00:00Z",
2169 },
2376 - ]),
2170 + ],
2171 },
2172 },
2173 });
@@ -2381,7 +2175,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2175 const status = yield* manager.status({ cwd: repoDir });
2176 expect(status.refName).toBe("feature/pushed-plain");
2177 expect(status.pr?.number).toBe(88);
2384 - expect(ghCalls.some((call) => call.includes("--head main"))).toBe(false);
2178 + expect(listedSelectors(providerCalls).includes("main")).toBe(false);
2179 }),
2180 );
2181
@@ -2412,32 +2206,34 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2206 forkDir,
2207 );
2208
2415 - const { manager, ghCalls } = yield* makeManager({
2416 - ghScenario: {
2209 + const { manager, providerCalls } = yield* makeManager({
2210 + providerScenario: {
2211 prListByHeadSelector: {
2418 - "feature/fork-plain": JSON.stringify([
2212 + "feature/fork-plain": [
2213 {
2214 number: 89,
2215 title: "Fork PR pushed without -u",
2216 url: "https://github.com/pingdotgg/codething-mvp/pull/89",
2217 baseRefName: "main",
2218 headRefName: "feature/fork-plain",
2425 - state: "OPEN",
2219 + state: "open",
2220 updatedAt: "2026-05-01T10:00:00Z",
2221 isCrossRepository: true,
2428 - headRepository: { nameWithOwner: "contributor/codething-mvp" },
2429 - headRepositoryOwner: { login: "contributor" },
2222 + headRepositoryNameWithOwner: "contributor/codething-mvp",
2223 + headRepositoryOwnerLogin: "contributor",
2224 },
2431 - ]),
2225 + ],
2226 },
2227 },
2228 });
2229
2230 const status = yield* manager.status({ cwd: repoDir });
2231 expect(status.pr?.number).toBe(89);
2438 - expect(ghCalls.some((call) => call.includes("--head feature/fork-plain"))).toBe(true);
2439 - expect(ghCalls.some((call) => call.includes("--head contributor:"))).toBe(false);
2440 - expect(ghCalls.some((call) => call.includes("--head main"))).toBe(false);
2232 + expect(listedSelectors(providerCalls).includes("feature/fork-plain")).toBe(true);
2233 + expect(
2234 + listedSelectors(providerCalls).some((selector) => selector.startsWith("contributor:")),
2235 + ).toBe(false);
2236 + expect(listedSelectors(providerCalls).includes("main")).toBe(false);
2237 }),
2238 );
2239
@@ -2448,16 +2244,16 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2244 yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
2245
2246 const { manager } = yield* makeManager({
2451 - ghScenario: {
2247 + providerScenario: {
2248 prListSequence: [
2453 - JSON.stringify([
2249 + [
2250 {
2251 number: 45,
2252 title: "Merged PR",
2253 url: "https://github.com/pingdotgg/codething-mvp/pull/45",
2254 baseRefName: "main",
2255 headRefName: "feature/status-open-over-merged",
2460 - state: "MERGED",
2256 + state: "merged",
2257 mergedAt: "2026-01-31T10:00:00Z",
2258 updatedAt: "2026-02-01T10:00:00Z",
2259 },
@@ -2467,10 +2263,10 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2263 url: "https://github.com/pingdotgg/codething-mvp/pull/46",
2264 baseRefName: "main",
2265 headRefName: "feature/status-open-over-merged",
2470 - state: "OPEN",
2266 + state: "open",
2267 updatedAt: "2026-01-30T10:00:00Z",
2268 },
2473 - ]),
2269 + ],
2270 ],
2271 },
2272 });
@@ -2506,10 +2302,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2302 headRefName: "feature/pr-sticky",
2303 };
2304 const { manager } = yield* makeManager({
2509 - ghScenario: {
2510 - prListSequence: [JSON.stringify([existingPr])],
2511 - failWith:
2512 - "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
2305 + providerScenario: {
2306 + prListSequence: [[existingPr]],
2307 + failWith: "The host is signed out.",
2308 failAfterCalls: 1,
2309 },
2310 });
@@ -2543,10 +2338,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2338 headRefName: "feature/pr-retarget",
2339 };
2340 const { manager } = yield* makeManager({
2546 - ghScenario: {
2547 - prListSequence: [JSON.stringify([existingPr])],
2548 - failWith:
2549 - "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
2341 + providerScenario: {
2342 + prListSequence: [[existingPr]],
2343 + failWith: "The host is signed out.",
2344 failAfterCalls: 1,
2345 },
2346 });
@@ -2974,11 +2768,11 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2768 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2769 NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
2770
2977 - const { manager, ghCalls } = yield* makeManager({
2978 - ghScenario: {
2771 + const { manager, providerCalls } = yield* makeManager({
2772 + providerScenario: {
2773 prListSequence: [
2980 - "[]",
2981 - JSON.stringify([
2774 + [],
2775 + [
2776 {
2777 number: 77,
2778 title: "Add no-upstream PR flow",
@@ -2986,7 +2780,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2780 baseRefName: "main",
2781 headRefName: "feature/no-upstream-pr",
2782 },
2989 - ]),
2783 + ],
2784 ],
2785 },
2786 });
@@ -3007,8 +2801,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2801 ),
2802 ).toBe("origin/feature/no-upstream-pr");
2803 expect(
3010 - ghCalls.some((call) =>
3011 - call.includes("pr create --base main --head feature/no-upstream-pr"),
2804 + created(providerCalls).some(
2805 + (call) => call.baseRefName === "main" && call.headSelector === "feature/no-upstream-pr",
2806 ),
2807 ).toBe(true);
2808 }),
@@ -3073,7 +2867,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2867 );
2868
2869 const recorded: Array<{ branch: string; baseBranch: string }> = [];
3076 - const { service } = createGitHubProviderWithFakeGh();
2870 + const { service } = createFakeSourceControlProvider();
2871 const { manager } = yield* makeManager({
2872 sourceControlProvider: {
2873 ...service,
@@ -3109,14 +2903,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2903 yield* runGit(repoDir, ["add", "master-default.txt"]);
2904 yield* runGit(repoDir, ["commit", "-m", "Master default"]);
2905
3112 - const { manager, ghCalls } = yield* makeManager({
3113 - ghScenario: {
2906 + const { manager, providerCalls } = yield* makeManager({
2907 + providerScenario: {
2908 // Mirrors a provider that cannot report a default branch, as the Azure
2909 // DevOps CLI does when it cannot detect the repository.
2910 defaultBranch: "",
2911 prListSequence: [
3118 - "[]",
3119 - JSON.stringify([
2912 + [],
2913 + [
2914 {
2915 number: 505,
2916 title: "Master default",
@@ -3124,7 +2918,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2918 baseRefName: "master",
2919 headRefName: "feature/master-default",
2920 },
3127 - ]),
2921 + ],
2922 ],
2923 },
2924 });
@@ -3136,8 +2930,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2930
2931 expect(result.pr.status).toBe("created");
2932 expect(
3139 - ghCalls.some((call) =>
3140 - call.includes("pr create --base master --head feature/master-default"),
2933 + created(providerCalls).some(
2934 + (call) => call.baseRefName === "master" && call.headSelector === "feature/master-default",
2935 ),
2936 ).toBe(true);
2937 }),
@@ -3152,10 +2946,10 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2946 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2947 yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
2948
3155 - const { manager, ghCalls } = yield* makeManager({
3156 - ghScenario: {
2949 + const { manager, providerCalls } = yield* makeManager({
2950 + providerScenario: {
2951 prListSequence: [
3158 - JSON.stringify([
2952 + [
2953 {
2954 number: 42,
2955 title: "Existing PR",
@@ -3163,7 +2957,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2957 baseRefName: "main",
2958 headRefName: "feature/existing-pr",
2959 },
3166 - ]),
2960 + ],
2961 ],
2962 },
2963 });
@@ -3184,41 +2978,34 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
2978 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
2979 },
2980 });
3187 - expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
2981 + expect(providerCalls.some((call) => call.operation === "getChangeRequest")).toBe(false);
2982 }),
2983 );
2984
3191 - it.effect("matches mounted Forgejo heads without confusing forks sharing a branch", () =>
3192 - Effect.gen(function* () {
2985 + it.effect("matches a host's mounted heads without confusing forks sharing a branch", () =>
2986 + Effect.sync(() => {
2987 + // A host that serves repositories below a mount names them without it.
2988 + const repositoryNameFromRemoteUrl = (url: string) =>
2989 + url.replace(/^https:\/\/[^/]+\/forgejo\//u, "").replace(/\.git$/u, "");
2990 for (const owner of ["maria", "reviewer"]) {
3194 - const mapped = toForgejoChangeRequest(
3195 - yield* decodeForgejoPullRequest({
3196 - number: 42,
3197 - title: "Greeting",
3198 - html_url: "https://forgejo.example/forgejo/maria/project/pulls/42",
3199 - state: "open",
3200 - merged: false,
3201 - base: {
3202 - ref: "main",
3203 - sha: "base",
3204 - repo: { full_name: "maria/project", owner: { login: "maria" } },
3205 - },
3206 - head: {
3207 - ref: "greeting",
3208 - sha: "head",
3209 - repo: { full_name: `${owner}/project`, owner: { login: owner } },
3210 - },
3211 - }),
3212 - );
2991 const pr = {
3214 - ...mapped,
3215 - isDraft: mapped.isDraft ?? false,
3216 - closedAt: mapped.closedAt ?? null,
3217 - mergedAt: mapped.mergedAt ?? null,
2992 + number: 42,
2993 + title: "Greeting",
2994 + url: "https://forgejo.example/forgejo/maria/project/pulls/42",
2995 + baseRefName: "main",
2996 + headRefName: "greeting",
2997 + state: "open" as const,
2998 + isDraft: false,
2999 + closedAt: null,
3000 + mergedAt: null,
3001 + updatedAt: Option.none(),
3002 + isCrossRepository: owner !== "maria",
3003 + headRepositoryNameWithOwner: `${owner}/project`,
3004 + headRepositoryOwnerLogin: owner,
3005 };
3006 const repository = GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
3007 `https://forgejo.example/forgejo/${owner}/project.git`,
3221 - { repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
3008 + { repositoryNameFromRemoteUrl },
3009 );
3010 expect(repository).toBe(`${owner}/project`);
3011 const context = {
@@ -3236,12 +3023,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3023 }),
3024 ).toBe(false);
3025 }
3239 - expect(
3240 - GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
3241 - "git@forgejo.example:maria/project.git",
3242 - { repositoryNameFromRemoteUrl: ForgejoSourceControlProvider.repositoryNameFromRemoteUrl },
3243 - ),
3244 - ).toBe("maria/project");
3026 expect(
3027 GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(
3028 "https://gitlab.example/group/maria/project.git",
@@ -3499,66 +3280,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3280 }),
3281 );
3282
3502 - it.effect("ignores unavailable or non-regular GitLab default templates", () =>
3503 - Effect.gen(function* () {
3504 - const repoDir = yield* makeTempDir("t3code-git-manager-");
3505 - yield* initRepo(repoDir);
3506 - const provider = yield* makeGitLabTemplateProvider();
3507 - const readTemplate = (treeish = "HEAD") =>
3508 - provider.readChangeRequestTemplate!({ cwd: repoDir, treeish });
3509 - expect(yield* readTemplate()).toEqual(Option.none());
3510 -
3511 - const templateDir = NodePath.join(repoDir, ".gitlab", "merge_request_templates");
3512 - const templatePath = ".gitlab/merge_request_templates/Default.md";
3513 - NodeFS.mkdirSync(templateDir, { recursive: true });
3514 - NodeFS.writeFileSync(NodePath.join(templateDir, "Bugfix.md"), "Not the default");
3515 - yield* runGit(repoDir, ["add", ".gitlab"]);
3516 - yield* runGit(repoDir, ["commit", "-m", "Add a selectable template"]);
3517 - expect(yield* readTemplate()).toEqual(Option.none());
3518 -
3519 - NodeFS.writeFileSync(NodePath.join(repoDir, templatePath), " \n\n");
3520 - yield* runGit(repoDir, ["add", ".gitlab"]);
3521 - yield* runGit(repoDir, ["commit", "-m", "Add a blank default"]);
3522 - expect(yield* readTemplate()).toEqual(Option.none());
3523 -
3524 - // Index modes exercise committed symlinks and submodules even on hosts without symlinks.
3525 - const { stdout: blob } = yield* runGit(repoDir, ["rev-parse", "HEAD:README.md"]);
3526 - yield* runGit(repoDir, ["update-index", "--cacheinfo", "120000", blob.trim(), templatePath]);
3527 - yield* runGit(repoDir, ["commit", "-m", "Replace default with a symlink"]);
3528 - expect(yield* readTemplate()).toEqual(Option.none());
3529 -
3530 - const { stdout: commit } = yield* runGit(repoDir, ["rev-parse", "HEAD"]);
3531 - yield* runGit(repoDir, [
3532 - "update-index",
3533 - "--cacheinfo",
3534 - "160000",
3535 - commit.trim(),
3536 - templatePath,
3537 - ]);
3538 - yield* runGit(repoDir, ["commit", "-m", "Replace default with a submodule"]);
3539 - expect(yield* readTemplate()).toEqual(Option.none());
3540 - expect(yield* readTemplate("missing-base")).toEqual(Option.none());
3541 - }),
3542 - );
3543 -
3544 - it.effect("bounds GitLab template content and marks truncation", () =>
3545 - Effect.gen(function* () {
3546 - const repoDir = yield* makeTempDir("t3code-git-manager-");
3547 - yield* initRepo(repoDir);
3548 - const templateDir = NodePath.join(repoDir, ".gitlab", "merge_request_templates");
3549 - const prefix = "a".repeat(8_000);
3550 - NodeFS.mkdirSync(templateDir, { recursive: true });
3551 - NodeFS.writeFileSync(NodePath.join(templateDir, "Default.md"), prefix + "EXCLUDED_SUFFIX");
3552 - yield* runGit(repoDir, ["add", ".gitlab"]);
3553 - yield* runGit(repoDir, ["commit", "-m", "Add a large template"]);
3554 - const provider = yield* makeGitLabTemplateProvider();
3555 -
3556 - expect(yield* provider.readChangeRequestTemplate!({ cwd: repoDir, treeish: "HEAD" })).toEqual(
3557 - Option.some(prefix + "\n\n[truncated]"),
3558 - );
3559 - }),
3560 - );
3561 -
3283 it.effect.each(["commit", "short-commit", "tag", "revision"] as const)(
3284 "creates a PR against the default branch with a legacy %s base setting",
3285 (kind) =>
@@ -3587,8 +3308,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3308 yield* runGit(repoDir, ["push", "-u", "origin", "feature/legacy-base"]);
3309 let generatedBase = "";
3310 let generatedSummary = "";
3590 - const { manager, ghCalls } = yield* makeManager({
3591 - ghScenario: { defaultBranch: "trunk", prListSequence: ["[]", "[]"] },
3311 + const { manager, providerCalls } = yield* makeManager({
3312 + providerScenario: { defaultBranch: "trunk", prListSequence: [[], []] },
3313 textGeneration: {
3314 generatePrContent: (input) => {
3315 generatedBase = input.baseBranch;
@@ -3604,8 +3325,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3325 expect(generatedBase).toBe("trunk");
3326 expect(generatedSummary).toContain("Feature commit");
3327 expect(
3607 - ghCalls.some((call) =>
3608 - call.includes("pr create --base trunk --head feature/legacy-base"),
3328 + created(providerCalls).some(
3329 + (call) => call.baseRefName === "trunk" && call.headSelector === "feature/legacy-base",
3330 ),
3331 ).toBe(true);
3332 }),
@@ -3658,8 +3379,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3379 yield* runGit(worktreePath, ["push", "-u", "origin", "feature/from-upstream"]);
3380
3381 const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
3661 - const { manager, ghCalls } = yield* makeManager({
3662 - ghScenario: { prListSequence: ["[]", "[]"] },
3382 + const { manager, providerCalls } = yield* makeManager({
3383 + providerScenario: { prListSequence: [[], []] },
3384 textGeneration: {
3385 generatePrContent: (input) => {
3386 generatedInputs.push(input);
@@ -3683,8 +3404,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3404 expect.soft(generated.diffPatch).not.toContain("fork-only work");
3405 expect.soft(generated.changeRequestTemplate).toBe("Upstream template");
3406 expect(
3686 - ghCalls.some((call) =>
3687 - call.includes("pr create --base release --head feature/from-upstream"),
3407 + created(providerCalls).some(
3408 + (call) => call.baseRefName === "release" && call.headSelector === "feature/from-upstream",
3409 ),
3410 ).toBe(true);
3411 }),
@@ -3738,8 +3459,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3459 yield* runGit(worktreePath, ["push", "-u", "origin", "feature/from-local"]);
3460
3461 const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
3741 - const { manager, ghCalls } = yield* makeManager({
3742 - ghScenario: { prListSequence: ["[]", "[]", "[]", "[]"] },
3462 + const { manager, providerCalls } = yield* makeManager({
3463 + providerScenario: { prListSequence: [[], [], [], []] },
3464 textGeneration: {
3465 generatePrContent: (input) => {
3466 generatedInputs.push(input);
@@ -3775,14 +3496,10 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3496 expect.soft(generated.diffPatch).not.toContain("pull_request_template.md");
3497 expect.soft(generated.changeRequestTemplate).toBe("Local branch template");
3498 }
3778 - expect
3779 - .soft(ghCalls.filter((call) => call.startsWith("pr create ")))
3780 - .toEqual([
3781 - expect.stringContaining("pr create --base upstream/release --head feature/from-local"),
3782 - expect.stringContaining(
3783 - "pr create --base upstream/release --head feature/legacy-local-base",
3784 - ),
3785 - ]);
3499 + expect.soft(created(providerCalls)).toEqual([
3500 + { baseRefName: "upstream/release", headSelector: "feature/from-local" },
3501 + { baseRefName: "upstream/release", headSelector: "feature/legacy-local-base" },
3502 + ]);
3503 }),
3504 );
3505
@@ -3845,9 +3562,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3562 yield* runGit(worktreePath, ["push", "-u", "origin", "feature/remote-base"]);
3563
3564 const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
3848 - const { manager, ghCalls } = yield* makeManager({
3849 - ghScenario: {
3850 - prListSequence: ["[]", "[]"],
3565 + const { manager, providerCalls } = yield* makeManager({
3566 + providerScenario: {
3567 + prListSequence: [[], []],
3568 },
3569 textGeneration: {
3570 generatePrContent: (input) => {
@@ -3875,8 +3592,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3592 expect.soft(generated.diffPatch).not.toContain("pull_request_template.md");
3593 expect.soft(generated.changeRequestTemplate).toBe("Updated main template");
3594 expect(
3878 - ghCalls.some((call) =>
3879 - call.includes(`pr create --base ${baseBranch} --head feature/remote-base`),
3595 + created(providerCalls).some(
3596 + (call) =>
3597 + call.baseRefName === baseBranch && call.headSelector === "feature/remote-base",
3598 ),
3599 ).toBe(true);
3600 }),
@@ -3896,37 +3614,33 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3614 yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
3615 yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
3616
3899 - const { manager, ghCalls } = yield* makeManager({
3900 - ghScenario: {
3617 + const { manager, providerCalls } = yield* makeManager({
3618 + providerScenario: {
3619 prListSequence: [
3902 - JSON.stringify([
3620 + [
3621 {
3622 number: 1661,
3623 title: "Fork PR with same branch name",
3624 url: "https://github.com/pingdotgg/t3code/pull/1661",
3625 baseRefName: "main",
3626 headRefName: "feature/no-fork-match",
3909 - state: "OPEN",
3627 + state: "open",
3628 isCrossRepository: true,
3911 - headRepository: {
3912 - nameWithOwner: "lnieuwenhuis/t3code",
3913 - },
3914 - headRepositoryOwner: {
3915 - login: "lnieuwenhuis",
3916 - },
3629 + headRepositoryNameWithOwner: "lnieuwenhuis/t3code",
3630 + headRepositoryOwnerLogin: "lnieuwenhuis",
3631 },
3918 - ]),
3919 - JSON.stringify([
3632 + ],
3633 + [
3634 {
3635 number: 188,
3636 title: "Add stacked git actions",
3637 url: "https://github.com/pingdotgg/codething-mvp/pull/188",
3638 baseRefName: "main",
3639 headRefName: "feature/no-fork-match",
3926 - state: "OPEN",
3640 + state: "open",
3641 isCrossRepository: false,
3642 },
3929 - ]),
3643 + ],
3644 ],
3645 },
3646 });
@@ -3947,8 +3661,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3661 },
3662 });
3663 expect(
3950 - ghCalls.some((call) =>
3951 - call.includes("pr create --base main --head feature/no-fork-match"),
3664 + created(providerCalls).some(
3665 + (call) => call.baseRefName === "main" && call.headSelector === "feature/no-fork-match",
3666 ),
3667 ).toBe(true);
3668 }),
@@ -3981,28 +3695,24 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3695 forkDir,
3696 );
3697
3984 - const { manager, ghCalls } = yield* makeManager({
3985 - ghScenario: {
3698 + const { manager, providerCalls } = yield* makeManager({
3699 + providerScenario: {
3700 prListSequenceByHeadSelector: {
3701 statemachine: [
3988 - JSON.stringify([]),
3989 - JSON.stringify([
3702 + [],
3703 + [
3704 {
3705 number: 188,
3706 title: "Add stacked git actions",
3707 url: "https://github.com/pingdotgg/codething-mvp/pull/188",
3708 baseRefName: "main",
3709 headRefName: "statemachine",
3996 - state: "OPEN",
3710 + state: "open",
3711 isCrossRepository: true,
3998 - headRepository: {
3999 - nameWithOwner: "octocat/codething-mvp",
4000 - },
4001 - headRepositoryOwner: {
4002 - login: "octocat",
4003 - },
3712 + headRepositoryNameWithOwner: "octocat/codething-mvp",
3713 + headRepositoryOwnerLogin: "octocat",
3714 },
4005 - ]),
3715 + ],
3716 ],
3717 },
3718 },
@@ -4016,11 +3726,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3726 expect(result.pr.status).toBe("created");
3727 expect(result.pr.number).toBe(188);
3728 expect(
4019 - ghCalls.some((call) => call.includes("pr create --base main --head octocat:statemachine")),
3729 + created(providerCalls).some(
3730 + (call) => call.baseRefName === "main" && call.headSelector === "octocat:statemachine",
3731 + ),
3732 ).toBe(true);
3733 expect(
4022 - ghCalls.some((call) =>
4023 - call.includes("pr create --base statemachine --head octocat:statemachine"),
3734 + created(providerCalls).some(
3735 + (call) =>
3736 + call.baseRefName === "statemachine" && call.headSelector === "octocat:statemachine",
3737 ),
3738 ).toBe(false);
3739 }),
@@ -4065,9 +3778,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3778 yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/91/head"]);
3779 yield* runGit(repoDir, ["reset", "--hard", firstCommit]);
3780 const headSha = reportedHead(pullHead);
4068 - const { manager, ghCalls } = yield* makeManager({
3781 + const { manager, providerCalls } = yield* makeManager({
3782 ...(gitSpawnGate ? { gitSpawnGate } : {}),
4070 - ghScenario: {
3783 + providerScenario: {
3784 pullRequest: {
3785 number: 91,
3786 title: "Safe checkout PR",
@@ -4080,7 +3793,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3793 syncCheckoutWithPullHead,
3794 },
3795 });
4083 - return { repoDir, manager, ghCalls, firstCommit, pullHead };
3796 + return { repoDir, manager, providerCalls, firstCommit, pullHead };
3797 });
3798
3799 it.effect.each(["switch", "create-and-switch", "feature-branch"] as const)(
@@ -4206,7 +3919,8 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3919 "local PR checkout refuses and preserves tracked edits (staged: %s)",
3920 (staged) =>
3921 Effect.gen(function* () {
4209 - const { repoDir, manager, ghCalls, firstCommit } = yield* setUpLocalCheckoutPullRequest();
3922 + const { repoDir, manager, providerCalls, firstCommit } =
3923 + yield* setUpLocalCheckoutPullRequest();
3924 NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "my unsaved edit\n");
3925 if (staged) {
3926 yield* runGit(repoDir, ["add", "README.md"]);
@@ -4225,13 +3939,15 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3939 );
3940 expect((yield* runGit(repoDir, ["status", "--porcelain"])).stdout).toBe(beforeStatus);
3941 expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim()).toBe(firstCommit);
4228 - expect(ghCalls.some((call) => call.startsWith("pr checkout"))).toBe(false);
3942 + expect(providerCalls.some((call) => call.operation === "checkoutChangeRequest")).toBe(
3943 + false,
3944 + );
3945 }),
3946 );
3947
3948 it.effect("local PR checkout refuses a diverged branch and keeps its extra commit", () =>
3949 Effect.gen(function* () {
4234 - const { repoDir, manager, ghCalls } = yield* setUpLocalCheckoutPullRequest();
3950 + const { repoDir, manager, providerCalls } = yield* setUpLocalCheckoutPullRequest();
3951 NodeFS.writeFileSync(NodePath.join(repoDir, "mine.txt"), "mine\n");
3952 yield* runGit(repoDir, ["add", "mine.txt"]);
3953 yield* runGit(repoDir, ["commit", "-m", "My unpublished commit"]);
@@ -4244,9 +3960,13 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3960 mode: "local",
3961 }).pipe(Effect.flip);
3962
4247 - // gh's fast-forward-only update fails rather than resetting the branch.
4248 - expect(error.message).toContain("GitHub request failed");
4249 - expect(ghCalls).toContain("pr checkout 91");
3963 + // The host's fast-forward-only update fails rather than resetting the branch.
3964 + expect(error.message).toContain("Host checkout failed");
3965 + expect(providerCalls).toContainEqual({
3966 + operation: "checkoutChangeRequest",
3967 + reference: "91",
3968 + force: false,
3969 + });
3970 expect((yield* runGit(repoDir, ["rev-parse", "feature/pr-safe"])).stdout.trim()).toBe(
3971 localCommit,
3972 );
@@ -4374,7 +4094,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4094 ]);
4095
4096 const { manager } = yield* makeManager({
4377 - ghScenario: {
4097 + providerScenario: {
4098 pullRequest: {
4099 number: 65,
4100 title: "Local upstream PR",
@@ -4432,7 +4152,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4152 ]);
4153
4154 const { manager } = yield* makeManager({
4435 - ghScenario: {
4155 + providerScenario: {
4156 pullRequest: {
4157 number: 66,
4158 title: "Local upstream PR without repo metadata",
@@ -4478,7 +4198,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4198 yield* runGit(repoDir, ["config", `url.${remoteDir}.insteadOf`, remoteUrl]);
4199
4200 const { manager: otherRepositoryManager } = yield* makeManager({
4481 - ghScenario: {
4201 + providerScenario: {
4202 pullRequest: {
4203 number: 79,
4204 title: "Another repository's PR",
@@ -4498,7 +4218,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4218 }),
4219 );
4220 const { manager: mergedManager } = yield* makeManager({
4501 - ghScenario: {
4221 + providerScenario: {
4222 pullRequest: {
4223 number: 77,
4224 title: "Merged PR",
@@ -4521,7 +4241,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4241 expect(localBranches).not.toContain("feature/no-pull-ref");
4242
4243 const { manager } = yield* makeManager({
4524 - ghScenario: {
4244 + providerScenario: {
4245 pullRequest: {
4246 number: 78,
4247 title: "Azure DevOps PR",
@@ -4572,7 +4292,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4292 yield* runGit(repoDir, ["checkout", "main"]);
4293
4294 const { manager } = yield* makeManager({
4575 - ghScenario: {
4295 + providerScenario: {
4296 pullRequest: {
4297 number: 81,
4298 title: "Fork PR",
@@ -4646,7 +4366,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4366 yield* runGit(repoDir, ["checkout", "main"]);
4367
4368 const { manager } = yield* makeManager({
4649 - ghScenario: {
4369 + providerScenario: {
4370 pullRequest: {
4371 number: 84,
4372 title: "Reused stale PR",
@@ -4712,7 +4432,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4432 yield* runGit(repoDir, ["checkout", "main"]);
4433
4434 const { manager } = yield* makeManager({
4715 - ghScenario: {
4435 + providerScenario: {
4436 pullRequest: {
4437 number: 86,
4438 title: "Force-pushed PR",
@@ -4791,7 +4511,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4511
4512 const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
4513 const { manager } = yield* makeManager({
4794 - ghScenario: {
4514 + providerScenario: {
4515 pullRequest: {
4516 number: 87,
4517 title: "Local commit PR",
@@ -4866,7 +4586,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4586
4587 const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
4588 const { manager } = yield* makeManager({
4869 - ghScenario: {
4589 + providerScenario: {
4590 pullRequest: {
4591 number: 89,
4592 title: "Dirty worktree PR",
@@ -4942,7 +4662,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4662 expect(page.nextCursor !== null).toBe(padding > 0);
4663 expect(page.refs.some((ref) => ref.name === localBranch)).toBe(padding === 0);
4664 const { manager } = yield* makeManager({
4945 - ghScenario: {
4665 + providerScenario: {
4666 repositoryCloneUrls: forkDir
4667 ? { "contributor/codething-mvp": { url: forkDir, sshUrl: forkDir } }
4668 : {},
@@ -4997,7 +4717,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4717 yield* runGit(repoDir, ["branch", "-D", "feature/pr-ref-only"]);
4718
4719 const { manager } = yield* makeManager({
5000 - ghScenario: {
4720 + providerScenario: {
4721 pullRequest: {
4722 number: 90,
4723 title: "Pull ref only PR",
@@ -5058,18 +4778,18 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4778 yield* runGit(repoDir, ["checkout", "main"]);
4779 yield* runGit(repoDir, ["branch", "-D", "feature/mr-ref-only"]);
4780
5061 - const { service } = createGitHubProviderWithFakeGh({
5062 - pullRequest: {
5063 - number: 93,
5064 - title: "Merge request ref only",
5065 - url: "https://gitlab.com/pingdotgg/codething-mvp/-/merge_requests/93",
5066 - baseRefName: "main",
5067 - headRefName: "feature/mr-ref-only",
5068 - state: "open",
5069 - },
5070 - });
4781 const { manager } = yield* makeManager({
5072 - sourceControlProvider: { ...service, kind: SourceControlProviderKind.make("gitlab") },
4782 + providerScenario: {
4783 + kind: "gitlab",
4784 + pullRequest: {
4785 + number: 93,
4786 + title: "Merge request ref only",
4787 + url: "https://gitlab.com/pingdotgg/codething-mvp/-/merge_requests/93",
4788 + baseRefName: "main",
4789 + headRefName: "feature/mr-ref-only",
4790 + state: "open",
4791 + },
4792 + },
4793 });
4794
4795 const result = yield* preparePullRequestThread(manager, {
@@ -5117,7 +4837,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4837
4838 const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
4839 const { manager } = yield* makeManager({
5120 - ghScenario: {
4840 + providerScenario: {
4841 pullRequest: {
4842 number: 94,
4843 title: "Fork main collision PR",
@@ -5219,7 +4939,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4939 yield* runGit(worktreePath, ["branch", "--unset-upstream"], true);
4940
4941 const { manager } = yield* makeManager({
5222 - ghScenario: {
4942 + providerScenario: {
4943 pullRequest: {
4944 number: 83,
4945 title: "Reused Fork PR",
@@ -5275,7 +4995,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4995 yield* runGit(repoDir, ["checkout", "main"]);
4996
4997 const { manager } = yield* makeManager({
5278 - ghScenario: {
4998 + providerScenario: {
4999 pullRequest: {
5000 number: 184,
5001 title: "Setup failure PR",
@@ -5318,7 +5038,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5038 yield* runGit(repoDir, ["checkout", "-b", "feature/pr-root-only"]);
5039
5040 const { manager } = yield* makeManager({
5321 - ghScenario: {
5041 + providerScenario: {
5042 pullRequest: {
5043 number: 79,
5044 title: "Root-only PR",
@@ -5370,20 +5090,20 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5090 return Effect.succeed({ title: "PR only branch", body: "Committed feature work" });
5091 },
5092 },
5373 - ghScenario: {
5093 + providerScenario: {
5094 prListSequence: [
5375 - JSON.stringify([]),
5376 - JSON.stringify([
5095 + [],
5096 + [
5097 {
5098 number: 201,
5099 title: "PR only branch",
5100 url: "https://github.com/pingdotgg/codething-mvp/pull/201",
5101 baseRefName: "main",
5102 headRefName: "feature/pr-only-follow-up",
5383 - state: "OPEN",
5103 + state: "open",
5104 isCrossRepository: false,
5105 },
5386 - ]),
5106 + ],
5107 ],
5108 },
5109 });
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
-18
@@ -266,24 +266,6 @@ describe("pull request toolkit handlers", () => {
266 }),
267 );
268
269 - it.effect("links a GitCafe pull request by its canonical /pull/ URL", () =>
270 - Effect.gen(function* () {
271 - const harness = yield* makeHarness();
272 - const result = yield* harness.call("link_pull_request", {
273 - url: "https://git.cafe/pingdotgg/t3code/pull/23897",
274 - });
275 - expect(result).toMatchObject({
276 - host: "git.cafe",
277 - repository: "pingdotgg/t3code",
278 - number: 23897,
279 - alreadyLinked: false,
280 - });
281 - expect(yield* Ref.get(harness.commands)).toMatchObject([
282 - { type: "thread.pull-request.link", host: "git.cafe", number: 23897 },
283 - ]);
284 - }),
285 - );
286 -
269 it.effect("watching an unlinked pull request links it first", () =>
270 Effect.gen(function* () {
271 const harness = yield* makeHarness();
apps/server/src/orchestration-v2/pullRequestWatch.forgejoComments.test.ts deleted
-94
@@ -1,94 +0,0 @@
1 -import type { ThreadPullRequestWatch } from "@t3tools/contracts";
2 -import { assert, describe, it } from "@effect/vitest";
3 -import * as Schema from "effect/Schema";
4 -import {
5 - ForgejoComment,
6 - forgejoComment,
7 -} from "@t3tools/source-control-forgejo/server/forgejoPullRequestJson";
8 -
9 -import { evaluatePullRequestWatch as evaluate } from "./pullRequestWatch.ts";
10 -
11 -// These cases read the head once or at one moment, so the no-checks notice never comes due.
12 -const evaluatePullRequestWatch = (
13 - ...args: Parameters<typeof evaluate> extends [...infer Head, number] ? Head : never
14 -) => evaluate(...args, 0);
15 -
16 -const decodeForgejoComment = Schema.decodeSync(ForgejoComment);
17 -
18 -describe("Forgejo comment watch boundary", () => {
19 - const createdAt = "2026-10-10T19:52:40Z";
20 - const editedAt = "2026-10-10T20:04:50Z";
21 - const seen = {
22 - startedAt: "2026-10-02T12:00:00.000Z",
23 - headSha: "aaaaaaaaaa",
24 - failedChecks: [],
25 - passed: false,
26 - passedChecks: [],
27 - remarksThrough: "2026-10-10T19:52:40.000Z",
28 - remarkIds: ["29061"],
29 - conflicting: false,
30 - wakes: 2,
31 - } satisfies ThreadPullRequestWatch;
32 - const finalDetail = {
33 - capabilities: {
34 - diff: true,
35 - comment: true,
36 - actions: [],
37 - mergeMethods: [],
38 - search: false,
39 - review: { inlineComment: true, reply: false, resolve: false, verdicts: [] },
40 - reviewers: { request: true, listCandidates: true },
41 - },
42 - headSha: seen.headSha,
43 - checks: [],
44 - mergeability: "mergeable",
45 - viewer: "agent-user",
46 - author: { login: "agent-user", name: null, avatarUrl: null },
47 - } satisfies Parameters<typeof evaluatePullRequestWatch>[1];
48 - const decodedComment = (updatedAt: string | null | undefined) =>
49 - forgejoComment(
50 - decodeForgejoComment({
51 - id: 29061,
52 - body: "Performance: five rounds complete",
53 - user: { login: "forgejo-actions" },
54 - created_at: createdAt,
55 - ...(updatedAt === undefined ? {} : { updated_at: updatedAt }),
56 - }),
57 - );
58 -
59 - it.each([undefined, null, createdAt, "2026-10-10T19:52:40.000Z"])(
60 - "does not wake for an unchanged comment with updated_at %s",
61 - (updatedAt) => {
62 - const comment = decodedComment(updatedAt);
63 - assert.isUndefined(comment.editedAt);
64 - assert.deepEqual(evaluatePullRequestWatch(seen, finalDetail, [comment]).changes, []);
65 - },
66 - );
67 -
68 - it("wakes once for the edit of an already-seen benchmark comment", () => {
69 - const finalComment = decodedComment(editedAt);
70 - assert.strictEqual(finalComment.editedAt, "2026-10-10T20:04:50.000Z");
71 - assert.isUndefined(decodedComment(createdAt).editedAt);
72 - const completed = evaluatePullRequestWatch(seen, finalDetail, [finalComment]);
73 - assert.deepEqual(completed.changes, [{ kind: "remarks", remarks: [finalComment] }]);
74 - assert.strictEqual(completed.next.remarksThrough, "2026-10-10T20:04:50.000Z");
75 - assert.deepEqual(
76 - evaluatePullRequestWatch(completed.next, finalDetail, [finalComment]).changes,
77 - [],
78 - );
79 - assert.deepEqual(
80 - evaluatePullRequestWatch(seen, finalDetail, [decodedComment(createdAt)]).changes,
81 - [],
82 - );
83 - const secondEdit = decodedComment("2026-10-10T20:05:50Z");
84 - const second = evaluatePullRequestWatch(completed.next, finalDetail, [secondEdit]);
85 - assert.deepEqual(second.changes, [{ kind: "remarks", remarks: [secondEdit] }]);
86 - assert.deepEqual(evaluatePullRequestWatch(second.next, finalDetail, [secondEdit]).changes, []);
87 - assert.deepEqual(
88 - evaluatePullRequestWatch(seen, finalDetail, [
89 - { ...finalComment, author: { login: "agent-user", name: null, avatarUrl: null } },
90 - ]).changes,
91 - [],
92 - );
93 - });
94 -});
apps/server/src/orchestration-v2/pullRequestWatch.test.ts
+22
@@ -283,6 +283,28 @@ describe("evaluatePullRequestWatch", () => {
283 ]);
284 });
285
286 + it("wakes once per edit of a remark seen at the watermark, never for the agent's own", () => {
287 + const seen = remark("ci-bot", "2026-10-10T19:52:40.000Z");
288 + const watching = watch({
289 + headSha: "aaaaaaaaaa",
290 + remarksThrough: seen.createdAt,
291 + remarkIds: [seen.id],
292 + wakes: 2,
293 + });
294 + assert.deepEqual(evaluatePullRequestWatch(watching, detail(), [seen]).changes, []);
295 + const edited = { ...seen, editedAt: "2026-10-10T20:04:50.000Z" };
296 + const first = evaluatePullRequestWatch(watching, detail(), [edited]);
297 + assert.deepEqual(first.changes, [{ kind: "remarks", remarks: [edited] }]);
298 + assert.strictEqual(first.next.remarksThrough, edited.editedAt);
299 + assert.deepEqual(evaluatePullRequestWatch(first.next, detail(), [edited]).changes, []);
300 + const again = { ...seen, editedAt: "2026-10-10T20:05:50.000Z" };
301 + const second = evaluatePullRequestWatch(first.next, detail(), [again]);
302 + assert.deepEqual(second.changes, [{ kind: "remarks", remarks: [again] }]);
303 + assert.deepEqual(evaluatePullRequestWatch(second.next, detail(), [again]).changes, []);
304 + const own = { ...edited, author: { login: "agent-user", name: null, avatarUrl: null } };
305 + assert.deepEqual(evaluatePullRequestWatch(watching, detail(), [own]).changes, []);
306 + });
307 +
308 it("does not treat a failed check read as a rerun", () => {
309 const failed = detail({ checks: [check("lint", "failure")] });
310 const reported = evaluatePullRequestWatch(watch(), failed, noRemarks);
apps/server/src/pullRequest/PullRequestService.test.ts
+279 -434
@@ -1,6 +1,5 @@
1 -import { SourceControlProviderKind, VcsProcessExitError } from "@t3tools/contracts";
1 +import { SourceControlProviderKind } from "@t3tools/contracts";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
3 import * as KeyValueStore from "effect/persistence/KeyValueStore";
4 import { assert, expect, it } from "@effect/vitest";
5 import * as Cause from "effect/Cause";
@@ -10,9 +9,7 @@ import * as Exit from "effect/Exit";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
13 -import * as Redacted from "effect/Redacted";
12 import * as Stream from "effect/Stream";
15 -import { HttpClient, HttpClientResponse } from "effect/http";
13 import * as TestClock from "effect/testing/TestClock";
14 import type {
15 OrchestrationProjectShell,
@@ -31,20 +28,7 @@ import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.t
28 import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
30 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
34 -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
35 -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
36 -import * as GitLabPullRequestProvider from "@t3tools/source-control-gitlab/server/GitLabPullRequestProvider";
37 -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
38 -import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
39 -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
40 -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
41 -import * as BitbucketPullRequestProvider from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestProvider";
42 -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
43 -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
44 -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
45 -import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider";
46 -import * as GitHubQuota from "@t3tools/source-control-github/server/GitHubQuota";
47 -import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
31 +import { fakePullRequestProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver";
32 import {
33 PullRequestProviderError,
34 type ProviderChangeRequest,
@@ -137,7 +121,7 @@ it.effect("does not wait for an in-flight detail read to display a preview", ()
121 const service = yield* makeService({
122 projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })],
123 providers: [
140 - fakeProvider(SourceControlProviderKind.make("github"), {
124 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
125 getChangeRequest: () =>
126 Deferred.succeed(detailStarted, undefined).pipe(
127 Effect.andThen(Deferred.await(releaseDetail)),
@@ -181,53 +165,10 @@ const FULL_REVIEW: PullRequestReviewCapabilities = {
165
166 const FULL_REVIEWERS: PullRequestReviewerCapabilities = { request: true, listCandidates: true };
167
184 -function fakeProvider(
185 - kind: SourceControlProviderKind,
186 - overrides: Partial<PullRequestProviderApi> = {},
187 -): PullRequestProviderApi {
188 - return {
189 - kind,
190 - capabilities: {
191 - diff: true,
192 - comment: true,
193 - actions: ["merge", "ready", "draft", "close", "reopen"],
194 - mergeMethods: ["merge"],
195 - search: true,
196 - reactions: true,
197 - review: FULL_REVIEW,
198 - reviewers: FULL_REVIEWERS,
199 - edit: { changeRequest: true, comment: true },
200 - },
201 - getViewer: () => Effect.succeed("bilal"),
202 - getViewerPermissions: () =>
203 - Effect.succeed({
204 - actions: ["merge", "ready", "draft", "close", "reopen"],
205 - comment: true,
206 - resolve: true,
207 - verdicts: ["comment", "approve", "request-changes"],
208 - requestReviewers: true,
209 - }),
210 - listChangeRequests: () => Effect.succeed({ items: [], truncated: false, continues: true }),
211 - getChangeRequest: () => Effect.die("unused"),
212 - getChangeRequestActivity: () => Effect.die("unused"),
213 - getDiff: () => Effect.die("unused"),
214 - runAction: () => Effect.void,
215 - updateChangeRequest: () => Effect.void,
216 - comment: () => Effect.void,
217 - updateComment: () => Effect.void,
218 - submitReview: () => Effect.void,
219 - replyToThread: () => Effect.void,
220 - setThreadResolution: () => Effect.void,
221 - setReaction: () => Effect.void,
222 - listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }),
223 - setReviewerRequest: () => Effect.void,
224 - ...(kind === "github" ? { mergeMessageRewrite: (message: string) => message } : {}),
225 - ...(kind === "azure-devops"
226 - ? { repositoryKey: ({ canonicalKey }: { readonly canonicalKey: string }) => canonicalKey }
227 - : {}),
228 - ...overrides,
229 - };
230 -}
168 +// Like Azure DevOps, whose repository names repeat across organizations and projects.
169 +const keyedByCanonicalKey = {
170 + repositoryKey: ({ canonicalKey }: { readonly canonicalKey: string }) => canonicalKey,
171 +};
172
173 function makeService(input: {
174 readonly settings?: ServerSettings;
@@ -290,7 +231,7 @@ it.effect("lists GitHub Enterprise PRs for a stored unknown repository after hos
231 }),
232 ],
233 providers: [
293 - fakeProvider(SourceControlProviderKind.make("github"), {
234 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
235 listChangeRequests: ({ host, repository }) => {
236 assert.strictEqual(host, "code.example.test");
237 assert.strictEqual(repository, "team/project");
@@ -346,7 +287,7 @@ it.effect("derives a legacy repository host after refining its provider", () =>
287 } as unknown as OrchestrationProjectShell;
288 const service = yield* makeService({
289 projects: [legacy],
349 - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))],
290 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("gitlab"))],
291 resolveHandle: ({ context }) =>
292 Effect.succeed({
293 context: {
@@ -377,7 +318,7 @@ it.effect("tries another checkout when provider refinement remains unknown", ()
318 });
319 const service = yield* makeService({
320 projects: [selfHosted, { ...selfHosted, id: "p2" as ProjectId, workspaceRoot: "/healthy" }],
380 - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))],
321 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("gitlab"))],
322 resolveHandle: ({ cwd, context }) => {
323 asked.push(cwd);
324 return cwd === "/gone"
@@ -419,7 +360,7 @@ it.effect("reads nothing from a host with no implementation, but reports it", ()
360 }),
361 ],
362 providers: [
422 - fakeProvider(SourceControlProviderKind.make("github"), {
363 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
364 listChangeRequests: (input) => {
365 listed.push(input.repository);
366 return Effect.succeed({
@@ -458,7 +399,7 @@ it.effect("says where each repository carries on, and from nothing it has run ou
399 project({ id: "p2", title: "web", workspaceRoot: "/b", repository: "acme/web" }),
400 ],
401 providers: [
461 - fakeProvider(SourceControlProviderKind.make("github"), {
402 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
403 listChangeRequests: ({ repository }) =>
404 Effect.succeed({
405 items: [changeRequest(1, "2026-07-02T00:00:00Z")],
@@ -491,7 +432,8 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows"
432 }),
433 ],
434 providers: [
494 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
435 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
436 + ...keyedByCanonicalKey,
437 listChangeRequests: () =>
438 Effect.succeed({
439 items: [changeRequest(7, "2026-07-02T00:00:00Z")],
@@ -511,80 +453,63 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows"
453 }),
454 );
455
514 -it.effect("continues Bitbucket listings through tied timestamps and terminates", () =>
515 - Effect.gen(function* () {
516 - const boundary = "2026-10-12T00:00:00.000Z";
517 - const older = "2026-10-11T00:00:00.000Z";
518 - const rows = [1, 2, 3, 4, 5].map((id) => ({
519 - id,
520 - title: `Pull request ${id}`,
521 - state: "OPEN",
522 - created_on: older,
523 - updated_on: id <= 3 ? boundary : older,
524 - source: { branch: { name: `feat/${id}` } },
525 - destination: { branch: { name: "main" } },
526 - links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${id}` } },
527 - }));
528 - const provider = yield* BitbucketPullRequestProvider.make.pipe(
529 - Effect.provide(
530 - BitbucketPullRequestApi.layer.pipe(
531 - Layer.provide(
532 - Layer.mock(BitbucketApi.BitbucketApi)({
533 - request: ({ url }) => {
534 - if (url === "/user") {
535 - return Effect.succeed({
536 - body: JSON.stringify({ nickname: "bilal" }),
537 - truncated: false,
538 - });
539 - }
540 - const filter =
541 - new URL(url, "https://api.bitbucket.org").searchParams.get("q") ?? "";
542 - const updatedBefore = /updated_on <= (\S+)/.exec(filter)?.[1];
543 - const excluded = new Set(
544 - Array.from(filter.matchAll(/id != (\d+)/g), (match) => Number(match[1])),
545 - );
546 - const values = rows.filter(
456 +it.effect(
457 + "continues a timestamp-paged host's listings through tied timestamps and terminates",
458 + () =>
459 + Effect.gen(function* () {
460 + const boundary = "2026-10-12T00:00:00.000Z";
461 + const older = "2026-10-11T00:00:00.000Z";
462 + const rows = [1, 2, 3, 4, 5].map((number) =>
463 + changeRequest(number, number <= 3 ? boundary : older),
464 + );
465 + const service = yield* makeService({
466 + projects: [
467 + project({
468 + id: "p1",
469 + title: "web",
470 + workspaceRoot: "/w",
471 + repository: "acme/web",
472 + provider: "bitbucket",
473 + host: "bitbucket.org",
474 + }),
475 + ],
476 + providers: [
477 + // Pages the way Bitbucket does: inclusively by update time, excluding rows already sent.
478 + fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), {
479 + listChangeRequests: ({ cursor, limit }) =>
480 + Effect.sync(() => {
481 + const seen = new Set(cursor?.seenAt ?? []);
482 + const matching = rows.filter(
483 (row) =>
548 - (updatedBefore === undefined || row.updated_on <= updatedBefore) &&
549 - !excluded.has(row.id),
484 + (cursor === undefined || row.updatedAt <= cursor.updatedBefore) &&
485 + !seen.has(row.number),
486 );
551 - return Effect.succeed({ body: JSON.stringify({ values }), truncated: false });
552 - },
553 - }),
554 - ),
555 - ),
556 - ),
557 - );
558 - const service = yield* makeService({
559 - projects: [
560 - project({
561 - id: "p1",
562 - title: "web",
563 - workspaceRoot: "/w",
564 - repository: "acme/web",
565 - provider: "bitbucket",
566 - host: "bitbucket.org",
567 - }),
568 - ],
569 - providers: [provider],
570 - });
571 - let page = yield* service.list({ state: "open", limit: 2 });
572 - assert.deepStrictEqual(
573 - page.entries.map((entry) => entry.number),
574 - [1, 2],
575 - );
576 - for (const expected of [[3, 4], [5]]) {
577 - assert.isTrue(page.truncated);
578 - assert.isNotEmpty(page.nextCursors);
579 - page = yield* service.list({ state: "open", limit: 2, cursors: page.nextCursors });
487 + return {
488 + items: matching.slice(0, limit),
489 + truncated: matching.length > limit,
490 + continues: true,
491 + };
492 + }),
493 + }),
494 + ],
495 + });
496 + let page = yield* service.list({ state: "open", limit: 2 });
497 assert.deepStrictEqual(
498 page.entries.map((entry) => entry.number),
582 - expected,
499 + [1, 2],
500 );
584 - }
585 - assert.isFalse(page.truncated);
586 - assert.deepStrictEqual(page.nextCursors, {});
587 - }),
501 + for (const expected of [[3, 4], [5]]) {
502 + assert.isTrue(page.truncated);
503 + assert.isNotEmpty(page.nextCursors);
504 + page = yield* service.list({ state: "open", limit: 2, cursors: page.nextCursors });
505 + assert.deepStrictEqual(
506 + page.entries.map((entry) => entry.number),
507 + expected,
508 + );
509 + }
510 + assert.isFalse(page.truncated);
511 + assert.deepStrictEqual(page.nextCursors, {});
512 + }),
513 );
514
515 it.effect("keeps a row already sent at the boundary instant from arriving twice", () =>
@@ -594,7 +519,7 @@ it.effect("keeps a row already sent at the boundary instant from arriving twice"
519 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
520 ],
521 providers: [
597 - fakeProvider(SourceControlProviderKind.make("github"), {
522 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
523 listChangeRequests: () =>
524 Effect.succeed({
525 items: [
@@ -631,7 +556,7 @@ it.effect("keeps the earlier exclusions when a slice ends on the instant it bega
556 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
557 ],
558 providers: [
634 - fakeProvider(SourceControlProviderKind.make("github"), {
559 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
560 listChangeRequests: () =>
561 Effect.succeed({
562 items: [
@@ -667,7 +592,7 @@ it.effect("calls a transient viewer failure a failed operation, not a signed-out
592 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
593 ],
594 providers: [
670 - fakeProvider(SourceControlProviderKind.make("github"), {
595 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
596 getViewer: () =>
597 Effect.fail(
598 new PullRequestProviderError({
@@ -701,7 +626,7 @@ it.effect("reports an unusable host over a merely failing one", () =>
626 }),
627 ],
628 providers: [
704 - fakeProvider(SourceControlProviderKind.make("github"), {
629 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
630 getViewer: () =>
631 Effect.fail(
632 new PullRequestProviderError({
@@ -712,7 +637,7 @@ it.effect("reports an unusable host over a merely failing one", () =>
637 }),
638 ),
639 }),
715 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
640 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
641 unavailableRequirement: {
642 missing: "Install glab.",
643 unauthenticated: "Run glab auth login.",
@@ -747,7 +672,7 @@ it.effect("tells two hosts of one kind apart in the switcher and the filter", ()
672 }),
673 ],
674 providers: [
750 - fakeProvider(SourceControlProviderKind.make("github"), {
675 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
676 listChangeRequests: ({ host }) =>
677 Effect.succeed({
678 items: host === "ghe.example.com" ? [changeRequest(2, "2026-07-05T00:00:00Z")] : [],
@@ -789,7 +714,7 @@ it.effect("reads a repository once when several worktrees share it", () =>
714 }),
715 ],
716 providers: [
792 - fakeProvider(SourceControlProviderKind.make("github"), {
717 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
718 listChangeRequests: () => {
719 calls += 1;
720 return Effect.succeed({
@@ -817,7 +742,7 @@ it.effect("keeps healthy repositories when one of them cannot be read", () =>
742 project({ id: "p2", title: "broken", workspaceRoot: "/b", repository: "pingdotgg/broken" }),
743 ],
744 providers: [
820 - fakeProvider(SourceControlProviderKind.make("github"), {
745 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
746 listChangeRequests: (input) =>
747 input.repository === "pingdotgg/broken"
748 ? Effect.fail(requestFailed)
@@ -868,7 +793,7 @@ it.effect("offers each label once across repositories, despite one that cannot b
793 }),
794 ],
795 providers: [
871 - fakeProvider(SourceControlProviderKind.make("github"), {
796 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
797 listRepositoryLabels: (input) => {
798 reads.push(input.repository);
799 return input.repository === "pingdotgg/broken"
@@ -886,7 +811,7 @@ it.effect("offers each label once across repositories, despite one that cannot b
811 },
812 }),
813 // A host with no repository labels is left out rather than failing the answer.
889 - fakeProvider(SourceControlProviderKind.make("gitlab")),
814 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab")),
815 ],
816 });
817
@@ -909,7 +834,7 @@ it.effect("puts the author a query names exactly ahead of those it only begins",
834 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
835 ],
836 providers: [
912 - fakeProvider(SourceControlProviderKind.make("github"), {
837 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
838 searchRepositoryAuthors: (input) => {
839 queries.push(input.query);
840 return Effect.succeed({
@@ -945,7 +870,7 @@ it.effect("tries another workspace on the same host for the viewer", () =>
870 project({ id: "p2", title: "healthy", workspaceRoot: "/healthy", repository: "acme/two" }),
871 ],
872 providers: [
948 - fakeProvider(SourceControlProviderKind.make("github"), {
873 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
874 getViewer: (input) =>
875 input.cwd === "/healthy"
876 ? Effect.succeed("bilal")
@@ -981,7 +906,7 @@ it.effect("routing verifies the current account on the requested host without ca
906 }),
907 ],
908 providers: [
984 - fakeProvider(SourceControlProviderKind.make("github"), {
909 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
910 getRoutingIdentity: (input) => {
911 assert.deepStrictEqual(input, { cwd: "/a", host: "github.example.test" });
912 return Effect.succeed({
@@ -1018,7 +943,7 @@ it.effect("refuses an action the host never claimed it could run", () =>
943 const service = yield* makeService({
944 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
945 providers: [
1021 - fakeProvider(SourceControlProviderKind.make("github"), {
946 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
947 capabilities: {
948 diff: true,
949 comment: true,
@@ -1051,6 +976,41 @@ it.effect("refuses an action the host never claimed it could run", () =>
976 }),
977 );
978
979 +it.effect(
980 + "asks to remove agent credits on merge only from a host that rewrites merge messages",
981 + () =>
982 + Effect.gen(function* () {
983 + const asked: Array<boolean | undefined> = [];
984 + const runAction: PullRequestProviderApi["runAction"] = (input) =>
985 + Effect.sync(() => {
986 + asked.push(input.removeAgentCreditsOnMerge);
987 + });
988 + for (const rewrites of [true, false]) {
989 + const service = yield* makeService({
990 + settings: { ...DEFAULT_SERVER_SETTINGS, removeAgentCreditsOnMerge: true },
991 + projects: [
992 + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
993 + ],
994 + providers: [
995 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
996 + runAction,
997 + getChangeRequestSummary: () =>
998 + Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")),
999 + ...(rewrites ? { mergeMessageRewrite: (message: string) => message } : {}),
1000 + }),
1001 + ],
1002 + });
1003 + yield* service.runAction({
1004 + projectId: "p1" as ProjectId,
1005 + repository: "acme/web",
1006 + number: 1,
1007 + action: "merge",
1008 + });
1009 + }
1010 + assert.deepStrictEqual(asked, [true, undefined]);
1011 + }),
1012 +);
1013 +
1014 it.effect("publishes a merge for immediate settlement only after host confirmation", () =>
1015 Effect.scoped(
1016 Effect.gen(function* () {
@@ -1063,7 +1023,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
1023 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1024 ],
1025 providers: [
1066 - fakeProvider(SourceControlProviderKind.make("github"), {
1026 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1027 getChangeRequestSummary: () =>
1028 confirmationFails
1029 ? Effect.fail(
@@ -1120,7 +1080,7 @@ it.effect("refreshes every reader before a queued merge confirmation finishes",
1080 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1081 ],
1082 providers: [
1123 - fakeProvider(SourceControlProviderKind.make("github"), {
1083 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1084 getChangeRequestSummary: () =>
1085 Effect.gen(function* () {
1086 yield* Deferred.succeed(confirmationStarted, undefined);
@@ -1161,7 +1121,7 @@ it.effect("runs branch deletion only when the host and viewer support it, never
1121 let actions = 0;
1122 let supported = false;
1123 let allowed = true;
1164 - const base = fakeProvider(SourceControlProviderKind.make("github"));
1124 + const base = fakePullRequestProvider(SourceControlProviderKind.make("github"));
1125 const service = yield* makeService({
1126 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1127 providers: [
@@ -1226,109 +1186,41 @@ it.effect("runs branch deletion only when the host and viewer support it, never
1186 }),
1187 );
1188
1229 -it.effect("keeps branch deletion on the credential that passed source repository permissions", () =>
1189 +it.effect("checks and deletes a branch inside one verified credential", () =>
1190 Effect.gen(function* () {
1231 - let activeToken = "account-a";
1232 - const requests: Array<{ operation: string; authorization: string | undefined }> = [];
1233 - const credentials = Layer.succeed(
1234 - GitHubCredentials.GitHubCredentials,
1235 - GitHubCredentials.GitHubCredentials.of({
1236 - get: (host) =>
1237 - Effect.sync(() => ({
1238 - host,
1239 - token: Redacted.make(activeToken),
1240 - source: "gh" as const,
1241 - fingerprint: `${host}:${activeToken}`,
1242 - })),
1243 - invalidate: () => Effect.void,
1244 - }),
1245 - );
1246 - const http = Layer.succeed(
1247 - HttpClient.HttpClient,
1248 - HttpClient.make((request) =>
1249 - Effect.sync(() => {
1250 - const operation = request.url.endsWith("/user")
1251 - ? "user"
1252 - : request.body._tag === "Uint8Array"
1253 - ? new TextDecoder().decode(request.body.body)
1254 - : "";
1255 - requests.push({ operation, authorization: request.headers["authorization"] });
1256 - let body;
1257 - if (operation === "user") {
1258 - body = { id: activeToken === "account-a" ? 101 : 202, login: activeToken };
1259 - } else if (operation.includes("query PullRequestBranchToDelete")) {
1260 - body = {
1261 - data: {
1262 - repository: {
1263 - pullRequest: {
1264 - state: "MERGED",
1265 - headRefName: "feature",
1266 - baseRefName: "main",
1267 - headRefOid: "abc123",
1268 - headRepository: { id: "FORK_REPO" },
1269 - },
1270 - },
1271 - },
1272 - };
1273 - } else if (operation.includes("query PullRequestSourceBranch")) {
1274 - body = {
1275 - data: {
1276 - node: {
1277 - __typename: "Repository",
1278 - defaultBranchRef: { name: "main" },
1279 - ref: { target: { __typename: "Commit", oid: "abc123" } },
1280 - },
1281 - },
1282 - };
1283 - } else if (operation.includes("updateRefs(")) {
1284 - body = { data: { updateRefs: { clientMutationId: null } } };
1285 - } else {
1286 - activeToken = "account-b";
1287 - body = {
1288 - data: {
1289 - repository: {
1290 - mergeCommitAllowed: true,
1291 - squashMergeAllowed: true,
1292 - rebaseMergeAllowed: true,
1293 - autoMergeAllowed: true,
1294 - viewerPermission: "READ",
1295 - pullRequest: {
1296 - viewerCanUpdate: false,
1297 - viewerDidAuthor: false,
1298 - headRepository: { viewerPermission: "WRITE" },
1299 - },
1300 - },
1301 - },
1302 - };
1303 - }
1304 - return HttpClientResponse.fromWeb(
1305 - request,
1306 - new Response(JSON.stringify(body), {
1307 - headers: { "content-type": "application/json" },
1308 - }),
1309 - );
1310 - }),
1311 - ),
1312 - );
1313 - const provider = yield* GitHubPullRequestProvider.make.pipe(
1314 - Effect.provide(
1315 - GitHubPullRequestApi.layer.pipe(
1316 - // GraphQL reads go over `http` too, through the same credential and quota as REST.
1317 - Layer.provide(
1318 - GitHubRest.layer.pipe(
1319 - Layer.provideMerge(Layer.mergeAll(credentials, http)),
1320 - Layer.provideMerge(GitHubQuota.layer),
1321 - Layer.provideMerge(SourceControlRateLimit.layer),
1322 - ),
1323 - ),
1324 - Layer.provide(TestSourceControlHost.layer()),
1325 - Layer.provide(NodeServices.layer),
1326 - ),
1327 - ),
1328 - );
1191 + let pinned = false;
1192 + const calls: Array<string> = [];
1193 const service = yield* makeService({
1194 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1331 - providers: [provider],
1195 + providers: [
1196 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1197 + capabilities: {
1198 + ...fakePullRequestProvider("github").capabilities,
1199 + actions: ["delete-branch"],
1200 + deleteBranch: true,
1201 + },
1202 + withVerifiedCredential: (_, use) =>
1203 + Effect.suspend(() => {
1204 + pinned = true;
1205 + return use({ accountId: "101", viewer: "bilal", credentialFingerprint: "a" });
1206 + }).pipe(Effect.ensuring(Effect.sync(() => (pinned = false)))),
1207 + getViewerPermissions: () =>
1208 + Effect.sync(() => {
1209 + calls.push(`permissions pinned=${pinned}`);
1210 + return {
1211 + actions: ["delete-branch"],
1212 + comment: true,
1213 + resolve: true,
1214 + verdicts: [],
1215 + requestReviewers: false,
1216 + };
1217 + }),
1218 + runAction: (input) =>
1219 + Effect.sync(() => {
1220 + calls.push(`${input.action} pinned=${pinned}`);
1221 + }),
1222 + }),
1223 + ],
1224 });
1225 yield* service.runAction({
1226 projectId: "p1" as ProjectId,
@@ -1336,21 +1228,7 @@ it.effect("keeps branch deletion on the credential that passed source repository
1228 number: 1,
1229 action: "delete-branch",
1230 });
1339 - assert.strictEqual(activeToken, "account-b");
1340 - assert.strictEqual(
1341 - requests.filter(({ operation }) => operation.includes("updateRefs(")).length,
1342 - 1,
1343 - );
1344 - assert.deepStrictEqual(
1345 - requests.map(({ authorization }) => authorization),
1346 - [
1347 - "Bearer account-a",
1348 - "Bearer account-a",
1349 - "Bearer account-a",
1350 - "Bearer account-a",
1351 - "Bearer account-a",
1352 - ],
1353 - );
1231 + assert.deepStrictEqual(calls, ["permissions pinned=true", "delete-branch pinned=true"]);
1232 }),
1233 );
1234
@@ -1360,7 +1238,7 @@ it.effect("refuses an action this viewer may not take, and says what access it t
1238 const service = yield* makeService({
1239 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1240 providers: [
1363 - fakeProvider(SourceControlProviderKind.make("github"), {
1241 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1242 getViewerPermissions: () =>
1243 Effect.succeed({
1244 actions: ["ready", "draft", "close", "reopen"],
@@ -1394,7 +1272,7 @@ it.effect("gates arming a merge for later exactly as it gates merging now", () =
1272 const service = yield* makeService({
1273 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1274 providers: [
1397 - fakeProvider(SourceControlProviderKind.make("github"), {
1275 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1276 capabilities: {
1277 diff: true,
1278 comment: true,
@@ -1455,7 +1333,7 @@ it.effect("keeps two hosts of one provider kind as two accounts", () =>
1333 }),
1334 ],
1335 providers: [
1458 - fakeProvider(SourceControlProviderKind.make("github"), {
1336 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1337 getViewer: (input) => Effect.succeed(viewerFor[input.cwd] ?? "unknown"),
1338 listChangeRequests: () =>
1339 Effect.succeed({
@@ -1490,7 +1368,7 @@ it.effect("stops new reads after a rate limit while leaving manual actions avail
1368 project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }),
1369 ],
1370 providers: [
1493 - fakeProvider(SourceControlProviderKind.make("github"), {
1371 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1372 listChangeRequests: () =>
1373 Effect.sync(() => {
1374 listCalls += 1;
@@ -1545,7 +1423,7 @@ it.effect("refuses a repository that does not belong to the requested project",
1423 projects: [
1424 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
1425 ],
1548 - providers: [fakeProvider(SourceControlProviderKind.make("github"))],
1426 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))],
1427 });
1428
1429 const error = yield* service
@@ -1574,7 +1452,7 @@ it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after
1452 }),
1453 ],
1454 providers: [
1577 - fakeProvider(SourceControlProviderKind.make("forgejo"), {
1455 + fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), {
1456 getViewer: (input) => {
1457 viewers.push(input.host);
1458 assert.strictEqual(input.host, "code.example:3000");
@@ -1662,7 +1540,7 @@ it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () =>
1540 remoteUrl: "http://code.example:4000/team/repo.git",
1541 }),
1542 ],
1665 - providers: [fakeProvider(SourceControlProviderKind.make("forgejo"))],
1543 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("forgejo"))],
1544 });
1545 const failure = yield* service
1546 .summary(
@@ -1690,7 +1568,7 @@ it.effect("resolves a project's repository identity when its shell has none cach
1568 const service = yield* makeService({
1569 projects: [{ ...resolved, repositoryIdentity: null }],
1570 providers: [
1693 - fakeProvider(SourceControlProviderKind.make("github"), {
1571 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1572 getChangeRequestSummary: () => Effect.succeed(changeRequest(7, "2026-07-02T00:00:00Z")),
1573 }),
1574 ],
@@ -1714,7 +1592,7 @@ it.effect("routes a hosted reference to another repository through a project on
1592 project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
1593 ],
1594 providers: [
1717 - fakeProvider(SourceControlProviderKind.make("github"), {
1595 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1596 getChangeRequestSummary: (input) =>
1597 Effect.sync(() => {
1598 seen.push({ cwd: input.cwd, repository: input.repository, host: input.host });
@@ -1749,7 +1627,8 @@ it.effect("routes Azure reads and writes through the requested organization's ch
1627 }),
1628 ),
1629 providers: [
1752 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
1630 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
1631 + ...keyedByCanonicalKey,
1632 getChangeRequestSummary: (input) =>
1633 Effect.sync(() => {
1634 seen.push(`read ${input.cwd} ${input.repository}`);
@@ -1815,7 +1694,8 @@ it.effect.each([
1694 target,
1695 ],
1696 providers: [
1818 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
1697 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
1698 + ...keyedByCanonicalKey,
1699 getChangeRequestSummary: (input) =>
1700 Effect.sync(() => {
1701 seen.push(`read ${input.cwd} ${input.repository}`);
@@ -1854,7 +1734,8 @@ it.effect("refuses Azure cross-organization reads and writes without its checkou
1734 }),
1735 ],
1736 providers: [
1857 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
1737 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
1738 + ...keyedByCanonicalKey,
1739 getChangeRequestSummary: () => Effect.die("must not read the wrong organization"),
1740 runAction: () => Effect.die("must not modify the wrong organization"),
1741 }),
@@ -1884,7 +1765,7 @@ it.effect("prefers a matching checkout over a non-repository project's directory
1765 project({ id: "repo", title: "API", workspaceRoot: "/api", repository: "acme/api" }),
1766 ],
1767 providers: [
1887 - fakeProvider(SourceControlProviderKind.make("github"), {
1768 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1769 getChangeRequestSummary: (input) =>
1770 Effect.sync(() => {
1771 seen.push(input.cwd);
@@ -1911,7 +1792,7 @@ it.effect("requires an explicit host for a non-repository project's linked PR",
1792 Effect.gen(function* () {
1793 const service = yield* makeService({
1794 projects: [project({ id: "inbox", title: "Inbox", workspaceRoot: "/home/alex" })],
1914 - providers: [fakeProvider(SourceControlProviderKind.make("github"))],
1795 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))],
1796 });
1797 const error = yield* service
1798 .summary(
@@ -1933,7 +1814,7 @@ it.effect("refuses a review request this viewer may not make, and says what acce
1814 const service = yield* makeService({
1815 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1816 providers: [
1936 - fakeProvider(SourceControlProviderKind.make("github"), {
1817 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1818 getViewerPermissions: () =>
1819 Effect.succeed({
1820 actions: ["ready", "draft", "close", "reopen"],
@@ -1990,7 +1871,7 @@ it.effect.each(["list", "listStats"] as const)(
1871 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1872 ],
1873 providers: [
1993 - fakeProvider(SourceControlProviderKind.make("github"), {
1874 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1875 listChangeRequests: () =>
1876 lookup.pipe(
1877 Effect.as({
@@ -2038,7 +1919,7 @@ it.effect("shares one cold viewer lookup across distinct concurrent lists", () =
1919 const service = yield* makeService({
1920 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1921 providers: [
2041 - fakeProvider(SourceControlProviderKind.make("github"), {
1922 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1923 getViewer: () =>
1924 Effect.sync(() => {
1925 viewerCalls += 1;
@@ -2076,7 +1957,7 @@ it.effect("a listing narrowed to some projects is its own cache entry", () =>
1957 project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),
1958 ],
1959 providers: [
2079 - fakeProvider(SourceControlProviderKind.make("github"), {
1960 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1961 listChangeRequestsAcross: (input) => {
1962 asked.push(input.repositories);
1963 return Effect.succeed({
@@ -2117,7 +1998,7 @@ it.effect(
1998 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1999 ],
2000 providers: [
2120 - fakeProvider(SourceControlProviderKind.make("github"), {
2001 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2002 listChangeRequests: ({ filters }) =>
2003 Effect.gen(function* () {
2004 reads += 1;
@@ -2171,7 +2052,7 @@ it.effect("does not revive old summaries when project epochs are evicted", () =>
2052 const service = yield* makeService({
2053 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2054 providers: [
2174 - fakeProvider(SourceControlProviderKind.make("github"), {
2055 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2056 getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("body"), title }),
2057 }),
2058 ],
@@ -2198,7 +2079,7 @@ it.effect("close and reopen notify subscribed readers after invalidating their c
2079 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
2080 ],
2081 providers: [
2201 - fakeProvider(SourceControlProviderKind.make("github"), {
2082 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2083 getChangeRequestSummary: () =>
2084 Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }),
2085 runAction: (input) =>
@@ -2257,7 +2138,7 @@ it.effect("reads a host's repositories in one search, and files the rows back un
2138 }),
2139 ],
2140 providers: [
2260 - fakeProvider(SourceControlProviderKind.make("github"), {
2141 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2142 listChangeRequests: ({ repository }) => {
2143 separately.push(repository);
2144 return Effect.succeed({ items: [], truncated: false, continues: true });
@@ -2273,7 +2154,7 @@ it.effect("reads a host's repositories in one search, and files the rows back un
2154 });
2155 },
2156 }),
2276 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
2157 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
2158 listChangeRequests: ({ repository }) => {
2159 separately.push(repository);
2160 return Effect.succeed({
@@ -2309,7 +2190,7 @@ it.effect("carries every repository of a slice on from the oldest row in it", ()
2190 project({ id: "p3", title: "docs", workspaceRoot: "/c", repository: "acme/docs" }),
2191 ],
2192 providers: [
2312 - fakeProvider(SourceControlProviderKind.make("github"), {
2193 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2194 listsAcrossMayOmitRepositories: true,
2195 listChangeRequestsAcross: () =>
2196 Effect.succeed({
@@ -2339,7 +2220,7 @@ it.effect("carries a slice on without sending the rows it already sent", () =>
2220 const service = yield* makeService({
2221 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2222 providers: [
2342 - fakeProvider(SourceControlProviderKind.make("github"), {
2223 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2224 listChangeRequestsAcross: (input) => {
2225 cursors.push(input.cursor);
2226 return Effect.succeed({
@@ -2382,7 +2263,7 @@ it.effect("reads a workspace larger than one search in chunks, and merges them",
2263 }),
2264 ),
2265 providers: [
2385 - fakeProvider(SourceControlProviderKind.make("github"), {
2266 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2267 listChangeRequestsAcross: (input) => {
2268 asked.push(input.repositories.length);
2269 return Effect.succeed({
@@ -2413,7 +2294,7 @@ it.effect(
2294 project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),
2295 ],
2296 providers: [
2416 - fakeProvider(SourceControlProviderKind.make("github"), {
2297 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2298 listsAcrossMayOmitRepositories: true,
2299 listChangeRequests: ({ repository }) => {
2300 separately.push(repository);
@@ -2455,7 +2336,7 @@ it.effect("believes a search's silence about a repository where searches cover e
2336 project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),
2337 ],
2338 providers: [
2458 - fakeProvider(SourceControlProviderKind.make("github"), {
2339 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2340 listChangeRequests: ({ repository }) => {
2341 separately.push(repository);
2342 return Effect.succeed({ items: [], truncated: false, continues: true });
@@ -2493,7 +2374,7 @@ it.effect("fills in the line counts for the rows it is given", () =>
2374 }),
2375 ],
2376 providers: [
2496 - fakeProvider(SourceControlProviderKind.make("github"), {
2377 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2378 listChangeRequestStats: (input) => {
2379 asked.push(input.changeRequests);
2380 return Effect.succeed([
@@ -2501,7 +2382,7 @@ it.effect("fills in the line counts for the rows it is given", () =>
2382 ]);
2383 },
2384 }),
2504 - fakeProvider(SourceControlProviderKind.make("gitlab")),
2385 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab")),
2386 ],
2387 });
2388
@@ -2543,7 +2424,7 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis
2424 const service = yield* makeService({
2425 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2426 providers: [
2546 - fakeProvider(SourceControlProviderKind.make("github"), {
2427 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2428 getChangeRequest: () =>
2429 Effect.sync(() => ({ ...hostedChangeRequest("body"), updatedAt: revision })),
2430 getChangeRequestSummary: () =>
@@ -2604,9 +2485,9 @@ it.effect("keeps routed reads separate when the GitHub account changes", () =>
2485 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
2486 ],
2487 providers: [
2607 - fakeProvider(SourceControlProviderKind.make("github"), {
2488 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2489 capabilities: {
2609 - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities,
2490 + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities,
2491 viewedFiles: "host",
2492 },
2493 getFilesViewed: () =>
@@ -2670,9 +2551,9 @@ it.effect("isolates routed caches for two credentials belonging to the same acco
2551 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
2552 ],
2553 providers: [
2673 - fakeProvider(SourceControlProviderKind.make("github"), {
2554 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2555 capabilities: {
2675 - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities,
2556 + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities,
2557 viewedFiles: "host",
2558 },
2559 getFilesViewed: () =>
@@ -2732,7 +2613,7 @@ it.effect("rejects mismatched routing credentials before use and preserves actio
2613 const service = yield* makeService({
2614 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2615 providers: [
2735 - fakeProvider(SourceControlProviderKind.make("github"), {
2616 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2617 getRoutingIdentity: () => Effect.succeed({ accountId: "101", viewer: "octocat" }),
2618 withVerifiedCredential: (_, use) =>
2619 use({
@@ -2788,7 +2669,7 @@ it.effect(
2669 project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
2670 ],
2671 providers: [
2791 - fakeProvider(SourceControlProviderKind.make("github"), {
2672 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2673 getChangeRequestSummary: () =>
2674 Effect.succeed({
2675 ...changeRequest(1, "2026-07-02T00:00:00Z"),
@@ -2828,7 +2709,7 @@ it.effect("notifies linked threads when detail changes draft status in either di
2709 const service = yield* makeService({
2710 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2711 providers: [
2831 - fakeProvider(SourceControlProviderKind.make("github"), {
2712 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2713 getChangeRequest: () =>
2714 Effect.sync(() => ({ ...hostedChangeRequest("body"), isDraft, updatedAt })),
2715 }),
@@ -2869,7 +2750,7 @@ it.effect("deduplicates routed PR reports without dropping draft changes", () =>
2750 const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
2751 const service = yield* makeService({
2752 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2872 - providers: [fakeProvider(SourceControlProviderKind.make("github"))],
2753 + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))],
2754 });
2755 const changes = yield* service.subscribeStateChanges;
2756 for (const isDraft of [true, true, false, false, true]) {
@@ -2895,7 +2776,7 @@ it.effect("preserves check observation time on cache hits and advances it on ref
2776 const service = yield* makeService({
2777 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2778 providers: [
2898 - fakeProvider(SourceControlProviderKind.make("github"), {
2779 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2780 getChangeRequestChecks: () =>
2781 Effect.sync(() => {
2782 reads += 1;
@@ -2922,7 +2803,7 @@ it.effect("reuses an observed merged state for strict settlement reads", () =>
2803 const service = yield* makeService({
2804 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2805 providers: [
2925 - fakeProvider(SourceControlProviderKind.make("github"), {
2806 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2807 getChangeRequest: () =>
2808 Effect.succeed({
2809 ...hostedChangeRequest("merged body", 4),
@@ -2952,7 +2833,7 @@ it.effect("does not let a stale detail reopen overwrite a fresher linked summary
2833 const service = yield* makeService({
2834 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2835 providers: [
2955 - fakeProvider(SourceControlProviderKind.make("github"), {
2836 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2837 getChangeRequest: () =>
2838 Effect.gen(function* () {
2839 detailCalls += 1;
@@ -3015,7 +2896,7 @@ it.effect("keeps a row of a host that ignored the filters if any name of a label
2896 }),
2897 ],
2898 providers: [
3018 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
2899 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
2900 listChangeRequests: () =>
2901 Effect.succeed({
2902 items: [
@@ -3078,7 +2959,7 @@ it.effect.each([false, true])(
2959 }),
2960 ],
2961 providers: [
3081 - fakeProvider(SourceControlProviderKind.make("github"), {
2962 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2963 capabilities,
2964 getViewerPermissions: () =>
2965 Effect.succeed({
@@ -3146,7 +3027,7 @@ it.effect("refuses a way of updating a branch that the host or the viewer does n
3027 const service = yield* makeService({
3028 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
3029 providers: [
3149 - fakeProvider(SourceControlProviderKind.make("github"), {
3030 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3031 capabilities: {
3032 diff: true,
3033 comment: true,
@@ -3205,7 +3086,7 @@ it.effect("keeps reading a host's thinned-out slices until a filtered page is fu
3086 }),
3087 ],
3088 providers: [
3208 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
3089 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3090 listChangeRequests: (input) => {
3091 const delivered = input.cursor?.delivered ?? 0;
3092 reads.push(delivered);
@@ -3252,7 +3133,7 @@ it.effect("hands a host's own resume position back on the next read", () =>
3133 }),
3134 ],
3135 providers: [
3255 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
3136 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3137 listChangeRequests: (input) => {
3138 resumed.push(input.cursor?.resumeAfter);
3139 return Effect.succeed({
@@ -3286,7 +3167,7 @@ it.effect("judges the review filter only on a host that summarises its reviews",
3167 }),
3168 ],
3169 providers: [
3289 - fakeProvider(SourceControlProviderKind.make("github"), {
3170 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3171 listChangeRequests: () =>
3172 Effect.succeed({
3173 items: [
@@ -3300,7 +3181,7 @@ it.effect("judges the review filter only on a host that summarises its reviews",
3181 continues: true,
3182 }),
3183 }),
3303 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
3184 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3185 listChangeRequests: () =>
3186 Effect.succeed({
3187 items: [changeRequest(3, "2026-07-02T00:00:00Z")],
@@ -3329,9 +3210,9 @@ it.effect("partial host viewed writes invalidate marks but keep the diff cached"
3210 const service = yield* makeService({
3211 projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
3212 providers: [
3332 - fakeProvider(SourceControlProviderKind.make("github"), {
3213 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3214 capabilities: {
3334 - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities,
3215 + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities,
3216 viewedFiles: "host",
3217 },
3218 getDiff: () =>
@@ -3383,7 +3264,7 @@ const environmentViewedProvider = (
3264 asked: Array<ReadonlyArray<string>>,
3265 unreadable: ReadonlySet<string> = new Set(),
3266 ) =>
3386 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
3267 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3268 capabilities: {
3269 diff: true,
3270 comment: true,
@@ -3434,73 +3315,54 @@ const GITLAB_REFERENCE = {
3315 number: 1,
3316 };
3317
3437 -it.effect("tracks Forgejo viewed files through its diff and refuses truncated baselines", () =>
3318 +it.effect("tracks environment viewed files by revision and refuses a baseline it cannot read", () =>
3319 Effect.gen(function* () {
3439 - let alpha = "b485fe5";
3440 - let truncated = false;
3441 - let diffReads = 0;
3442 - const provider = yield* ForgejoPullRequestProvider.make.pipe(
3443 - Effect.provide(
3444 - Layer.mock(ForgejoCli.ForgejoCli)({
3445 - api: (input) => {
3446 - assert.strictEqual(input.host, "forge.example:3000");
3447 - const viewer = input.path === "user";
3448 - if (!viewer) {
3449 - assert.strictEqual(input.repository, "reviewer/project");
3450 - assert.strictEqual(input.path, "repos/reviewer/project/pulls/1.diff");
3451 - diffReads++;
3452 - }
3453 - return Effect.succeed({
3454 - exitCode: ChildProcessSpawner.ExitCode(0),
3455 - stdout: viewer
3456 - ? JSON.stringify({ login: "reviewer" })
3457 - : truncated
3458 - ? `diff --git a/alpha.ts b/alpha.ts\nindex eb2d7c5..${alpha} 100644\n`
3459 - : [
3460 - "diff --git a/alpha.ts b/alpha.ts",
3461 - `index eb2d7c5..${alpha} 100644`,
3462 - "diff --git a/beta.ts b/beta.ts",
3463 - "index b39e8b3..5851425 100644",
3464 - 'diff --git "a/caf\\303\\251 notes.txt" "b/caf\\303\\251 notes.txt"',
3465 - "index ffd99ce..6dd9855 100644",
3466 - "diff --git a/deleted.txt b/deleted.txt",
3467 - "deleted file mode 100644",
3468 - "index 233f5c6..0000000",
3469 - "diff --git a/old.txt b/renamed.txt",
3470 - "similarity index 100%",
3471 - "rename from old.txt",
3472 - "rename to renamed.txt",
3473 - "",
3474 - ].join("\n"),
3475 - stderr: "",
3476 - stdoutTruncated: !viewer && truncated,
3477 - stderrTruncated: false,
3478 - });
3479 - },
3480 - }),
3481 - ),
3482 - );
3320 + const revisions = new Map([
3321 + ["alpha.ts", "b485fe5"],
3322 + ["beta.ts", "5851425"],
3323 + ["café notes.txt", "6dd9855"],
3324 + ["deleted.txt", "0000000"],
3325 + ["renamed.txt", ""],
3326 + ]);
3327 + let unreadable = false;
3328 + let revisionReads = 0;
3329 const service = yield* makeService({
3330 projects: [
3331 project({
3486 - id: "forgejo",
3487 - title: "on forgejo",
3488 - workspaceRoot: "/forgejo",
3489 - repository: "reviewer/project",
3490 - provider: SourceControlProviderKind.make("forgejo"),
3491 - host: "forge.example:3000",
3492 - remoteUrl: "http://forge.example:3000/reviewer/project.git",
3332 + id: "p1",
3333 + title: "on gitlab",
3334 + workspaceRoot: "/a",
3335 + repository: "group/project",
3336 + provider: SourceControlProviderKind.make("gitlab"),
3337 }),
3338 ],
3495 - providers: [provider],
3339 + providers: [
3340 + {
3341 + ...environmentViewedProvider(revisions, []),
3342 + getFileRevisions: (input) =>
3343 + Effect.suspend(() => {
3344 + revisionReads++;
3345 + return unreadable
3346 + ? Effect.fail(
3347 + new PullRequestProviderError({
3348 + provider: SourceControlProviderKind.make("gitlab"),
3349 + operation: "getFileRevisions",
3350 + reason: "failed",
3351 + detail: "The diff exceeded the output limit.",
3352 + }),
3353 + )
3354 + : Effect.succeed({
3355 + revisions: new Map(
3356 + input.paths.map((path) => [path, revisions.get(path) ?? ""] as const),
3357 + ),
3358 + complete: true,
3359 + });
3360 + }),
3361 + },
3362 + ],
3363 });
3497 - const reference = {
3498 - projectId: "forgejo" as ProjectId,
3499 - repository: "reviewer/project",
3500 - host: "forge.example:3000",
3501 - number: 1,
3502 - };
3503 - const paths = ["alpha.ts", "beta.ts", "café notes.txt", "deleted.txt", "renamed.txt"];
3364 + const reference = GITLAB_REFERENCE;
3365 + const paths = [...revisions.keys()];
3366 yield* service.setFilesViewed({
3367 ...reference,
3368 files: paths.map((path) => ({ path, viewed: true })),
@@ -3509,9 +3371,9 @@ it.effect("tracks Forgejo viewed files through its diff and refuses truncated ba
3371 new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])),
3372 new Map(paths.map((path) => [path, "viewed"])),
3373 );
3512 - assert.strictEqual(diffReads, 1);
3374 + assert.strictEqual(revisionReads, 1);
3375
3514 - alpha = "aabbccd";
3376 + revisions.set("alpha.ts", "aabbccd");
3377 yield* service.invalidate({ reference });
3378 assert.deepStrictEqual(
3379 new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])),
@@ -3525,13 +3387,13 @@ it.effect("tracks Forgejo viewed files through its diff and refuses truncated ba
3387 (yield* service.filesViewed(reference)).files.some((file) => file.path === "beta.ts"),
3388 );
3389
3528 - truncated = true;
3390 + unreadable = true;
3391 yield* service.invalidate({ reference });
3392 yield* service.setFilesViewed({
3393 ...reference,
3394 files: [{ path: "beta.ts", viewed: true }],
3395 });
3534 - truncated = false;
3396 + unreadable = false;
3397 yield* service.invalidate({ reference });
3398 assert.deepStrictEqual(
3399 (yield* service.filesViewed(reference)).files.find((file) => file.path === "beta.ts"),
@@ -3771,7 +3633,7 @@ it.effect("finishes two presses on one file in the order they were made", () =>
3633 }),
3634 ],
3635 providers: [
3774 - fakeProvider(SourceControlProviderKind.make("gitlab"), {
3636 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3637 capabilities: {
3638 diff: true,
3639 comment: true,
@@ -3820,7 +3682,8 @@ const azureViewedService = (projects: ReadonlyArray<OrchestrationProjectShell>)
3682 makeService({
3683 projects,
3684 providers: [
3823 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
3685 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
3686 + ...keyedByCanonicalKey,
3687 capabilities: {
3688 diff: true,
3689 comment: true,
@@ -3965,7 +3828,8 @@ it.effect("keeps Azure continuation cursors separate for repositories with the s
3828 }),
3829 ),
3830 providers: [
3968 - fakeProvider(SourceControlProviderKind.make("azure-devops"), {
3831 + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), {
3832 + ...keyedByCanonicalKey,
3833 listChangeRequests: (input) =>
3834 Effect.sync(() => {
3835 seen.push(input.cwd);
@@ -3987,38 +3851,9 @@ it.effect("keeps Azure continuation cursors separate for repositories with the s
3851 }),
3852 );
3853
3990 -it.effect("pauses uncached GitLab activity after only the reactions endpoint is rate limited", () =>
3854 +it.effect("pauses uncached activity on a host after one activity read is rate limited", () =>
3855 Effect.gen(function* () {
3992 - let commandCalls = 0;
3993 - const provider = yield* GitLabPullRequestProvider.make.pipe(
3994 - Effect.provide(
3995 - GitLabPullRequestCli.layer.pipe(
3996 - Layer.provide(GitLabCli.layer),
3997 - Layer.provide(
3998 - TestSourceControlHost.layer({
3999 - process: {
4000 - run: (input) =>
4001 - Effect.suspend(() => {
4002 - commandCalls += 1;
4003 - return input.args[1] === "graphql"
4004 - ? Effect.fail(
4005 - new VcsProcessExitError({
4006 - operation: input.operation,
4007 - command: input.command,
4008 - cwd: input.cwd,
4009 - exitCode: 1,
4010 - detail: "API rate limit exceeded.",
4011 - failureKind: "rate-limited",
4012 - }),
4013 - )
4014 - : Effect.succeed(TestSourceControlHost.processOutput("[]"));
4015 - }),
4016 - },
4017 - }),
4018 - ),
4019 - ),
4020 - ),
4021 - );
3856 + let activityReads = 0;
3857 const service = yield* makeService({
3858 projects: [
3859 project({
@@ -4030,7 +3865,22 @@ it.effect("pauses uncached GitLab activity after only the reactions endpoint is
3865 host: "gitlab.example.test",
3866 }),
3867 ],
4033 - providers: [provider],
3868 + providers: [
3869 + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), {
3870 + getChangeRequestActivity: () =>
3871 + Effect.suspend(() => {
3872 + activityReads++;
3873 + return Effect.fail(
3874 + new PullRequestProviderError({
3875 + provider: SourceControlProviderKind.make("gitlab"),
3876 + operation: "getChangeRequestActivity",
3877 + reason: "rate-limited",
3878 + detail: "API rate limit exceeded.",
3879 + }),
3880 + );
3881 + }),
3882 + }),
3883 + ],
3884 });
3885 const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
3886
@@ -4038,17 +3888,12 @@ it.effect("pauses uncached GitLab activity after only the reactions endpoint is
3888 _tag: "Failure",
3889 failure: {
3890 _tag: "PullRequestOperationError",
4041 - cause: {
4042 - _tag: "PullRequestProviderError",
4043 - reason: "rate-limited",
4044 - cause: { _tag: "GitLabCliRateLimitError" },
4045 - },
3891 + cause: { _tag: "PullRequestProviderError", reason: "rate-limited" },
3892 },
3893 });
4048 - const firstCommandCalls = commandCalls;
4049 - assert.isAbove(firstCommandCalls, 0);
3894 + assert.strictEqual(activityReads, 1);
3895
4051 - // A different merge request cannot reuse the first request's cached failure.
3896 + // A different change request cannot reuse the first request's cached failure.
3897 expect(yield* Effect.result(service.activity({ ...reference, number: 2 }))).toMatchObject({
3898 _tag: "Failure",
3899 failure: {
@@ -4063,7 +3908,7 @@ it.effect("pauses uncached GitLab activity after only the reactions endpoint is
3908 },
3909 },
3910 });
4066 - assert.strictEqual(commandCalls, firstCommandCalls);
3911 + assert.strictEqual(activityReads, 1);
3912 }),
3913 );
3914
@@ -4075,7 +3920,7 @@ it.effect("expands only files the change request changes, across every slice of
3920 project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
3921 ],
3922 providers: [
4078 - fakeProvider(SourceControlProviderKind.make("github"), {
3923 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3924 getDiff: (input) =>
3925 Effect.succeed(
3926 input.cursor === undefined
apps/server/src/pullRequest/pullRequestSyncKey.test.ts
+4 -6
@@ -5,12 +5,10 @@ import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
5
6 describe("pullRequestSyncKey", () => {
7 const reference = { projectId: ProjectId.make("project"), repository: "web", number: 7 };
8 - it.each([
9 - "dev.azure.com/org/project/_git/web",
10 - "ssh.dev.azure.com/v3/org/project/web",
11 - "vs-ssh.visualstudio.com/v3/org/project/web",
12 - "org.visualstudio.com/defaultcollection/project/_git/web",
13 - ])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => {
8 + // Every spelling of the key reaches dev.azure.com through the definition's canonical key,
9 + // which the Azure DevOps package tests.
10 + it("resolves hostless and checkout-host references named by the bare repository", () => {
11 + const canonicalKey = "ssh.dev.azure.com/v3/org/project/web";
12 const identity = {
13 canonicalKey,
14 provider: SourceControlProviderKind.make("azure-devops"),
apps/server/src/sourceControl/SourceControlDiscovery.test.ts
+92 -412
@@ -1,451 +1,131 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
1 +import { SourceControlProviderKind, VcsProcessSpawnError } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as Effect from "effect/Effect";
5 -import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
8 -import * as Path from "effect/Path";
9 -import * as Schema from "effect/Schema";
10 -import { ChildProcessSpawner } from "effect/process";
11 -import { HttpClient } from "effect/http";
12 -import { VcsProcessSpawnError } from "@t3tools/contracts";
7 +import { providerAuth } from "@t3tools/source-control-core/server/discovery";
8 +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9 +import {
10 + fakeDiscovery,
11 + fakeSourceControlProvider,
12 +} from "@t3tools/source-control-testing/fakeSourceControlDriver";
13 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
14
14 -import * as ServerSettings from "../serverSettings.ts";
15 import * as ServerConfig from "../config.ts";
16 -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
16 +import * as ServerSettings from "../serverSettings.ts";
17 import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
18 import * as VcsProcess from "../vcs/VcsProcess.ts";
19 -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
20 -import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
21 -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
22 -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
23 -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
24 -import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy";
25 -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
26 -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
27 -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
28 -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
29 -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
30 -import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
31 -import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
32 -import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
19 import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
34 -import * as BuiltInDriversTestkit from "./builtInDrivers.testkit.ts";
20 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
36 -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
37 -import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
21
39 -const layerSourceControlProviderRegistryTest = (input: {
40 - readonly bitbucket: Partial<BitbucketApi.BitbucketApi["Service"]>;
41 - readonly process: Partial<VcsProcess.VcsProcess["Service"]>;
42 -}) =>
43 - SourceControlProviderRegistry.layer.pipe(
44 - Layer.provide(BuiltInDriversTestkit.layerOverHostServices),
45 - Layer.provide(
46 - Layer.mergeAll(
47 - ServerConfig.layerTest(process.cwd(), {
48 - prefix: "t3-source-control-registry-test-",
49 - }).pipe(Layer.provide(NodeServices.layer)),
50 - Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
51 - Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
52 - Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
53 - Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
54 - ServerSettings.ServerSettingsService.layerTest(),
55 - Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
56 - Layer.mock(GitHubCredentials.GitHubCredentials)({}),
57 - Layer.mock(GitHubRest.GitHubRest)({}),
58 - // The GitHub provider's GraphQL reads go through these; no test here makes one.
59 - Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
60 - Layer.succeed(
61 - HttpClient.HttpClient,
62 - HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
63 - ),
64 - Layer.mock(GitVcsDriver.GitVcsDriver)({}),
65 - Layer.mock(GitLabCli.GitLabCli)({}),
66 - Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
67 - Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
68 - Layer.mock(GitCafeApi.GitCafeApi)({}),
69 - Layer.mock(GitCafeCredentials.GitCafeCredentials)({
70 - cliEnv: () => Effect.succeed({}),
71 - }),
72 - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
73 - Layer.mock(VcsProcess.VcsProcess)(input.process),
74 - ServerSourceControlHost.layer.pipe(
75 - Layer.provide(
76 - Layer.mergeAll(
77 - Layer.mock(VcsProcess.VcsProcess)(input.process),
78 - ServerSettings.ServerSettingsService.layerTest(),
79 - Layer.mock(GitVcsDriver.GitVcsDriver)({}),
80 - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
81 - ),
82 - ),
83 - ),
84 - ),
85 - ),
22 +const kind = SourceControlProviderKind.make;
23 +
24 +// Serves both the host's runs and the server's own VCS probes, whose inputs share these fields.
25 +const run = (
26 + input: Pick<
27 + SourceControlHost.SourceControlProcessInput,
28 + "operation" | "command" | "args" | "cwd"
29 + >,
30 +): Effect.Effect<SourceControlHost.SourceControlProcessOutput, VcsProcessSpawnError> => {
31 + if (input.args[0] === "--version") {
32 + return input.command === "missing-cli"
33 + ? Effect.fail(
34 + new VcsProcessSpawnError({
35 + operation: input.operation,
36 + command: input.command,
37 + cwd: input.cwd,
38 + cause: new Error(`${input.command} not found`),
39 + }),
40 + )
41 + : Effect.succeed(TestSourceControlHost.processOutput(`${input.command} version test\n`));
42 + }
43 + return Effect.succeed(
44 + TestSourceControlHost.processOutput(`signed in as ${input.command}-user\n`),
45 );
46 +};
47
88 -const processOutput = (
89 - stdout: string,
90 - options?: {
91 - readonly stderr?: string;
92 - readonly exitCode?: ChildProcessSpawner.ExitCode;
93 - },
94 -): VcsProcess.VcsProcessOutput => ({
95 - exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
96 - stdout,
97 - stderr: options?.stderr ?? "",
98 - stdoutTruncated: false,
99 - stderrTruncated: false,
48 +const cliDiscovery = (name: string) => ({
49 + type: "cli" as const,
50 + kind: kind(name),
51 + label: name,
52 + installHint: `Install ${name}.`,
53 + executable: name === "beta" ? "missing-cli" : `${name}-cli`,
54 + versionArgs: ["--version"],
55 + authArgs: ["auth", "status"],
56 + parseAuth: ({ stdout }: { readonly stdout: string }) =>
57 + providerAuth({ status: "authenticated", account: /as (\S+)/.exec(stdout)?.[1] }),
58 });
59
102 -const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
103 -
104 -it.effect("probes provider authentication without exposing token details", () => {
105 - const processMock = {
106 - run: (input: VcsProcess.VcsProcessInput) => {
107 - if (input.args[0] === "--version") {
108 - return Effect.succeed(processOutput(`${input.command} version test\n`));
109 - }
110 - if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {
111 - return Effect.succeed(
112 - processOutput(
113 - encodeJson({
114 - hosts: {
115 - "github.com": [
116 - {
117 - state: "success",
118 - active: true,
119 - host: "github.com",
120 - login: "octocat",
121 - tokenSource: "keyring",
122 - gitProtocol: "ssh",
123 - },
124 - ],
125 - },
126 - }),
127 - ),
128 - );
129 - }
130 - if (input.command === "glab" && input.args.join(" ") === "auth status") {
131 - return Effect.succeed(
132 - processOutput(`gitlab.com
133 -Logged in to gitlab.com as gitlab-user
134 -`),
135 - );
136 - }
137 - if (input.command === "tea" && input.args[0] === "login") {
138 - return Effect.succeed(
139 - processOutput(
140 - encodeJson([
141 - {
142 - name: "forgejo",
143 - url: "https://forgejo.example.com",
144 - ssh_host: "forgejo.example.com",
145 - user: "forgejo-user",
146 - valid: "true",
147 - default: "true",
148 - },
149 - ]),
150 - ),
151 - );
152 - }
153 - if (
154 - input.command === "az" &&
155 - input.args.join(" ") === "account show --query user.name -o tsv"
156 - ) {
157 - return Effect.succeed(processOutput("azure-user@example.com\n"));
158 - }
159 - if (input.command === "cafe" && input.args.slice(-3).join(" ") === "auth status --json") {
160 - return Effect.succeed(
161 - processOutput(
162 - encodeJson({ schemaVersion: 1, data: { host: "git.cafe", username: "cafe-user" } }),
163 - ),
164 - );
165 - }
166 - return Effect.fail(
167 - new VcsProcessSpawnError({
168 - operation: input.operation,
169 - command: input.command,
170 - cwd: input.cwd,
171 - cause: new Error(`${input.command} not found`),
172 - }),
173 - );
174 - },
175 - } satisfies Partial<VcsProcess.VcsProcess["Service"]>;
176 - const layerTest = SourceControlDiscovery.layer.pipe(
177 - Layer.provide(
178 - ServerConfig.layerTest(process.cwd(), {
179 - prefix: "t3-source-control-auth-discovery-",
180 - }),
181 - ),
182 - Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
183 - Layer.provide(
184 - layerSourceControlProviderRegistryTest({
185 - process: processMock,
186 - bitbucket: {
187 - probeAuth: Effect.succeed({
188 - status: "authenticated",
189 - account: Option.some("bitbucket-user"),
190 - host: Option.some("bitbucket.org"),
191 - detail: Option.none(),
192 - }),
193 - },
60 +const layerDiscovery = Layer.effect(
61 + SourceControlProviderRegistry.SourceControlProviderRegistry,
62 + SourceControlProviderRegistry.makeWithProviders(
63 + [
64 + cliDiscovery("alpha"),
65 + cliDiscovery("beta"),
66 + fakeDiscovery("gamma", {
67 + probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })),
68 }),
195 - ),
196 - Layer.provideMerge(NodeServices.layer),
197 - );
69 + ].map((discovery) => ({
70 + kind: discovery.kind,
71 + provider: fakeSourceControlProvider(discovery.kind),
72 + discovery,
73 + })),
74 + ),
75 +).pipe(
76 + Layer.provideMerge(TestSourceControlHost.layer({ process: { run } })),
77 + Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
78 + Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
79 + Layer.provideMerge(Layer.mock(VcsProcess.VcsProcess)({ run })),
80 + Layer.provideMerge(
81 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
82 + ),
83 + Layer.provideMerge(NodeServices.layer),
84 +);
85
199 - return Effect.gen(function* () {
86 +it.effect("reports every hosting integration in registry order with its sign-in", () =>
87 + Effect.gen(function* () {
88 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
89 const result = yield* discovery.discover;
90
91 assert.deepStrictEqual(
92 result.sourceControlProviders.map((item) => ({
93 kind: item.kind,
94 + status: item.status,
95 + version: item.version,
96 auth: item.auth.status,
97 account: item.auth.account,
208 - detail: item.auth.detail,
98 })),
99 [
100 {
212 - kind: SourceControlProviderKind.make("github"),
101 + kind: kind("alpha"),
102 + status: "available",
103 + version: Option.some("alpha-cli version test"),
104 auth: "authenticated",
214 - account: Option.some("octocat"),
215 - detail: Option.none(),
105 + account: Option.some("alpha-cli-user"),
106 },
107 {
218 - kind: SourceControlProviderKind.make("gitlab"),
219 - auth: "authenticated",
220 - account: Option.some("gitlab-user"),
221 - detail: Option.none(),
108 + kind: kind("beta"),
109 + status: "missing",
110 + version: Option.none(),
111 + auth: "unknown",
112 + account: Option.none(),
113 },
114 {
224 - kind: SourceControlProviderKind.make("gitcafe"),
115 + kind: kind("gamma"),
116 + status: "available",
117 + version: Option.none(),
118 auth: "authenticated",
226 - account: Option.some("cafe-user"),
227 - detail: Option.none(),
228 - },
229 - {
230 - kind: SourceControlProviderKind.make("forgejo"),
231 - auth: "authenticated",
232 - account: Option.some("forgejo-user"),
233 - detail: Option.none(),
234 - },
235 - {
236 - kind: SourceControlProviderKind.make("bitbucket"),
237 - auth: "authenticated",
238 - account: Option.some("bitbucket-user"),
239 - detail: Option.none(),
240 - },
241 - {
242 - kind: SourceControlProviderKind.make("azure-devops"),
243 - auth: "authenticated",
244 - account: Option.some("azure-user@example.com"),
245 - detail: Option.none(),
119 + account: Option.some("api-user"),
120 },
121 ],
122 );
249 - }).pipe(Effect.provide(layerTest));
250 -});
251 -
252 -it.effect(
253 - "checks out fj pull refs and preserves existing branches and dirty files until forced",
254 - () =>
255 - Effect.gen(function* () {
256 - const fs = yield* FileSystem.FileSystem;
257 - const git = yield* VcsProcess.VcsProcess;
258 - const path = yield* Path.Path;
259 - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" });
260 - const source = path.join(root, "source");
261 - const cwd = path.join(root, "checkout");
262 - yield* fs.makeDirectory(source);
263 - for (const args of [
264 - ["init", "-b", "main"],
265 - ["config", "user.name", "Test"],
266 - ["config", "user.email", "test@example.com"],
267 - ])
268 - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
269 - yield* fs.writeFileString(path.join(source, "base.txt"), "base\n");
270 - for (const args of [
271 - ["add", "base.txt"],
272 - ["commit", "-m", "base"],
273 - ])
274 - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
275 - const base = (yield* git.run({
276 - operation: "test.setup",
277 - command: "git",
278 - cwd: source,
279 - args: ["rev-parse", "HEAD"],
280 - })).stdout.trim();
281 - yield* git.run({
282 - operation: "test.setup",
283 - command: "git",
284 - cwd: root,
285 - args: ["clone", source, cwd],
286 - });
287 - yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n");
288 - for (const args of [
289 - ["add", "feature.txt"],
290 - ["commit", "-m", "feature"],
291 - ["update-ref", "refs/pull/42/head", "HEAD"],
292 - ])
293 - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
294 - const head = (yield* git.run({
295 - operation: "test.setup",
296 - command: "git",
297 - cwd: source,
298 - args: ["rev-parse", "HEAD"],
299 - })).stdout.trim();
300 - const fetched: string[] = [];
301 - const host = yield* SourceControlHost.SourceControlHost;
302 - const provider = yield* ForgejoSourceControlProvider.make.pipe(
303 - Effect.provideService(
304 - SourceControlHost.SourceControlHost,
305 - SourceControlHost.SourceControlHost.of({
306 - settings: host.settings,
307 - git: host.git,
308 - process: {
309 - run: (input) => {
310 - if (input.args[0] !== "fetch") return git.run(input);
311 - const url = input.args[2];
312 - assert.isDefined(url);
313 - fetched.push(url!);
314 - return git.run({
315 - ...input,
316 - args: input.args.map((arg) =>
317 - arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
318 - ),
319 - });
320 - },
321 - },
322 - }),
323 - ),
324 - Effect.provide(
325 - Layer.mock(ForgejoCli.ForgejoCli)({
326 - resolveRepository: () =>
327 - Effect.succeed({
328 - command: "fj",
329 - login: "work",
330 - repository: "reviewer/project",
331 - baseUrl: "https://forgejo.test",
332 - }),
333 - api: (input) => {
334 - assert.include(
335 - ["repos/reviewer/project", "repos/reviewer/project/pulls/42"],
336 - input.path,
337 - );
338 - return Effect.succeed(
339 - processOutput(
340 - encodeJson(
341 - input.path.endsWith("/pulls/42")
342 - ? {
343 - number: 42,
344 - title: "Checkout",
345 - html_url: "https://forgejo.test/reviewer/project/pulls/42",
346 - state: "open",
347 - merged: false,
348 - base: { ref: "main", sha: base, repo: null },
349 - head: { ref: "feature", sha: head, repo: null },
350 - }
351 - : {
352 - full_name: "reviewer/project",
353 - clone_url: source,
354 - ssh_url: "git@forgejo.test:reviewer/project.git",
355 - default_branch: "main",
356 - },
357 - ),
358 - ),
359 - );
360 - },
361 - }),
362 - ),
363 - );
364 - yield* provider.checkoutChangeRequest({
365 - cwd,
366 - reference: "https://forgejo.test/reviewer/project/pulls/42",
367 - });
368 - assert.strictEqual(
369 - (yield* git.run({
370 - operation: "test.verify",
371 - command: "git",
372 - cwd,
373 - args: ["branch", "--show-current"],
374 - })).stdout.trim(),
375 - "pulls/42",
376 - );
377 - assert.strictEqual(
378 - (yield* git.run({
379 - operation: "test.verify",
380 - command: "git",
381 - cwd,
382 - args: ["rev-parse", "HEAD"],
383 - })).stdout.trim(),
384 - head,
385 - );
386 - assert.strictEqual(
387 - yield* fs.readFileString(path.join(cwd, "feature.txt")),
388 - "pull request change\n",
389 - );
390 - for (const args of [
391 - ["checkout", "main"],
392 - ["branch", "-f", "pulls/42", "main"],
393 - ])
394 - yield* git.run({ operation: "test.setup", command: "git", cwd, args });
395 - yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n");
396 - yield* provider.checkoutChangeRequest({ cwd, reference: "42" });
397 - assert.strictEqual(
398 - (yield* git.run({
399 - operation: "test.verify",
400 - command: "git",
401 - cwd,
402 - args: ["rev-parse", "HEAD"],
403 - })).stdout.trim(),
404 - base,
405 - );
406 - assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false);
407 - yield* provider.checkoutChangeRequest({
408 - cwd,
409 - reference: "42",
410 - force: true,
411 - context: {
412 - provider: {
413 - kind: SourceControlProviderKind.make("forgejo"),
414 - name: "Forgejo",
415 - baseUrl: "https://forgejo.test",
416 - },
417 - remoteName: "origin",
418 - remoteUrl: "git@forgejo.test:maria/project.git",
419 - },
420 - });
421 - assert.strictEqual(
422 - (yield* git.run({
423 - operation: "test.verify",
424 - command: "git",
425 - cwd,
426 - args: ["rev-parse", "HEAD"],
427 - })).stdout.trim(),
428 - head,
429 - );
430 - assert.strictEqual(
431 - yield* fs.readFileString(path.join(cwd, "base.txt")),
432 - "uncommitted work\n",
433 - );
434 - assert.strictEqual(
435 - yield* fs.readFileString(path.join(cwd, "feature.txt")),
436 - "pull request change\n",
437 - );
438 - assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]);
439 - }).pipe(
440 - Effect.scoped,
441 - Effect.provide(
442 - ServerSourceControlHost.layer.pipe(
443 - Layer.provideMerge(VcsProcess.layer),
444 - Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
445 - Layer.provideMerge(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
446 - Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
447 - Layer.provideMerge(NodeServices.layer),
448 - ),
449 - ),
450 - ),
123 + assert.deepStrictEqual(
124 + result.versionControlSystems.map((item) => [item.kind, item.status]),
125 + [
126 + ["git", "available"],
127 + ["jj", "available"],
128 + ],
129 + );
130 + }).pipe(Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery)))),
131 );
apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+192 -283
@@ -9,54 +9,78 @@ import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as PlatformError from "effect/PlatformError";
11 import * as PubSub from "effect/PubSub";
12 -import * as Redacted from "effect/Redacted";
12 +import * as Schema from "effect/Schema";
13 import * as Stream from "effect/Stream";
14 import * as TestClock from "effect/testing/TestClock";
15 -import { HttpClient } from "effect/http";
16 -import { ChildProcessSpawner } from "effect/process";
15 import {
16 DEFAULT_SERVER_SETTINGS,
17 VcsProcessSpawnError,
18 VcsProcessTimeoutError,
19 } from "@t3tools/contracts";
20 +import type {
21 + SourceControlCliDiscoverySpec,
22 + SourceControlManagedCliDiscoverySpec,
23 + SourceControlProviderDiscoverySpec,
24 +} from "@t3tools/source-control-core/server/discovery";
25 +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
26 +import { fakeSourceControlProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver";
27 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
28
29 import * as ServerSettings from "../serverSettings.ts";
30 import * as ServerConfig from "../config.ts";
31 import type * as VcsDriver from "../vcs/VcsDriver.ts";
32 import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
27 -import * as VcsProcess from "../vcs/VcsProcess.ts";
28 -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
29 -import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
30 -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
31 -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
32 -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
33 -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
34 -import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy";
35 -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
36 -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
37 -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
38 -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
39 -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
40 -import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
41 -import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
42 -import * as BuiltInDriversTestkit from "./builtInDrivers.testkit.ts";
33 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
44 -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
34
35 const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
36 +const kind = SourceControlProviderKind.make;
37
48 -const processOutput = (
49 - stdout: string,
50 - options?: {
51 - readonly stderr?: string;
52 - readonly exitCode?: ChildProcessSpawner.ExitCode;
53 - },
54 -): VcsProcess.VcsProcessOutput => ({
55 - exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
56 - stdout,
57 - stderr: options?.stderr ?? "",
58 - stdoutTruncated: false,
59 - stderrTruncated: false,
38 +class NotAnswered extends Schema.TaggedError<NotAnswered>()("NotAnswered", {}) {}
39 +
40 +const linkSubject = (host: string) => () =>
41 + Effect.succeed({ title: `${host} subject`, body: null });
42 +
43 +/** Only GitHub and GitLab read linked subjects, as in production. */
44 +const PROVIDERS = [
45 + fakeSourceControlProvider("github", { resolveLink: linkSubject("github") }),
46 + fakeSourceControlProvider("gitlab", { resolveLink: linkSubject("gitlab") }),
47 + fakeSourceControlProvider("forgejo"),
48 + fakeSourceControlProvider("bitbucket"),
49 + fakeSourceControlProvider("azure-devops"),
50 +];
51 +
52 +/** A host CLI that claims every server it is signed in to, as `glab` does. */
53 +const claimingCli = (claims: string): SourceControlCliDiscoverySpec => ({
54 + type: "cli",
55 + kind: kind(claims),
56 + label: claims,
57 + installHint: `Install ${claims}.`,
58 + executable: `${claims}-cli`,
59 + versionArgs: ["--version"],
60 + authArgs: ["auth", "status"],
61 + remoteRefinementArgs: ({ provider }) => ["auth", "status", "--hostname", provider.name],
62 + parseAuth: () => ({
63 + status: "unknown",
64 + account: Option.none(),
65 + host: Option.none(),
66 + detail: Option.none(),
67 + }),
68 + refineUnknownRemote: ({ context, auth }) =>
69 + auth.stdout.includes(`Logged in to ${context.provider.name}`)
70 + ? { kind: kind(claims), name: `${claims} Self-Hosted`, baseUrl: context.provider.baseUrl }
71 + : null,
72 +});
73 +
74 +const managedCli = (
75 + claims: string,
76 + refine: SourceControlManagedCliDiscoverySpec["refineUnknownRemote"],
77 +): SourceControlManagedCliDiscoverySpec => ({
78 + type: "managed-cli",
79 + kind: kind(claims),
80 + label: claims,
81 + installHint: `Install ${claims}.`,
82 + probe: () => Effect.die("unused"),
83 + refineUnknownRemote: refine,
84 });
85
86 function makeRegistry(input: {
@@ -64,12 +88,9 @@ function makeRegistry(input: {
88 readonly name: string;
89 readonly url: string;
90 }>;
67 - readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
68 - readonly githubApi?: Partial<GitHubRest.GitHubRest["Service"]>;
69 - readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
70 - readonly forgejo?: Partial<ForgejoCli.ForgejoCli["Service"]>;
91 + readonly discovery?: ReadonlyArray<SourceControlProviderDiscoverySpec>;
92 + readonly run?: SourceControlHost.SourceControlHost["Service"]["process"]["run"];
93 readonly settings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
72 - readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
94 }) {
95 const driver = {
96 listRemotes: () =>
@@ -87,116 +108,89 @@ function makeRegistry(input: {
108 }),
109 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
110
90 - const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
91 - get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
92 - resolve:
93 - input.resolve ??
94 - (() =>
95 - Effect.succeed({
96 - kind: "git",
97 - repository: {
98 - kind: "git",
99 - rootPath: "/repo",
100 - metadataPath: null,
101 - freshness: {
102 - source: "live-local" as const,
103 - observedAt: TEST_EPOCH,
104 - expiresAt: Option.none(),
105 - },
106 - },
107 - driver: driver as unknown as VcsDriver.VcsDriver["Service"],
108 - })),
109 - });
110 -
111 - const layerProcess = Layer.mock(VcsProcess.VcsProcess)({
112 - run: () => Effect.succeed(processOutput("")),
113 - ...input.process,
114 - });
115 -
116 - return SourceControlProviderRegistry.make.pipe(
111 + const discovery = input.discovery ?? [claimingCli("gitlab")];
112 + return SourceControlProviderRegistry.makeWithProviders(
113 + PROVIDERS.map((provider) => ({
114 + kind: provider.kind,
115 + provider,
116 + discovery: discovery.find((spec) => spec.kind === provider.kind) ?? {
117 + type: "api",
118 + kind: provider.kind,
119 + label: provider.kind,
120 + installHint: "unused",
121 + probeAuth: Effect.die("unused"),
122 + },
123 + })),
124 + ).pipe(
125 Effect.provide(
118 - BuiltInDriversTestkit.layerOverHostServices.pipe(
119 - Layer.provideMerge(
120 - Layer.mergeAll(
121 - NodeServices.layer,
122 - layerRegistry,
123 - layerProcess,
124 - ServerSourceControlHost.layer.pipe(
125 - Layer.provide(
126 - Layer.mergeAll(
127 - layerProcess,
128 - layerRegistry,
129 - ServerSettings.ServerSettingsService.layerTest(),
130 - Layer.mock(GitVcsDriver.GitVcsDriver)({}),
131 - ),
132 - ),
133 - ),
134 - Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
135 - Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
136 - Layer.mock(BitbucketApi.BitbucketApi)({}),
137 - Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
138 - input.settings
139 - ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
140 - : ServerSettings.ServerSettingsService.layerTest(),
141 - Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
142 - Layer.mock(GitHubCredentials.GitHubCredentials)({}),
143 - // The GitHub provider's GraphQL reads go through these; no test here makes one.
144 - Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
145 - Layer.succeed(
146 - HttpClient.HttpClient,
147 - HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
148 - ),
149 - Layer.mock(GitHubRest.GitHubRest)({
150 - // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
151 - credential: (host) =>
152 - Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
153 - ...input.githubApi,
154 - }),
155 - Layer.mock(GitVcsDriver.GitVcsDriver)({}),
156 - Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
157 - Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
158 - Layer.mock(ForgejoCli.ForgejoCli)({
159 - listLogins: () => Effect.succeed([]),
160 - ...input.forgejo,
161 - }),
162 - Layer.mock(GitCafeApi.GitCafeApi)({}),
163 - Layer.mock(GitCafeCredentials.GitCafeCredentials)({
164 - cliEnv: () => Effect.succeed({}),
126 + Layer.mergeAll(
127 + Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
128 + resolve: () =>
129 + Effect.succeed({
130 + kind: "git",
131 + repository: {
132 + kind: "git",
133 + rootPath: "/repo",
134 + metadataPath: null,
135 + freshness: {
136 + source: "live-local" as const,
137 + observedAt: TEST_EPOCH,
138 + expiresAt: Option.none(),
139 + },
140 + },
141 + driver: driver as unknown as VcsDriver.VcsDriver["Service"],
142 }),
166 - ServerConfig.layerTest(process.cwd(), {
167 - prefix: "t3-source-control-registry-test-",
168 - }).pipe(Layer.provide(NodeServices.layer)),
169 - ),
170 - ),
143 + }),
144 + TestSourceControlHost.layer({
145 + process: {
146 + run: input.run ?? (() => Effect.succeed(TestSourceControlHost.processOutput(""))),
147 + },
148 + }),
149 + input.settings
150 + ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
151 + : ServerSettings.ServerSettingsService.layerTest(),
152 + ServerConfig.layerTest(process.cwd(), {
153 + prefix: "t3-source-control-registry-test-",
154 + }).pipe(Layer.provide(NodeServices.layer)),
155 ),
156 ),
157 );
158 }
159
176 -it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
160 +const signedIn = (host: string) => () =>
161 + Effect.succeed(TestSourceControlHost.processOutput(` ✓ Logged in to ${host} as user\n`));
162 +
163 +it.effect("routes an unknown remote to the integration that claims its server", () =>
164 Effect.gen(function* () {
165 + const asked: Array<string> = [];
166 const registry = yield* makeRegistry({
179 - remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
180 - process: {
181 - run: () =>
182 - Effect.succeed(
183 - processOutput(
184 - `gitlab.com
185 - x gitlab.com: API call failed: 401 Unauthorized
186 - ! No token found
187 -self-hosted.example.test
188 - ✓ Logged in to self-hosted.example.test as gitlab-user
189 - ✓ Token found: ******
190 -`,
191 - { exitCode: ChildProcessSpawner.ExitCode(1) },
192 - ),
193 - ),
167 + remotes: [{ name: "origin", url: "git@self-hosted.example.test:group/project.git" }],
168 + run: (input) => {
169 + asked.push([input.command, ...input.args].join(" "));
170 + return signedIn("self-hosted.example.test")();
171 },
172 });
173
197 - const provider = yield* registry.resolve({ cwd: "/repo" });
174 + const handle = yield* registry.resolveHandle({ cwd: "/repo" });
175
199 - assert.strictEqual(provider.kind, "gitlab");
176 + assert.strictEqual(handle.provider.kind, "gitlab");
177 + assert.deepStrictEqual(handle.context?.provider, {
178 + kind: kind("gitlab"),
179 + name: "gitlab Self-Hosted",
180 + baseUrl: "https://self-hosted.example.test",
181 + });
182 + assert.deepStrictEqual(asked, ["gitlab-cli auth status --hostname self-hosted.example.test"]);
183 + }),
184 +);
185 +
186 +it.effect("leaves a remote no integration claims unknown, with its server's address", () =>
187 + Effect.gen(function* () {
188 + const registry = yield* makeRegistry({
189 + remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
190 + });
191 + const handle = yield* registry.resolveHandle({ cwd: "/repo" });
192 + assert.strictEqual(handle.provider.kind, kind("unknown"));
193 + assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
194 }),
195 );
196
@@ -204,21 +198,14 @@ it.effect("refines the caller-selected remote instead of choosing another config
198 Effect.gen(function* () {
199 const registry = yield* makeRegistry({
200 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
207 - process: {
208 - run: () =>
209 - Effect.succeed(
210 - processOutput(`self-hosted.example.test
211 - ✓ Logged in to self-hosted.example.test as gitlab-user
212 -`),
213 - ),
214 - },
201 + run: signedIn("self-hosted.example.test"),
202 });
203
204 const handle = yield* registry.resolveHandle({
205 cwd: "/repo",
206 context: {
207 provider: {
221 - kind: SourceControlProviderKind.make("unknown"),
208 + kind: kind("unknown"),
209 name: "self-hosted.example.test",
210 baseUrl: "https://self-hosted.example.test",
211 },
@@ -232,29 +219,6 @@ it.effect("refines the caller-selected remote instead of choosing another config
219 }),
220 );
221
235 -it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
236 - Effect.gen(function* () {
237 - const registry = yield* makeRegistry({
238 - remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
239 - process: {
240 - run: () =>
241 - Effect.succeed(
242 - processOutput(
243 - `self-hosted.example.test:8443
244 - ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
245 - ✓ Token found: ******
246 -`,
247 - ),
248 - ),
249 - },
250 - });
251 -
252 - const provider = yield* registry.resolve({ cwd: "/repo" });
253 -
254 - assert.strictEqual(provider.kind, "gitlab");
255 - }),
256 -);
257 -
222 it.effect("falls back to a non-origin remote when origin is not configured", () =>
223 Effect.gen(function* () {
224 const registry = yield* makeRegistry({
@@ -268,44 +232,22 @@ it.effect("falls back to a non-origin remote when origin is not configured", ()
232 );
233
234 it.effect(
271 - "routes linked subjects by URL independently of the checkout and skips unsupported links",
235 + "routes linked subjects to the host that serves them, independently of the checkout",
236 () =>
237 Effect.gen(function* () {
238 const registry = yield* makeRegistry({
239 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
276 - githubApi: {
277 - rest: () =>
278 - Effect.succeed({
279 - status: 200,
280 - headers: {},
281 - body: JSON.stringify({ title: "GitHub issue", body: null }),
282 - truncated: false,
283 - invalidUtf8: false,
284 - }),
285 - },
286 - gitlab: {
287 - execute: () =>
288 - Effect.succeed(
289 - processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
290 - ),
291 - },
240 });
293 - for (const [url, expected] of [
294 - ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
295 - [
296 - "https://gitlab.com/team/sub/project/-/merge_requests/2",
297 - { title: "GitLab MR", body: "Nested project" },
298 - ],
241 + for (const [url, host] of [
242 + ["https://github.com/team/project/issues/1", "github"],
243 + ["https://gitlab.com/team/sub/project/-/merge_requests/2", "gitlab"],
244 ] as const) {
245 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
246 assert.ok(lookup);
302 - assert.deepStrictEqual(yield* lookup, expected);
247 + assert.deepStrictEqual(yield* lookup, { title: `${host} subject`, body: null });
248 }
249 for (const url of [
250 "https://example.test/team/project/issues/1",
306 - "https://github.attacker.test/team/project/issues/1",
307 - "https://gitlab.attacker.test/team/project/-/issues/1",
308 - "https://github.com/team/project",
251 "https://codeberg.org/team/project/issues/1",
252 "https://bitbucket.org/team/project/pull-requests/1",
253 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
@@ -315,70 +257,38 @@ it.effect(
257 assert.strictEqual(
258 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
259 undefined,
260 + url,
261 );
262 }
263 }).pipe(Effect.scoped),
264 );
265
323 -it.effect.each([
324 - { name: "a credential", credential: "found", expected: "github" },
325 - { name: "a host turned off in Settings", credential: "disabled", expected: "github" },
326 - { name: "no credential", credential: "missing", expected: "unknown" },
327 -] as const)("resolves custom-host remotes with $name", (scenario) =>
266 +it.effect("does not refine a context whose server address is empty", () =>
267 Effect.gen(function* () {
329 - const hosts: Array<string> = [];
330 - const commands: Array<string> = [];
331 - const registry = yield* makeRegistry({
332 - remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
333 - process: {
334 - run: ({ command }) => {
335 - commands.push(command);
336 - return Effect.succeed(processOutput(""));
337 - },
338 - },
339 - githubApi: {
340 - credential: (host) => {
341 - hosts.push(host);
342 - return scenario.credential === "found"
343 - ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
344 - : scenario.credential === "disabled"
345 - ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
346 - : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
347 - },
348 - },
349 - });
350 - const handle = yield* registry.resolveHandle({ cwd: "/repo" });
351 - assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected));
352 - assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
353 - assert.deepStrictEqual(hosts, ["code.example.test"]);
354 - assert.notInclude(commands, "gh");
355 - }),
356 -);
357 -
358 -it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
359 - Effect.gen(function* () {
360 - const hosts: string[] = [];
268 + let asked = 0;
269 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
270 const registry = yield* makeRegistry({
271 remotes: [{ name: "origin", url: remoteUrl }],
364 - githubApi: {
365 - credential: (host) => {
366 - hosts.push(host);
367 - return Effect.succeed({
368 - token: Redacted.make("token"),
369 - fingerprint: `${host}:fingerprint`,
370 - });
371 - },
372 - },
272 + discovery: [
273 + managedCli("github", ({ context }) => {
274 + asked += 1;
275 + return Effect.succeed(
276 + context.provider.baseUrl === ""
277 + ? null
278 + : { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl },
279 + );
280 + }),
281 + ],
282 });
283 const context = {
375 - provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
284 + provider: { kind: kind("unknown"), name: "Unknown", baseUrl: "" },
285 remoteName: "origin",
286 remoteUrl,
287 };
379 - const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
380 - assert.deepStrictEqual(unresolved.context, context);
381 - assert.deepStrictEqual(hosts, []);
288 + assert.deepStrictEqual(
289 + (yield* registry.resolveHandle({ cwd: "/repo", context })).context,
290 + context,
291 + );
292
293 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
294 assert.strictEqual(resolved.provider.kind, "github");
@@ -386,7 +296,7 @@ it.effect("skips GitHub discovery for the identity resolver's empty base URL", (
296 resolved.context?.provider.baseUrl,
297 "https://githubenterprise.dev.example.com",
298 );
389 - assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
299 + assert.strictEqual(asked, 2);
300 }),
301 );
302
@@ -406,7 +316,7 @@ const resolveUnknown = (
316 cwd: `/${repository}`,
317 context: {
318 provider: {
409 - kind: SourceControlProviderKind.make("unknown"),
319 + kind: kind("unknown"),
320 name: "git.example.internal",
321 baseUrl: "https://git.example.internal",
322 },
@@ -421,24 +331,16 @@ it.effect("asks once for every checkout of a server no integration claims", () =
331 const release = yield* Deferred.make<void>();
332 const registry = yield* makeRegistry({
333 remotes: [],
424 - process: {
425 - run: ({ command, args, cwd }) => {
426 - asked.push([command, ...args].join(" "));
427 - return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
428 - },
429 - },
430 - githubApi: {
431 - credential: (host) => {
432 - asked.push(`credential ${host}`);
433 - return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
434 - },
435 - },
436 - forgejo: {
437 - listLogins: ({ command = "tea", cwd }) => {
438 - asked.push(command);
439 - const cause = notFound(command, cwd);
440 - return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause }));
441 - },
334 + discovery: [
335 + claimingCli("gitlab"),
336 + managedCli("github", ({ context }) => {
337 + asked.push(`managed ${context.provider.name}`);
338 + return Effect.succeed(null);
339 + }),
340 + ],
341 + run: ({ command, args, cwd }) => {
342 + asked.push([command, ...args].join(" "));
343 + return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
344 },
345 });
346
@@ -461,10 +363,8 @@ it.effect("asks once for every checkout of a server no integration claims", () =
363 );
364 const once = asked.slice();
365 assert.sameMembers(once, [
464 - "credential git.example.internal",
465 - "glab auth status --hostname Git.Example.Internal",
466 - "fj",
467 - "tea",
366 + "managed git.example.internal",
367 + "gitlab-cli auth status --hostname git.example.internal",
368 ]);
369
370 yield* TestClock.adjust("5 minutes");
@@ -476,20 +376,27 @@ it.effect("asks once for every checkout of a server no integration claims", () =
376 it.effect("asks again after a check that could not answer", () =>
377 Effect.gen(function* () {
378 let asks = 0;
379 + let managedAsks = 0;
380 const registry = yield* makeRegistry({
381 remotes: [],
481 - process: {
482 - run: ({ command, cwd }) => {
483 - asks += 1;
484 - return Effect.fail(
485 - new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
486 - );
487 - },
382 + discovery: [
383 + claimingCli("gitlab"),
384 + managedCli("github", () => {
385 + managedAsks += 1;
386 + return Effect.fail(new NotAnswered());
387 + }),
388 + ],
389 + run: ({ command, cwd }) => {
390 + asks += 1;
391 + return Effect.fail(
392 + new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
393 + );
394 },
395 });
396 yield* resolveUnknown(registry, "a");
397 yield* resolveUnknown(registry, "b");
398 assert.strictEqual(asks, 2);
399 + assert.strictEqual(managedAsks, 2);
400 }),
401 );
402
@@ -497,7 +404,7 @@ it.effect("asks again once Settings change", () =>
404 Effect.gen(function* () {
405 const changes = yield* PubSub.unbounded<typeof DEFAULT_SERVER_SETTINGS>();
406 const handled = yield* Deferred.make<void>();
500 - let signedIn = false;
407 + let claims = false;
408 const registry = yield* makeRegistry({
409 remotes: [],
410 settings: {
@@ -514,16 +421,18 @@ it.effect("asks again once Settings change", () =>
421 ),
422 ),
423 },
517 - process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) },
518 - githubApi: {
519 - credential: (host) =>
520 - signedIn
521 - ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
522 - : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
523 - },
424 + discovery: [
425 + managedCli("github", ({ context }) =>
426 + Effect.succeed(
427 + claims
428 + ? { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl }
429 + : null,
430 + ),
431 + ),
432 + ],
433 });
434 assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown");
526 - signedIn = true;
435 + claims = true;
436 assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown");
437
438 yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS);
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+1 -1
@@ -357,7 +357,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
357 },
358 );
359
360 -export const make = Effect.gen(function* () {
360 +const make = Effect.gen(function* () {
361 const drivers = yield* BuiltInDrivers.SourceControlDrivers;
362 return yield* makeWithProviders(
363 drivers.map(({ driver, instance }): SourceControlProviderRegistration => ({
apps/server/src/sourceControl/builtInDrivers.testkit.ts deleted
-40
@@ -1,40 +0,0 @@
1 -import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
2 -import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
3 -import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
4 -import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";
5 -import * as GitHubDriver from "@t3tools/source-control-github/server/driver";
6 -import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
7 -import type {
8 - SourceControlDriver,
9 - SourceControlDriverInstance,
10 -} from "@t3tools/source-control-core/server/driver";
11 -import * as Effect from "effect/Effect";
12 -import * as Layer from "effect/Layer";
13 -
14 -import * as BuiltInDrivers from "./builtInDrivers.ts";
15 -
16 -const entry = (
17 - driver: SourceControlDriver,
18 - instance: SourceControlDriverInstance,
19 -): BuiltInDrivers.SourceControlDriverEntry => ({ driver, instance });
20 -
21 -/** Every built-in driver over whatever stands in for its host's own services. */
22 -export const layerOverHostServices = Layer.effect(
23 - BuiltInDrivers.SourceControlDrivers,
24 - Effect.all([
25 - GitHubDriver.makeInstance.pipe(Effect.map((instance) => entry(GitHubDriver.driver, instance))),
26 - GitLabDriver.makeInstance.pipe(Effect.map((instance) => entry(GitLabDriver.driver, instance))),
27 - GitCafeDriver.makeInstance.pipe(
28 - Effect.map((instance) => entry(GitCafeDriver.driver, instance)),
29 - ),
30 - ForgejoDriver.makeInstance.pipe(
31 - Effect.map((instance) => entry(ForgejoDriver.driver, instance)),
32 - ),
33 - BitbucketDriver.makeInstance.pipe(
34 - Effect.map((instance) => entry(BitbucketDriver.driver, instance)),
35 - ),
36 - AzureDevOpsDriver.makeInstance.pipe(
37 - Effect.map((instance) => entry(AzureDevOpsDriver.driver, instance)),
38 - ),
39 - ]),
40 -);
packages/source-control-azure-devops/package.json
-28
@@ -7,34 +7,6 @@
7 "types": "./src/client/definition.ts",
8 "import": "./src/client/definition.ts"
9 },
10 - "./server/AzureDevOpsCli": {
11 - "types": "./src/server/AzureDevOpsCli.ts",
12 - "import": "./src/server/AzureDevOpsCli.ts"
13 - },
14 - "./server/azureDevOpsDiff": {
15 - "types": "./src/server/azureDevOpsDiff.ts",
16 - "import": "./src/server/azureDevOpsDiff.ts"
17 - },
18 - "./server/AzureDevOpsPullRequestCli": {
19 - "types": "./src/server/AzureDevOpsPullRequestCli.ts",
20 - "import": "./src/server/AzureDevOpsPullRequestCli.ts"
21 - },
22 - "./server/azureDevOpsPullRequestJson": {
23 - "types": "./src/server/azureDevOpsPullRequestJson.ts",
24 - "import": "./src/server/azureDevOpsPullRequestJson.ts"
25 - },
26 - "./server/AzureDevOpsPullRequestProvider": {
27 - "types": "./src/server/AzureDevOpsPullRequestProvider.ts",
28 - "import": "./src/server/AzureDevOpsPullRequestProvider.ts"
29 - },
30 - "./server/azureDevOpsPullRequests": {
31 - "types": "./src/server/azureDevOpsPullRequests.ts",
32 - "import": "./src/server/azureDevOpsPullRequests.ts"
33 - },
34 - "./server/AzureDevOpsSourceControlProvider": {
35 - "types": "./src/server/AzureDevOpsSourceControlProvider.ts",
36 - "import": "./src/server/AzureDevOpsSourceControlProvider.ts"
37 - },
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.test.ts new
+27
@@ -0,0 +1,27 @@
1 +import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Option from "effect/Option";
4 +import { ChildProcessSpawner } from "effect/process";
5 +
6 +import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
7 +
8 +const { parseAuth } = AzureDevOpsSourceControlProvider.discovery;
9 +
10 +it("reads the signed-in Azure account and says when az is signed out", () => {
11 + assert.deepStrictEqual(parseAuth(processOutput("azure-user@example.com\n")), {
12 + status: "authenticated",
13 + account: Option.some("azure-user@example.com"),
14 + host: Option.some("dev.azure.com"),
15 + detail: Option.none(),
16 + });
17 + assert.strictEqual(
18 + parseAuth(
19 + processOutput("", {
20 + stderr: "Please run 'az login' to setup account.\n",
21 + exitCode: ChildProcessSpawner.ExitCode(1),
22 + }),
23 + ).status,
24 + "unauthenticated",
25 + );
26 + assert.strictEqual(parseAuth(processOutput("\n")).status, "unknown");
27 +});
packages/source-control-azure-devops/src/server/driver.ts
+1 -2
@@ -14,8 +14,7 @@ import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlPro
14
15 const services = AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer));
16
17 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
18 -export const makeInstance = Effect.all({
17 +const makeInstance = Effect.all({
18 sourceControl: AzureDevOpsSourceControlProvider.make,
19 discovery: Effect.succeed(AzureDevOpsSourceControlProvider.discovery),
20 pullRequests: AzureDevOpsPullRequestProvider.make,
packages/source-control-bitbucket/package.json
+2 -24
@@ -7,30 +7,6 @@
7 "types": "./src/client/definition.ts",
8 "import": "./src/client/definition.ts"
9 },
10 - "./server/BitbucketApi": {
11 - "types": "./src/server/BitbucketApi.ts",
12 - "import": "./src/server/BitbucketApi.ts"
13 - },
14 - "./server/BitbucketPullRequestApi": {
15 - "types": "./src/server/BitbucketPullRequestApi.ts",
16 - "import": "./src/server/BitbucketPullRequestApi.ts"
17 - },
18 - "./server/bitbucketPullRequestJson": {
19 - "types": "./src/server/bitbucketPullRequestJson.ts",
20 - "import": "./src/server/bitbucketPullRequestJson.ts"
21 - },
22 - "./server/BitbucketPullRequestProvider": {
23 - "types": "./src/server/BitbucketPullRequestProvider.ts",
24 - "import": "./src/server/BitbucketPullRequestProvider.ts"
25 - },
26 - "./server/bitbucketPullRequests": {
27 - "types": "./src/server/bitbucketPullRequests.ts",
28 - "import": "./src/server/bitbucketPullRequests.ts"
29 - },
30 - "./server/BitbucketSourceControlProvider": {
31 - "types": "./src/server/BitbucketSourceControlProvider.ts",
32 - "import": "./src/server/BitbucketSourceControlProvider.ts"
33 - },
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
@@ -48,7 +24,9 @@
24 "effect": "catalog:"
25 },
26 "devDependencies": {
27 + "@effect/platform-node": "catalog:",
28 "@effect/vitest": "catalog:",
29 + "@t3tools/source-control-testing": "workspace:*",
30 "@types/node": "catalog:",
31 "vite-plus": "catalog:"
32 }
packages/source-control-bitbucket/src/server/BitbucketApi.test.ts renamed
+55 -77
@@ -14,14 +14,13 @@ import * as Schema from "effect/Schema";
14 import * as TestClock from "effect/testing/TestClock";
15 import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
16
17 -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
17 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
19 -import * as ServerSettings from "../serverSettings.ts";
20 -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
21 -import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
22 -import type * as VcsDriver from "../vcs/VcsDriver.ts";
23 -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
24 -import * as VcsProcess from "../vcs/VcsProcess.ts";
18 +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
19 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
20 +
21 +import * as BitbucketApi from "./BitbucketApi.ts";
22 +
23 +type HostGit = SourceControlHost.SourceControlHost["Service"]["git"];
24
25 const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
26
@@ -71,7 +70,7 @@ function makeLayer(input: {
70 request: HttpClientRequest.HttpClientRequest,
71 ) => HttpClientError.HttpClientError;
72 readonly stall?: boolean;
74 - readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
73 + readonly git?: Partial<HostGit>;
74 readonly env?: Record<string, string>;
75 }) {
76 const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
@@ -84,89 +83,54 @@ function makeLayer(input: {
83 ),
84 );
85 const gitMock = {
87 - readConfigValue: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"]>(() =>
86 + readConfigValue: vi.fn<HostGit["readConfigValue"]>(() =>
87 Effect.succeed<string | null>("git@bitbucket.org:pingdotgg/t3code.git"),
88 ),
90 - resolvePrimaryRemoteName: vi.fn<
91 - GitVcsDriver.GitVcsDriver["Service"]["resolvePrimaryRemoteName"]
92 - >(() => Effect.succeed("origin")),
93 - ensureRemote: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["ensureRemote"]>(() =>
94 - Effect.succeed("octocat"),
95 - ),
96 - fetchRemoteBranch: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteBranch"]>(
97 - () => Effect.void,
89 + resolvePrimaryRemoteName: vi.fn<HostGit["resolvePrimaryRemoteName"]>(() =>
90 + Effect.succeed("origin"),
91 ),
99 - fetchRemoteTrackingBranch: vi.fn<
100 - GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"]
101 - >(() => Effect.void),
102 - setBranchUpstream: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"]>(
103 - () => Effect.void,
104 - ),
105 - switchRef: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["switchRef"]>((request) =>
92 + ensureRemote: vi.fn<HostGit["ensureRemote"]>(() => Effect.succeed("octocat")),
93 + fetchRemoteBranch: vi.fn<HostGit["fetchRemoteBranch"]>(() => Effect.void),
94 + fetchRemoteTrackingBranch: vi.fn<HostGit["fetchRemoteTrackingBranch"]>(() => Effect.void),
95 + setBranchUpstream: vi.fn<HostGit["setBranchUpstream"]>(() => Effect.void),
96 + switchRef: vi.fn<HostGit["switchRef"]>((request) =>
97 Effect.succeed({ refName: request.refName }),
98 ),
108 - listLocalBranchNames: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["listLocalBranchNames"]>(() =>
109 - Effect.succeed([]),
110 - ),
99 + listLocalBranchNames: vi.fn<HostGit["listLocalBranchNames"]>(() => Effect.succeed([])),
100 };
101 const git = {
102 ...gitMock,
103 ...input.git,
115 - } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
116 -
117 - const driver = {
118 - listRemotes: vi.fn(() =>
119 - Effect.succeed({
120 - remotes: [
121 - {
122 - name: "origin",
123 - url: "git@bitbucket.org:pingdotgg/t3code.git",
124 - pushUrl: Option.none(),
125 - isPrimary: true,
126 - },
127 - ],
128 - freshness: {
129 - source: "live-local" as const,
130 - observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
131 - expiresAt: Option.none(),
132 - },
133 - }),
134 - ),
135 - } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
104 + } satisfies Partial<HostGit>;
105
137 - const resolve = vi.fn(() =>
106 + const listRemotes = vi.fn(() =>
107 Effect.succeed({
139 - kind: "git" as const,
140 - repository: {
141 - kind: "git" as const,
142 - rootPath: "/repo",
143 - metadataPath: null,
144 - freshness: {
145 - source: "live-local" as const,
146 - observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
147 - expiresAt: Option.none(),
108 + remotes: [
109 + {
110 + name: "origin",
111 + url: "git@bitbucket.org:pingdotgg/t3code.git",
112 + pushUrl: Option.none(),
113 + isPrimary: true,
114 },
115 + ],
116 + freshness: {
117 + source: "live-local" as const,
118 + observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
119 + expiresAt: Option.none(),
120 },
150 - driver: driver as unknown as VcsDriver.VcsDriver["Service"],
121 }),
122 );
123 + // The outer effect resolves the repository; the inner one lists its remotes.
124 + const resolve = vi.fn((_cwd: string) => Effect.succeed(Effect.suspend(listRemotes)));
125
126 const layer = BitbucketApi.layer.pipe(
155 - Layer.provide(ServerSourceControlHost.layer),
127 Layer.provide(SourceControlRateLimit.layer),
157 - Layer.provide(Layer.mock(VcsProcess.VcsProcess)({})),
128 Layer.provide(
129 Layer.succeed(
130 HttpClient.HttpClient,
131 HttpClient.make((request) => execute(request)),
132 ),
133 ),
164 - Layer.provide(
165 - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
166 - resolve,
167 - }),
168 - ),
169 - Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)),
134 Layer.provide(
135 ConfigProvider.layer(
136 ConfigProvider.fromEnv({
@@ -178,11 +142,11 @@ function makeLayer(input: {
142 }),
143 ),
144 ),
181 - Layer.provideMerge(ServerSettings.layerTest()),
145 + Layer.provideMerge(TestSourceControlHost.layer({ git: { ...git, remotes: resolve } })),
146 Layer.provideMerge(NodeServices.layer),
147 );
148
185 - return { execute, git: gitMock, resolve, listRemotes: driver.listRemotes, layer };
149 + return { execute, git: gitMock, resolve, listRemotes, layer };
150 }
151
152 it.effect("parses pull request responses from the Bitbucket REST API", () => {
@@ -476,6 +440,20 @@ it.effect("creates pull requests using the official REST payload shape", () => {
440 }).pipe(Effect.provide(layer), Effect.scoped);
441 });
442
443 +it.effect("reports the account Bitbucket confirms for the configured credential", () => {
444 + const { layer } = makeLayer({
445 + response: () => Response.json({ username: "bitbucket-user" }),
446 + });
447 +
448 + return Effect.gen(function* () {
449 + const bitbucket = yield* BitbucketApi.BitbucketApi;
450 + const auth = yield* bitbucket.probeAuth;
451 + assert.strictEqual(auth.status, "authenticated");
452 + assert.deepStrictEqual(auth.account, Option.some("bitbucket-user"));
453 + assert.deepStrictEqual(auth.host, Option.some("bitbucket.org"));
454 + }).pipe(Effect.provide(layer));
455 +});
456 +
457 it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
458 const { execute, layer } = makeLayer({
459 response: () => Response.json({ username: "bitbucket-user" }),
@@ -485,12 +463,12 @@ it.effect("prefers credentials saved in settings over the environment, without a
463
464 return Effect.gen(function* () {
465 const bitbucket = yield* BitbucketApi.BitbucketApi;
488 - const settings = yield* ServerSettings.ServerSettingsService;
466 + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
467
468 yield* bitbucket.probeAuth;
469 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
470
493 - yield* settings.updateSettings({
471 + yield* settings.update({
472 sourceControlHosts: {
473 bitbucket: { email: "saved@example.com", apiToken: "saved-api-token" },
474 },
@@ -498,13 +476,13 @@ it.effect("prefers credentials saved in settings over the environment, without a
476 yield* bitbucket.probeAuth;
477 assert.strictEqual(lastAuthorization(), basic("saved@example.com", "saved-api-token"));
478
501 - yield* settings.updateSettings({
479 + yield* settings.update({
480 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
481 });
482 yield* bitbucket.probeAuth;
483 assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
484
507 - yield* settings.updateSettings({
485 + yield* settings.update({
486 sourceControlHosts: { bitbucket: { accessToken: "", apiToken: "" } },
487 });
488 yield* bitbucket.probeAuth;
@@ -519,11 +497,11 @@ it.effect("never puts a saved token that is unsafe for an HTTP header on the wir
497
498 return Effect.gen(function* () {
499 const bitbucket = yield* BitbucketApi.BitbucketApi;
522 - const settings = yield* ServerSettings.ServerSettingsService;
500 + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
501
502 // Fetch would reject this header with an error quoting the token, and that error reaches
503 // clients. The unusable token is ignored, so the environment credential is used instead.
526 - yield* settings.updateSettings({
504 + yield* settings.update({
505 sourceControlHosts: { bitbucket: { accessToken: "saved\ntoken" } },
506 });
507 yield* bitbucket.probeAuth;
@@ -542,11 +520,11 @@ it.effect("reports saved credentials as configured when Bitbucket cannot confirm
520
521 return Effect.gen(function* () {
522 const bitbucket = yield* BitbucketApi.BitbucketApi;
545 - const settings = yield* ServerSettings.ServerSettingsService;
523 + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
524
525 assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
526
549 - yield* settings.updateSettings({
527 + yield* settings.update({
528 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
529 });
530 assert.deepStrictEqual(yield* bitbucket.probeAuth, {
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.listing.test.ts new
+88
@@ -0,0 +1,88 @@
1 +import { assert, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +
5 +import * as BitbucketApi from "./BitbucketApi.ts";
6 +import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
7 +import * as BitbucketPullRequestProvider from "./BitbucketPullRequestProvider.ts";
8 +
9 +it.effect("pages through rows that share an update instant by excluding those already sent", () =>
10 + Effect.gen(function* () {
11 + const boundary = "2026-10-12T00:00:00.000Z";
12 + const older = "2026-10-11T00:00:00.000Z";
13 + const rows = [1, 2, 3, 4, 5].map((id) => ({
14 + id,
15 + title: `Pull request ${id}`,
16 + state: "OPEN",
17 + created_on: older,
18 + updated_on: id <= 3 ? boundary : older,
19 + source: { branch: { name: `feat/${id}` } },
20 + destination: { branch: { name: "main" } },
21 + links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${id}` } },
22 + }));
23 + const filters: string[] = [];
24 + const provider = yield* BitbucketPullRequestProvider.make.pipe(
25 + Effect.provide(
26 + BitbucketPullRequestApi.layer.pipe(
27 + Layer.provide(
28 + Layer.mock(BitbucketApi.BitbucketApi)({
29 + request: ({ url }) => {
30 + const filter =
31 + new URL(url, "https://api.bitbucket.org").searchParams.get("q") ?? "";
32 + filters.push(filter);
33 + const updatedBefore = /updated_on <= (\S+)/.exec(filter)?.[1];
34 + const excluded = new Set(
35 + Array.from(filter.matchAll(/id != (\d+)/g), (match) => Number(match[1])),
36 + );
37 + const values = rows.filter(
38 + (row) =>
39 + (updatedBefore === undefined || row.updated_on <= updatedBefore) &&
40 + !excluded.has(row.id),
41 + );
42 + return Effect.succeed({ body: JSON.stringify({ values }), truncated: false });
43 + },
44 + }),
45 + ),
46 + ),
47 + ),
48 + );
49 + const list = (cursor?: {
50 + readonly updatedBefore: string;
51 + readonly delivered: number;
52 + readonly seenAt: ReadonlyArray<number>;
53 + }) =>
54 + provider.listChangeRequests({
55 + cwd: "/w",
56 + repository: "acme/web",
57 + host: "bitbucket.org",
58 + state: "open",
59 + involvement: "all",
60 + viewer: "bilal",
61 + limit: 2,
62 + ...(cursor === undefined ? {} : { cursor }),
63 + });
64 +
65 + const first = yield* list();
66 + assert.deepStrictEqual(
67 + first.items.map((item) => item.number),
68 + [1, 2],
69 + );
70 + assert.isTrue(first.truncated);
71 +
72 + const second = yield* list({ updatedBefore: boundary, delivered: 2, seenAt: [1, 2] });
73 + assert.deepStrictEqual(
74 + second.items.map((item) => item.number),
75 + [3, 4],
76 + );
77 + assert.include(filters.at(-1), `updated_on <= ${boundary}`);
78 + assert.include(filters.at(-1), "id != 1");
79 + assert.include(filters.at(-1), "id != 2");
80 +
81 + const last = yield* list({ updatedBefore: older, delivered: 4, seenAt: [4] });
82 + assert.deepStrictEqual(
83 + last.items.map((item) => item.number),
84 + [5],
85 + );
86 + assert.isFalse(last.truncated);
87 + }),
88 +);
packages/source-control-bitbucket/src/server/driver.ts
+1 -2
@@ -18,8 +18,7 @@ const services = BitbucketPullRequestApi.layer.pipe(
18 Layer.orDie,
19 );
20
21 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
22 -export const makeInstance = Effect.all({
21 +const makeInstance = Effect.all({
22 sourceControl: BitbucketSourceControlProvider.make,
23 discovery: BitbucketSourceControlProvider.makeDiscovery,
24 pullRequests: BitbucketPullRequestProvider.make,
packages/source-control-forgejo/package.json
+1 -20
@@ -10,26 +10,6 @@
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
13 - },
14 - "./server/ForgejoCli": {
15 - "types": "./src/server/ForgejoCli.ts",
16 - "import": "./src/server/ForgejoCli.ts"
17 - },
18 - "./server/forgejoPullRequestJson": {
19 - "types": "./src/server/forgejoPullRequestJson.ts",
20 - "import": "./src/server/forgejoPullRequestJson.ts"
21 - },
22 - "./server/ForgejoPullRequestProvider": {
23 - "types": "./src/server/ForgejoPullRequestProvider.ts",
24 - "import": "./src/server/ForgejoPullRequestProvider.ts"
25 - },
26 - "./server/forgejoPullRequests": {
27 - "types": "./src/server/forgejoPullRequests.ts",
28 - "import": "./src/server/forgejoPullRequests.ts"
29 - },
30 - "./server/ForgejoSourceControlProvider": {
31 - "types": "./src/server/ForgejoSourceControlProvider.ts",
32 - "import": "./src/server/ForgejoSourceControlProvider.ts"
13 }
14 },
15 "scripts": {
@@ -44,6 +24,7 @@
24 "effect": "catalog:"
25 },
26 "devDependencies": {
27 + "@effect/platform-node": "catalog:",
28 "@effect/vitest": "catalog:",
29 "@t3tools/source-control-testing": "workspace:*",
30 "@types/node": "catalog:",
packages/source-control-forgejo/src/server/ForgejoCheckout.test.ts new
+205
@@ -0,0 +1,205 @@
1 +import { SourceControlProviderKind } from "@t3tools/contracts";
2 +import { assert, it } from "@effect/vitest";
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Layer from "effect/Layer";
7 +import * as Path from "effect/Path";
8 +import * as Schema from "effect/Schema";
9 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
10 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
11 +import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
12 +
13 +import * as ForgejoCli from "./ForgejoCli.ts";
14 +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
15 +
16 +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
17 +
18 +it.effect(
19 + "checks out fj pull refs and preserves existing branches and dirty files until forced",
20 + () =>
21 + Effect.gen(function* () {
22 + const fs = yield* FileSystem.FileSystem;
23 + const git = (yield* SourceControlHost.SourceControlHost).process;
24 + const path = yield* Path.Path;
25 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" });
26 + const source = path.join(root, "source");
27 + const cwd = path.join(root, "checkout");
28 + yield* fs.makeDirectory(source);
29 + for (const args of [
30 + ["init", "-b", "main"],
31 + ["config", "user.name", "Test"],
32 + ["config", "user.email", "test@example.com"],
33 + ])
34 + yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
35 + yield* fs.writeFileString(path.join(source, "base.txt"), "base\n");
36 + for (const args of [
37 + ["add", "base.txt"],
38 + ["commit", "-m", "base"],
39 + ])
40 + yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
41 + const base = (yield* git.run({
42 + operation: "test.setup",
43 + command: "git",
44 + cwd: source,
45 + args: ["rev-parse", "HEAD"],
46 + })).stdout.trim();
47 + yield* git.run({
48 + operation: "test.setup",
49 + command: "git",
50 + cwd: root,
51 + args: ["clone", source, cwd],
52 + });
53 + yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n");
54 + for (const args of [
55 + ["add", "feature.txt"],
56 + ["commit", "-m", "feature"],
57 + ["update-ref", "refs/pull/42/head", "HEAD"],
58 + ])
59 + yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
60 + const head = (yield* git.run({
61 + operation: "test.setup",
62 + command: "git",
63 + cwd: source,
64 + args: ["rev-parse", "HEAD"],
65 + })).stdout.trim();
66 + const fetched: string[] = [];
67 + const provider = yield* ForgejoSourceControlProvider.make.pipe(
68 + Effect.provide(
69 + Layer.merge(
70 + TestSourceControlHost.layerWithRealGit({
71 + process: {
72 + run: (input) => {
73 + if (input.args[0] !== "fetch") return git.run(input);
74 + const url = input.args[2];
75 + assert.isDefined(url);
76 + fetched.push(url!);
77 + return git.run({
78 + ...input,
79 + args: input.args.map((arg) =>
80 + arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
81 + ),
82 + });
83 + },
84 + },
85 + }),
86 + Layer.mock(ForgejoCli.ForgejoCli)({
87 + resolveRepository: () =>
88 + Effect.succeed({
89 + command: "fj",
90 + login: "work",
91 + repository: "reviewer/project",
92 + baseUrl: "https://forgejo.test",
93 + }),
94 + api: (input) => {
95 + assert.include(
96 + ["repos/reviewer/project", "repos/reviewer/project/pulls/42"],
97 + input.path,
98 + );
99 + return Effect.succeed(
100 + processOutput(
101 + encodeJson(
102 + input.path.endsWith("/pulls/42")
103 + ? {
104 + number: 42,
105 + title: "Checkout",
106 + html_url: "https://forgejo.test/reviewer/project/pulls/42",
107 + state: "open",
108 + merged: false,
109 + base: { ref: "main", sha: base, repo: null },
110 + head: { ref: "feature", sha: head, repo: null },
111 + }
112 + : {
113 + full_name: "reviewer/project",
114 + clone_url: source,
115 + ssh_url: "git@forgejo.test:reviewer/project.git",
116 + default_branch: "main",
117 + },
118 + ),
119 + ),
120 + );
121 + },
122 + }),
123 + ),
124 + ),
125 + );
126 + yield* provider.checkoutChangeRequest({
127 + cwd,
128 + reference: "https://forgejo.test/reviewer/project/pulls/42",
129 + });
130 + assert.strictEqual(
131 + (yield* git.run({
132 + operation: "test.verify",
133 + command: "git",
134 + cwd,
135 + args: ["branch", "--show-current"],
136 + })).stdout.trim(),
137 + "pulls/42",
138 + );
139 + assert.strictEqual(
140 + (yield* git.run({
141 + operation: "test.verify",
142 + command: "git",
143 + cwd,
144 + args: ["rev-parse", "HEAD"],
145 + })).stdout.trim(),
146 + head,
147 + );
148 + assert.strictEqual(
149 + yield* fs.readFileString(path.join(cwd, "feature.txt")),
150 + "pull request change\n",
151 + );
152 + for (const args of [
153 + ["checkout", "main"],
154 + ["branch", "-f", "pulls/42", "main"],
155 + ])
156 + yield* git.run({ operation: "test.setup", command: "git", cwd, args });
157 + yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n");
158 + yield* provider.checkoutChangeRequest({ cwd, reference: "42" });
159 + assert.strictEqual(
160 + (yield* git.run({
161 + operation: "test.verify",
162 + command: "git",
163 + cwd,
164 + args: ["rev-parse", "HEAD"],
165 + })).stdout.trim(),
166 + base,
167 + );
168 + assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false);
169 + yield* provider.checkoutChangeRequest({
170 + cwd,
171 + reference: "42",
172 + force: true,
173 + context: {
174 + provider: {
175 + kind: SourceControlProviderKind.make("forgejo"),
176 + name: "Forgejo",
177 + baseUrl: "https://forgejo.test",
178 + },
179 + remoteName: "origin",
180 + remoteUrl: "git@forgejo.test:maria/project.git",
181 + },
182 + });
183 + assert.strictEqual(
184 + (yield* git.run({
185 + operation: "test.verify",
186 + command: "git",
187 + cwd,
188 + args: ["rev-parse", "HEAD"],
189 + })).stdout.trim(),
190 + head,
191 + );
192 + assert.strictEqual(
193 + yield* fs.readFileString(path.join(cwd, "base.txt")),
194 + "uncommitted work\n",
195 + );
196 + assert.strictEqual(
197 + yield* fs.readFileString(path.join(cwd, "feature.txt")),
198 + "pull request change\n",
199 + );
200 + assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]);
201 + }).pipe(
202 + Effect.scoped,
203 + Effect.provide(Layer.merge(TestSourceControlHost.layerWithRealGit(), NodeServices.layer)),
204 + ),
205 +);
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.test.ts new
+68
@@ -0,0 +1,68 @@
1 +import { assert, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5 +
6 +import * as ForgejoCli from "./ForgejoCli.ts";
7 +import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
8 +
9 +it.effect("reads file revisions from the pull request diff and refuses a truncated one", () =>
10 + Effect.gen(function* () {
11 + let truncated = false;
12 + const diff = [
13 + "diff --git a/alpha.ts b/alpha.ts",
14 + "index eb2d7c5..b485fe5 100644",
15 + "diff --git a/beta.ts b/beta.ts",
16 + "index b39e8b3..5851425 100644",
17 + 'diff --git "a/caf\\303\\251 notes.txt" "b/caf\\303\\251 notes.txt"',
18 + "index ffd99ce..6dd9855 100644",
19 + "diff --git a/deleted.txt b/deleted.txt",
20 + "deleted file mode 100644",
21 + "index 233f5c6..0000000",
22 + "diff --git a/old.txt b/renamed.txt",
23 + "similarity index 100%",
24 + "rename from old.txt",
25 + "rename to renamed.txt",
26 + "",
27 + ].join("\n");
28 + const provider = yield* ForgejoPullRequestProvider.make.pipe(
29 + Effect.provide(
30 + Layer.mock(ForgejoCli.ForgejoCli)({
31 + api: (input) => {
32 + assert.strictEqual(input.host, "forge.example:3000");
33 + assert.strictEqual(input.repository, "reviewer/project");
34 + assert.strictEqual(input.path, "repos/reviewer/project/pulls/1.diff");
35 + return Effect.succeed({
36 + ...TestSourceControlHost.processOutput(diff),
37 + stdoutTruncated: truncated,
38 + });
39 + },
40 + }),
41 + ),
42 + );
43 + const reference = {
44 + cwd: "/forgejo",
45 + repository: "reviewer/project",
46 + host: "forge.example:3000",
47 + number: 1,
48 + };
49 + const paths = ["alpha.ts", "beta.ts", "café notes.txt", "deleted.txt", "renamed.txt"];
50 + assert.isDefined(provider.getFileRevisions);
51 + const answer = yield* provider.getFileRevisions!({ ...reference, paths });
52 + assert.isTrue(answer.complete);
53 + assert.deepStrictEqual(
54 + paths.map((path) => [path, answer.revisions.get(path)]),
55 + [
56 + ["alpha.ts", "b485fe5"],
57 + ["beta.ts", "5851425"],
58 + ["café notes.txt", "6dd9855"],
59 + ["deleted.txt", "0000000"],
60 + ["renamed.txt", ""],
61 + ],
62 + );
63 +
64 + truncated = true;
65 + const refused = yield* Effect.flip(provider.getFileRevisions!({ ...reference, paths }));
66 + assert.strictEqual(refused._tag, "PullRequestProviderError");
67 + }),
68 +);
packages/source-control-forgejo/src/server/driver.ts
+1 -2
@@ -12,8 +12,7 @@ import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts
12
13 const services = ForgejoCli.layer;
14
15 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
16 -export const makeInstance = Effect.all({
15 +const makeInstance = Effect.all({
16 sourceControl: ForgejoSourceControlProvider.make,
17 discovery: ForgejoSourceControlProvider.makeDiscovery,
18 pullRequests: ForgejoPullRequestProvider.make,
packages/source-control-forgejo/src/server/forgejoPullRequestJson.test.ts new
+36
@@ -0,0 +1,36 @@
1 +import { assert, describe, it } from "@effect/vitest";
2 +import * as Schema from "effect/Schema";
3 +
4 +import { ForgejoComment, forgejoComment } from "./forgejoPullRequestJson.ts";
5 +
6 +const decodeForgejoComment = Schema.decodeSync(ForgejoComment);
7 +
8 +describe("forgejoComment", () => {
9 + const createdAt = "2026-10-10T19:52:40Z";
10 + const comment = (updatedAt: string | null | undefined) =>
11 + forgejoComment(
12 + decodeForgejoComment({
13 + id: 29061,
14 + body: "Performance: five rounds complete",
15 + user: { login: "forgejo-actions" },
16 + created_at: createdAt,
17 + ...(updatedAt === undefined ? {} : { updated_at: updatedAt }),
18 + }),
19 + );
20 +
21 + it.each([undefined, null, createdAt, "2026-10-10T19:52:40.000Z"])(
22 + "reads no edit from an updated_at of %s",
23 + (updatedAt) => {
24 + const mapped = comment(updatedAt);
25 + assert.strictEqual(mapped.createdAt, "2026-10-10T19:52:40.000Z");
26 + assert.isUndefined(mapped.editedAt);
27 + },
28 + );
29 +
30 + it("reads a later updated_at as an edit, in UTC milliseconds", () => {
31 + const mapped = comment("2026-10-10T20:04:50Z");
32 + assert.strictEqual(mapped.id, "29061");
33 + assert.strictEqual(mapped.author?.login, "forgejo-actions");
34 + assert.strictEqual(mapped.editedAt, "2026-10-10T20:04:50.000Z");
35 + });
36 +});
packages/source-control-forgejo/src/server/forgejoPullRequests.test.ts new
+46
@@ -0,0 +1,46 @@
1 +import { expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 +
5 +import { repositoryNameFromRemoteUrl } from "./ForgejoSourceControlProvider.ts";
6 +import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts";
7 +
8 +const decodeForgejoPullRequest = Schema.decodeEffect(ForgejoPullRequestSchema);
9 +
10 +it.effect("names a mounted server's heads by owner and repository, apart from forks", () =>
11 + Effect.gen(function* () {
12 + for (const owner of ["maria", "reviewer"]) {
13 + const changeRequest = toForgejoChangeRequest(
14 + yield* decodeForgejoPullRequest({
15 + number: 42,
16 + title: "Greeting",
17 + html_url: "https://forgejo.example/forgejo/maria/project/pulls/42",
18 + state: "open",
19 + merged: false,
20 + base: {
21 + ref: "main",
22 + sha: "base",
23 + repo: { full_name: "maria/project", owner: { login: "maria" } },
24 + },
25 + head: {
26 + ref: "greeting",
27 + sha: "head",
28 + repo: { full_name: `${owner}/project`, owner: { login: owner } },
29 + },
30 + }),
31 + );
32 + expect(changeRequest).toMatchObject({
33 + headRefName: "greeting",
34 + isCrossRepository: owner !== "maria",
35 + headRepositoryNameWithOwner: `${owner}/project`,
36 + headRepositoryOwnerLogin: owner,
37 + });
38 + expect(
39 + repositoryNameFromRemoteUrl(`https://forgejo.example/forgejo/${owner}/project.git`),
40 + ).toBe(`${owner}/project`);
41 + }
42 + expect(repositoryNameFromRemoteUrl("git@forgejo.example:maria/project.git")).toBe(
43 + "maria/project",
44 + );
45 + }),
46 +);
packages/source-control-gitcafe/package.json
-24
@@ -10,30 +10,6 @@
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
13 - },
14 - "./server/gitCafeHosts": {
15 - "types": "./src/server/gitCafeHosts.ts",
16 - "import": "./src/server/gitCafeHosts.ts"
17 - },
18 - "./server/GitCafeApi": {
19 - "types": "./src/server/GitCafeApi.ts",
20 - "import": "./src/server/GitCafeApi.ts"
21 - },
22 - "./server/GitCafeCredentials": {
23 - "types": "./src/server/GitCafeCredentials.ts",
24 - "import": "./src/server/GitCafeCredentials.ts"
25 - },
26 - "./server/gitCafePullRequestJson": {
27 - "types": "./src/server/gitCafePullRequestJson.ts",
28 - "import": "./src/server/gitCafePullRequestJson.ts"
29 - },
30 - "./server/GitCafePullRequestProvider": {
31 - "types": "./src/server/GitCafePullRequestProvider.ts",
32 - "import": "./src/server/GitCafePullRequestProvider.ts"
33 - },
34 - "./server/GitCafeSourceControlProvider": {
35 - "types": "./src/server/GitCafeSourceControlProvider.ts",
36 - "import": "./src/server/GitCafeSourceControlProvider.ts"
13 }
14 },
15 "scripts": {
packages/source-control-gitcafe/src/server/driver.ts
+1 -2
@@ -14,8 +14,7 @@ import * as GitCafeSourceControlProvider from "./GitCafeSourceControlProvider.ts
14
15 const services = GitCafeApi.layer.pipe(Layer.provideMerge(GitCafeCredentials.layer));
16
17 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
18 -export const makeInstance = Effect.all({
17 +const makeInstance = Effect.all({
18 sourceControl: GitCafeSourceControlProvider.make,
19 discovery: GitCafeSourceControlProvider.makeDiscovery,
20 pullRequests: GitCafePullRequestProvider.make,
packages/source-control-github/package.json
-60
@@ -10,66 +10,6 @@
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
13 - },
14 - "./server/GitHubRest": {
15 - "types": "./src/server/GitHubRest.ts",
16 - "import": "./src/server/GitHubRest.ts"
17 - },
18 - "./server/gitHubAuthStatus": {
19 - "types": "./src/server/gitHubAuthStatus.ts",
20 - "import": "./src/server/gitHubAuthStatus.ts"
21 - },
22 - "./server/gitHubChangeRequestTemplate": {
23 - "types": "./src/server/gitHubChangeRequestTemplate.ts",
24 - "import": "./src/server/gitHubChangeRequestTemplate.ts"
25 - },
26 - "./server/gitHubConditionalChecks": {
27 - "types": "./src/server/gitHubConditionalChecks.ts",
28 - "import": "./src/server/gitHubConditionalChecks.ts"
29 - },
30 - "./server/GitHubCredentials": {
31 - "types": "./src/server/GitHubCredentials.ts",
32 - "import": "./src/server/GitHubCredentials.ts"
33 - },
34 - "./server/GitHubRequestPolicy": {
35 - "types": "./src/server/GitHubRequestPolicy.ts",
36 - "import": "./src/server/GitHubRequestPolicy.ts"
37 - },
38 - "./server/GitHubPullRequestApi": {
39 - "types": "./src/server/GitHubPullRequestApi.ts",
40 - "import": "./src/server/GitHubPullRequestApi.ts"
41 - },
42 - "./server/gitHubPullRequestJson": {
43 - "types": "./src/server/gitHubPullRequestJson.ts",
44 - "import": "./src/server/gitHubPullRequestJson.ts"
45 - },
46 - "./server/GitHubPullRequestProvider": {
47 - "types": "./src/server/GitHubPullRequestProvider.ts",
48 - "import": "./src/server/GitHubPullRequestProvider.ts"
49 - },
50 - "./server/gitHubPullRequests": {
51 - "types": "./src/server/gitHubPullRequests.ts",
52 - "import": "./src/server/gitHubPullRequests.ts"
53 - },
54 - "./server/GitHubQuota": {
55 - "types": "./src/server/GitHubQuota.ts",
56 - "import": "./src/server/GitHubQuota.ts"
57 - },
58 - "./server/gitHubRepositoryResolution": {
59 - "types": "./src/server/gitHubRepositoryResolution.ts",
60 - "import": "./src/server/gitHubRepositoryResolution.ts"
61 - },
62 - "./server/GitHubSourceControlProvider": {
63 - "types": "./src/server/GitHubSourceControlProvider.ts",
64 - "import": "./src/server/GitHubSourceControlProvider.ts"
65 - },
66 - "./server/githubStackActions": {
67 - "types": "./src/server/githubStackActions.ts",
68 - "import": "./src/server/githubStackActions.ts"
69 - },
70 - "./server/githubStackRebase": {
71 - "types": "./src/server/githubStackRebase.ts",
72 - "import": "./src/server/githubStackRebase.ts"
13 }
14 },
15 "scripts": {
packages/source-control-github/src/server/GitHubPullRequestProvider.credential.test.ts new
+146
@@ -0,0 +1,146 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Redacted from "effect/Redacted";
6 +import { HttpClient, HttpClientResponse } from "effect/http";
7 +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
8 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
9 +
10 +import * as GitHubCredentials from "./GitHubCredentials.ts";
11 +import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
12 +import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
13 +import * as GitHubQuota from "./GitHubQuota.ts";
14 +import * as GitHubRest from "./GitHubRest.ts";
15 +
16 +it.effect("keeps branch deletion on the credential that passed source repository permissions", () =>
17 + Effect.gen(function* () {
18 + let activeToken = "account-a";
19 + const requests: Array<{ operation: string; authorization: string | undefined }> = [];
20 + const credentials = Layer.succeed(
21 + GitHubCredentials.GitHubCredentials,
22 + GitHubCredentials.GitHubCredentials.of({
23 + get: (host) =>
24 + Effect.sync(() => ({
25 + host,
26 + token: Redacted.make(activeToken),
27 + source: "gh" as const,
28 + fingerprint: `${host}:${activeToken}`,
29 + })),
30 + invalidate: () => Effect.void,
31 + }),
32 + );
33 + const http = Layer.succeed(
34 + HttpClient.HttpClient,
35 + HttpClient.make((request) =>
36 + Effect.sync(() => {
37 + const operation = request.url.endsWith("/user")
38 + ? "user"
39 + : request.body._tag === "Uint8Array"
40 + ? new TextDecoder().decode(request.body.body)
41 + : "";
42 + requests.push({ operation, authorization: request.headers["authorization"] });
43 + let body;
44 + if (operation === "user") {
45 + body = { id: activeToken === "account-a" ? 101 : 202, login: activeToken };
46 + } else if (operation.includes("query PullRequestBranchToDelete")) {
47 + body = {
48 + data: {
49 + repository: {
50 + pullRequest: {
51 + state: "MERGED",
52 + headRefName: "feature",
53 + baseRefName: "main",
54 + headRefOid: "abc123",
55 + headRepository: { id: "FORK_REPO" },
56 + },
57 + },
58 + },
59 + };
60 + } else if (operation.includes("query PullRequestSourceBranch")) {
61 + body = {
62 + data: {
63 + node: {
64 + __typename: "Repository",
65 + defaultBranchRef: { name: "main" },
66 + ref: { target: { __typename: "Commit", oid: "abc123" } },
67 + },
68 + },
69 + };
70 + } else if (operation.includes("updateRefs(")) {
71 + body = { data: { updateRefs: { clientMutationId: null } } };
72 + } else {
73 + // The credential rotates the moment the permission read is answered.
74 + activeToken = "account-b";
75 + body = {
76 + data: {
77 + repository: {
78 + mergeCommitAllowed: true,
79 + squashMergeAllowed: true,
80 + rebaseMergeAllowed: true,
81 + autoMergeAllowed: true,
82 + viewerPermission: "READ",
83 + pullRequest: {
84 + viewerCanUpdate: false,
85 + viewerDidAuthor: false,
86 + headRepository: { viewerPermission: "WRITE" },
87 + },
88 + },
89 + },
90 + };
91 + }
92 + return HttpClientResponse.fromWeb(
93 + request,
94 + new Response(JSON.stringify(body), {
95 + headers: { "content-type": "application/json" },
96 + }),
97 + );
98 + }),
99 + ),
100 + );
101 + const provider = yield* GitHubPullRequestProvider.make.pipe(
102 + Effect.provide(
103 + GitHubPullRequestApi.layer.pipe(
104 + // GraphQL reads go over `http` too, through the same credential and quota as REST.
105 + Layer.provide(
106 + GitHubRest.layer.pipe(
107 + Layer.provideMerge(Layer.mergeAll(credentials, http)),
108 + Layer.provideMerge(GitHubQuota.layer),
109 + Layer.provideMerge(SourceControlRateLimit.layer),
110 + ),
111 + ),
112 + Layer.provide(TestSourceControlHost.layer()),
113 + Layer.provide(NodeServices.layer),
114 + ),
115 + ),
116 + );
117 + const reference = { cwd: "/a", repository: "acme/web", host: "github.com", number: 1 };
118 + assert.isDefined(provider.withVerifiedCredential);
119 + yield* provider.withVerifiedCredential!({ cwd: "/a", host: "github.com" }, () =>
120 + Effect.gen(function* () {
121 + const permissions = yield* provider.getViewerPermissions({
122 + ...reference,
123 + includeUpdateBranch: false,
124 + });
125 + assert.include(permissions.actions, "delete-branch");
126 + yield* provider.runAction({ ...reference, action: "delete-branch" });
127 + }),
128 + );
129 +
130 + assert.strictEqual(activeToken, "account-b");
131 + assert.strictEqual(
132 + requests.filter(({ operation }) => operation.includes("updateRefs(")).length,
133 + 1,
134 + );
135 + assert.deepStrictEqual(
136 + requests.map(({ authorization }) => authorization),
137 + [
138 + "Bearer account-a",
139 + "Bearer account-a",
140 + "Bearer account-a",
141 + "Bearer account-a",
142 + "Bearer account-a",
143 + ],
144 + );
145 + }),
146 +);
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+1 -1
@@ -101,7 +101,7 @@ export function gitHubViewerPermissions(
101 };
102 }
103
104 -export function gitHubProviderFailure(
104 +function gitHubProviderFailure(
105 error: GitHubPullRequestApi.GitHubPullRequestApiError,
106 ): PullRequestProviderFailure {
107 switch (error._tag) {
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+9 -7
@@ -772,13 +772,15 @@ it.effect.each(["pull", "issues"])(
772 title: "Pairing expiry",
773 body: "Preserve remote access",
774 });
775 - assert.strictEqual(
776 - provider.resolveLink?.({
777 - cwd: "/unrelated",
778 - url: new URL("https://github.com/owner/repo"),
779 - }),
780 - undefined,
781 - );
775 + for (const url of [
776 + "https://github.com/owner/repo",
777 + "https://github.attacker.test/owner/repo/issues/42",
778 + ]) {
779 + assert.strictEqual(
780 + provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
781 + undefined,
782 + );
783 + }
784 }),
785 );
786
packages/source-control-github/src/server/driver.ts
+1 -2
@@ -19,8 +19,7 @@ const services = GitHubPullRequestApi.layer.pipe(
19 Layer.provideMerge(GitHubRest.layerWithDependencies),
20 );
21
22 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
23 -export const makeInstance = Effect.all({
22 +const makeInstance = Effect.all({
23 sourceControl: GitHubSourceControlProvider.make,
24 discovery: GitHubSourceControlProvider.makeDiscovery,
25 pullRequests: GitHubPullRequestProvider.make,
packages/source-control-github/src/server/gitHubChangeRequestTemplate.test.ts renamed
+9 -14
@@ -6,11 +6,11 @@ import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Path from "effect/Path";
8
9 -import * as ServerConfig from "../config.ts";
10 -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
11 -import * as VcsProcess from "../vcs/VcsProcess.ts";
12 -import * as GitHubChangeRequestTemplate from "@t3tools/source-control-github/server/gitHubChangeRequestTemplate";
9 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
10 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12 +
13 +import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
14
15 const TEMPLATE_DIRECTORIES = [
16 ".github/PULL_REQUEST_TEMPLATE",
@@ -18,19 +18,14 @@ const TEMPLATE_DIRECTORIES = [
18 "docs/PULL_REQUEST_TEMPLATE",
19 ] as const;
20
21 -const layerPrTemplateDetectionTest = GitVcsDriver.layer.pipe(
22 - Layer.provide(
23 - ServerConfig.layerTest(process.cwd(), {
24 - prefix: "t3-pr-template-test-",
25 - }),
26 - ),
27 - Layer.provideMerge(VcsProcess.layer),
28 - Layer.provideMerge(NodeServices.layer),
21 +const layerPrTemplateDetectionTest = Layer.merge(
22 + TestSourceControlHost.layerWithRealGit(),
23 + NodeServices.layer,
24 );
25
26 const runGit = (cwd: string, args: ReadonlyArray<string>) =>
27 Effect.gen(function* () {
33 - const git = yield* GitVcsDriver.GitVcsDriver;
28 + const { git } = yield* SourceControlHost.SourceControlHost;
29 return yield* git.execute({
30 operation: "PrTemplateDetection.test.runGit",
31 cwd,
@@ -70,7 +65,7 @@ const commitTemplates = (cwd: string) =>
65
66 const detectTemplate = (cwd: string, treeish = "HEAD") =>
67 Effect.gen(function* () {
73 - const git = yield* GitVcsDriver.GitVcsDriver;
68 + const { git } = yield* SourceControlHost.SourceControlHost;
69 return yield* GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
70 });
71
packages/source-control-github/src/server/gitHubDiscovery.test.ts new
+79
@@ -0,0 +1,79 @@
1 +import { SourceControlProviderKind } from "@t3tools/contracts";
2 +import * as HostProcess from "@t3tools/shared/HostProcess";
3 +import { assert, it } from "@effect/vitest";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Redacted from "effect/Redacted";
7 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8 +
9 +import * as GitHubCredentials from "./GitHubCredentials.ts";
10 +import * as GitHubRest from "./GitHubRest.ts";
11 +import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
12 +
13 +const unknownContext = (baseUrl: string) => ({
14 + provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl },
15 + remoteName: "origin",
16 + remoteUrl: "git@code.example.test:team/project.git",
17 +});
18 +
19 +// The default host dies on any command, so refinement never reaches `gh`.
20 +const makeDiscovery = (credential: GitHubRest.GitHubRest["Service"]["credential"]) =>
21 + GitHubSourceControlProvider.makeDiscovery.pipe(
22 + Effect.provide(
23 + Layer.mergeAll(
24 + Layer.mock(GitHubRest.GitHubRest)({ credential }),
25 + TestSourceControlHost.layer(),
26 + ),
27 + ),
28 + Effect.provideService(HostProcess.Environment, {}),
29 + );
30 +
31 +it.effect.each([
32 + { name: "a credential", credential: "found", claimed: true },
33 + { name: "a host turned off in Settings", credential: "disabled", claimed: true },
34 + { name: "no credential", credential: "missing", claimed: false },
35 +] as const)("claims a custom-host remote with $name", (scenario) =>
36 + Effect.gen(function* () {
37 + const hosts: Array<string> = [];
38 + const discovery = yield* makeDiscovery((host) => {
39 + hosts.push(host);
40 + return scenario.credential === "found"
41 + ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
42 + : scenario.credential === "disabled"
43 + ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
44 + : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
45 + });
46 + if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
47 + const provider = yield* discovery.refineUnknownRemote({
48 + cwd: "/repo",
49 + context: unknownContext("https://code.example.test"),
50 + });
51 + assert.deepStrictEqual(
52 + provider,
53 + scenario.claimed
54 + ? {
55 + kind: SourceControlProviderKind.make("github"),
56 + name: "GitHub Self-Hosted",
57 + baseUrl: "https://code.example.test",
58 + }
59 + : null,
60 + );
61 + assert.deepStrictEqual(hosts, ["code.example.test"]);
62 + }),
63 +);
64 +
65 +it.effect("asks for no credential when the identity resolver left the base URL empty", () =>
66 + Effect.gen(function* () {
67 + const hosts: Array<string> = [];
68 + const discovery = yield* makeDiscovery((host) => {
69 + hosts.push(host);
70 + return Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` });
71 + });
72 + if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
73 + assert.strictEqual(
74 + yield* discovery.refineUnknownRemote({ cwd: "/repo", context: unknownContext("") }),
75 + null,
76 + );
77 + assert.deepStrictEqual(hosts, []);
78 + }),
79 +);
packages/source-control-github/src/server/gitHubPullRequests.test.ts
+52
@@ -25,3 +25,55 @@ it("names a fork's head repository from its owner when gh leaves nameWithOwner o
25 headRepositoryOwnerLogin: "binbandit",
26 });
27 });
28 +
29 +it("skips rows that do not decode and trims the ones that do", () => {
30 + const decoded = decodeGitHubPullRequestListJson(
31 + JSON.stringify([
32 + {
33 + number: 0,
34 + title: "invalid",
35 + url: "https://github.com/pingdotgg/codething-mvp/pull/0",
36 + baseRefName: "main",
37 + headRefName: "feature/invalid",
38 + },
39 + {
40 + number: 15,
41 + title: " Valid PR title ",
42 + url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
43 + baseRefName: " main ",
44 + headRefName: "\tfeature/status-valid-pr-entry\t",
45 + headRepository: { nameWithOwner: " " },
46 + headRepositoryOwner: { login: " " },
47 + },
48 + ]),
49 + );
50 +
51 + const rows = Result.getOrThrow(decoded);
52 + expect(rows).toHaveLength(1);
53 + expect(rows[0]).toMatchObject({
54 + number: 15,
55 + title: "Valid PR title",
56 + url: "https://github.com/pingdotgg/codething-mvp/pull/15",
57 + baseRefName: "main",
58 + headRefName: "feature/status-valid-pr-entry",
59 + state: "open",
60 + });
61 + expect(rows[0]).not.toHaveProperty("headRepositoryNameWithOwner");
62 + expect(rows[0]).not.toHaveProperty("headRepositoryOwnerLogin");
63 +});
64 +
65 +it("reads lowercase closed and merged states", () => {
66 + const row = (number: number, state: string) => ({
67 + number,
68 + title: "PR",
69 + url: `https://github.com/pingdotgg/codething-mvp/pull/${number}`,
70 + baseRefName: "main",
71 + headRefName: "feature/status-lowercase-state",
72 + state,
73 + });
74 + const decoded = decodeGitHubPullRequestListJson(
75 + JSON.stringify([row(16, "closed"), row(17, "merged"), row(18, "open")]),
76 + );
77 +
78 + expect(Result.getOrThrow(decoded).map((pr) => pr.state)).toEqual(["closed", "merged", "open"]);
79 +});
packages/source-control-github/src/server/githubStackRebase.test.ts renamed
+7 -15
@@ -5,30 +5,22 @@ import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Redacted from "effect/Redacted";
7
8 -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
9 -import { cascadeRebaseStack } from "@t3tools/source-control-github/server/githubStackRebase";
8 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
10
11 -import * as ServerSettings from "../serverSettings.ts";
12 -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
13 -import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
14 -import * as VcsProcess from "../vcs/VcsProcess.ts";
15 -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
11 +import * as GitHubRest from "./GitHubRest.ts";
12 +import { cascadeRebaseStack } from "./githubStackRebase.ts";
13
14 const layer = Layer.mergeAll(
15 Layer.mock(GitHubRest.GitHubRest)({
16 credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
17 }),
21 - ServerSourceControlHost.layer.pipe(
22 - Layer.provide(ServerSettings.layerTest()),
23 - Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
24 - Layer.provide(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
25 - Layer.provideMerge(VcsProcess.layer),
26 - ),
18 + TestSourceControlHost.layerWithRealGit(),
19 ).pipe(Layer.provideMerge(NodeServices.layer));
20
21 const setup = Effect.gen(function* () {
22 const fs = yield* FileSystem.FileSystem;
31 - const process = yield* VcsProcess.VcsProcess;
23 + const { process } = yield* SourceControlHost.SourceControlHost;
24 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cascade-test-" });
25 const remote = `${root}/remote.git`;
26 const work = `${root}/work`;
@@ -122,7 +114,7 @@ it.layer(layer)("cascadeRebaseStack", (it) => {
114 Effect.gen(function* () {
115 const repo = yield* setup;
116 const fs = yield* FileSystem.FileSystem;
125 - const process = yield* VcsProcess.VcsProcess;
117 + const { process } = yield* SourceControlHost.SourceControlHost;
118 const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cascade-conflict-" });
119 const run = (...args: string[]) =>
120 process.run({
packages/source-control-gitlab/package.json
-28
@@ -10,34 +10,6 @@
10 "./server/driver": {
11 "types": "./src/server/driver.ts",
12 "import": "./src/server/driver.ts"
13 - },
14 - "./server/gitLabAuthStatus": {
15 - "types": "./src/server/gitLabAuthStatus.ts",
16 - "import": "./src/server/gitLabAuthStatus.ts"
17 - },
18 - "./server/GitLabCli": {
19 - "types": "./src/server/GitLabCli.ts",
20 - "import": "./src/server/GitLabCli.ts"
21 - },
22 - "./server/gitLabMergeRequestJson": {
23 - "types": "./src/server/gitLabMergeRequestJson.ts",
24 - "import": "./src/server/gitLabMergeRequestJson.ts"
25 - },
26 - "./server/gitLabMergeRequests": {
27 - "types": "./src/server/gitLabMergeRequests.ts",
28 - "import": "./src/server/gitLabMergeRequests.ts"
29 - },
30 - "./server/GitLabPullRequestCli": {
31 - "types": "./src/server/GitLabPullRequestCli.ts",
32 - "import": "./src/server/GitLabPullRequestCli.ts"
33 - },
34 - "./server/GitLabPullRequestProvider": {
35 - "types": "./src/server/GitLabPullRequestProvider.ts",
36 - "import": "./src/server/GitLabPullRequestProvider.ts"
37 - },
38 - "./server/GitLabSourceControlProvider": {
39 - "types": "./src/server/GitLabSourceControlProvider.ts",
40 - "import": "./src/server/GitLabSourceControlProvider.ts"
13 }
14 },
15 "scripts": {
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.rateLimit.test.ts new
+55
@@ -0,0 +1,55 @@
1 +import { VcsProcessExitError } from "@t3tools/contracts";
2 +import { expect, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
6 +
7 +import * as GitLabCli from "./GitLabCli.ts";
8 +import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
9 +import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
10 +
11 +it.effect("reports activity as rate limited when only the reactions endpoint is", () =>
12 + Effect.gen(function* () {
13 + const provider = yield* GitLabPullRequestProvider.make.pipe(
14 + Effect.provide(
15 + GitLabPullRequestCli.layer.pipe(
16 + Layer.provide(GitLabCli.layer),
17 + Layer.provide(
18 + TestSourceControlHost.layer({
19 + process: {
20 + run: (input) =>
21 + input.args[1] === "graphql"
22 + ? Effect.fail(
23 + new VcsProcessExitError({
24 + operation: input.operation,
25 + command: input.command,
26 + cwd: input.cwd,
27 + exitCode: 1,
28 + detail: "API rate limit exceeded.",
29 + failureKind: "rate-limited",
30 + }),
31 + )
32 + : Effect.succeed(TestSourceControlHost.processOutput("[]")),
33 + },
34 + }),
35 + ),
36 + ),
37 + ),
38 + );
39 + const reference = {
40 + cwd: "/repo",
41 + repository: "acme/web",
42 + host: "gitlab.example.test",
43 + number: 1,
44 + };
45 +
46 + expect(yield* Effect.result(provider.getChangeRequestActivity(reference))).toMatchObject({
47 + _tag: "Failure",
48 + failure: {
49 + _tag: "PullRequestProviderError",
50 + reason: "rate-limited",
51 + cause: { _tag: "GitLabCliRateLimitError" },
52 + },
53 + });
54 + }),
55 +);
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts new
+188
@@ -0,0 +1,188 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 +import * as NodeFS from "node:fs";
3 +import * as NodeOS from "node:os";
4 +import * as NodePath from "node:path";
5 +
6 +import type { GitCommandError } from "@t3tools/contracts";
7 +
8 +import { assert, expect, it } from "@effect/vitest";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Option from "effect/Option";
12 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
13 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
14 +
15 +import * as GitLabCli from "./GitLabCli.ts";
16 +import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
17 +
18 +it.effect("lists a nested-group fork's merge requests by source branch and names its project", () =>
19 + Effect.gen(function* () {
20 + const branch = "feature/NestedGroups";
21 + const output = JSON.stringify([
22 + {
23 + iid: 2,
24 + title: "Another subgroup's fork",
25 + web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",
26 + target_branch: "main",
27 + source_branch: branch,
28 + state: "opened",
29 + updated_at: "2026-04-08T15:00:00Z",
30 + source_project_id: 102,
31 + target_project_id: 100,
32 + source_project: { path_with_namespace: "Group/Other/Fork" },
33 + },
34 + {
35 + iid: 1,
36 + title: "This subgroup's fork",
37 + web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
38 + target_branch: "main",
39 + source_branch: branch,
40 + state: "opened",
41 + updated_at: "2026-04-07T15:00:00Z",
42 + source_project_id: 101,
43 + target_project_id: 100,
44 + source_project: { path_with_namespace: "Group/Subgroup/Fork" },
45 + },
46 + ]);
47 + const calls: SourceControlHost.SourceControlProcessInput[] = [];
48 + const provider = yield* GitLabSourceControlProvider.make.pipe(
49 + Effect.provide(
50 + GitLabCli.layer.pipe(
51 + Layer.provideMerge(
52 + TestSourceControlHost.layer({
53 + process: {
54 + run: (input) =>
55 + Effect.sync(() => {
56 + calls.push(input);
57 + return TestSourceControlHost.processOutput(output);
58 + }),
59 + },
60 + }),
61 + ),
62 + ),
63 + ),
64 + );
65 +
66 + for (const headSelector of [branch, `Group/Subgroup:${branch}`]) {
67 + const changeRequests = yield* provider.listChangeRequests({
68 + cwd: "/repo",
69 + headSelector,
70 + state: "all",
71 + limit: 20,
72 + });
73 + expect(changeRequests).toMatchObject([
74 + {
75 + number: 2,
76 + headRefName: branch,
77 + isCrossRepository: true,
78 + headRepositoryNameWithOwner: "Group/Other/Fork",
79 + },
80 + {
81 + number: 1,
82 + url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
83 + headRefName: branch,
84 + isCrossRepository: true,
85 + headRepositoryNameWithOwner: "Group/Subgroup/Fork",
86 + },
87 + ]);
88 + }
89 + assert.lengthOf(calls, 2);
90 + for (const call of calls) {
91 + expect(call.command).toBe("glab");
92 + expect(call.args).toEqual([
93 + "mr",
94 + "list",
95 + "--source-branch",
96 + branch,
97 + "--all",
98 + "--per-page",
99 + "20",
100 + "--output",
101 + "json",
102 + ]);
103 + }
104 + }),
105 +);
106 +
107 +const withRepository = <A, E>(
108 + test: (input: {
109 + readonly git: (...args: string[]) => Effect.Effect<string, GitCommandError>;
110 + readonly write: (path: string, contents: string) => Effect.Effect<void>;
111 + readonly readTemplate: (treeish?: string) => Effect.Effect<Option.Option<string>>;
112 + }) => Effect.Effect<A, E>,
113 +) =>
114 + Effect.gen(function* () {
115 + const host = yield* SourceControlHost.SourceControlHost;
116 + const cwd = yield* Effect.acquireRelease(
117 + Effect.sync(() => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-gitlab-template-"))),
118 + (directory) => Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
119 + );
120 + const git = (...args: string[]) =>
121 + host.git
122 + .execute({ operation: "GitLabTemplate.test", cwd, args })
123 + .pipe(Effect.map((result) => result.stdout.trim()));
124 + const write = (path: string, contents: string) =>
125 + Effect.sync(() => {
126 + NodeFS.mkdirSync(NodePath.dirname(NodePath.join(cwd, path)), { recursive: true });
127 + NodeFS.writeFileSync(NodePath.join(cwd, path), contents);
128 + });
129 + yield* git("init", "--initial-branch=main");
130 + yield* git("config", "user.email", "test@example.com");
131 + yield* git("config", "user.name", "Test User");
132 + yield* write("README.md", "hello\n");
133 + yield* git("add", "README.md");
134 + yield* git("commit", "-m", "Initial commit");
135 + const provider = yield* GitLabSourceControlProvider.make.pipe(
136 + Effect.provide(Layer.mock(GitLabCli.GitLabCli)({})),
137 + );
138 + return yield* test({
139 + git,
140 + write,
141 + readTemplate: (treeish = "HEAD") => provider.readChangeRequestTemplate!({ cwd, treeish }),
142 + });
143 + }).pipe(Effect.scoped, Effect.provide(TestSourceControlHost.layerWithRealGit()));
144 +
145 +const DEFAULT_TEMPLATE = ".gitlab/merge_request_templates/Default.md";
146 +
147 +it.effect("ignores unavailable or non-regular GitLab default templates", () =>
148 + withRepository(({ git, write, readTemplate }) =>
149 + Effect.gen(function* () {
150 + expect(yield* readTemplate()).toEqual(Option.none());
151 +
152 + yield* write(".gitlab/merge_request_templates/Bugfix.md", "Not the default");
153 + yield* git("add", ".gitlab");
154 + yield* git("commit", "-m", "Add a selectable template");
155 + expect(yield* readTemplate()).toEqual(Option.none());
156 +
157 + yield* write(DEFAULT_TEMPLATE, " \n\n");
158 + yield* git("add", ".gitlab");
159 + yield* git("commit", "-m", "Add a blank default");
160 + expect(yield* readTemplate()).toEqual(Option.none());
161 +
162 + // Index modes exercise committed symlinks and submodules even on hosts without symlinks.
163 + const blob = yield* git("rev-parse", "HEAD:README.md");
164 + yield* git("update-index", "--cacheinfo", "120000", blob, DEFAULT_TEMPLATE);
165 + yield* git("commit", "-m", "Replace default with a symlink");
166 + expect(yield* readTemplate()).toEqual(Option.none());
167 +
168 + const commit = yield* git("rev-parse", "HEAD");
169 + yield* git("update-index", "--cacheinfo", "160000", commit, DEFAULT_TEMPLATE);
170 + yield* git("commit", "-m", "Replace default with a submodule");
171 + expect(yield* readTemplate()).toEqual(Option.none());
172 + expect(yield* readTemplate("missing-base")).toEqual(Option.none());
173 + }),
174 + ),
175 +);
176 +
177 +it.effect("bounds GitLab template content and marks truncation", () =>
178 + withRepository(({ git, write, readTemplate }) =>
179 + Effect.gen(function* () {
180 + const prefix = "a".repeat(8_000);
181 + yield* write(DEFAULT_TEMPLATE, prefix + "EXCLUDED_SUFFIX");
182 + yield* git("add", ".gitlab");
183 + yield* git("commit", "-m", "Add a large template");
184 +
185 + expect(yield* readTemplate()).toEqual(Option.some(prefix + "\n\n[truncated]"));
186 + }),
187 + ),
188 +);
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts
+9 -7
@@ -234,13 +234,15 @@ it.effect.each(["merge_requests", "issues"])(
234 title: "Pairing expiry",
235 body: "Preserve remote access",
236 });
237 - assert.strictEqual(
238 - provider.resolveLink?.({
239 - cwd: "/unrelated",
240 - url: new URL("https://gitlab.com/owner/repo"),
241 - }),
242 - undefined,
243 - );
237 + for (const url of [
238 + "https://gitlab.com/owner/repo",
239 + "https://gitlab.attacker.test/team/project/-/issues/1",
240 + ]) {
241 + assert.strictEqual(
242 + provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
243 + undefined,
244 + );
245 + }
246 }),
247 );
248
packages/source-control-gitlab/src/server/driver.ts
+1 -2
@@ -14,8 +14,7 @@ import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
14
15 const services = GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer));
16
17 -/** Over this host's own services, which `driver` builds; tests stand in for them. */
18 -export const makeInstance = Effect.all({
17 +const makeInstance = Effect.all({
18 sourceControl: GitLabSourceControlProvider.make,
19 discovery: Effect.succeed(GitLabSourceControlProvider.discovery),
20 pullRequests: GitLabPullRequestProvider.make,
packages/source-control-gitlab/src/server/gitLabDiscovery.test.ts new
+76
@@ -0,0 +1,76 @@
1 +import {
2 + parseGitRemoteHost,
3 + unknownRemoteProvider,
4 +} from "@t3tools/source-control-core/client/definition";
5 +import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
6 +import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
7 +import { assert, it } from "@effect/vitest";
8 +import * as Effect from "effect/Effect";
9 +import * as Option from "effect/Option";
10 +import { ChildProcessSpawner } from "effect/process";
11 +
12 +import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
13 +
14 +it("reads the account from glab output without status marks", () => {
15 + const auth = GitLabSourceControlProvider.discovery.parseAuth(
16 + processOutput(`gitlab.com
17 +Logged in to gitlab.com as gitlab-user
18 +`),
19 + );
20 + assert.strictEqual(auth.status, "authenticated");
21 + assert.deepStrictEqual(auth.account, Option.some("gitlab-user"));
22 +});
23 +
24 +it.effect.each([
25 + {
26 + name: "without relying on host naming",
27 + remoteUrl: "https://self-hosted.example.test/group/project.git",
28 + host: "self-hosted.example.test",
29 + stdout: `gitlab.com
30 + x gitlab.com: API call failed: 401 Unauthorized
31 + ! No token found
32 +self-hosted.example.test
33 + ✓ Logged in to self-hosted.example.test as gitlab-user
34 + ✓ Token found: ******
35 +`,
36 + exitCode: 1,
37 + },
38 + {
39 + name: "on a non-standard port",
40 + remoteUrl: "https://self-hosted.example.test:8443/group/project.git",
41 + host: "self-hosted.example.test:8443",
42 + stdout: `self-hosted.example.test:8443
43 + ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
44 + ✓ Token found: ******
45 +`,
46 + exitCode: 0,
47 + },
48 +] as const)("claims a self-hosted remote glab is signed in to $name", (scenario) =>
49 + Effect.gen(function* () {
50 + const remote = parseGitRemoteHost(scenario.remoteUrl);
51 + assert.ok(remote);
52 + const asked: Array<ReadonlyArray<string>> = [];
53 + const verdict = yield* refineUnknownRemoteProvider({
54 + specs: [GitLabSourceControlProvider.discovery],
55 + cwd: "/repo",
56 + context: {
57 + provider: unknownRemoteProvider(remote),
58 + remoteName: "origin",
59 + remoteUrl: scenario.remoteUrl,
60 + },
61 + process: {
62 + run: ({ command, args }) => {
63 + asked.push([command, ...args]);
64 + return Effect.succeed(
65 + processOutput(scenario.stdout, {
66 + exitCode: ChildProcessSpawner.ExitCode(scenario.exitCode),
67 + }),
68 + );
69 + },
70 + },
71 + });
72 + assert.deepStrictEqual(asked, [["glab", "auth", "status", "--hostname", scenario.host]]);
73 + assert.strictEqual(verdict.provider?.kind, "gitlab");
74 + assert.strictEqual(verdict.settled, true);
75 + }),
76 +);
packages/source-control-testing/package.json
+5
@@ -3,6 +3,10 @@
3 "private": true,
4 "type": "module",
5 "exports": {
6 + "./fakeSourceControlDriver": {
7 + "types": "./src/fakeSourceControlDriver.ts",
8 + "import": "./src/fakeSourceControlDriver.ts"
9 + },
10 "./TestSourceControlHost": {
11 "types": "./src/TestSourceControlHost.ts",
12 "import": "./src/TestSourceControlHost.ts"
@@ -12,6 +16,7 @@
16 "typecheck": "tsc --noEmit"
17 },
18 "dependencies": {
19 + "@effect/platform-node": "catalog:",
20 "@t3tools/contracts": "workspace:*",
21 "@t3tools/shared": "workspace:*",
22 "@t3tools/source-control-core": "workspace:*",
packages/source-control-testing/src/TestSourceControlHost.ts
+125
@@ -1,15 +1,21 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 import {
3 DEFAULT_SERVER_SETTINGS,
4 + GitCommandError,
5 type ServerSettings,
6 type ServerSettingsPatch,
7 + VcsProcessExitError,
8 + VcsProcessSpawnError,
9 } from "@t3tools/contracts";
10 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
11 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12 import * as Context from "effect/Context";
13 import * as Effect from "effect/Effect";
14 import * as Layer from "effect/Layer";
15 +import * as ChildProcess from "effect/process/ChildProcess";
16 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17 import * as Ref from "effect/Ref";
18 +import * as Stream from "effect/Stream";
19
20 export interface TestSourceControlHostOptions {
21 readonly settings?: ServerSettings;
@@ -78,3 +84,122 @@ export const processOutput = (
84 stdoutTruncated: false,
85 stderrTruncated: false,
86 });
87 +
88 +const TRUNCATION_MARKER = "\n\n[truncated]";
89 +const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
90 +
91 +const collectText = <E>(stream: Stream.Stream<Uint8Array, E>, maxBytes: number, marker: string) =>
92 + Stream.runCollect(stream).pipe(
93 + Effect.map((chunks) => {
94 + const bytes = Buffer.concat(Array.from(chunks));
95 + const truncated = bytes.byteLength > maxBytes;
96 + const text = bytes.subarray(0, maxBytes).toString("utf8");
97 + return { text: truncated ? `${text}${marker}` : text, truncated };
98 + }),
99 + );
100 +
101 +/**
102 + * Runs commands for real, the way the server's host does in the parts a forge reads: output is
103 + * capped and marked, and a non-zero exit fails unless allowed. It has none of the server's
104 + * timeouts, concurrency limits, generic failure classification, or retries.
105 + */
106 +const runForReal = (
107 + spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
108 + input: SourceControlHost.SourceControlProcessInput,
109 +): Effect.Effect<
110 + SourceControlHost.SourceControlProcessOutput,
111 + VcsProcessSpawnError | VcsProcessExitError
112 +> => {
113 + const context = {
114 + operation: input.operation,
115 + command: input.command,
116 + cwd: input.cwd,
117 + argumentCount: input.args.length,
118 + };
119 + const maxBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
120 + const marker = input.appendTruncationMarker ? TRUNCATION_MARKER : "";
121 + return Effect.gen(function* () {
122 + const child = yield* spawner.spawn(
123 + ChildProcess.make(input.command, input.args, {
124 + cwd: input.spawnCwd ?? input.cwd,
125 + ...(input.env === undefined ? {} : { env: input.env, extendEnv: true }),
126 + }),
127 + );
128 + const [stdout, stderr] = yield* Effect.all(
129 + [
130 + collectText(
131 + input.onStdoutChunk === undefined
132 + ? child.stdout
133 + : child.stdout.pipe(
134 + Stream.tap((chunk) => Effect.sync(() => input.onStdoutChunk?.(chunk))),
135 + ),
136 + maxBytes,
137 + marker,
138 + ),
139 + collectText(child.stderr, maxBytes, marker),
140 + input.stdin === undefined
141 + ? Effect.void
142 + : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin),
143 + ],
144 + { concurrency: "unbounded" },
145 + );
146 + const exitCode = yield* child.exitCode;
147 + if (exitCode !== 0 && !input.allowNonZeroExit) {
148 + return yield* VcsProcessExitError.fromProcessExit(
149 + context,
150 + { exitCode, stderr: stderr.text, stderrTruncated: stderr.truncated },
151 + input.classifyFailure?.(stderr.text) ?? "command-failed",
152 + input.notFoundDetail === undefined ? undefined : { notFoundDetail: input.notFoundDetail },
153 + );
154 + }
155 + return {
156 + exitCode,
157 + stdout: stdout.text,
158 + stderr: stderr.text,
159 + stdoutTruncated: stdout.truncated,
160 + stderrTruncated: stderr.truncated,
161 + };
162 + }).pipe(
163 + Effect.scoped,
164 + Effect.catchTags({
165 + PlatformError: (cause) => Effect.fail(new VcsProcessSpawnError({ ...context, cause })),
166 + }),
167 + );
168 +};
169 +
170 +/**
171 + * `layer` whose `process.run` and `git.execute` spawn real processes, for a forge test that needs
172 + * a real repository. Every other git operation still dies unless supplied.
173 + */
174 +export const layerWithRealGit = (
175 + options: TestSourceControlHostOptions = {},
176 +): Layer.Layer<SourceControlHost.SourceControlHost | TestSourceControlHostSettings> =>
177 + Layer.unwrap(
178 + Effect.gen(function* () {
179 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
180 + const run = (input: SourceControlHost.SourceControlProcessInput) =>
181 + runForReal(spawner, input);
182 + return layer({
183 + ...options,
184 + process: { run, ...options.process },
185 + git: {
186 + execute: (input) =>
187 + run({ ...input, command: "git" }).pipe(
188 + Effect.mapError(
189 + (cause) =>
190 + new GitCommandError({
191 + operation: input.operation,
192 + command: "git",
193 + cwd: input.cwd,
194 + argumentCount: input.args.length,
195 + ...(cause._tag === "VcsProcessExitError" ? { exitCode: cause.exitCode } : {}),
196 + detail: cause.message,
197 + cause,
198 + }),
199 + ),
200 + ),
201 + ...options.git,
202 + },
203 + });
204 + }),
205 + ).pipe(Layer.provide(NodeServices.layer));
packages/source-control-testing/src/fakeSourceControlDriver.ts new
+132
@@ -0,0 +1,132 @@
1 +import {
2 + SourceControlProviderKind,
3 + type PullRequestReviewCapabilities,
4 + type PullRequestReviewerCapabilities,
5 +} from "@t3tools/contracts";
6 +import {
7 + providerAuth,
8 + type SourceControlProviderDiscoverySpec,
9 +} from "@t3tools/source-control-core/server/discovery";
10 +import type { SourceControlDriverInstance } from "@t3tools/source-control-core/server/driver";
11 +import type { PullRequestProviderApi } from "@t3tools/source-control-core/server/PullRequestProvider";
12 +import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
13 +import * as Effect from "effect/Effect";
14 +
15 +const FULL_REVIEW: PullRequestReviewCapabilities = {
16 + inlineComment: true,
17 + reply: true,
18 + resolve: true,
19 + verdicts: ["comment", "approve", "request-changes"],
20 +};
21 +
22 +const FULL_REVIEWERS: PullRequestReviewerCapabilities = { request: true, listCandidates: true };
23 +
24 +const kindOf = (kind: string) => SourceControlProviderKind.make(kind);
25 +
26 +/**
27 + * A pull request provider that can do everything and holds nothing: lists are empty, writes
28 + * succeed, and reads a test did not supply die.
29 + */
30 +export function fakePullRequestProvider(
31 + kind: string,
32 + overrides: Partial<PullRequestProviderApi> = {},
33 +): PullRequestProviderApi {
34 + return {
35 + kind: kindOf(kind),
36 + capabilities: {
37 + diff: true,
38 + comment: true,
39 + actions: ["merge", "ready", "draft", "close", "reopen"],
40 + mergeMethods: ["merge"],
41 + search: true,
42 + reactions: true,
43 + review: FULL_REVIEW,
44 + reviewers: FULL_REVIEWERS,
45 + edit: { changeRequest: true, comment: true },
46 + },
47 + getViewer: () => Effect.succeed("bilal"),
48 + getViewerPermissions: () =>
49 + Effect.succeed({
50 + actions: ["merge", "ready", "draft", "close", "reopen"],
51 + comment: true,
52 + resolve: true,
53 + verdicts: ["comment", "approve", "request-changes"],
54 + requestReviewers: true,
55 + }),
56 + listChangeRequests: () => Effect.succeed({ items: [], truncated: false, continues: true }),
57 + getChangeRequest: () => Effect.die("unused"),
58 + getChangeRequestActivity: () => Effect.die("unused"),
59 + getDiff: () => Effect.die("unused"),
60 + runAction: () => Effect.void,
61 + updateChangeRequest: () => Effect.void,
62 + comment: () => Effect.void,
63 + updateComment: () => Effect.void,
64 + submitReview: () => Effect.void,
65 + replyToThread: () => Effect.void,
66 + setThreadResolution: () => Effect.void,
67 + setReaction: () => Effect.void,
68 + listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }),
69 + setReviewerRequest: () => Effect.void,
70 + ...overrides,
71 + };
72 +}
73 +
74 +type SourceControlProviderService = SourceControlProvider.SourceControlProvider["Service"];
75 +
76 +const unexpected = (kind: string, operation: string) => () =>
77 + Effect.die(`Unexpected ${kind} ${operation} in a test that supplied none.`);
78 +
79 +/** A source control provider whose every operation dies unless the test supplies it. */
80 +export function fakeSourceControlProvider(
81 + kind: string,
82 + overrides: Partial<SourceControlProviderService> = {},
83 +): SourceControlProviderService {
84 + return {
85 + kind: kindOf(kind),
86 + listChangeRequests: unexpected(kind, "listChangeRequests"),
87 + getChangeRequest: unexpected(kind, "getChangeRequest"),
88 + createChangeRequest: unexpected(kind, "createChangeRequest"),
89 + getRepositoryCloneUrls: unexpected(kind, "getRepositoryCloneUrls"),
90 + createRepository: unexpected(kind, "createRepository"),
91 + getDefaultBranch: unexpected(kind, "getDefaultBranch"),
92 + checkoutChangeRequest: unexpected(kind, "checkoutChangeRequest"),
93 + ...overrides,
94 + };
95 +}
96 +
97 +/** Discovery over an API integration that reports an unknown sign-in. */
98 +export function fakeDiscovery(
99 + kind: string,
100 + overrides: Partial<Extract<SourceControlProviderDiscoverySpec, { readonly type: "api" }>> = {},
101 +): SourceControlProviderDiscoverySpec {
102 + return {
103 + type: "api",
104 + kind: kindOf(kind),
105 + label: kind,
106 + installHint: `Install ${kind}.`,
107 + probeAuth: Effect.succeed(providerAuth({ status: "unknown" })),
108 + ...overrides,
109 + };
110 +}
111 +
112 +export interface FakeSourceControlDriverOptions {
113 + readonly sourceControl?: Partial<SourceControlProviderService>;
114 + /** Null for a host whose pull requests this build cannot read. */
115 + readonly pullRequests?: Partial<PullRequestProviderApi> | null;
116 + readonly discovery?: SourceControlProviderDiscoverySpec;
117 + readonly fetchMedia?: SourceControlDriverInstance["fetchMedia"];
118 +}
119 +
120 +/** A driver instance for a host named `kind` that needs none of the server's services. */
121 +export function fakeSourceControlDriverInstance(
122 + kind: string,
123 + options: FakeSourceControlDriverOptions = {},
124 +): SourceControlDriverInstance {
125 + return {
126 + sourceControl: fakeSourceControlProvider(kind, options.sourceControl),
127 + discovery: options.discovery ?? fakeDiscovery(kind),
128 + pullRequests:
129 + options.pullRequests === null ? null : fakePullRequestProvider(kind, options.pullRequests),
130 + ...(options.fetchMedia === undefined ? {} : { fetchMedia: options.fetchMedia }),
131 + };
132 +}
pnpm-lock.yaml
+12
@@ -1868,9 +1868,15 @@ importers:
1868 specifier: 4.0.5
1869 version: 4.0.5
1870 devDependencies:
1871 + '@effect/platform-node':
1872 + specifier: 4.0.5
1873 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6)
1874 '@effect/vitest':
1875 specifier: 4.0.5
1876 version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
1877 + '@t3tools/source-control-testing':
1878 + specifier: workspace:*
1879 + version: link:../source-control-testing
1880 '@types/node':
1881 specifier: 24.12.4
1882 version: 24.12.4
@@ -1918,6 +1924,9 @@ importers:
1924 specifier: 4.0.5
1925 version: 4.0.5
1926 devDependencies:
1927 + '@effect/platform-node':
1928 + specifier: 4.0.5
1929 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6)
1930 '@effect/vitest':
1931 specifier: 4.0.5
1932 version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@astrojs/compiler-rs@0.5.1)(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
@@ -2029,6 +2038,9 @@ importers:
2038
2039 packages/source-control-testing:
2040 dependencies:
2041 + '@effect/platform-node':
2042 + specifier: 4.0.5
2043 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6)
2044 '@t3tools/contracts':
2045 specifier: workspace:*
2046 version: link:../contracts