@app-vitals/agent-admin 1.87.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.
Files changed (30) hide show
  1. package/openapi.json +253 -0
  2. package/openapi.platform.json +297 -0
  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/GitHubRepoSnapshot.ts +33 -1
  8. package/prisma/migrations/20261125000000_add_github_snapshot_repository_selection/migration.sql +2 -0
  9. package/prisma/schema/schema.prisma +2 -0
  10. package/src/admin-boot.ts +11 -0
  11. package/src/agents-api.smoke.test.ts +88 -0
  12. package/src/agents-api.ts +15 -0
  13. package/src/fixtures/github-enterprise-cassette.json +16 -0
  14. package/src/github-agent-installation-crawler.ts +27 -8
  15. package/src/github-agent-installation-crawler.unit.test.ts +76 -1
  16. package/src/github-enterprise-api.integration.test.ts +127 -0
  17. package/src/github-enterprise-api.smoke.test.ts +188 -5
  18. package/src/github-enterprise-api.ts +212 -4
  19. package/src/github-enterprise-client.ts +23 -1
  20. package/src/github-enterprise-client.unit.test.ts +65 -0
  21. package/src/github-installation-selection.integration.test.ts +91 -0
  22. package/src/github-installation-wiring.ts +5 -0
  23. package/src/github-repo-cache.ts +8 -0
  24. package/src/github-sync-switch.integration.test.ts +297 -0
  25. package/src/github-sync-switch.unit.test.ts +467 -0
  26. package/src/github-sync.ts +205 -24
  27. package/src/github-uninstall.ts +70 -0
  28. package/src/github-uninstall.unit.test.ts +78 -0
  29. package/src/installation-ports.ts +43 -0
  30. package/src/installation-repos-service.ts +2 -0
@@ -23,6 +23,10 @@ import { type AdminUIEnv } from "./admin-ui.ts";
23
23
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
24
24
  import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
25
25
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
26
+ import {
27
+ PrismaInstallationAgents,
28
+ PrismaInstallationAudit,
29
+ } from "./installation-ports.ts";
26
30
  import { createAdminPrismaClient } from "./prisma-client.ts";
27
31
  import { identityCrypto, makeStrictTokenCrypto } from "./token-crypto.ts";
28
32
 
@@ -354,3 +358,126 @@ describeOrSkip("github-enterprise API (integration)", () => {
354
358
  expect(denied.status).toBe(403);
355
359
  });
356
360
  });
