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