Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
6import {
7 IssueTrackerKind,
8 type IssueTrackerProjectBinding,
9 SourceControlProviderKind,
10 type OrchestrationProjectShell,
11 type ProjectId,
12} from "@t3tools/contracts";
13import {
14 IssueTrackerError,
15 type IssueTrackerApi,
16 type StandaloneIssueTrackerApi,
17 type TrackerIssueDetail,
18} from "@t3tools/source-control-core/server/IssueTracker";
19
20import { PersistenceSqlError } from "../persistence/Errors.ts";
21import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
22import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
23
24import * as ProjectService from "../project/ProjectService.ts";
25import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
26import * as IssueService from "./IssueService.ts";
27import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
28
29const GITHUB = IssueTrackerKind.make("github");
30const LINEAR = IssueTrackerKind.make("linear");
31
32/** A standalone tracker shaped like Linear: its own host, team keys for scopes, `ENG-1` keys. */
33function fakeStandaloneTracker(
34 overrides: Partial<IssueTrackerApi> = {},
35): StandaloneIssueTrackerApi {
36 return {
37 ...fakeTracker({
38 getViewer: () => Effect.succeed("usr_julius"),
39 getIssue: (input) =>
40 Effect.succeed({
41 ...issue(input.key),
42 url: `https://linear.app/acme/issue/${input.key}/canonical-title`,
43 displayKey: input.key,
44 viewer: "usr_julius",
45 }),
46 ...overrides,
47 }),
48 kind: LINEAR,
49 standalone: {
50 tracker: LINEAR,
51 displayName: "Linear",
52 host: "linear.app",
53 scopeNoun: "team",
54 credential: { label: "Personal API key", helpUrl: null },
55 },
56 parseIssueUrl: (url) => {
57 const links = new Map([
58 ["https://linear.app/acme/issue/ENG-1/old-title", "acme"],
59 ["https://linear.app/acme/issue/ENG-1/issue-title", "acme"],
60 ["https://linear.app/acme/issue/ENG-1/canonical-title", "acme"],
61 ["https://linear.app/other-workspace/issue/ENG-1/old-title", "other-workspace"],
62 ]);
63 const workspace = links.get(url.href);
64 return workspace === undefined
65 ? null
66 : { host: "linear.app", workspace, scope: "ENG", key: "ENG-1" };
67 },
68 probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }),
69 };
70}
71
72function project(input: {
73 readonly id: string;
74 readonly repository?: string;
75 readonly provider?: string;
76 readonly host?: string;
77}): OrchestrationProjectShell {
78 const host = input.host ?? "github.com";
79 return {
80 id: input.id as ProjectId,
81 title: input.id,
82 workspaceRoot: `/w/${input.id}`,
83 ...(input.repository
84 ? {
85 repositoryIdentity: {
86 canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
87 locator: {
88 source: "git-remote" as const,
89 remoteName: "origin",
90 remoteUrl: `https://${host}/${input.repository}.git`,
91 },
92 provider: SourceControlProviderKind.make(input.provider ?? "github"),
93 displayName: input.repository,
94 },
95 }
96 : {}),
97 defaultModelSelection: null,
98 scripts: [],
99 createdAt: "2026-07-01T00:00:00Z",
100 updatedAt: "2026-07-01T00:00:00Z",
101 };
102}
103
104function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
105 return {
106 key,
107 displayKey: `#${key}`,
108 title: `Issue ${key}`,
109 url: `https://github.com/acme/web/issues/${key}`,
110 author: null,
111 state: { category: "open", name: "open" },
112 createdAt: "2026-07-01T00:00:00Z",
113 updatedAt,
114 closedAt: null,
115 assignees: [],
116 labels: [],
117 commentCount: 0,
118 body: "",
119 viewer: "julius",
120 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
121 states: [],
122 comments: [],
123 commentsCursor: null,
124 events: [],
125 linkedPullRequests: [],
126 };
127}
128
129function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
130 return {
131 kind: GITHUB,
132 capabilities: {
133 create: true,
134 edit: true,
135 comment: true,
136 labels: true,
137 assignees: true,
138 reactions: false,
139 templates: false,
140 linkedPullRequests: true,
141 events: true,
142 search: true,
143 },
144 getViewer: () => Effect.succeed("julius"),
145 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
146 getIssue: (input) => Effect.succeed(issue(input.key)),
147 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
148 comment: () => Effect.void,
149 update: () => Effect.void,
150 setState: () => Effect.void,
151 ...overrides,
152 };
153}
154
155function makeService(input: {
156 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
157 readonly trackers: ReadonlyArray<IssueTrackerApi>;
158 readonly bindings?: Record<string, IssueTrackerProjectBinding>;
159 readonly bindingsFailure?: PersistenceSqlError;
160}) {
161 return IssueService.IssueService.pipe(
162 Effect.provide(
163 IssueService.layer.pipe(
164 Layer.provide(
165 Layer.mergeAll(
166 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
167 list:
168 input.bindingsFailure !== undefined
169 ? Effect.fail(input.bindingsFailure)
170 : Effect.succeed(
171 new Map(
172 Object.entries(input.bindings ?? {}).map(([id, binding]) => [
173 id as ProjectId,
174 binding,
175 ]),
176 ),
177 ),
178 }),
179 Layer.succeed(
180 IssueTrackerRegistry.IssueTrackerRegistry,
181 IssueTrackerRegistry.fromTrackers(input.trackers),
182 ),
183 Layer.mock(ProjectService.ProjectService)({
184 listShells: () => Effect.succeed(input.projects),
185 getShell: (projectId) =>
186 Effect.succeed(
187 Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
188 ),
189 }),
190 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
191 resolve: () => Effect.succeed(null),
192 }),
193 ),
194 ),
195 ),
196 ),
197 );
198}
199
200describe("IssueService", () => {
201 it.effect("places a project where its host keeps its issues", () =>
202 Effect.gen(function* () {
203 const azure = IssueTrackerKind.make("azure-devops");
204 const service = yield* makeService({
205 projects: [
206 project({
207 id: "p",
208 provider: "azure-devops",
209 host: "dev.azure.com",
210 repository: "acme/Web App/_git/web",
211 }),
212 ],
213 trackers: [fakeTracker({ kind: azure })],
214 });
215 expect(yield* service.projectScope("p" as ProjectId)).toEqual({
216 projectId: "p",
217 tracker: "azure-devops",
218 host: "dev.azure.com",
219 scope: "acme/Web App",
220 });
221 }),
222 );
223
224 it.effect("reads another repository on the same host but refuses to write to it", () =>
225 Effect.gen(function* () {
226 const writes: string[] = [];
227 const service = yield* makeService({
228 projects: [project({ id: "web", repository: "acme/web" })],
229 trackers: [
230 fakeTracker({
231 comment: (input) =>
232 Effect.sync(() => {
233 writes.push(`${input.scope}#${input.key}`);
234 }),
235 }),
236 ],
237 });
238 const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
239 const external = { ...own, scope: "other/backend", key: "7" };
240
241 expect((yield* service.detail(own)).writable).toBe(true);
242 // The external issue is served by the project's checkout and credentials, read-only.
243 const detail = yield* service.detail(external);
244 expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
245
246 yield* service.comment({ ...own, body: "ok" });
247 const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
248 expect(refused).toMatchObject({
249 _tag: "Failure",
250 failure: { _tag: "IssueOperationError", reason: "read-only" },
251 });
252 expect(writes).toEqual(["acme/web#1"]);
253
254 // A link's port picks the server: the project bound with it, not a default-port namesake.
255 const ported = yield* makeService({
256 projects: [
257 project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
258 project({
259 id: "ported",
260 repository: "acme/web",
261 provider: "forgejo",
262 host: "gitea.test:8443",
263 }),
264 ],
265 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
266 });
267 expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
268 projectId: "ported",
269 host: "gitea.test:8443",
270 key: "3",
271 writable: true,
272 });
273 expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
274 projectId: "plain",
275 host: "gitea.test",
276 });
277
278 // A GitHub Enterprise Server's hostname need not say "github"; its project vouches for it.
279 const enterprise = yield* makeService({
280 projects: [project({ id: "ghes", repository: "acme/web", host: "code.acme.test" })],
281 trackers: [fakeTracker()],
282 });
283 expect(
284 yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"),
285 ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true });
286
287 // Another host is not reachable through this project's credentials at all.
288 const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
289 expect(elsewhere).toMatchObject({
290 _tag: "IssueUnavailableError",
291 reason: "tracker-unsupported",
292 });
293 }),
294 );
295
296 it.effect("resolves both legacy Azure work item URLs through the bound project", () =>
297 Effect.gen(function* () {
298 const tracker = IssueTrackerKind.make("azure-devops");
299 const host = "acme.visualstudio.com";
300 const service = yield* makeService({
301 projects: [
302 project({ id: "api", repository: "Api/_git/api", provider: tracker, host }),
303 project({
304 id: "web",
305 repository: "DefaultCollection/Web/_git/web",
306 provider: tracker,
307 host,
308 }),
309 ],
310 trackers: [fakeTracker({ kind: tracker })],
311 });
312 for (const path of ["Web", "DefaultCollection/Web"]) {
313 const ref = yield* service.resolveUrl(
314 `https://${host}/${path}/_workitems/edit/9`,
315 "api" as ProjectId,
316 );
317 expect(ref).toEqual({
318 projectId: "web",
319 tracker,
320 host,
321 scope: "DefaultCollection/Web",
322 key: "9",
323 writable: true,
324 });
325 }
326 }),
327 );
328
329 it.effect("sends writes as interactive requests and reads as background ones", () =>
330 Effect.gen(function* () {
331 const interactive: Array<readonly [string, boolean]> = [];
332 const record = (operation: string) =>
333 Effect.gen(function* () {
334 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
335 });
336 const service = yield* makeService({
337 projects: [project({ id: "web", repository: "acme/web" })],
338 trackers: [
339 fakeTracker({
340 getComments: () =>
341 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
342 comment: () => record("comment"),
343 }),
344 ],
345 });
346 const ref = {
347 projectId: "web" as ProjectId,
348 tracker: GITHUB,
349 scope: "acme/web",
350 key: "42",
351 };
352 yield* service.comments({ ...ref, cursor: "next" });
353 yield* service.comment({ ...ref, body: "Repro attached." });
354 expect(interactive).toEqual([
355 ["comments", false],
356 ["comment", true],
357 ]);
358 }),
359 );
360
361 it.effect("refuses what the tracker did not declare before calling it", () =>
362 Effect.gen(function* () {
363 let calls = 0;
364 const service = yield* makeService({
365 projects: [project({ id: "web", repository: "acme/web" })],
366 trackers: [
367 fakeTracker({
368 setState: () =>
369 Effect.sync(() => {
370 calls += 1;
371 }),
372 setReaction: () =>
373 Effect.sync(() => {
374 calls += 1;
375 }),
376 }),
377 ],
378 });
379 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
380
381 // The state is the tracker's own name, passed through: the tracker is what proves it.
382 yield* service.setState({ ...ref, state: "In Review" });
383 const reaction = yield* Effect.flip(
384 service.react({ ...ref, content: "heart", reacted: true }),
385 );
386 expect(reaction._tag).toBe("IssueOperationError");
387 expect(calls).toBe(1);
388 }),
389 );
390
391 it.effect("deduplicates and pages repositories despite partial failures", () =>
392 Effect.gen(function* () {
393 const listed: string[] = [];
394 let failContinuation = true;
395 const service = yield* makeService({
396 projects: [
397 project({ id: "web", repository: "Acme/Web" }),
398 project({ id: "web-worktree", repository: "acme/web" }),
399 project({ id: "api", repository: "acme/api" }),
400 project({ id: "docs", repository: "acme/docs" }),
401 project({
402 id: "gitlab",
403 repository: "acme/gl",
404 provider: "gitlab",
405 host: "gitlab.com",
406 }),
407 project({ id: "plain" }),
408 ],
409 trackers: [
410 fakeTracker({
411 listIssues: (input) =>
412 Effect.gen(function* () {
413 listed.push(input.scope);
414 if (input.scope === "acme/api")
415 return yield* new IssueTrackerError({
416 tracker: GITHUB,
417 operation: "listIssues",
418 reason: "failed",
419 // A tracker may fail without a detail; the wire error still needs one.
420 detail: " ",
421 });
422 if (input.scope === "acme/docs")
423 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
424 if (input.cursor === "next" && failContinuation) {
425 failContinuation = false;
426 return yield* new IssueTrackerError({
427 tracker: GITHUB,
428 operation: "listIssues",
429 reason: "failed",
430 detail: "try again",
431 });
432 }
433 if (input.cursor === "next")
434 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
435 return {
436 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
437 nextCursor: "next",
438 };
439 }),
440 }),
441 ],
442 });
443 const result = yield* service.list({ state: "open" });
444 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
445 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
446 ["web", "2"],
447 ["docs", "3"],
448 ["web", "1"],
449 ]);
450 expect(
451 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
452 ).toEqual(["Acme/Web", "Acme/Web"]);
453 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
454 expect(result.errors).toEqual([
455 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
456 ]);
457 expect(result.viewers).toEqual({});
458 expect(result.trackers).toEqual([
459 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
460 expect.objectContaining({
461 host: "gitlab.com",
462 tracker: "gitlab",
463 projectCount: 1,
464 configured: false,
465 capabilities: null,
466 }),
467 ]);
468
469 // Narrowing to one host still names every tracker, so the client can switch between them.
470 // Narrowing by involvement reads the account it compares against.
471 const narrowed = yield* service.list({
472 state: "open",
473 host: "github.com",
474 involvement: "assigned",
475 });
476 expect(narrowed.viewers).toEqual({ "github.com": "julius" });
477 expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true);
478 expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([
479 "github.com",
480 "gitlab.com",
481 ]);
482
483 // A continuation only reads the scopes it names.
484 listed.length = 0;
485 const failed = yield* service.list({
486 state: "open",
487 cursors: result.nextCursors,
488 });
489 expect(listed).toEqual(["Acme/Web"]);
490 expect(failed.nextCursors).toEqual(result.nextCursors);
491 expect(failed.errors).toEqual([
492 { projectId: "web", projectTitle: "web", message: "try again" },
493 ]);
494 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
495 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
496 expect(next.nextCursors).toEqual({});
497 expect(next.errors).toEqual([]);
498
499 // The cursor belongs to the scope, not to the project whose spelling first read it.
500 listed.length = 0;
501 const through = yield* service.list({
502 state: "open",
503 projectId: "web-worktree" as ProjectId,
504 cursors: result.nextCursors,
505 });
506 expect(listed).toEqual(["acme/web"]);
507 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
508 }),
509 );
510});
511
512describe("IssueService with a standalone tracker", () => {
513 it.effect("rejects a URL from another workspace with the same team and issue key", () =>
514 Effect.gen(function* () {
515 const service = yield* makeService({
516 projects: [project({ id: "web" })],
517 trackers: [fakeStandaloneTracker()],
518 bindings: { web: { tracker: LINEAR, scope: "ENG" } },
519 });
520 expect(
521 yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"),
522 ).toMatchObject({ key: "ENG-1", writable: true });
523 const refused = yield* service
524 .resolveUrl("https://linear.app/other-workspace/issue/ENG-1/old-title")
525 .pipe(Effect.result);
526 expect(refused).toMatchObject({
527 _tag: "Failure",
528 failure: {
529 _tag: "IssueOperationError",
530 operation: "resolveUrl",
531 reason: "not-found",
532 detail: "This issue URL does not belong to the connected workspace.",
533 },
534 });
535 }),
536 );
537
538 it.effect("lists a bound project's standalone scope beside its git host and serves both", () =>
539 Effect.gen(function* () {
540 const listed: string[] = [];
541 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
542 listIssues: (input) =>
543 Effect.sync(() => {
544 listed.push(`${tracker} ${input.host} ${input.scope}`);
545 return { items: [issue(tracker === LINEAR ? "ENG-1" : "1")], nextCursor: null };
546 }),
547 });
548 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
549 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
550 const bound = yield* makeService({
551 projects: [...projects, project({ id: "api", repository: "acme/api" })],
552 trackers,
553 bindings: { ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG" } },
554 });
555
556 const result = yield* bound.list({ state: "open" });
557 expect(listed.sort()).toEqual([
558 "github github.com acme/api",
559 "github github.com acme/web",
560 "linear linear.app ENG",
561 ]);
562 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
563 [
564 ["github", "acme/api", "1"],
565 ["github", "acme/web", "1"],
566 ["linear", "ENG", "ENG-1"],
567 ],
568 );
569 expect(result.trackers.map((tracker) => [tracker.tracker, tracker.host]).sort()).toEqual([
570 ["github", "github.com"],
571 ["linear", "linear.app"],
572 ]);
573 expect(result.scopes).toContainEqual({
574 projectId: "web",
575 tracker: "linear",
576 host: "linear.app",
577 scope: "ENG",
578 });
579 // Narrowed to one project, both of its trackers are still read.
580 listed.length = 0;
581 const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId });
582 expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]);
583 expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([
584 ["web", "ENG"],
585 ["web", "acme/web"],
586 ]);
587 // A reference picks the project's tracker by kind; both are the project's own, so writable.
588 const linearRef = {
589 projectId: "web" as ProjectId,
590 tracker: LINEAR,
591 scope: "ENG",
592 key: "ENG-1",
593 };
594 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
595 expect(
596 yield* bound.detail({
597 projectId: "web" as ProjectId,
598 tracker: GITHUB,
599 scope: "acme/web",
600 key: "1",
601 }),
602 ).toMatchObject({ host: "github.com", writable: true });
603
604 const resolved = yield* bound
605 .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId)
606 .pipe(Effect.result);
607 expect(resolved).toMatchObject({
608 _tag: "Success",
609 success: {
610 projectId: "web",
611 tracker: LINEAR,
612 host: "linear.app",
613 scope: "ENG",
614 key: "ENG-1",
615 writable: true,
616 },
617 });
618
619 // Unbound, the standalone scope is gone and its references are unsupported.
620 listed.length = 0;
621 const unbound = yield* makeService({ projects, trackers });
622 const after = yield* unbound.list({ state: "open" });
623 expect(listed).toEqual(["github github.com acme/web"]);
624 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
625 const refused = yield* Effect.flip(unbound.detail(linearRef));
626 expect(refused).toMatchObject({
627 _tag: "IssueUnavailableError",
628 reason: "tracker-unsupported",
629 });
630
631 // A project with no remote at all can still be bound, and then has only the standalone one.
632 const standaloneOnly = yield* makeService({
633 projects,
634 trackers,
635 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
636 });
637 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
638 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
639 ["notes", "OPS"],
640 ]);
641
642 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
643 const unreadable = yield* makeService({
644 projects,
645 trackers,
646 bindingsFailure: new PersistenceSqlError({
647 operation: "IssueTrackerBindingsRepository.list",
648 detail: "disk I/O error",
649 }),
650 });
651 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
652 _tag: "IssueOperationError",
653 operation: "listProjects",
654 });
655 }),
656 );
657});