@app-vitals/agent-admin 1.88.0 → 1.89.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.
@@ -50,6 +50,12 @@ import {
50
50
  GithubEnterpriseError,
51
51
  type GithubEnterpriseErrorKind,
52
52
  } from "./github-enterprise-client.ts";
53
+ import {
54
+ findAgentInstallation,
55
+ GITHUB_UNINSTALL_AUDIT_PLAN_HASH,
56
+ planOrgUninstall,
57
+ uninstallBlockReason,
58
+ } from "./github-uninstall.ts";
53
59
  import { resolveValidation } from "./github-enterprise-warnings.ts";
54
60
  import { GithubLookupClient } from "./github-lookup-client.ts";
55
61
  import {
@@ -58,8 +64,18 @@ import {
58
64
  } from "./github-lookup-repositories.ts";
59
65
  import type { GithubRefreshAction } from "./github-refresh-action.ts";
60
66
  import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
61
- import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
67
+ import {
68
+ CLIENT_ID_RE,
69
+ type InstallationAgentsPort,
70
+ type InstallationAuditPort,
71
+ SLUG_RE,
72
+ } from "./installation-ports.ts";
62
73
  import { ErrorSchema } from "./openapi-schemas.ts";
74
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
75
+ import {
76
+ blockRepoRemovalWork,
77
+ previewRepoRemovalWork,
78
+ } from "./repo-removal-open-work.ts";
63
79
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
64
80
 
65
81
  // ─── Deps ─────────────────────────────────────────────────────────────────────
@@ -79,6 +95,16 @@ export interface GithubEnterpriseApiDeps {
79
95
  * and runs (best effort) after an App is saved or an agent App is installed.
80
96
  */
81
97
  refreshAction?: GithubRefreshAction;
98
+ /**
99
+ * GIS-1.5: what DELETE /orgs/{org}/install cleans up after the App is
100
+ * uninstalled (the agent's repos, one audit row, open work). Without it the
101
+ * route answers 503 and never uninstalls.
102
+ */
103
+ uninstall?: {
104
+ agents: InstallationAgentsPort;
105
+ audit: InstallationAuditPort;
106
+ openWork?: OpenWorkPort;
107
+ };
82
108
  /** Test seams; default to the real GitHub API. */
83
109
  fetchFn?: typeof fetch;
84
110
  apiBase?: string;
@@ -244,6 +270,48 @@ const InstallResultSchema = z
244
270
  })
245
271
  .openapi("GithubEnterpriseInstallResult");
246
272
 
273
+ const UninstallQuerySchema = AccountQuerySchema.extend({
274
+ agentId: z
275
+ .string()
276
+ .min(1)
277
+ .openapi({ param: { name: "agentId", in: "query" }, example: "agent-id" }),
278
+ preview: z
279
+ .enum(["true", "false"])
280
+ .optional()
281
+ .openapi({
282
+ param: { name: "preview", in: "query" },
283
+ description:
284
+ "true: list the repos and open work an uninstall would affect and change nothing.",
285
+ }),
286
+ confirmRemovals: z
287
+ .enum(["true", "false"])
288
+ .optional()
289
+ .openapi({
290
+ param: { name: "confirmRemovals", in: "query" },
291
+ description: "Required when more than 10 agent repos would be removed.",
292
+ }),
293
+ });
294
+
295
+ const UninstallResultSchema = z
296
+ .object({
297
+ status: z.enum(["preview", "uninstalled"]),
298
+ org: z.string(),
299
+ installationId: z.number(),
300
+ repos: z.array(z.string()).openapi({
301
+ description: "The agent's repos in the org, removed from the agent.",
302
+ }),
303
+ openWork: z.array(
304
+ z.object({
305
+ id: z.string(),
306
+ repo: z.string(),
307
+ title: z.string().optional(),
308
+ }),
309
+ ),
310
+ warnings: z.array(z.string()),
311
+ auditId: z.string().optional(),
312
+ })
313
+ .openapi("GithubEnterpriseUninstallResult");
314
+
247
315
  // ─── Routes ───────────────────────────────────────────────────────────────────
248
316
 
249
317
  const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
