@app-vitals/agent-admin 1.110.0 → 1.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -0
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
  7. package/prisma/client/models/UserNotificationPrefs.ts +29 -1
  8. package/prisma/migrations/20261201000000_rename_user_notification_prefs_to_user_prefs/migration.sql +4 -0
  9. package/prisma/schema/schema.prisma +3 -0
  10. package/src/admin-boot.ts +6 -5
  11. package/src/admin-ui-github-identity-pages.ts +35 -139
  12. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  13. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  14. package/src/admin-ui-installation-repos-pages.ts +2 -23
  15. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  16. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  17. package/src/admin-ui-pages.ts +4 -5
  18. package/src/admin-ui.ts +51 -36
  19. package/src/agents-api.smoke.test.ts +26 -315
  20. package/src/agents-api.ts +1 -107
  21. package/src/drop-email-key-columns-migration.integration.test.ts +0 -4
  22. package/src/github-access-preview.ts +2 -2
  23. package/src/github-enterprise-api.smoke.test.ts +26 -0
  24. package/src/github-enterprise-api.ts +18 -2
  25. package/src/github-enterprise-client.integration.test.ts +0 -41
  26. package/src/github-enterprise-client.ts +0 -25
  27. package/src/github-enterprise-client.unit.test.ts +0 -18
  28. package/src/github-installation-wiring.ts +18 -12
  29. package/src/github-sync-all-repos.unit.test.ts +116 -0
  30. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  31. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  32. package/src/github-sync.ts +103 -137
  33. package/src/github-sync.unit.test.ts +82 -1
  34. package/src/installation-ports.ts +1 -40
  35. package/src/principals-api.integration.test.ts +3 -3
  36. package/src/reconcile-open-work.integration.test.ts +0 -1
  37. package/src/user-notification-prefs.ts +10 -65
  38. package/src/user-notification-prefs.unit.test.ts +9 -0
  39. package/src/user-prefs-rename-migration.integration.test.ts +71 -0
  40. package/src/{user-notification-prefs.integration.test.ts → user-prefs.integration.test.ts} +22 -5
  41. package/src/user-prefs.ts +98 -0
  42. package/src/github-access-preview.integration.test.ts +0 -399
  43. package/src/github-sync-switch.integration.test.ts +0 -297
  44. package/src/github-sync-switch.unit.test.ts +0 -467
package/src/agents-api.ts CHANGED
@@ -111,7 +111,6 @@ import {
111
111
  NotFoundError,
112
112
  UnprocessableEntityError,
113
113
  } from "./errors.ts";
114
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
115
114
  import type { GithubSyncService } from "./github-sync.ts";
116
115
  import { normalizeGithubUsername } from "./github-username.ts";
117
116
  import type { InstallationReposService } from "./installation-repos-service.ts";
