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 IssueTrackerAccountId,
8 IssueTrackerKind,
9 type IssueTrackerProjectBinding,
10 SourceControlProviderKind,
11 type OrchestrationProjectShell,
12 type ProjectId,
13} from "@t3tools/contracts";
14import {
15 IssueTrackerError,
16 type IssueTrackerApi,
17 type StandaloneIssueTrackerApi,
18 type TrackerIssueDetail,
19} from "@t3tools/source-control-core/server/IssueTracker";
20import { IssueTrackerAccount } from "@t3tools/source-control-core/server/IssueTrackerHost";
21
22import { PersistenceSqlError } from "../persistence/Errors.ts";
23import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
24import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
25
26import * as ProjectService from "../project/ProjectService.ts";
27import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
28import * as IssueService from "./IssueService.ts";
29import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
30
31const GITHUB = IssueTrackerKind.make("github");
32const LINEAR = IssueTrackerKind.make("linear");
33
34/** A standalone tracker shaped like Linear: its own host, team keys for scopes, `ENG-1` keys. */
35function fakeStandaloneTracker(
36 overrides: Partial<IssueTrackerApi> = {},
37): StandaloneIssueTrackerApi {
38 return {
39 ...fakeTracker({
40 getViewer: () => Effect.succeed("usr_julius"),
41 getIssue: (input) =>
42 Effect.succeed({
43 ...issue(input.key),
44 url: `https://linear.app/acme/issue/${input.key}/canonical-title`,
45 displayKey: input.key,
46 viewer: "usr_julius",
47 }),
48 ...overrides,
49 }),
50 kind: LINEAR,
51 standalone: {
52 tracker: LINEAR,
53 displayName: "Linear",
54 host: "linear.app",
55 scopeNoun: "team",
56 credential: { label: "Personal API key", helpUrl: null },
57 },
58 parseIssueUrl: (url) => {
59 const links = new Map([
60 ["https://linear.app/acme/issue/ENG-1/old-title", "acme"],
61 ["https://linear.app/acme/issue/ENG-1/issue-title", "acme"],
62 ["https://linear.app/acme/issue/ENG-1/canonical-title", "acme"],
63 ["https://linear.app/other-workspace/issue/ENG-1/old-title", "other-workspace"],
64 ["https://linear.app/other-workspace/issue/ENG-1/canonical-title", "other-workspace"],
65 ]);
66 const workspace = links.get(url.href);
67 return workspace === undefined
68 ? null
69 : { host: "linear.app", workspace, scope: "ENG", key: "ENG-1" };
70 },
71 probeCredential: () => Effect.succeed({ account: "julius", scopes: [] }),
72 };
73}
74
75function project(input: {
76 readonly id: string;
77 readonly repository?: string;
78 readonly provider?: string;
79 readonly host?: string;
80}): OrchestrationProjectShell {
81 const host = input.host ?? "github.com";
82 return {
83 id: input.id as ProjectId,
84 title: input.id,
85 workspaceRoot: `/w/${input.id}`,
86 ...(input.repository
87 ? {
88 repositoryIdentity: {
89 canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
90 locator: {
91 source: "git-remote" as const,
92 remoteName: "origin",
93 remoteUrl: `https://${host}/${input.repository}.git`,
94 },
95 provider: SourceControlProviderKind.make(input.provider ?? "github"),
96 displayName: input.repository,
97 },
98 }
99 : {}),
100 defaultModelSelection: null,
101 scripts: [],
102 createdAt: "2026-07-01T00:00:00Z",
103 updatedAt: "2026-07-01T00:00:00Z",
104 };
105}
106
107function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
108 return {
109 key,
110 displayKey: `#${key}`,
111 title: `Issue ${key}`,
112 url: `https://github.com/acme/web/issues/${key}`,
113 author: null,
114 state: { category: "open", name: "open" },
115 createdAt: "2026-07-01T00:00:00Z",
116 updatedAt,
117 closedAt: null,
118 assignees: [],
119 labels: [],
120 commentCount: 0,
121 body: "",
122 viewer: "julius",
123 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
124 states: [],
125 comments: [],
126 commentsCursor: null,
127 events: [],
128 linkedPullRequests: [],
129 };
130}
131
132function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
133 return {
134 kind: GITHUB,
135 capabilities: {
136 create: true,
137 edit: true,
138 comment: true,
139 labels: true,
140 assignees: true,
141 reactions: false,
142 templates: false,
143 linkedPullRequests: true,
144 events: true,
145 search: true,
146 },
147 getViewer: () => Effect.succeed("julius"),
148 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
149 getIssue: (input) => Effect.succeed(issue(input.key)),
150 getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
151 comment: () => Effect.void,
152 update: () => Effect.void,
153 setState: () => Effect.void,
154 ...overrides,
155 };
156}
157
158function makeService(input: {
159 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
160 readonly trackers: ReadonlyArray<IssueTrackerApi>;
161 readonly bindings?: Record<string, IssueTrackerProjectBinding>;
162 readonly readBindings?: ReturnType<
163 IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]
164 >;
165}) {
166 return IssueService.IssueService.pipe(
167 Effect.provide(
168 IssueService.layer.pipe(
169 Layer.provide(
170 Layer.mergeAll(
171 Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
172 list: () =>
173 input.readBindings ??
174 Effect.succeed(
175 new Map(
176 Object.entries(input.bindings ?? {}).map(([id, binding]) => [
177 id as ProjectId,
178 binding,
179 ]),
180 ),
181 ),
182 }),
183 Layer.succeed(
184 IssueTrackerRegistry.IssueTrackerRegistry,
185 IssueTrackerRegistry.fromTrackers(input.trackers),
186 ),
187 Layer.mock(ProjectService.ProjectService)({
188 listShells: () => Effect.succeed(input.projects),
189 getShell: (projectId) =>
190 Effect.succeed(
191 Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
192 ),
193 }),
194 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
195 resolve: () => Effect.succeed(null),
196 }),
197 ),
198 ),
199 ),
200 ),
201 );
202}
203
204describe("IssueService", () => {
205 it.effect("places a project where its host keeps its issues", () =>
206 Effect.gen(function* () {
207 const azure = IssueTrackerKind.make("azure-devops");
208 const service = yield* makeService({
209 projects: [
210 project({
211 id: "p",
212 provider: "azure-devops",
213 host: "dev.azure.com",
214 repository: "acme/Web App/_git/web",
215 }),
216 ],
217 trackers: [fakeTracker({ kind: azure })],
218 });
219 expect(yield* service.projectScope("p" as ProjectId)).toEqual({
220 projectId: "p",
221 tracker: "azure-devops",
222 host: "dev.azure.com",
223 scope: "acme/Web App",
224 });
225 }),
226 );
227
228 it.effect("reads another repository on the same host but refuses to write to it", () =>
229 Effect.gen(function* () {
230 const writes: string[] = [];
231 const service = yield* makeService({
232 projects: [project({ id: "web", repository: "acme/web" })],
233 trackers: [
234 fakeTracker({
235 comment: (input) =>
236 Effect.sync(() => {
237 writes.push(`${input.scope}#${input.key}`);
238 }),
239 }),
240 ],
241 });
242 const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
243 const external = { ...own, scope: "other/backend", key: "7" };
244
245 expect((yield* service.detail(own)).writable).toBe(true);
246 // The external issue is served by the project's checkout and credentials, read-only.
247 const detail = yield* service.detail(external);
248 expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
249
250 yield* service.comment({ ...own, body: "ok" });
251 const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
252 expect(refused).toMatchObject({
253 _tag: "Failure",
254 failure: { _tag: "IssueOperationError", reason: "read-only" },
255 });
256 expect(writes).toEqual(["acme/web#1"]);
257
258 // A link's port picks the server: the project bound with it, not a default-port namesake.
259 const ported = yield* makeService({
260 projects: [
261 project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
262 project({
263 id: "ported",
264 repository: "acme/web",
265 provider: "forgejo",
266 host: "gitea.test:8443",
267 }),
268 ],
269 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
270 });
271 expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
272 projectId: "ported",
273 host: "gitea.test:8443",
274 key: "3",
275 writable: true,
276 });
277 expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
278 projectId: "plain",
279 host: "gitea.test",
280 });
281
282 // A GitHub Enterprise Server's hostname need not say "github"; its project vouches for it.
283 const enterprise = yield* makeService({
284 projects: [project({ id: "ghes", repository: "acme/web", host: "code.acme.test" })],
285 trackers: [fakeTracker()],
286 });
287 expect(
288 yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"),
289 ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true });
290
291 // The same holds for a self-hosted Forgejo.
292 const forgejo = yield* makeService({
293 projects: [
294 project({
295 id: "forge",
296 repository: "acme/web",
297 provider: "forgejo",
298 host: "code.acme.test",
299 }),
300 ],
301 trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
302 });
303 expect(yield* forgejo.resolveUrl("https://code.acme.test/acme/web/issues/7")).toMatchObject({
304 projectId: "forge",
305 host: "code.acme.test",
306 key: "7",
307 });
308
309 // A fork lists its upstream's issues and its own, counted once, and may write to both.
310 const fork = project({ id: "fork", repository: "acme/web" });
311 const forked = yield* makeService({
312 projects: [
313 {
314 ...fork,
315 repositoryIdentity: {
316 ...fork.repositoryIdentity!,
317 origin: { canonicalKey: "github.com/me/web" },
318 },
319 },
320 ],
321 trackers: [
322 fakeTracker({
323 listIssues: (input) =>
324 Effect.succeed({ items: [issue(input.scope)], nextCursor: null }),
325 comment: (input) =>
326 Effect.sync(() => {
327 writes.push(`${input.scope}#${input.key}`);
328 }),
329 }),
330 ],
331 });
332 const listed = yield* forked.list({ state: "open" });
333 expect(listed.entries.map((entry) => entry.scope).sort()).toEqual(["acme/web", "me/web"]);
334 expect(listed.trackers).toEqual([expect.objectContaining({ projectCount: 1 })]);
335 yield* forked.comment({
336 ...own,
337 projectId: "fork" as ProjectId,
338 scope: "me/web",
339 body: "ok",
340 });
341 expect(writes).toEqual(["acme/web#1", "me/web#1"]);
342
343 // Another host is not reachable through this project's credentials at all.
344 const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
345 expect(elsewhere).toMatchObject({
346 _tag: "IssueUnavailableError",
347 reason: "tracker-unsupported",
348 });
349 }),
350 );
351
352 it.effect(
353 "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout",
354 () =>
355 Effect.gen(function* () {
356 // A plain folder project, while GitHub itself is a supported tracker.
357 const service = yield* makeService({
358 projects: [project({ id: "folder" })],
359 trackers: [fakeTracker()],
360 });
361 const resolved = yield* service
362 .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId)
363 .pipe(Effect.result);
364 if (resolved._tag === "Failure") {
365 expect(resolved.failure).not.toMatchObject({
366 _tag: "IssueUnavailableError",
367 reason: "tracker-unsupported",
368 });
369 }
370 }),
371 );
372
373 it.effect("resolves both legacy Azure work item URLs through the bound project", () =>
374 Effect.gen(function* () {
375 const tracker = IssueTrackerKind.make("azure-devops");
376 const host = "acme.visualstudio.com";
377 const service = yield* makeService({
378 projects: [
379 project({ id: "api", repository: "Api/_git/api", provider: tracker, host }),
380 project({
381 id: "web",
382 repository: "DefaultCollection/Web/_git/web",
383 provider: tracker,
384 host,
385 }),
386 ],
387 trackers: [fakeTracker({ kind: tracker })],
388 });
389 for (const path of ["Web", "DefaultCollection/Web"]) {
390 const ref = yield* service.resolveUrl(
391 `https://${host}/${path}/_workitems/edit/9`,
392 "api" as ProjectId,
393 );
394 expect(ref).toEqual({
395 projectId: "web",
396 tracker,
397 host,
398 scope: "DefaultCollection/Web",
399 key: "9",
400 writable: true,
401 });
402 }
403 }),
404 );
405
406 it.effect("sends writes as interactive requests and reads as background ones", () =>
407 Effect.gen(function* () {
408 const interactive: Array<readonly [string, boolean]> = [];
409 const record = (operation: string) =>
410 Effect.gen(function* () {
411 interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
412 });
413 const service = yield* makeService({
414 projects: [project({ id: "web", repository: "acme/web" })],
415 trackers: [
416 fakeTracker({
417 getComments: () =>
418 record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
419 comment: () => record("comment"),
420 }),
421 ],
422 });
423 const ref = {
424 projectId: "web" as ProjectId,
425 tracker: GITHUB,
426 scope: "acme/web",
427 key: "42",
428 };
429 yield* service.comments({ ...ref, cursor: "next" });
430 yield* service.comment({ ...ref, body: "Repro attached." });
431 expect(interactive).toEqual([
432 ["comments", false],
433 ["comment", true],
434 ]);
435 }),
436 );
437
438 it.effect("shares one tracker read of an issue until a write or an explicit refresh", () =>
439 Effect.gen(function* () {
440 let reads = 0;
441 const service = yield* makeService({
442 projects: [
443 project({ id: "web", repository: "acme/web" }),
444 project({ id: "worktree", repository: "acme/web" }),
445 ],
446 trackers: [
447 fakeTracker({
448 getIssue: (input) => Effect.sync(() => (reads++, issue(input.key))),
449 }),
450 ],
451 });
452 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "42" };
453 // Every client and project polling one issue costs the tracker one read.
454 yield* Effect.all(
455 [
456 service.detail(ref),
457 service.detail(ref),
458 service.detail({ ...ref, projectId: "worktree" as ProjectId }),
459 ],
460 { concurrency: "unbounded" },
461 );
462 expect((yield* service.detail(ref)).projectId).toBe("web");
463 expect(reads).toBe(1);
464 yield* service.detail({ ...ref, key: "43" });
465 expect(reads).toBe(2);
466
467 yield* service.comment({ ...ref, body: "Repro attached." });
468 yield* service.detail(ref);
469 expect(reads).toBe(3);
470
471 // An explicit refresh sees what changed on the tracker itself.
472 yield* service.detail({ ...ref, refresh: true });
473 yield* service.detail(ref);
474 expect(reads).toBe(4);
475 }),
476 );
477
478 it.effect("refuses what the tracker did not declare before calling it", () =>
479 Effect.gen(function* () {
480 let calls = 0;
481 const service = yield* makeService({
482 projects: [project({ id: "web", repository: "acme/web" })],
483 trackers: [
484 fakeTracker({
485 setState: () =>
486 Effect.sync(() => {
487 calls += 1;
488 }),
489 setReaction: () =>
490 Effect.sync(() => {
491 calls += 1;
492 }),
493 }),
494 ],
495 });
496 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
497
498 // The state is the tracker's own name, passed through: the tracker is what proves it.
499 yield* service.setState({ ...ref, state: "In Review" });
500 const reaction = yield* Effect.flip(
501 service.react({ ...ref, content: "heart", reacted: true }),
502 );
503 expect(reaction._tag).toBe("IssueOperationError");
504 expect(calls).toBe(1);
505 }),
506 );
507
508 it.effect("deduplicates and pages repositories despite partial failures", () =>
509 Effect.gen(function* () {
510 const listed: string[] = [];
511 let failContinuation = true;
512 const service = yield* makeService({
513 projects: [
514 project({ id: "web", repository: "Acme/Web" }),
515 project({ id: "web-worktree", repository: "acme/web" }),
516 project({ id: "api", repository: "acme/api" }),
517 project({ id: "docs", repository: "acme/docs" }),
518 project({
519 id: "gitlab",
520 repository: "acme/gl",
521 provider: "gitlab",
522 host: "gitlab.com",
523 }),
524 project({ id: "plain" }),
525 ],
526 trackers: [
527 fakeTracker({
528 listIssues: (input) =>
529 Effect.gen(function* () {
530 listed.push(input.scope);
531 if (input.scope === "acme/api")
532 return yield* new IssueTrackerError({
533 tracker: GITHUB,
534 operation: "listIssues",
535 reason: "failed",
536 // A tracker may fail without a detail; the wire error still needs one.
537 detail: " ",
538 });
539 if (input.scope === "acme/docs")
540 return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
541 if (input.cursor === "next" && failContinuation) {
542 failContinuation = false;
543 return yield* new IssueTrackerError({
544 tracker: GITHUB,
545 operation: "listIssues",
546 reason: "failed",
547 detail: "try again",
548 });
549 }
550 if (input.cursor === "next")
551 return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
552 return {
553 items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
554 nextCursor: "next",
555 };
556 }),
557 }),
558 ],
559 });
560 const result = yield* service.list({ state: "open" });
561 expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
562 expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
563 ["web", "2"],
564 ["docs", "3"],
565 ["web", "1"],
566 ]);
567 expect(
568 result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
569 ).toEqual(["Acme/Web", "Acme/Web"]);
570 expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
571 expect(result.errors).toEqual([
572 { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
573 ]);
574 expect(result.viewers).toEqual({});
575 expect(result.trackers).toEqual([
576 expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
577 expect.objectContaining({
578 host: "gitlab.com",
579 tracker: "gitlab",
580 projectCount: 1,
581 configured: false,
582 capabilities: null,
583 }),
584 ]);
585
586 // Narrowing to one host still names every tracker, so the client can switch between them.
587 // Narrowing by involvement reads the account it compares against.
588 const narrowed = yield* service.list({
589 state: "open",
590 host: "github.com",
591 involvement: "assigned",
592 });
593 expect(narrowed.viewers).toEqual({ "github.com": "julius" });
594 expect(narrowed.entries.every((entry) => entry.host === "github.com")).toBe(true);
595 expect(narrowed.trackers.map((tracker) => tracker.host)).toEqual([
596 "github.com",
597 "gitlab.com",
598 ]);
599
600 // A continuation only reads the scopes it names.
601 listed.length = 0;
602 const failed = yield* service.list({
603 state: "open",
604 cursors: result.nextCursors,
605 });
606 expect(listed).toEqual(["Acme/Web"]);
607 expect(failed.nextCursors).toEqual(result.nextCursors);
608 expect(failed.errors).toEqual([
609 { projectId: "web", projectTitle: "web", message: "try again" },
610 ]);
611 const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
612 expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
613 expect(next.nextCursors).toEqual({});
614 expect(next.errors).toEqual([]);
615
616 // The cursor belongs to the scope, not to the project whose spelling first read it.
617 listed.length = 0;
618 const through = yield* service.list({
619 state: "open",
620 projectId: "web-worktree" as ProjectId,
621 cursors: result.nextCursors,
622 });
623 expect(listed).toEqual(["acme/web"]);
624 expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
625 }),
626 );
627});
628
629describe("IssueService with a standalone tracker", () => {
630 it.effect("reads bindings once per listing and sees changes on the next listing", () =>
631 Effect.gen(function* () {
632 const web = project({ id: "web", repository: "acme/web" });
633 const docs = project({ id: "docs", repository: "acme/docs" });
634 let reads = 0;
635 let scope = "ENG";
636 const service = yield* makeService({
637 projects: [web, docs],
638 trackers: [fakeTracker(), fakeStandaloneTracker()],
639 readBindings: Effect.sync(() => {
640 reads += 1;
641 return new Map([[web.id, { tracker: LINEAR, scope }]]);
642 }),
643 });
644
645 const first = yield* service.list({ state: "open" });
646 expect(first.scopes?.map((entry) => entry.scope)).toEqual(["ENG", "acme/web", "acme/docs"]);
647 expect(reads).toBe(1);
648
649 scope = "OPS";
650 const next = yield* service.list({ state: "open", refresh: true });
651 expect(next.scopes?.map((entry) => entry.scope)).toEqual(["OPS", "acme/web", "acme/docs"]);
652 expect(reads).toBe(2);
653
654 const missing = yield* service.list({ state: "open", projectId: "missing" as ProjectId });
655 expect(missing.scopes).toEqual([]);
656 expect(reads).toBe(2);
657 }),
658 );
659
660 it.effect("reads each project's team as the account it is bound with", () =>
661 Effect.gen(function* () {
662 const asWhom = Effect.map(IssueTrackerAccount, (account) => account ?? "first");
663 const fail = (reason: IssueTrackerError["reason"], retryAt?: number) =>
664 new IssueTrackerError({
665 tracker: LINEAR,
666 operation: "read",
667 reason,
668 detail: reason,
669 ...(retryAt === undefined ? {} : { retryAt }),
670 });
671 const twoAccounts = (overrides: Partial<IssueTrackerApi>) =>
672 makeService({
673 projects: [project({ id: "work" }), project({ id: "home" })],
674 trackers: [fakeStandaloneTracker(overrides)],
675 bindings: {
676 work: { tracker: LINEAR, scope: "ENG" },
677 home: {
678 tracker: LINEAR,
679 accountId: IssueTrackerAccountId.make("second"),
680 scope: "ENG",
681 },
682 },
683 });
684 const calls: string[] = [];
685 const service = yield* twoAccounts({
686 getViewer: () => Effect.map(asWhom, (account) => `viewer-${account}`),
687 listIssues: (input) =>
688 Effect.map(asWhom, (account) => {
689 calls.push(`${account} ${input.cursor ?? ""}`);
690 return { items: [issue("ENG-1")], nextCursor: `${account}-next` };
691 }),
692 getIssue: (input) =>
693 Effect.map(asWhom, (account) => ({
694 ...issue(input.key),
695 title: account,
696 url: `https://linear.app/${account === "first" ? "acme" : "other-workspace"}/issue/${input.key}/canonical-title`,
697 })),
698 });
699
700 // The same team key on two accounts is two scopes, each with its own cursor and viewer.
701 const listed = yield* service.list({ state: "open", involvement: "assigned" });
702 expect(calls.sort()).toEqual(["first ", "second "]);
703 expect(listed).toMatchObject({
704 viewers: { "linear.app": "viewer-first", "linear.app second": "viewer-second" },
705 nextCursors: { "linear.app eng": "first-next", "linear.app second/eng": "second-next" },
706 });
707 calls.length = 0;
708 yield* service.list({ state: "open", cursors: { "linear.app second/eng": "second-next" } });
709 expect(calls).toEqual(["second second-next"]);
710 const ref = { tracker: LINEAR, scope: "ENG", key: "ENG-1", projectId: "home" as ProjectId };
711 expect(yield* service.detail(ref)).toMatchObject({ title: "second" });
712
713 // A link resolves through the account whose workspace it names, whichever is preferred.
714 expect(
715 yield* service.resolveUrl(
716 "https://linear.app/other-workspace/issue/ENG-1/old-title",
717 "work" as ProjectId,
718 ),
719 ).toMatchObject({ projectId: "home", issue: { title: "second" } });
720
721 // One refused key leaves the group usable, even on a continuation that skips the other.
722 const refusing = (refused: ReadonlyArray<string>) =>
723 twoAccounts({
724 listIssues: () =>
725 Effect.flatMap(asWhom, (account) =>
726 refused.includes(account)
727 ? Effect.fail(fail("unauthenticated"))
728 : Effect.succeed({ items: [], nextCursor: null }),
729 ),
730 });
731 const partly = yield* (yield* refusing(["second"])).list({ state: "open" });
732 expect(partly).toMatchObject({
733 trackers: [{ configured: true }],
734 errors: [{ projectId: "home" }],
735 });
736 const continued = yield* (yield* refusing(["second"])).list({
737 state: "open",
738 cursors: { "linear.app second/eng": "second-next" },
739 });
740 expect(continued.trackers).toMatchObject([{ configured: true }]);
741 const none = yield* (yield* refusing(["first", "second"])).list({ state: "open" });
742 expect(none.trackers).toMatchObject([{ configured: false }]);
743
744 // The preferred account missing the key does not hide why the link's own account failed.
745 const limited = yield* twoAccounts({
746 getIssue: () =>
747 Effect.flatMap(asWhom, (account) =>
748 Effect.fail(account === "first" ? fail("not-found") : fail("rate-limited", 60)),
749 ),
750 });
751 expect(
752 yield* Effect.flip(
753 limited.resolveUrl(
754 "https://linear.app/other-workspace/issue/ENG-1/old-title",
755 "work" as ProjectId,
756 ),
757 ),
758 ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
759
760 // Two users of one workspace: the account bound to the link's exact team serves it.
761 const sameWorkspace = yield* makeService({
762 projects: [project({ id: "ops" }), project({ id: "eng" })],
763 trackers: [fakeStandaloneTracker()],
764 bindings: {
765 ops: { tracker: LINEAR, scope: "OPS" },
766 eng: { tracker: LINEAR, accountId: IssueTrackerAccountId.make("second"), scope: "ENG" },
767 },
768 });
769 expect(
770 yield* sameWorkspace.resolveUrl(
771 "https://linear.app/acme/issue/ENG-1/old-title",
772 "ops" as ProjectId,
773 ),
774 ).toMatchObject({ projectId: "eng", writable: true });
775 }),
776 );
777
778 it.effect("rejects a URL from another workspace with the same team and issue key", () =>
779 Effect.gen(function* () {
780 const service = yield* makeService({
781 projects: [project({ id: "web" })],
782 trackers: [fakeStandaloneTracker()],
783 bindings: { web: { tracker: LINEAR, scope: "ENG" } },
784 });
785 expect(
786 yield* service.resolveUrl("https://linear.app/acme/issue/ENG-1/old-title"),
787 ).toMatchObject({ key: "ENG-1", writable: true });
788 const refused = yield* service
789 .resolveUrl("https://linear.app/other-workspace/issue/ENG-1/old-title")
790 .pipe(Effect.result);
791 expect(refused).toMatchObject({
792 _tag: "Failure",
793 failure: {
794 _tag: "IssueOperationError",
795 operation: "resolveUrl",
796 reason: "not-found",
797 detail: "This issue URL does not belong to the connected workspace.",
798 },
799 });
800 }),
801 );
802
803 it.effect("lists a bound project's standalone scopes beside its git host and serves them", () =>
804 Effect.gen(function* () {
805 const listed: string[] = [];
806 const record = (tracker: IssueTrackerKind): Partial<IssueTrackerApi> => ({
807 listIssues: (input) =>
808 Effect.sync(() => {
809 listed.push(`${tracker} ${input.host} ${input.scope}`);
810 return {
811 items: [issue(tracker === LINEAR ? `${input.scope}-1` : "1")],
812 nextCursor: null,
813 };
814 }),
815 });
816 const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
817 const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
818 const bound = yield* makeService({
819 projects: [...projects, project({ id: "api", repository: "acme/api" })],
820 trackers,
821 bindings: {
822 ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG", additionalScopes: ["OPS"] },
823 },
824 });
825
826 const result = yield* bound.list({ state: "open" });
827 expect(listed.sort()).toEqual([
828 "github github.com acme/api",
829 "github github.com acme/web",
830 "linear linear.app ENG",
831 "linear linear.app OPS",
832 ]);
833 expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
834 [
835 ["github", "acme/api", "1"],
836 ["github", "acme/web", "1"],
837 ["linear", "ENG", "ENG-1"],
838 ["linear", "OPS", "OPS-1"],
839 ],
840 );
841 expect(
842 result.trackers
843 .map((tracker) => [tracker.tracker, tracker.host, tracker.projectCount])
844 .sort(),
845 ).toEqual([
846 ["github", "github.com", 2],
847 ["linear", "linear.app", 1],
848 ]);
849 expect(result.scopes).toContainEqual({
850 projectId: "web",
851 tracker: "linear",
852 host: "linear.app",
853 scope: "ENG",
854 });
855 // Narrowed to one project, both of its trackers are still read.
856 listed.length = 0;
857 const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId });
858 expect(listed.sort()).toEqual([
859 "github github.com acme/web",
860 "linear linear.app ENG",
861 "linear linear.app OPS",
862 ]);
863 expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([
864 ["web", "ENG"],
865 ["web", "OPS"],
866 ["web", "acme/web"],
867 ]);
868 listed.length = 0;
869 yield* bound.list({ state: "open", excludeProjectIds: ["web" as ProjectId] });
870 expect(listed).toEqual(["github github.com acme/api"]);
871 // A reference picks the project's tracker by kind; both are the project's own, so writable.
872 const linearRef = {
873 projectId: "web" as ProjectId,
874 tracker: LINEAR,
875 scope: "ENG",
876 key: "ENG-1",
877 };
878 expect(yield* bound.detail(linearRef)).toMatchObject({ host: "linear.app", writable: true });
879 expect(yield* bound.detail({ ...linearRef, scope: "OPS", key: "OPS-1" })).toMatchObject({
880 writable: true,
881 });
882 expect(yield* bound.detail({ ...linearRef, scope: "QA", key: "QA-1" })).toMatchObject({
883 writable: false,
884 });
885 expect((yield* bound.projectScope("web" as ProjectId)).scope).toBe("ENG");
886 expect((yield* bound.projectScope("web" as ProjectId, { key: "ops-12" })).scope).toBe("OPS");
887 expect(yield* bound.projectScope("web" as ProjectId, { scope: "ACME/Web" })).toMatchObject({
888 tracker: GITHUB,
889 host: "github.com",
890 scope: "acme/web",
891 });
892 expect(
893 yield* bound.detail({
894 projectId: "web" as ProjectId,
895 tracker: GITHUB,
896 scope: "acme/web",
897 key: "1",
898 }),
899 ).toMatchObject({ host: "github.com", writable: true });
900
901 const resolved = yield* bound
902 .resolveUrl("https://linear.app/acme/issue/ENG-1/issue-title", "web" as ProjectId)
903 .pipe(Effect.result);
904 expect(resolved).toMatchObject({
905 _tag: "Success",
906 success: {
907 projectId: "web",
908 tracker: LINEAR,
909 host: "linear.app",
910 scope: "ENG",
911 key: "ENG-1",
912 writable: true,
913 },
914 });
915
916 // Unbound, the standalone scope is gone and its references are unsupported.
917 listed.length = 0;
918 const unbound = yield* makeService({ projects, trackers });
919 const after = yield* unbound.list({ state: "open" });
920 expect(listed).toEqual(["github github.com acme/web"]);
921 expect(after.trackers.map((tracker) => tracker.tracker)).toEqual(["github"]);
922 const refused = yield* Effect.flip(unbound.detail(linearRef));
923 expect(refused).toMatchObject({
924 _tag: "IssueUnavailableError",
925 reason: "tracker-unsupported",
926 });
927
928 // A project with no remote at all can still be bound, and then has only the standalone one.
929 const standaloneOnly = yield* makeService({
930 projects,
931 trackers,
932 bindings: { ["notes" as ProjectId]: { tracker: LINEAR, scope: "OPS" } },
933 });
934 const notes = yield* standaloneOnly.list({ state: "open", projectId: "notes" as ProjectId });
935 expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
936 ["notes", "OPS"],
937 ]);
938
939 // Bindings that cannot be read fail the listing; they are not taken for "none bound".
940 const unreadable = yield* makeService({
941 projects,
942 trackers,
943 readBindings: Effect.fail(
944 new PersistenceSqlError({
945 operation: "IssueTrackerBindingsRepository.list",
946 detail: "disk I/O error",
947 }),
948 ),
949 });
950 expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
951 _tag: "IssueOperationError",
952 operation: "listProjects",
953 });
954 }),
955 );
956
957 it.effect("orders merged entries by createdAt when sort is created and updatedAt otherwise", () =>
958 Effect.gen(function* () {
959 const seenSorts: string[] = [];
960 const service = yield* makeService({
961 projects: [
962 project({ id: "web", repository: "acme/web" }),
963 project({ id: "api", repository: "acme/api" }),
964 ],
965 trackers: [
966 fakeTracker({
967 listIssues: (input) => {
968 seenSorts.push(input.sort);
969 if (input.scope === "acme/web") {
970 return Effect.succeed({
971 items: [
972 {
973 ...issue("old-created-recent-update"),
974 createdAt: "2026-07-06T01:00:00+02:00",
975 updatedAt: "2026-07-10T00:00:00Z",
976 },
977 ],
978 nextCursor: null,
979 });
980 }
981 return Effect.succeed({
982 items: [
983 {
984 ...issue("new-created-older-update"),
985 createdAt: "2026-07-05T23:30:00Z",
986 updatedAt: "2026-07-06T00:00:00Z",
987 },
988 ],
989 nextCursor: null,
990 });
991 },
992 }),
993 ],
994 });
995
996 const byCreated = yield* service.list({ state: "open", sort: "created" });
997 expect(seenSorts).toEqual(["created", "created"]);
998 expect(byCreated.entries.map((entry) => entry.key)).toEqual([
999 "new-created-older-update",
1000 "old-created-recent-update",
1001 ]);
1002
1003 seenSorts.length = 0;
1004 const byUpdated = yield* service.list({ state: "open" });
1005 expect(seenSorts).toEqual(["updated", "updated"]);
1006 expect(byUpdated.entries.map((entry) => entry.key)).toEqual([
1007 "old-created-recent-update",
1008 "new-created-older-update",
1009 ]);
1010 }),
1011 );
1012});