@@ -408,6 +476,27 @@ const installRoute = createRoute({
408
476
  },
409
477
  });
410
478
 
479
+ const uninstallRoute = createRoute({
480
+ method: "delete",
481
+ path: "/github-enterprise/orgs/{org}/install",
482
+ tags,
483
+ summary: "Uninstall an agent's App from an organization",
484
+ description:
485
+ "Admin-only. Finds the agent App's installation on the org (client id, slug or app id) and deletes it with the installer App, removes that org's repos from the agent's repos, blocks the agent's open tasks and PRs on them through the open-work port (a port failure is a warning) and writes one audit row (uninstall:org). `preview=true` lists the repos and open work that would be affected and changes nothing. 404 when the App is not installed on the org; 422 when more than 10 repos would be removed without `confirmRemovals=true`; 502 (with a failed audit row) when GitHub refuses.",
486
+ request: { params: OrgParamSchema, query: UninstallQuerySchema },
487
+ responses: {
488
+ 200: {
489
+ description: "Uninstalled, or the preview",
490
+ content: { "application/json": { schema: UninstallResultSchema } },
491
+ },
492
+ 400: { description: "Bad request", ...jsonError },
493
+ 409: { description: "Installer App not configured", ...jsonError },
494
+ 503: { description: "Uninstall is not available", ...jsonError },
495
+ ...upstreamErrors,
496
+ ...errorResponses,
497
+ },
498
+ });
499
+
411
500
  // ─── Error mapping ────────────────────────────────────────────────────────────
412
501
 