@@ -276,11 +275,6 @@ export interface AdminDeps {
276
275
  AgentGitHubInstallationsService,
277
276
  "push" | "get"
278
277
  >;
279
- /**
280
- * GHE-2.4: backs GET /agents/:id/github-access. Optional (additive); absent
281
- * means the enterprise Apps are not wired, reported as `unconfigured`.
282
- */
283
- githubAccessPreview?: GithubAccessPreviewFn;
284
278
  /**
285
279
  * IRM-1.7: optional host-supplied open-work port. When an agent's own repos
286
280
  * lose a repo (DELETE /agents/{id}/repos/{owner}/{name} or a PATCH that
@@ -591,46 +585,6 @@ const GitHubInstallationsSnapshotWrapperSchema = z
591
585
  .object({ snapshot: AgentGitHubInstallationsSnapshotSchema })
592
586
  .openapi("GitHubInstallationsSnapshotWrapper");
593
587
 
594
- const GithubAccessOrgSchema = z.object({
595
- org: z.string(),
596
- status: z.enum([
597
- "ok",
598
- "lookup_app_not_installed",
599
- "rate_limited",
600
- "partial",
601
- "error",
602
- ]),
603
- repos: z.array(
604
- z.object({
605
- fullName: z.string(),
606
- level: z.enum(["admin", "maintain", "write", "triage", "read", "none"]),
607
- canPush: z.boolean(),
608
- }),
609
- ),
610
- unresolved: z.number().int(),
611
- });
612
-
613
- const GithubAccessPreviewSchema = z
614
- .object({
615
- status: z.enum(["ok", "user_not_found", "unconfigured"]).openapi({
616
- description:
617
- "`unconfigured` when the lookup App or its key is not set (no GitHub call was made). The installer App is optional.",
618
- }),
619
- access: z
620
- .object({
621
- username: z.string(),
622
- outcome: z.enum(["ok", "user_not_found"]),
623
- userVerified: z.boolean(),
624
- orgs: z.array(GithubAccessOrgSchema),
625
- unresolved: z.number().int(),
626
- complete: z.boolean(),
627
- checkedAt: z.string(),
628
- })
629
- .optional()
630
- .openapi({ description: "Resolver output; absent when unconfigured." }),
631
- })
632
- .openapi("GithubAccessPreview");
633
-
634
588
  const GITHUB_APPS_UNCONFIGURED = "GitHub Apps are not configured";
635
589
 
636
590
  const RepoFullNameSchema = z
@@ -762,13 +716,6 @@ const SkippedOrgsSchema = z.array(
762
716
  }),
763
717
  );
764
718
 
765
- const SelectionSwitchesSchema = z
766
- .array(z.object({ org: z.string(), repos: z.array(z.string()) }))
767
- .openapi({
768
- description:
769
- "Orgs whose agent App installation is on All repositories. Sync switches each to Selected repositories (first 50 repos in the switch, the rest added in batches) before any add or remove; `repos` is the resulting list: the installed repos minus the org's confirmed removals. An org the bound user can push to nothing in is skipped (see `skippedOrgs`) and stays on All repositories.",
770
- });
771
-
772
719
  const GithubSyncPreviewSchema = z
773
720
  .object({
774
721
  status: z.enum(["previewed", "skipped"]).openapi({
@@ -788,10 +735,9 @@ const GithubSyncPreviewSchema = z
788
735
  description:
789
736
  "Configured agent repos the bound user can no longer push to. The agent's repos are never added to.",
790
737
  }),
791
- selectionSwitches: SelectionSwitchesSchema.optional(),
792
738
  skippedOrgs: SkippedOrgsSchema.optional().openapi({
793
739
  description:
794
- "Orgs whose access listing is missing, partial or failed, whose cached access data is incomplete or stale, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed. `reason` says why (for stale data, when it was checked).",
740
+ "Orgs whose access listing is missing, partial or failed, whose cached access data is incomplete or stale, or whose lookup App is not installed or installed on selected repositories only, or whose agent App installation is on All repositories (uninstall and reinstall with selected repositories); nothing there is added or removed. `reason` says why (for stale data, when it was checked).",
795
741
  }),
796
742
  openWork: z.array(OpenWorkItemSchema).optional().openapi({
797
743
  description:
@@ -831,7 +777,6 @@ const GithubSyncApplyResultSchema = z
831
777
  appAdds: z.array(z.string()).optional(),
832
778
  appRemoves: z.array(z.string()).optional(),
833
779
  agentRemoves: z.array(z.string()).optional(),
834
- selectionSwitches: SelectionSwitchesSchema.optional(),
835
780
  notApplied: z
836
781
  .array(z.object({ repo: z.string(), reason: z.string() }))
837
782
  .optional()
@@ -1859,26 +1804,6 @@ const getGitHubInstallationsRoute = createRoute({
1859
1804
  },
1860
1805
  });
1861
1806
 
1862
- const getGithubAccessRoute = createRoute({
1863
- method: "get",
1864
- path: "/agents/{id}/github-access",
1865
- summary: "Preview the repos the agent's bound GitHub user can reach",
1866
- description:
1867
- "Platform-admin only (session members, ops keys and agent keys get 403): the response lists repo names the bound user can reach. Read-only; nothing is stored. 404 for an unknown agent; 422 when no githubUsername is bound. Returns `status: unconfigured` (not an error, no GitHub call) when the lookup App is not configured (the installer App is optional), and `status: user_not_found` when the user does not exist on GitHub; otherwise `access` is the resolver output (per-org status, repos with level and canPush, unresolved count, complete flag).",
1868
- request: { params: AgentIdParamSchema },
1869
- responses: {
1870
- 200: {
1871
- description: "Access preview",
1872
- content: { "application/json": { schema: GithubAccessPreviewSchema } },
1873
- },
1874
- 401: { description: "Unauthorized", ...jsonError },
1875
- 403: { description: "Platform admin required", ...jsonError },
1876
- 404: { description: "Agent not found", ...jsonError },
1877
- 422: { description: "Agent has no githubUsername", ...jsonError },
1878
- 502: { description: "GitHub unavailable or refused", ...jsonError },
1879
- },
1880
- });
1881
-
1882
1807
  const installationReposErrors = {
1883
1808
  401: { description: "Unauthorized", ...jsonError },
1884
1809
  403: { description: "Platform admin required", ...jsonError },
@@ -3512,31 +3437,6 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3512
3437
  return c.json({ bakedMarketplaces: stored }, 200);
3513
3438
  });
3514
3439
 
3515
- // GET /agents/:id/github-access — GHE-2.4 read-only preview. Platform admin
3516
- // only: never session members, ops/read keys or agent keys.
3517
- app.openapi(getGithubAccessRoute, async (c) => {
3518
- if (c.get("isAdmin") !== true) {
3519
- throw new ForbiddenError(
3520
- "Admin access required to preview GitHub access",
3521
- );
3522
- }
3523
- const { id: agentId } = c.req.valid("param");
3524
- const agent = await agentService.getDetail(agentId);
3525
- if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
3526
- if (!agent.githubUsername) {
3527
- throw new UnprocessableEntityError(
3528
- "agent has no githubUsername bound; set one with PATCH /agents/{id}",
3529
- );
3530
- }
3531
- if (!deps.githubAccessPreview)
3532
- return c.json({ status: "unconfigured" as const }, 200);
3533
- const preview = await deps.githubAccessPreview(
3534
- agent.githubUsername,
3535
- agent.accountId,
3536
- );
3537
- return c.json(preview, 200);
3538
- });
3539
-
3540
3440
  // /agents/:id/github-installation/repos — IRM-1.2. Platform admin only;
3541
3441
  // responses carry repo names and ids, never tokens.
3542
3442
  const installationReposService = (c: {
@@ -3611,9 +3511,6 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3611
3511
  appAdds: plan.appAdds,
3612
3512
  appRemoves: plan.appRemoves,
3613
3513
  agentRemoves: plan.agentRemoves,
3614
- ...(plan.selectionSwitches?.length
3615
- ? { selectionSwitches: plan.selectionSwitches }
3616
- : {}),
3617
3514
  skippedOrgs: plan.skippedOrgs,
3618
3515
  openWork: result.openWork,
3619
3516
  warnings: result.warnings,
@@ -3673,9 +3570,6 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3673
3570
  appAdds: plan.appAdds,
3674
3571
  appRemoves: plan.appRemoves,
3675
3572
  agentRemoves: plan.agentRemoves,
3676
- ...(plan.selectionSwitches?.length
3677
- ? { selectionSwitches: plan.selectionSwitches }
3678
- : {}),
3679
3573
  notApplied: plan.notApplied,
3680
3574
  skippedOrgs: plan.skippedOrgs,
3681
3575
  warnings:
@@ -85,10 +85,6 @@ describeOrSkip("drop_email_key_columns migration (ACM-5.1)", () => {
85
85
  await client.end();
86
86
  });
87
87
 
88
- it("is the last migration in apply order", () => {
89
- expect(ALL_MIGRATIONS.at(-1)).toBe(DROP);
90
- });
91
-
92
88
  it("aborts, changing nothing, while any row has a NULL memberId", async () => {
93
89
  await seed(null);
94
90
  await expect(client.query(migrationSql(DROP))).rejects.toThrow(
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * admin/src/github-access-preview.ts
3
- * Result type and port for GET /agents/:id/github-access (GHE-2.4): a
4
- * read-only preview of the repos an agent's bound GitHub user can reach.
3
+ * Result type and port (GHE-2.4) for the live resolver of the repos an agent's
4
+ * bound GitHub user can reach, consumed by the installation-repos service and Sync.
5
5
  * The implementation lives in github-enterprise-api.ts (the only module that
6
6
  * may read the App keys); agents-api.ts only sees this port.
7
7
  */
@@ -722,6 +722,32 @@ describe("POST install", () => {
722
722
  expect(h.calls).toContain(INSTALL);
723
723
  });
724
724
 
725
+ it("rejects selected with no repositories and over 50 with a clear 400", async () => {
726
+ const h = build({
727
+ routes: { "GET /apps/example-agent-app": "public_app_success" },
728
+ });
729
+ await seed(h);
730
+ const empty = await post(h, {
731
+ agentId: "agent-1",
732
+ repositorySelection: "selected",
733
+ repositories: [],
734
+ });
735
+ expect(empty.status).toBe(400);
736
+ expect(((await empty.json()) as { error: string }).error).toMatch(
737
+ /at least one repository/,
738
+ );
739
+ const many = await post(h, {
740
+ agentId: "agent-1",
741
+ repositorySelection: "selected",
742
+ repositories: Array.from({ length: 51 }, (_, i) => `r${i}`),
743
+ });
744
+ expect(many.status).toBe(400);
745
+ expect(((await many.json()) as { error: string }).error).toMatch(
746
+ /at most 50/,
747
+ );
748
+ expect(h.calls).not.toContain(INSTALL);
749
+ });
750
+
725
751
  it("refuses a private App (public lookup 404) with a clear 422", async () => {
726
752
  const h = build({
727
753
  routes: { "GET /apps/example-agent-app": "public_app_private_404" },
@@ -251,7 +251,10 @@ const InstallBodySchema = z
251
251
  .object({
252
252
  agentId: z.string().min(1).openapi({ example: "agent-id" }),
253
253
  repositorySelection: z.enum(["all", "selected", "none"]).default("all"),
254
- repositories: z.array(z.string().min(1)).max(50).optional(),
254
+ repositories: z
255
+ .array(z.string().min(1))
256
+ .max(50, "at most 50 repositories can be selected")
257
+ .optional(),
255
258
  })
256
259
  .openapi("GithubEnterpriseInstallBody");
257
260
 
@@ -572,7 +575,7 @@ function serializeApp(m: GitHubEnterpriseAppMetadata) {
572
575
  // ─── Access preview (GHE-2.4) ─────────────────────────────────────────────────
573
576
 
574
577
  /**
575
- * Backs GET /agents/:id/github-access. Unconfigured (the lookup App, or its
578
+ * Live access resolver used by the installation-repos service and Sync. Unconfigured (the lookup App, or its
576
579
  * key, missing) returns before any GitHub
577
580
  * call. A GitHub failure while listing orgs is rethrown as a 502 carrying only
578
581
  * the mapped, non-leaky message.
@@ -1035,6 +1038,19 @@ export function createGithubEnterpriseApp(
1035
1038
  const body = c.req.valid("json");
1036
1039
  const { accountId } = c.req.valid("query");
1037
1040
 
1041
+ if (
1042
+ body.repositorySelection === "selected" &&
1043
+ (body.repositories ?? []).length === 0
1044
+ ) {
1045
+ return c.json(
1046
+ {
1047
+ error:
1048
+ "repositories: select at least one repository when repositorySelection is selected",
1049
+ },
1050
+ 400,
1051
+ );
1052
+ }
1053
+
1038
1054
  const installer = await appService.get("installer", accountId);
1039
1055
  if (!installer) {
1040
1056
  throw new ConflictError("the installer App is not configured");
@@ -461,44 +461,3 @@ describe("removeRepositories", () => {
461
461
  });
462
462
  }
463
463
  });
464
-
465
- describe("setRepositorySelection", () => {
466
- it("toggles to selected with repositories", async () => {
467
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_success" });
468
- const inst = await client.setRepositorySelection("acme-eng", 501, {
469
- repositorySelection: "selected",
470
- repositories: ["repo-1"],
471
- });
472
- expect(inst.repositorySelection).toBe("selected");
473
- const last = calls[calls.length - 1] as Recorded;
474
- expect(last.method).toBe("PATCH");
475
- expect(JSON.parse(last.body ?? "")).toEqual({
476
- repository_selection: "selected",
477
- repositories: ["repo-1"],
478
- });
479
- });
480
-
481
- it("toggles to all without sending repositories", async () => {
482
- const { client, calls } = makeClient({ [SELECTION]: "install_selection_all" });
483
- const inst = await client.setRepositorySelection("acme-eng", 501, {
484
- repositorySelection: "all",
485
- repositories: ["ignored"],
486
- });
487
- expect(inst.repositorySelection).toBe("all");
488
- expect(JSON.parse((calls[calls.length - 1] as Recorded).body ?? "")).toEqual({
489
- repository_selection: "all",
490
- });
491
- });
492
-
493
- for (const [suffix, kind, status] of ERRORS) {
494
- it(`${suffix} -> ${kind}`, async () => {
495
- const { client } = makeClient({ [SELECTION]: `install_selection_${suffix}` });
496
- const e = await errOf(
497
- client.setRepositorySelection("acme-eng", 501, { repositorySelection: "all" }),
498
- );
499
- expect(e.kind).toBe(kind);
500
- expect(e.status).toBe(status);
501
- expectNoSecrets(e);
502
- });
503
- }
504
- });
@@ -456,31 +456,6 @@ export class GithubEnterpriseClient {
456
456
  );
457
457
  }
458
458
 
459
- /** Toggle an installation between "all" and "selected" repositories. */
460
- async setRepositorySelection(
461
- org: string,
462
- installationId: number,
463
- input: SetRepositorySelectionInput,
464
- ): Promise<AppInstallation> {
465
- const context = "GitHub set installation repository selection";
466
- const path = this.repositoriesPath(org, installationId);
467
- const repos = input.repositories ?? [];
468
- if (input.repositorySelection === "selected" && (repos.length === 0 || repos.length > MAX_REPOSITORIES)) {
469
- throw new GithubEnterpriseError(
470
- "validation",
471
- `setRepositorySelection: repositories must list 1-${MAX_REPOSITORIES} names when repositorySelection is "selected"`,
472
- );
473
- }
474
- const body: Record<string, unknown> = { repository_selection: input.repositorySelection };
475
- if (input.repositorySelection === "selected") body.repositories = repos;
476
- const { token } = await this.getInstallationToken();
477
- const res = await this.request<RawInstallation>("PATCH", path, token, context, body);
478
- if (typeof res.data?.id !== "number") {
479
- throw new GithubEnterpriseError("unexpected", `${context}: response missing id`);
480
- }
481
- return toInstallation(res.data);
482
- }
483
-
484
459
  // ─── internals ──────────────────────────────────────────────────────────────
485
460
 
486
461
  private repositoriesPath(org: string, installationId: number): string {
@@ -136,24 +136,6 @@ describe("repository client validation", () => {
136
136
  .catch((e) => e);
137
137
  expect(err.kind).toBe("validation");
138
138
  });
139
-
140
- it("rejects selected without repositories before any network call", async () => {
141
- const err = await client
142
- .setRepositorySelection("o", 1, { repositorySelection: "selected" })
143
- .catch((e) => e);
144
- expect(err.kind).toBe("validation");
145
- });
146
-
147
- it("rejects selected with more than 50 repositories", async () => {
148
- const repositories = Array.from({ length: 51 }, (_, i) => `r${i}`);
149
- const err = await client
150
- .setRepositorySelection("o", 1, {
151
- repositorySelection: "selected",
152
- repositories,
153
- })
154
- .catch((e) => e);
155
- expect(err.kind).toBe("validation");
156
- });
157
139
  });
158
140
 
159
141
  describe("GithubEnterpriseClient.uninstallFromOrg", () => {
@@ -9,24 +9,24 @@
9
9
 
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import type { Clock } from "./clock.ts";
13
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
14
+ import {
15
+ crawlAgentInstallation,
16
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
17
+ lookupKeysForApp,
18
+ } from "./github-agent-installation-crawler.ts";
12
19
  import type {
13
20
  GithubAppsState,
14
21
  GithubAppsStateFn,
15
22
  } from "./github-apps-state.ts";
16
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
17
- import type { Clock } from "./clock.ts";
18
23
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
19
24
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
20
- import {
21
- DEPLOYMENT_WIDE_ACCOUNT_KEY,
22
- lookupKeysForApp,
23
- } from "./github-agent-installation-crawler.ts";
24
25
  import { GithubLookupClient } from "./github-lookup-client.ts";
25
26
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
26
27
  import type { CrawlStore } from "./github-repo-crawler.ts";
27
28
  import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
28
29
  import type { RefreshDiscovery } from "./github-repo-refresher.ts";
29
- import { canPushForRole } from "./user-repo-access-resolver.ts";
30
30
  import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
31
31
  import {
32
32
  createInstallationPort,
@@ -42,6 +42,7 @@ import {
42
42
  type InstalledOrgsClient,
43
43
  } from "./installation-repos-service.ts";
44
44
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
45
+ import { canPushForRole } from "./user-repo-access-resolver.ts";
45
46
 
46
47
  export interface GithubInstallationWiringDeps {
47
48
  prisma: PrismaClient;
@@ -97,11 +98,6 @@ export function lazyInstallerClient(
97
98
  (await client(accountId)).addRepositories(org, id, names),
98
99
  removeRepositories: async (org, id, names, accountId) =>
99
100
  (await client(accountId)).removeRepositories(org, id, names),
100
- setRepositorySelection: async (org, id, input, accountId) =>
101
- (await client(accountId)).setRepositorySelection(org, id, {
102
- repositorySelection: input.repositorySelection,
103
- repositories: [...input.repositories],
104
- }),
105
101
  };
106
102
  }
107
103
 
@@ -260,6 +256,16 @@ export function createGithubSync(
260
256
  return undefined;
261
257
  }
262
258
  },
259
+ // Re-crawl just the changed org so the UI list is current after apply.
260
+ refreshAgentSnapshot: async (agent, org) => {
261
+ await crawlAgentInstallation({
262
+ agent,
263
+ org,
264
+ client,
265
+ store: cache,
266
+ clock: { now: deps.now ?? (() => new Date()) },
267
+ });
268
+ },
263
269
  ...deps.syncOverrides,
264
270
  installation:
265
271
  deps.installationRepos ??
@@ -0,0 +1,116 @@
1
+ /**
2
+ * admin/src/github-sync-all-repos.unit.test.ts
3
+ * GIS-1.2: an org whose agent installation is on All repositories is skipped
4
+ * by Sync (never switched), with the uninstall-and-reinstall message.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import {
9
+ ALL_REPOS_INSTALLATION_REASON,
10
+ NOT_INSTALLED_ORG_REASON,
11
+ planGithubSync,
12
+ } from "./github-sync.ts";
13
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
14
+
15
+ type Sel = "all" | "selected" | null;
16
+
17
+ const access = (pushable: string[], all: string[]): UserRepoAccessResult => ({
18
+ username: "octo",
19
+ outcome: "ok",
20
+ userVerified: true,
21
+ orgs: [
22
+ {
23
+ org: "acme",
24
+ status: "ok",
25
+ unresolved: 0,
26
+ repos: all.map((fullName) => ({
27
+ fullName,
28
+ canPush: pushable.includes(fullName),
29
+ level: pushable.includes(fullName)
30
+ ? ("write" as const)
31
+ : ("read" as const),
32
+ })),
33
+ },
34
+ ],
35
+ unresolved: 0,
36
+ complete: true,
37
+ checkedAt: "2026-11-25T00:00:00.000Z",
38
+ });
39
+
40
+ const INSTALLED = ["acme/a", "acme/b"];
41
+ const plan = (
42
+ selection: Sel | undefined,
43
+ requested?: {
44
+ appAdds: string[];
45
+ appRemoves: string[];
46
+ agentRemoves: string[];
47
+ },
48
+ selectionKey = "acme",
49
+ ) =>
50
+ planGithubSync({
51
+ username: "octo",
52
+ access: access(["acme/a", "acme/new"], [...INSTALLED, "acme/new"]),
53
+ agentRepos: [],
54
+ installationRepos: { acme: INSTALLED },
55
+ ...(selection === undefined
56
+ ? {}
57
+ : { selections: { [selectionKey]: selection } }),
58
+ ...(requested ? { requested } : {}),
59
+ });
60
+
61
+ describe("planGithubSync on an All repositories installation", () => {
62
+ it("skips the org with the reinstall message and plans nothing for it", () => {
63
+ const p = plan("all");
64
+ expect(ALL_REPOS_INSTALLATION_REASON).toBe(
65
+ "Sync does not work when the app has access to all repositories; uninstall the app and install again with selected repositories.",
66
+ );
67
+ expect(p.skippedOrgs).toEqual([
68
+ { org: "acme", reason: ALL_REPOS_INSTALLATION_REASON },
69
+ ]);
70
+ expect(p.appAdds).toEqual([]);
71
+ expect(p.appRemoves).toEqual([]);
72
+ expect(p.removedRepos).toEqual([]);
73
+ expect(p.warnings[0]).toContain("uninstall the app and install again");
74
+ expect("selectionSwitches" in p).toBe(false);
75
+ });
76
+
77
+ it("reports confirmed lists for the org as not applied", () => {
78
+ const p = plan("all", {
79
+ appAdds: ["acme/new"],
80
+ appRemoves: ["acme/b"],
81
+ agentRemoves: [],
82
+ });
83
+ expect(p.appAdds).toEqual([]);
84
+ expect(p.appRemoves).toEqual([]);
85
+ expect(p.notApplied.map((n) => n.repo)).toEqual(["acme/b", "acme/new"]);
86
+ expect(p.skippedOrgs).toHaveLength(1);
87
+ });
88
+
89
+ it("matches the selection key case-insensitively", () => {
90
+ expect(plan("all", undefined, "ACME").skippedOrgs).toHaveLength(1);
91
+ });
92
+
93
+ it("never treats selected, null or a missing selection as all", () => {
94
+ for (const sel of ["selected", null, undefined] as const) {
95
+ const p = plan(sel);
96
+ expect(p.skippedOrgs).toEqual([]);
97
+ expect(p.appAdds).toEqual(["acme/new"]);
98
+ expect(p.appRemoves).toEqual(["acme/b"]);
99
+ }
100
+ });
101
+
102
+ it("still reports an add for an org with no installation as not applied", () => {
103
+ const p = planGithubSync({
104
+ username: "octo",
105
+ access: access(["acme/a", "acme/new"], [...INSTALLED, "acme/new"]),
106
+ agentRepos: [],
107
+ installationRepos: { other: ["other/x"] },
108
+ requested: { appAdds: ["acme/new"], appRemoves: [], agentRemoves: [] },
109
+ });
110
+ expect(p.appAdds).toEqual([]);
111
+ expect(p.notApplied).toContainEqual({
112
+ repo: "acme/new",
113
+ reason: NOT_INSTALLED_ORG_REASON,
114
+ });
115
+ });
116
+ });