361
+
362
+ describeOrSkip("DELETE /orgs/{org}/install (integration)", () => {
363
+ let prisma: PrismaClient;
364
+
365
+ beforeEach(async () => {
366
+ prisma = createAdminPrismaClient(TEST_DB as string);
367
+ await prisma.gitHubReconcileAudit.deleteMany();
368
+ await prisma.gitHubEnterpriseApp.deleteMany();
369
+ await prisma.agentEnv.deleteMany();
370
+ await prisma.agentToken.deleteMany();
371
+ await prisma.agentCronJob.deleteMany();
372
+ await prisma.agentTool.deleteMany();
373
+ await prisma.agent.deleteMany();
374
+ });
375
+
376
+ afterEach(async () => {
377
+ await prisma.$disconnect();
378
+ });
379
+
380
+ async function setup(deleteStatus: number) {
381
+ const appService = new GitHubEnterpriseAppService(
382
+ prisma,
383
+ makeStrictTokenCrypto(ENC_KEY),
384
+ );
385
+ await appService.save({
386
+ role: "installer",
387
+ appId: "12345",
388
+ slug: "example-installer",
389
+ enterpriseSlug: "acme",
390
+ privateKey: PEM,
391
+ });
392
+ const envService = new AgentEnvService(prisma, identityCrypto);
393
+ const agent = await prisma.agent.create({
394
+ data: {
395
+ name: "Uninstall Agent",
396
+ repos: ["acme-eng/a", "acme-eng/b", "other/c"],
397
+ },
398
+ });
399
+ await envService.upsert(agent.id, { GH_APP_SLUG: "target-app" });
400
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
401
+ const u = new URL(input.toString());
402
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
403
+ const json = (k: string) =>
404
+ new Response(JSON.stringify(cassette[k]?.body), {
405
+ status: cassette[k]?.status,
406
+ });
407
+ switch (key) {
408
+ case "GET /enterprises/acme/installation":
409
+ return json("enterprise_installation_success");
410
+ case "POST /app/installations/4242/access_tokens":
411
+ return json("access_token_success");
412
+ case "GET /enterprises/acme/apps/organizations/acme-eng/installations":
413
+ return json("org_installations_success");
414
+ case "DELETE /enterprises/acme/apps/organizations/acme-eng/installations/501":
415
+ return deleteStatus === 204
416
+ ? new Response(null, { status: 204 })
417
+ : json("uninstall_403");
418
+ }
419
+ throw new Error(`no route for ${key}`);
420
+ }) as typeof fetch;
421
+ const blocked: string[] = [];
422
+ const app = createGithubEnterpriseApp({
423
+ appService,
424
+ agentService: new AgentService(prisma),
425
+ agentEnvService: envService,
426
+ sessionSecret: "test-secret-32chars-for-ghe-api!!",
427
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
428
+ agentTokenService: { validate: async () => null },
429
+ uninstall: {
430
+ agents: new PrismaInstallationAgents(prisma, envService),
431
+ audit: new PrismaInstallationAudit(prisma),
432
+ openWork: {
433
+ listOpenWork: async () => [],
434
+ blockOpenWork: async (_a, repos) => {
435
+ blocked.push(...repos);
436
+ },
437
+ },
438
+ },
439
+ fetchFn,
440
+ apiBase: "https://ghe.test",
441
+ });
442
+ const del = () =>
443
+ app.request(
444
+ `/github-enterprise/orgs/acme-eng/install?agentId=${agent.id}`,
445
+ { method: "DELETE", headers: ADMIN },
446
+ );
447
+ return { agent, del, blocked };
448
+ }
449
+
450
+ it("updates the agent's repos and writes an applied audit row", async () => {
451
+ const { agent, del, blocked } = await setup(204);
452
+ const res = await del();
453
+ expect(res.status).toBe(200);
454
+ const row = await prisma.agent.findUniqueOrThrow({
455
+ where: { id: agent.id },
456
+ });
457
+ expect(row.repos).toEqual(["other/c"]);
458
+ const audits = await prisma.gitHubReconcileAudit.findMany({
459
+ where: { agentId: agent.id },
460
+ });
461
+ expect(audits).toHaveLength(1);
462
+ expect(audits[0]?.planHash).toBe("uninstall:org");
463
+ expect(audits[0]?.result).toEqual({ status: "applied" });
464
+ expect(blocked.sort()).toEqual(["acme-eng/a", "acme-eng/b"]);
465
+ });
466
+
467
+ it("a GitHub refusal writes a failed audit row and keeps the repos", async () => {
468
+ const { agent, del } = await setup(403);
469
+ const res = await del();
470
+ expect(res.status).toBe(502);
471
+ const row = await prisma.agent.findUniqueOrThrow({
472
+ where: { id: agent.id },
473
+ });
474
+ expect(row.repos).toHaveLength(3);
475
+ const audits = await prisma.gitHubReconcileAudit.findMany({
476
+ where: { agentId: agent.id },
477
+ });
478
+ expect(audits).toHaveLength(1);
479
+ expect((audits[0]?.result as { status: string } | undefined)?.status).toBe(
480
+ "failed",
481
+ );
482
+ });
483
+ });
@@ -9,7 +9,10 @@ import { describe, expect, it } from "bun:test";
9
9
  import { generateKeyPairSync } from "node:crypto";
10
10
  import { readFileSync } from "node:fs";
11
11
  import { parseAdminApiKeys } from "./api-auth.ts";
12
- import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
12
+ import {
13
+ createGithubEnterpriseApp,
14
+ type GithubEnterpriseApiDeps,
15
+ } from "./github-enterprise-api.ts";
13
16
  import type {
14
17
  GitHubEnterpriseAppMetadata,
15
18
  GitHubEnterpriseAppRole,
@@ -100,10 +103,16 @@ function replayFetch(routes: Record<string, string>) {
100
103
  const key = routes[base];
101
104
  if (!key) throw new Error(`no route for ${base}`);
102
105
  const entry = cassette[key] as CassetteEntry;
103
- return new Response(JSON.stringify(entry.body), {
104
- status: entry.status,
105
- headers: { "Content-Type": "application/json", ...(entry.headers ?? {}) },
106
- });
106
+ return new Response(
107
+ entry.status === 204 ? null : JSON.stringify(entry.body),
108
+ {
109
+ status: entry.status,
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ ...(entry.headers ?? {}),
113
+ },
114
+ },
115
+ );
107
116
  }) as typeof fetch;