413
502
  interface Mapped {
@@ -675,6 +764,7 @@ export function createGithubEnterpriseApp(
675
764
  slug: string | null;
676
765
  invalid: boolean;
677
766
  clientId: string | null;
767
+ appId: number | null;
678
768
  }> => {
679
769
  if (!(await deps.agentService.getSummary(agentId))) {
680
770
  throw new NotFoundError(`agent ${agentId} not found`);
@@ -685,11 +775,13 @@ export function createGithubEnterpriseApp(
685
775
  storedClientId && CLIENT_ID_RE.test(storedClientId)
686
776
  ? storedClientId
687
777
  : null;
778
+ const rawAppId = Number(env?.GH_APP_ID?.trim());
779
+ const appId = Number.isInteger(rawAppId) && rawAppId > 0 ? rawAppId : null;
688
780
  const slug = env?.GH_APP_SLUG;
689
- if (!slug) return { slug: null, invalid: false, clientId };
781
+ if (!slug) return { slug: null, invalid: false, clientId, appId };
690
782
  return SLUG_RE.test(slug)
691
- ? { slug, invalid: false, clientId }
692
- : { slug: null, invalid: true, clientId };
783
+ ? { slug, invalid: false, clientId, appId }
784
+ : { slug: null, invalid: true, clientId, appId };
693
785
  };
694
786
 
695
787
  /** Public-lookup client id; reason is set when the App is private (404). */
@@ -990,5 +1082,121 @@ export function createGithubEnterpriseApp(
990
1082
  );
991
1083
  });
992
1084
 
1085
+ app.openapi(uninstallRoute, async (c) => {
1086
+ requireAdmin(c);
1087
+ const { org } = c.req.valid("param");
1088
+ const query = c.req.valid("query");
1089
+ const { accountId, agentId } = query;
1090
+ const port = deps.uninstall;
1091
+ if (!port) {
1092
+ return c.json({ error: "App uninstall is not available" }, 503);
1093
+ }
1094
+
1095
+ const installer = await appService.get("installer", accountId);
1096
+ if (!installer) {
1097
+ throw new ConflictError("the installer App is not configured");
1098
+ }
1099
+ const agent = await agentApp(agentId);
1100
+ const record = await port.agents.get(agentId);
1101
+ if (!record) throw new NotFoundError(`agent ${agentId} not found`);
1102
+
1103
+ const client = await clientFor(installer, accountId);
1104
+ const installation = findAgentInstallation(
1105
+ await client.listOrgInstallations(org),
1106
+ { clientId: agent.clientId, slug: agent.slug, appId: agent.appId },
1107
+ );
1108
+ if (!installation) {
1109
+ throw new NotFoundError(`the agent's App is not installed on org ${org}`);
1110
+ }
1111
+
1112
+ const plan = planOrgUninstall({ org, agentRepos: record.repos });
1113
+ const work = await previewRepoRemovalWork(
1114
+ port.openWork,
1115
+ agentId,
1116
+ plan.repos,
1117
+ );
1118
+ const base = {
1119
+ org,
1120
+ installationId: installation.id,
1121
+ repos: plan.repos,
1122
+ openWork: work.openWork,
1123
+ };
1124
+ if (query.preview === "true") {
1125
+ return c.json(
1126
+ { status: "preview" as const, ...base, warnings: work.warnings },
1127
+ 200,
1128
+ );
1129
+ }
1130
+ if (plan.needsConfirm && query.confirmRemovals !== "true") {
1131
+ throw new UnprocessableEntityError(
1132
+ `${plan.repos.length} repos would be removed; resend with confirmRemovals=true to apply`,
1133
+ );
1134
+ }
1135
+
1136
+ const writeAudit = (error?: string) =>
1137
+ port.audit.write({
1138
+ agentId,
1139
+ caller: "admin",
1140
+ planHash: GITHUB_UNINSTALL_AUDIT_PLAN_HASH,
1141
+ diff: {
1142
+ installationAdds: [],
1143
+ installationRemoves: error === undefined ? plan.repos : [],
1144
+ configAdds: [],
1145
+ configRemoves: [],
1146
+ },
1147
+ result:
1148
+ error === undefined
1149
+ ? { status: "applied" }
1150
+ : { status: "failed", error },
1151
+ });
1152
+
1153
+ try {
1154
+ await client.uninstallFromOrg(org, installation.id);
1155
+ } catch (err) {
1156
+ const reason =
1157
+ err instanceof GithubEnterpriseError
1158
+ ? mapEnterpriseFailure(err.kind).message
1159
+ : "GitHub uninstall failed";
1160
+ const auditId = await writeAudit(reason);
1161
+ throw new BadGatewayError(
1162
+ `GitHub refused the uninstall: ${reason} Audit ${auditId} records the failure.`,
1163
+ );
1164
+ }
1165
+
1166
+ // GitHub has uninstalled; a cleanup failure is audited and reported, never hidden.
1167
+ let cleanupError: string | undefined;
1168
+ try {
1169
+ if (plan.repos.length > 0) {
1170
+ const drop = new Set(plan.repos);
1171
+ await port.agents.setRepos(
1172
+ agentId,
1173
+ record.repos.filter((r) => !drop.has(r)),
1174
+ );
1175
+ }
1176
+ } catch (err) {
1177
+ cleanupError = err instanceof Error ? err.message : String(err);
1178
+ }
1179
+ const auditId = await writeAudit(cleanupError);
1180
+ if (cleanupError !== undefined) {
1181
+ throw new BadGatewayError(
1182
+ `the App was uninstalled but the agent's repos could not be updated; audit ${auditId} records the failure`,
1183
+ );
1184
+ }
1185
+ const warnings = [
1186
+ ...work.warnings,
1187
+ ...(await blockRepoRemovalWork(
1188
+ port.openWork,
1189
+ agentId,
1190
+ plan.repos,
1191
+ uninstallBlockReason,
1192
+ )),
1193
+ ];
1194
+ await markStaleQuietly();
1195
+ return c.json(
1196
+ { status: "uninstalled" as const, ...base, warnings, auditId },
1197
+ 200,
1198
+ );
1199
+ });
1200
+
993
1201
  return app;
994
1202
  }
@@ -361,6 +361,28 @@ export class GithubEnterpriseClient {
361
361
  return { installation: toInstallation(res.data), created: res.status === 201 };
362
362
  }
363
363
 