108
117
  return { fetchFn, calls };
109
118
  }
@@ -119,6 +128,7 @@ function build(
119
128
  routes?: Record<string, string>;
120
129
  agents?: Record<string, Record<string, string> | null>;
121
130
  refreshAction?: GithubRefreshAction;
131
+ uninstall?: GithubEnterpriseApiDeps["uninstall"];
122
132
  } = {},
123
133
  ) {
124
134
  const appService = fakeAppService();
@@ -154,6 +164,7 @@ function build(
154
164
  ),
155
165
  agentTokenService: { validate: async () => null },
156
166
  ...(opts.refreshAction ? { refreshAction: opts.refreshAction } : {}),
167
+ ...(opts.uninstall ? { uninstall: opts.uninstall } : {}),
157
168
  fetchFn,
158
169
  apiBase: "https://ghe.test",
159
170
  });
@@ -989,3 +1000,175 @@ describe("refresh action (GLC-2.4)", () => {
989
1000
  expect(res2.status).toBe(200);
990
1001
  });
991
1002
  });
1003
+
1004
+ describe("DELETE install (uninstall)", () => {
1005
+ const DELETE_INST =
1006
+ "DELETE /enterprises/acme/apps/organizations/org-1/installations/501";
1007
+ const INSTS_ROUTE =
1008
+ "GET /enterprises/acme/apps/organizations/org-1/installations";
1009
+
1010
+ function harness(
1011
+ opts: {
1012
+ repos?: string[];
1013
+ deleteStatus?: number;
1014
+ openWorkFails?: boolean;
1015
+ noInstall?: boolean;
1016
+ } = {},
1017
+ ) {
1018
+ const state = {
1019
+ repos: opts.repos ?? ["org-1/a", "org-1/b", "other/c"],
1020
+ audits: [] as {
1021
+ planHash: string;
1022
+ diff: unknown;
1023
+ result: { status: string };
1024
+ }[],
1025
+ blocked: [] as string[],
1026
+ deleted: 0,
1027
+ };
1028
+ const h = build({
1029
+ agents: {
1030
+ "agent-1": {
1031
+ GH_APP_SLUG: "target-app",
1032
+ GH_APP_CLIENT_ID: "Iv1.targetapp0001",
1033
+ },
1034
+ },
1035
+ routes: {
1036
+ [DELETE_INST]:
1037
+ opts.deleteStatus === 403 ? "uninstall_403" : "uninstall_success",
1038
+ [INSTS_ROUTE]: opts.noInstall
1039
+ ? "installable_orgs_empty"
1040
+ : "org_installations_success",
1041
+ },
1042
+ uninstall: {
1043
+ agents: {
1044
+ get: async (id: string) => ({
1045
+ id,
1046
+ repos: [...state.repos],
1047
+ githubUsername: null,
1048
+ }),
1049
+ setRepos: async (_id: string, repos: string[]) => {
1050
+ state.repos = repos;
1051
+ },
1052
+ },
1053
+ audit: {
1054
+ write: async (e: never) => {
1055
+ state.audits.push(e);
1056
+ return `audit-${state.audits.length}`;
1057
+ },
1058
+ },
1059
+ openWork: {
1060
+ listOpenWork: async (_a: string, repos: readonly string[]) => {
1061
+ if (opts.openWorkFails) throw new Error("port down");
1062
+ return repos.map((repo) => ({ id: `t-${repo}`, repo }));
1063
+ },
1064
+ blockOpenWork: async (_a: string, repos: readonly string[]) => {
1065
+ if (opts.openWorkFails) throw new Error("port down");
1066
+ state.blocked.push(...repos);
1067
+ },
1068
+ },
1069
+ },
1070
+ });
1071
+ return { h, state, del: DELETE_INST, status: opts.deleteStatus ?? 204 };
1072
+ }
1073
+
1074
+ async function run(
1075
+ o: ReturnType<typeof harness>,
1076
+ query: string,
1077
+ headers: Record<string, string> = ADMIN,
1078
+ ) {
1079
+ return o.h.app.request(
1080
+ `/github-enterprise/orgs/org-1/install?agentId=agent-1${query}`,
1081
+ {
1082
+ method: "DELETE",
1083
+ headers,
1084
+ },
1085
+ );
1086
+ }
1087
+
1088
+ it("uninstalls, removes the org's repos, blocks open work and audits", async () => {
1089
+ const o = harness();
1090
+ await seed(o.h);
1091
+ const res = await run(o, "");
1092
+ expect(res.status).toBe(200);
1093
+ const body = (await res.json()) as Record<string, unknown>;
1094
+ expect(body).toMatchObject({
1095
+ status: "uninstalled",
1096
+ org: "org-1",
1097
+ installationId: 501,
1098
+ repos: ["org-1/a", "org-1/b"],
1099
+ auditId: "audit-1",
1100
+ });
1101
+ expect(o.h.calls).toContain(o.del);
1102
+ expect(o.state.repos).toEqual(["other/c"]);
1103
+ expect(o.state.blocked.sort()).toEqual(["org-1/a", "org-1/b"]);
1104
+ expect(o.state.audits[0]).toMatchObject({
1105
+ planHash: "uninstall:org",
1106
+ result: { status: "applied" },
1107
+ });
1108
+ });
1109
+
1110
+ it("preview lists repos and open work and changes nothing", async () => {
1111
+ const o = harness();
1112
+ await seed(o.h);
1113
+ const res = await run(o, "&preview=true");
1114
+ expect(res.status).toBe(200);
1115
+ const body = (await res.json()) as { status: string; openWork: unknown[] };
1116
+ expect(body.status).toBe("preview");
1117
+ expect(body.openWork).toHaveLength(2);
1118
+ expect(o.h.calls).not.toContain(o.del);
1119
+ expect(o.state.repos).toHaveLength(3);
1120
+ expect(o.state.audits).toHaveLength(0);
1121
+ expect(o.state.blocked).toHaveLength(0);
1122
+ });
1123
+
1124
+ it("a port failure on preview is a warning", async () => {
1125
+ const o = harness({ openWorkFails: true });
1126
+ await seed(o.h);
1127
+ const body = (await (await run(o, "&preview=true")).json()) as {
1128
+ warnings: string[];
1129
+ };
1130
+ expect(body.warnings.join()).toContain("port down");
1131
+ });
1132
+
1133
+ it("not installed is a distinct 404 and changes nothing", async () => {
1134
+ const o = harness({ noInstall: true });
1135
+ await seed(o.h);
1136
+ const res = await run(o, "");
1137
+ expect(res.status).toBe(404);
1138
+ expect(((await res.json()) as { error: string }).error).toContain(
1139
+ "not installed",
1140
+ );
1141
+ expect(o.state.audits).toHaveLength(0);
1142
+ expect(o.state.repos).toHaveLength(3);
1143
+ });
1144
+
1145
+ it("a GitHub refusal is 502 with a failed audit row and repos untouched", async () => {
1146
+ const o = harness({ deleteStatus: 403 });
1147
+ await seed(o.h);
1148
+ const res = await run(o, "");
1149
+ expect(res.status).toBe(502);
1150
+ expect(o.state.audits[0]?.result.status).toBe("failed");
1151
+ expect(o.state.repos).toHaveLength(3);
1152
+ expect(o.state.blocked).toHaveLength(0);
1153
+ });
1154
+
1155
+ it("more than 10 repos need confirmRemovals", async () => {
1156
+ const many = Array.from({ length: 11 }, (_, i) => `org-1/r${i}`);
1157
+ const o = harness({ repos: many });
1158
+ await seed(o.h);
1159
+ const refused = await run(o, "");
1160
+ expect(refused.status).toBe(422);
1161
+ expect(o.h.calls).not.toContain(o.del);
1162
+ const ok = await run(o, "&confirmRemovals=true");
1163
+ expect(ok.status).toBe(200);
1164
+ expect(o.state.repos).toEqual([]);
1165
+ });
1166
+
1167
+ it("non-admin callers get 403 and nothing is called", async () => {
1168
+ const o = harness();
1169
+ await seed(o.h);
1170
+ const res = await run(o, "", { Authorization: "Bearer tok-read" });
1171
+ expect(res.status).toBe(403);
1172
+ expect(o.h.calls).toHaveLength(0);
1173
+ });
1174
+ });
@@ -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,