364
+ /**
365
+ * Uninstall an App from an enterprise-owned org (DELETE the org
366
+ * installation). Same `enterprise_organization_installations` write
367
+ * permission as install; GitHub answers 204.
368
+ */
369
+ async uninstallFromOrg(org: string, installationId: number): Promise<void> {
370
+ if (!Number.isInteger(installationId) || installationId <= 0) {
371
+ throw new GithubEnterpriseError(
372
+ "validation",
373
+ "installationId must be a positive integer",
374
+ );
375
+ }
376
+ const { token } = await this.getInstallationToken();
377
+ const ent = encodeURIComponent(this.enterprise);
378
+ await this.request<unknown>(
379
+ "DELETE",
380
+ `/enterprises/${ent}/apps/organizations/${encodeURIComponent(org)}/installations/${installationId}`,
381
+ token,
382
+ "GitHub uninstall App from org",
383
+ );
384
+ }
385
+
364
386
  /** List all repositories an installation can access (paginated). */
365
387
  async listInstallationRepositories(
366
388
  org: string,
@@ -514,7 +536,7 @@ export class GithubEnterpriseClient {
514
536
  }
515
537
 
516
538
  private async request<T>(
517
- method: "GET" | "POST" | "PATCH",
539
+ method: "GET" | "POST" | "PATCH" | "DELETE",
518
540
  path: string,
519
541
  bearer: string,
520
542
  context: string,
@@ -150,3 +150,68 @@ describe("repository client validation", () => {
150
150
  expect(err.kind).toBe("validation");
151
151
  });
152
152
  });
153
+
154
+ describe("GithubEnterpriseClient.uninstallFromOrg", () => {
155
+ const { privateKey } = require("node:crypto").generateKeyPairSync("rsa", {
156
+ modulusLength: 2048,
157
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
158
+ publicKeyEncoding: { type: "spki", format: "pem" },
159
+ });
160
+ const make = (deleteStatus: number) => {
161
+ const calls: { method: string; path: string; auth: string }[] = [];
162
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
163
+ const u = new URL(input.toString());
164
+ const method = init?.method ?? "GET";
165
+ calls.push({
166
+ method,
167
+ path: u.pathname,
168
+ auth: ((init?.headers ?? {}) as Record<string, string>)
169
+ .Authorization as string,
170
+ });
171
+ if (u.pathname === "/enterprises/acme/installation")
172
+ return Response.json({ id: 4242 });
173
+ if (u.pathname === "/app/installations/4242/access_tokens")
174
+ return Response.json(
175
+ { token: "ghs_t", expires_at: "2099-01-01T00:00:00Z" },
176
+ { status: 201 },
177
+ );
178
+ if (method === "DELETE") {
179
+ return deleteStatus === 204
180
+ ? new Response(null, { status: 204 })
181
+ : Response.json({ message: "nope" }, { status: deleteStatus });
182
+ }
183
+ throw new Error(`unexpected ${method} ${u.pathname}`);
184
+ }) as typeof fetch;
185
+ const client = new GithubEnterpriseClient({
186
+ appId: "1",
187
+ enterprise: "acme",
188
+ privateKey,
189
+ fetchFn,
190
+ });
191
+ return { client, calls };
192
+ };
193
+
194
+ it("DELETEs the org installation with the installation token (204)", async () => {
195
+ const { client, calls } = make(204);
196
+ await client.uninstallFromOrg("org-1", 601);
197
+ const del = calls.find((c) => c.method === "DELETE");
198
+ expect(del?.path).toBe(
199
+ "/enterprises/acme/apps/organizations/org-1/installations/601",
200
+ );
201
+ expect(del?.auth).toBe("Bearer ghs_t");
202
+ });
203
+
204
+ it("maps a refusal to a typed error", async () => {
205
+ const { client } = make(403);
206
+ const err = await client.uninstallFromOrg("org-1", 601).catch((e) => e);
207
+ expect(err).toBeInstanceOf(GithubEnterpriseError);
208
+ expect(err.kind).toBe("permission");
209
+ });
210
+
211
+ it("rejects a bad installation id before any network call", async () => {
212
+ const { client, calls } = make(204);
213
+ const err = await client.uninstallFromOrg("org-1", 0).catch((e) => e);
214
+ expect(err.kind).toBe("validation");
215
+ expect(calls).toHaveLength(0);
216
+ });
217
+ });
@@ -94,6 +94,11 @@ export function lazyInstallerClient(
94
94
  (await client(accountId)).addRepositories(org, id, names),
95
95
  removeRepositories: async (org, id, names, accountId) =>
96
96
  (await client(accountId)).removeRepositories(org, id, names),
97
+ setRepositorySelection: async (org, id, input, accountId) =>
98
+ (await client(accountId)).setRepositorySelection(org, id, {
99
+ repositorySelection: input.repositorySelection,
100
+ repositories: [...input.repositories],
101
+ }),
97
102
  };
98
103
  }
99
104
 
@@ -0,0 +1,297 @@
1
+ /**
2
+ * admin/src/github-sync-switch.integration.test.ts
3
+ * GIS-1.2: apply ordering for an "all" installation against the recorded
4
+ * enterprise cassette (real GithubEnterpriseClient, fetch replaced by the
5
+ * recording) with the real cache and a real GitHubReconcileAudit row.
6
+ *
7
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import { generateKeyPairSync } from "node:crypto";
12
+ import { readFileSync } from "node:fs";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { GithubSyncService } from "./github-sync.ts";
15
+ import { lazyInstallerClient } from "./github-installation-wiring.ts";
16
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
17
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
18
+ import {
19
+ createInstallationPort,
20
+ PrismaInstallationAudit,
21
+ } from "./installation-ports.ts";
22
+ import { createInstallationReposPort } from "./installation-repos-service.ts";
23
+ import { createAdminPrismaClient } from "./prisma-client.ts";
24
+
25
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
26
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
27
+
28
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
29
+ modulusLength: 2048,
30
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
31
+ publicKeyEncoding: { type: "spki", format: "pem" },
32
+ });
33
+ const cassette = JSON.parse(
34
+ readFileSync(
35
+ new URL("./fixtures/github-enterprise-cassette.json", import.meta.url)
36
+ .pathname,
37
+ "utf-8",
38
+ ),
39
+ ) as Record<string, { status: number; body: unknown }>;
40
+
41
+ const INST = "/enterprises/acme/apps/organizations/acme-eng/installations";
42
+ const APP_ID = 777;
43
+ const AGENT_ID = "gis-it-agent";
44
+ const ORG = "acme-eng";
45
+ const REPOS = ["acme-eng/repo-1", "acme-eng/repo-2"];
46
+
47
+ function routeTable(selection: string): Record<string, string> {
48
+ return {
49
+ "GET /enterprises/acme/installation": "enterprise_installation_success",
50
+ "POST /app/installations/4242/access_tokens": "access_token_success",
51
+ [`GET ${INST}`]: selection,
52
+ [`GET ${INST}/501/repositories`]: "install_repos_success",
53
+ [`PATCH ${INST}/501/repositories`]: "install_selection_success",
54
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_success",
55
+ [`PATCH ${INST}/501/repositories/remove`]: "install_repos_remove_success",
56
+ };
57
+ }
58
+
59
+ describeOrSkip("GitHub Sync all-to-selected switch (integration)", () => {
60
+ let prisma: PrismaClient;
61
+ let cache: GitHubRepoCacheService;
62
+ const checkedAt = new Date(Date.now() - 60_000);
63
+
64
+ const clean = async () => {
65
+ await prisma.gitHubReconcileAudit.deleteMany({
66
+ where: { agentId: AGENT_ID },
67
+ });
68
+ await prisma.gitHubRepoAccess.deleteMany({
69
+ where: { accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY, org: ORG },
70
+ });
71
+ await prisma.gitHubCachedRepo.deleteMany();
72
+ await prisma.gitHubRepoSnapshot.deleteMany();
73
+ };
74
+
75
+ async function seed(selection: "all" | "selected", repos: string[]) {
76
+ const key = {
77
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
78
+ appKind: "agent" as const,
79
+ appRef: String(APP_ID),
80
+ org: ORG,
81
+ };
82
+ const snap = await cache.upsertSnapshot(key, {
83
+ completedAt: checkedAt,
84
+ totalCount: repos.length,
85
+ repositorySelection: selection,
86
+ lastError: null,
87
+ });
88
+ await cache.upsertRepos(
89
+ snap.id,
90
+ repos.map((fullName, i) => ({ githubId: i + 1, fullName })),
91
+ checkedAt,
92
+ );
93
+ for (const full of REPOS) {
94
+ await prisma.gitHubRepoAccess.upsert({
95
+ where: {
96
+ accountId_org_repo_username: {
97
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
98
+ org: ORG,
99
+ repo: full.split("/")[1] as string,
100
+ username: "dev",
101
+ },
102
+ },
103
+ create: {
104
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
105
+ org: ORG,
106
+ repo: full.split("/")[1] as string,
107
+ username: "dev",
108
+ canPush: full === "acme-eng/repo-1",
109
+ level: full === "acme-eng/repo-1" ? "write" : "read",
110
+ checkedAt,
111
+ status: "ok",
112
+ },
113
+ update: {},
114
+ });
115
+ }
116
+ }
117
+
118
+ function service(requests: string[], patchBodies: unknown[]) {
119
+ // The installation's repo list follows a landed selection switch.
120
+ let installed = [...REPOS];
121
+ const table = routeTable("org_installations_success");
122
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
123
+ const u = new URL(input.toString());
124
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
125
+ if (key === "GET /enterprises/acme/apps/installable_organizations") {
126
+ return new Response(JSON.stringify([{ id: 5010, login: ORG }]), {
127
+ status: 200,
128
+ });
129
+ }
130
+ const name = table[key];
131
+ if (!name) throw new Error(`no route for ${key}`);
132
+ if (key.startsWith("PATCH") || key.startsWith("DELETE")) {
133
+ requests.push(key);
134
+ patchBodies.push(JSON.parse(String(init?.body ?? "{}")));
135
+ }
136
+ const entry = cassette[name];
137
+ if (!entry) throw new Error(`no cassette entry ${name}`);
138
+ if (key === `GET ${INST}/501/repositories`) {
139
+ return new Response(
140
+ JSON.stringify(
141
+ installed.map((full_name, i) => ({
142
+ id: i + 1,
143
+ name: full_name.split("/")[1],
144
+ full_name,
145
+ })),
146
+ ),
147
+ { status: 200, headers: { "Content-Type": "application/json" } },
148
+ );
149
+ }
150
+ if (key === `PATCH ${INST}/501/repositories` && entry.status === 200) {
151
+ installed = (
152
+ patchBodies.at(-1) as { repositories: string[] }
153
+ ).repositories.map((n) => `${ORG}/${n}`);
154
+ }
155
+ return new Response(JSON.stringify(entry.body), {
156
+ status: entry.status,
157
+ headers: { "Content-Type": "application/json" },
158
+ });
159
+ }) as typeof fetch;
160
+ const client = lazyInstallerClient({
161
+ appService: {
162
+ get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
163
+ getPrivateKey: async () => PEM,
164
+ },
165
+ fetchFn,
166
+ });
167
+ let repos = ["acme-eng/repo-2"];
168
+ return new GithubSyncService({
169
+ agents: {
170
+ get: async () => ({
171
+ id: AGENT_ID,
172
+ githubUsername: "dev",
173
+ appId: APP_ID,
174
+ repos,
175
+ }),
176
+ setRepos: async (_id, next) => {
177
+ requests.push("setRepos");
178
+ repos = next;
179
+ },
180
+ },
181
+ access: async () => {
182
+ throw new Error("live resolver must not be used");
183
+ },
184
+ cache,
185
+ lookupRepos: async () => [
186
+ { org: ORG, completedAt: checkedAt, repos: REPOS },
187
+ ],
188
+ verifyPush: async (_u, repo) => repo === "acme-eng/repo-1",
189
+ installation: createInstallationReposPort(
190
+ createInstallationPort(client),
191
+ client,
192
+ ),
193
+ audit: new PrismaInstallationAudit(prisma),
194
+ });
195
+ }
196
+
197
+ beforeEach(async () => {
198
+ prisma = createAdminPrismaClient(TEST_DB as string);
199
+ cache = new GitHubRepoCacheService(prisma);
200
+ await clean();
201
+ });
202
+ afterEach(async () => {
203
+ await clean();
204
+ await prisma.$disconnect();
205
+ });
206
+
207
+ it("switches first, folds the removal, writes the audit row; a later preview has nothing to do", async () => {
208
+ await seed("all", REPOS);
209
+ const requests: string[] = [];
210
+ const bodies: unknown[] = [];
211
+ const svc = service(requests, bodies);
212
+
213
+ const before = await svc.preview(AGENT_ID);
214
+ if (before.status !== "previewed") throw new Error(before.status);
215
+ expect(before.plan.selectionSwitches).toEqual([
216
+ { org: ORG, repos: ["acme-eng/repo-1"] },
217
+ ]);
218
+ expect(before.plan.appRemoves).toEqual(["acme-eng/repo-2"]);
219
+ expect(requests).toEqual([]);
220
+
221
+ const r = await svc.apply({
222
+ agentId: AGENT_ID,
223
+ caller: "root",
224
+ appAdds: [],
225
+ appRemoves: ["acme-eng/repo-2"],
226
+ agentRemoves: ["acme-eng/repo-2"],
227
+ });
228
+ expect(r.status).toBe("applied");
229
+ // PATCH selection (no /add or /remove: the removal is folded), then agent repos.
230
+ expect(requests).toEqual([`PATCH ${INST}/501/repositories`, "setRepos"]);
231
+ expect(bodies[0]).toEqual({
232
+ repository_selection: "selected",
233
+ repositories: ["repo-1"],
234
+ });
235
+
236
+ const rows = await prisma.gitHubReconcileAudit.findMany({
237
+ where: { agentId: AGENT_ID },
238
+ });
239
+ expect(rows).toHaveLength(1);
240
+ expect(rows[0]?.result).toEqual({ status: "applied" });
241
+ expect(rows[0]?.diff).toMatchObject({
242
+ installationRemoves: ["acme-eng/repo-2"],
243
+ configRemoves: ["acme-eng/repo-2"],
244
+ selectionSwitches: [{ org: ORG, repos: ["acme-eng/repo-1"] }],
245
+ });
246
+
247
+ // The next crawl records "selected" and the shrunk repo list.
248
+ await prisma.gitHubCachedRepo.deleteMany();
249
+ await prisma.gitHubRepoSnapshot.deleteMany();
250
+ await seed("selected", ["acme-eng/repo-1"]);
251
+ const after = await svc.preview(AGENT_ID);
252
+ if (after.status !== "previewed") throw new Error(after.status);
253
+ expect(after.plan.selectionSwitches).toEqual([]);
254
+ expect([
255
+ after.plan.appAdds,
256
+ after.plan.appRemoves,
257
+ after.plan.agentRemoves,
258
+ ]).toEqual([[], [], []]);
259
+ });
260
+
261
+ it("records a failed audit row with nothing landed when GitHub answers 403", async () => {
262
+ await seed("all", REPOS);
263
+ const requests: string[] = [];
264
+ const svc = service(requests, []);
265
+ // Swap the recorded success for the recorded 403 on the PATCH.
266
+ const original = cassette.install_selection_success;
267
+ cassette.install_selection_success =
268
+ cassette.install_selection_403 as never;
269
+ try {
270
+ const r = await svc.apply({
271
+ agentId: AGENT_ID,
272
+ caller: "root",
273
+ appAdds: [],
274
+ appRemoves: ["acme-eng/repo-2"],
275
+ agentRemoves: [],
276
+ });
277
+ if (r.status !== "failed") throw new Error(r.status);
278
+ expect(r.error).toContain(
279
+ "enterprise_organization_installation_repositories",
280
+ );
281
+ } finally {
282
+ cassette.install_selection_success = original as never;
283
+ }
284
+ expect(requests).toEqual([`PATCH ${INST}/501/repositories`]);
285
+ const rows = await prisma.gitHubReconcileAudit.findMany({
286
+ where: { agentId: AGENT_ID },
287
+ });
288
+ expect(rows).toHaveLength(1);
289
+ expect(rows[0]?.result).toMatchObject({ status: "failed" });
290
+ expect(rows[0]?.diff).toEqual({
291
+ installationAdds: [],
292
+ installationRemoves: [],
293
+ configAdds: [],
294
+ configRemoves: [],
295
+ });
296
+ });
297
+ });