@app-vitals/agent-admin 1.37.0 → 1.39.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.37.0",
3
+ "version": "1.39.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.37.0",
45
+ "@app-vitals/agent-lib": "1.39.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -103,12 +103,14 @@ import { HttpGithubAppProvisioningClient } from "./github-app-provisioning-clien
103
103
  import {
104
104
  createGithubAccessPreview,
105
105
  createGithubEnterpriseApp,
106
+ createGithubLookupService,
106
107
  } from "./github-enterprise-api.ts";
107
108
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
108
109
  import {
109
110
  createGithubInstallationRepos,
110
111
  createGithubSync,
111
112
  } from "./github-installation-wiring.ts";
113
+
112
114
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
113
115
  import { HttpChatClient } from "./http-chat-client.ts";
114
116
  import { HttpOktaAuthClient } from "./okta-auth-client.ts";
@@ -178,6 +180,12 @@ export async function startAdmin(
178
180
  },
179
181
  );
180
182
 
183
+ // Shared by the extension context's githubLookup and the GHE routes below.
184
+ const githubEnterpriseAppService = new GitHubEnterpriseAppService(
185
+ prisma,
186
+ makeStrictTokenCrypto(),
187
+ );
188
+
181
189
  // Construct TokenCrypto — reads SHIPWRIGHT_ENCRYPTION_KEY at call time
182
190
  const crypto = makeTokenCrypto();
183
191
 
@@ -382,6 +390,9 @@ export async function startAdmin(
382
390
  accountService,
383
391
  callerScopeResolver,
384
392
  provisioner,
393
+ githubLookup: createGithubLookupService({
394
+ appService: githubEnterpriseAppService,
395
+ }),
385
396
  },
386
397
  };
387
398
  const resolvedExtensions = resolveAdminExtensions(
@@ -467,10 +478,6 @@ export async function startAdmin(
467
478
  // MUST be mounted before admin-ui (/admin/*) to avoid shadowing.
468
479
  // Built before the admin API: GHE-2.4's access preview reads the same Apps.
469
480
  // Strict crypto: no plain-text key storage.
470
- const githubEnterpriseAppService = new GitHubEnterpriseAppService(
471
- prisma,
472
- makeStrictTokenCrypto(),
473
- );
474
481
  const githubAccessPreview = createGithubAccessPreview({
475
482
  appService: githubEnterpriseAppService,
476
483
  });
@@ -61,6 +61,7 @@ import type { AgentService } from "./agents.ts";
61
61
  import type { AdminDeps, parseAdminApiKeys } from "./agents-api.ts";
62
62
  import type { AgentPhaseMethodologyServiceLike } from "./api.ts";
63
63
  import type { createCallerScopeResolver } from "./caller-scope.ts";
64
+ import type { GithubLookupService } from "./github-lookup-repositories.ts";
64
65
  import type { PushService } from "./push-service.ts";
65
66
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
66
67
  import type { ServiceIntegration } from "./service-integration.ts";
@@ -85,6 +86,11 @@ export interface AdminPlatformServices {
85
86
  accountService: AccountService;
86
87
  callerScopeResolver: ReturnType<typeof createCallerScopeResolver>;
87
88
  provisioner: AgentProvisioner;
89
+ /**
90
+ * Lists the repositories the lookup GitHub App can see. Optional so existing
91
+ * extensions (and contexts they build) keep compiling.
92
+ */
93
+ githubLookup?: GithubLookupService;
88
94
  }
89
95
 
90
96
  /** Everything an extension's hooks may need from the platform. */
@@ -5,6 +5,7 @@ import {
5
5
  type AdminBackgroundPass,
6
6
  type AdminExtension,
7
7
  type AdminExtensionContext,
8
+ type AdminPlatformServices,
8
9
  type AgentDetailCardSlot,
9
10
  applyOpenApiContributions,
10
11
  collectOpenApiContributions,
@@ -630,3 +631,19 @@ describe("withExtensionAgentTypes", () => {
630
631
  expect(wrapped.hasExtensionType?.("specialist")).toBe(false);
631
632
  });
632
633
  });
634
+
635
+ describe("AdminPlatformServices.githubLookup", () => {
636
+ it("is optional: a services object without it satisfies the type", () => {
637
+ // Compile-time check (tsc): the Omit<> shape is assignable only while the
638
+ // member is optional.
639
+ const without = {} as Omit<AdminPlatformServices, "githubLookup">;
640
+ const services: AdminPlatformServices = without;
641
+ expect(services.githubLookup).toBeUndefined();
642
+ const withLookup: Pick<AdminPlatformServices, "githubLookup"> = {
643
+ githubLookup: {
644
+ listRepositories: async () => ({ configured: false, repos: [] }),
645
+ },
646
+ };
647
+ expect(withLookup.githubLookup).toBeDefined();
648
+ });
649
+ });
@@ -959,6 +959,92 @@ describeOrSkip("AgentCronRunService (integration)", () => {
959
959
  expect(items.some((r) => r.id === skippedWithOutcome.id)).toBe(true);
960
960
  });
961
961
 
962
+ describe("outcomes filter", () => {
963
+ async function seed() {
964
+ const agentId = await createAgent(prisma);
965
+ const cronId = await createCron(cronJobService, agentId);
966
+ const mk = (day: string, skipped: boolean, outcome: string | null) =>
967
+ runService.create(cronId, agentId, {
968
+ startedAt: new Date(`2026-01-${day}T08:00:00Z`),
969
+ skipped,
970
+ outcome,
971
+ });
972
+ const skipped = await mk("01", true, null);
973
+ const unknown = await mk("02", false, null);
974
+ const completed = await mk("03", false, "completed");
975
+ const failed = await mk("04", false, "failed");
976
+ return { agentId, ids: { skipped, unknown, completed, failed } };
977
+ }
978
+
979
+ const idsOf = (items: { id: string }[]) => items.map((r) => r.id).sort();
980
+
981
+ it("listForAgent() single outcomes value selects just that bucket", async () => {
982
+ const { agentId, ids } = await seed();
983
+ for (const key of [
984
+ "skipped",
985
+ "unknown",
986
+ "completed",
987
+ "failed",
988
+ ] as const) {
989
+ const { items, total } = await runService.listForAgent(agentId, {
990
+ outcomes: [key],
991
+ });
992
+ expect(total).toBe(1);
993
+ expect(idsOf(items)).toEqual([ids[key].id]);
994
+ }
995
+ });
996
+
997
+ it("listForAgent() multiple outcomes values are OR'd and total matches", async () => {
998
+ const { agentId, ids } = await seed();
999
+ const { items, total } = await runService.listForAgent(agentId, {
1000
+ outcomes: ["skipped", "unknown", "failed"],
1001
+ limit: 2,
1002
+ });
1003
+ expect(total).toBe(3);
1004
+ expect(items).toHaveLength(2);
1005
+ const all = await runService.listForAgent(agentId, {
1006
+ outcomes: ["skipped", "unknown", "failed"],
1007
+ });
1008
+ expect(idsOf(all.items)).toEqual(
1009
+ [ids.skipped.id, ids.unknown.id, ids.failed.id].sort(),
1010
+ );
1011
+ });
1012
+
1013
+ it("listForAgent() empty outcomes is no filter; outcomes beats outcome", async () => {
1014
+ const { agentId, ids } = await seed();
1015
+ const none = await runService.listForAgent(agentId, { outcomes: [] });
1016
+ expect(none.total).toBe(4);
1017
+ const both = await runService.listForAgent(agentId, {
1018
+ outcome: "completed",
1019
+ outcomes: ["failed"],
1020
+ });
1021
+ expect(idsOf(both.items)).toEqual([ids.failed.id]);
1022
+ });
1023
+
1024
+ it("listForAgent() legacy outcome still works", async () => {
1025
+ const { agentId, ids } = await seed();
1026
+ const { items, total } = await runService.listForAgent(agentId, {
1027
+ outcome: "completed",
1028
+ });
1029
+ expect(total).toBe(1);
1030
+ expect(idsOf(items)).toEqual([ids.completed.id]);
1031
+ });
1032
+
1033
+ it("listAcrossAgents() applies outcomes with matching total", async () => {
1034
+ const { agentId, ids } = await seed();
1035
+ const { items, total } = await runService.listAcrossAgents([agentId], {
1036
+ outcomes: ["unknown", "completed"],
1037
+ });
1038
+ expect(total).toBe(2);
1039
+ expect(idsOf(items)).toEqual([ids.unknown.id, ids.completed.id].sort());
1040
+ const single = await runService.listAcrossAgents([agentId], {
1041
+ outcomes: ["skipped"],
1042
+ });
1043
+ expect(single.total).toBe(1);
1044
+ expect(single.items[0].id).toBe(ids.skipped.id);
1045
+ });
1046
+ });
1047
+
962
1048
  it("listForAgent() never returns a second agent's runs", async () => {
963
1049
  const agentId1 = await createAgent(prisma, "Agent 1");
964
1050
  const agentId2 = await createAgent(prisma, "Agent 2");
@@ -146,6 +146,13 @@ interface ListForAgentOptions {
146
146
  * WHERE skipped = false AND outcome = value. Omitted means no filter.
147
147
  */
148
148
  outcome?: string;
149
+ /**
150
+ * Multi-select variant of `outcome`; values are OR'd. "skipped" ->
151
+ * skipped = true; "unknown" -> skipped = false AND outcome IS NULL; any
152
+ * other value -> skipped = false AND outcome = value. An empty array is no
153
+ * filter. When given, `outcomes` wins over `outcome`.
154
+ */
155
+ outcomes?: string[];
149
156
  limit?: number;
150
157
  offset?: number;
151
158
  }
@@ -171,10 +178,45 @@ interface ListAcrossAgentsOptions {
171
178
  * WHERE skipped = false AND outcome = value. Omitted means no filter.
172
179
  */
173
180
  outcome?: string;
181
+ /**
182
+ * Multi-select variant of `outcome`; values are OR'd. "skipped" ->
183
+ * skipped = true; "unknown" -> skipped = false AND outcome IS NULL; any
184
+ * other value -> skipped = false AND outcome = value. An empty array is no
185
+ * filter. When given, `outcomes` wins over `outcome`.
186
+ */
187
+ outcomes?: string[];
174
188
  limit?: number;
175
189
  offset?: number;
176
190
  }
177
191
 
192
+ /** Where-clause fragment for one outcome filter value (see `outcomes`). */
193
+ function outcomeClause(value: string): Prisma.AgentCronRunWhereInput {
194
+ if (value === "skipped") return { skipped: true };
195
+ if (value === "unknown") return { skipped: false, outcome: null };
196
+ return { skipped: false, outcome: value };
197
+ }
198
+
199
+ /**
200
+ * Translate the `outcome` / `outcomes` list options into a where fragment.
201
+ * `outcomes` (OR'd) wins over the legacy single `outcome`; an empty `outcomes`
202
+ * array is no filter (it does not fall back to `outcome`).
203
+ */
204
+ export function buildOutcomeWhere(opts?: {
205
+ outcome?: string;
206
+ outcomes?: string[];
207
+ }): Prisma.AgentCronRunWhereInput {
208
+ if (opts?.outcomes !== undefined) {
209
+ return opts.outcomes.length > 0
210
+ ? { OR: opts.outcomes.map(outcomeClause) }
211
+ : {};
212
+ }
213
+ if (opts?.outcome === "skipped") return { skipped: true };
214
+ if (opts?.outcome !== undefined) {
215
+ return { skipped: false, outcome: opts.outcome };
216
+ }
217
+ return {};
218
+ }
219
+
178
220
  export class AgentCronRunService {
179
221
  constructor(private prisma: PrismaClient) {}
180
222
 
@@ -450,12 +492,7 @@ export class AgentCronRunService {
450
492
  if (opts?.cronId) {
451
493
  where.cronId = opts.cronId;
452
494
  }
453
- if (opts?.outcome === "skipped") {
454
- where.skipped = true;
455
- } else if (opts?.outcome !== undefined) {
456
- where.skipped = false;
457
- where.outcome = opts.outcome;
458
- }
495
+ Object.assign(where, buildOutcomeWhere(opts));
459
496
 
460
497
  const [items, total] = await this.prisma.$transaction([
461
498
  this.prisma.agentCronRun.findMany({
@@ -494,12 +531,7 @@ export class AgentCronRunService {
494
531
  if (opts?.cronId) {
495
532
  where.cronId = opts.cronId;
496
533
  }
497
- if (opts?.outcome === "skipped") {
498
- where.skipped = true;
499
- } else if (opts?.outcome !== undefined) {
500
- where.skipped = false;
501
- where.outcome = opts.outcome;
502
- }
534
+ Object.assign(where, buildOutcomeWhere(opts));
503
535
 
504
536
  const [items, total] = await this.prisma.$transaction([
505
537
  this.prisma.agentCronRun.findMany({
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Unit tests for agent-cron-runs.ts's pure outcome-filter mapping
3
+ * (buildOutcomeWhere): no DB, just the where-clause shape.
4
+ */
5
+ import { describe, expect, test } from "bun:test";
6
+ import { buildOutcomeWhere } from "./agent-cron-runs.ts";
7
+
8
+ describe("buildOutcomeWhere", () => {
9
+ test("no options yields no filter", () => {
10
+ expect(buildOutcomeWhere()).toEqual({});
11
+ expect(buildOutcomeWhere({})).toEqual({});
12
+ });
13
+
14
+ test("legacy outcome: skipped matches the boolean flag only", () => {
15
+ expect(buildOutcomeWhere({ outcome: "skipped" })).toEqual({
16
+ skipped: true,
17
+ });
18
+ });
19
+
20
+ test("legacy outcome: other value requires skipped=false and equality", () => {
21
+ expect(buildOutcomeWhere({ outcome: "success" })).toEqual({
22
+ skipped: false,
23
+ outcome: "success",
24
+ });
25
+ });
26
+
27
+ test("outcomes: each value maps to its clause", () => {
28
+ expect(buildOutcomeWhere({ outcomes: ["skipped"] })).toEqual({
29
+ OR: [{ skipped: true }],
30
+ });
31
+ expect(buildOutcomeWhere({ outcomes: ["unknown"] })).toEqual({
32
+ OR: [{ skipped: false, outcome: null }],
33
+ });
34
+ expect(buildOutcomeWhere({ outcomes: ["failed"] })).toEqual({
35
+ OR: [{ skipped: false, outcome: "failed" }],
36
+ });
37
+ });
38
+
39
+ test("outcomes: multiple values are OR'd in order", () => {
40
+ expect(
41
+ buildOutcomeWhere({ outcomes: ["skipped", "unknown", "completed"] }),
42
+ ).toEqual({
43
+ OR: [
44
+ { skipped: true },
45
+ { skipped: false, outcome: null },
46
+ { skipped: false, outcome: "completed" },
47
+ ],
48
+ });
49
+ });
50
+
51
+ test("outcomes: empty array is no filter", () => {
52
+ expect(buildOutcomeWhere({ outcomes: [] })).toEqual({});
53
+ });
54
+
55
+ test("outcomes wins over outcome when both are passed", () => {
56
+ expect(
57
+ buildOutcomeWhere({ outcome: "success", outcomes: ["failed"] }),
58
+ ).toEqual({ OR: [{ skipped: false, outcome: "failed" }] });
59
+ });
60
+
61
+ test("empty outcomes still wins over outcome (no filter)", () => {
62
+ expect(buildOutcomeWhere({ outcome: "success", outcomes: [] })).toEqual({});
63
+ });
64
+ });
@@ -16,18 +16,17 @@
16
16
  * Auth: admin key or admin session (every other caller class gets 403).
17
17
  */
18
18
 
19
- import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
20
19
  import { createPrivateKey } from "node:crypto";
21
20
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
22
21
  import { HTTPException } from "hono/http-exception";
23
22
  import type { AgentEnvService } from "./agent-envs.ts";
23
+ import type { AgentTokenService } from "./agent-tokens.ts";
24
+ import type { AgentService } from "./agents.ts";
24
25
  import {
25
26
  type AdminApiKey,
26
27
  type AdminAuthEnv,
27
28
  createAdminAuthMiddleware,
28
29
  } from "./api-auth.ts";
29
- import type { AgentTokenService } from "./agent-tokens.ts";
30
- import type { AgentService } from "./agents.ts";
31
30
  import {
32
31
  ApiError,
33
32
  BadGatewayError,
@@ -36,23 +35,30 @@ import {
36
35
  NotFoundError,
37
36
  UnprocessableEntityError,
38
37
  } from "./errors.ts";
38
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
39
39
  import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
40
- import {
41
- GithubEnterpriseClient,
42
- GithubEnterpriseError,
43
- type GithubEnterpriseErrorKind,
44
- type AppInstallation,
45
- } from "./github-enterprise-client.ts";
46
40
  import {
47
41
  GITHUB_ENTERPRISE_APP_ROLES,
48
42
  type GitHubEnterpriseAppMetadata,
49
43
  type GitHubEnterpriseAppRole,
50
44
  type GitHubEnterpriseAppService,
51
45
  } from "./github-enterprise-apps.ts";
46
+ import {
47
+ type AppInstallation,
48
+ GithubEnterpriseClient,
49
+ GithubEnterpriseError,
50
+ type GithubEnterpriseErrorKind,
51
+ } from "./github-enterprise-client.ts";
52
+ import { resolveValidation } from "./github-enterprise-warnings.ts";
52
53
  import { GithubLookupClient } from "./github-lookup-client.ts";
53
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
54
+ import {
55
+ type GithubLookupService,
56
+ type LookupInstallerPort,
57
+ type LookupRepositoriesPort,
58
+ listLookupRepositories,
59
+ } from "./github-lookup-repositories.ts";
60
+ import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
54
61
  import { ErrorSchema } from "./openapi-schemas.ts";
55
- import { resolveValidation } from "./github-enterprise-warnings.ts";
56
62
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
57
63
 
58
64
  // ─── Deps ─────────────────────────────────────────────────────────────────────
@@ -111,12 +117,10 @@ const AppMetadataSchema = z
111
117
  appId: z.string().openapi({ example: "12345" }),
112
118
  slug: z.string().openapi({ example: "example-installer" }),
113
119
  enterpriseSlug: z.string().nullable().openapi({ example: "acme" }),
114
- keySet: z
115
- .boolean()
116
- .openapi({
117
- description:
118
- "True when a private key is stored. The key is never returned.",
119
- }),
120
+ keySet: z.boolean().openapi({
121
+ description:
122
+ "True when a private key is stored. The key is never returned.",
123
+ }),
120
124
  lastValidationStatus: z.string().nullable().openapi({ example: "valid" }),
121
125
  lastValidatedAt: z.string().nullable(),
122
126
  lastValidationError: z.string().nullable(),
@@ -137,21 +141,14 @@ const PutAppBodySchema = z
137
141
  .object({
138
142
  appId: z.string().regex(/^\d+$/).openapi({ example: "12345" }),
139
143
  slug: z.string().regex(SLUG_RE).openapi({ example: "example-installer" }),
140
- enterpriseSlug: z
141
- .string()
142
- .regex(SLUG_RE)
143
- .nullish()
144
- .openapi({
145
- description: "Required for the installer role.",
146
- example: "acme",
147
- }),
148
- privateKey: z
149
- .string()
150
- .min(1)
151
- .openapi({
152
- description:
153
- "PEM private key. Write-only: encrypted at rest, never returned.",
154
- }),
144
+ enterpriseSlug: z.string().regex(SLUG_RE).nullish().openapi({
145
+ description: "Required for the installer role.",
146
+ example: "acme",
147
+ }),
148
+ privateKey: z.string().min(1).openapi({
149
+ description:
150
+ "PEM private key. Write-only: encrypted at rest, never returned.",
151
+ }),
155
152
  })
156
153
  .openapi("PutGithubEnterpriseAppBody");
157
154
 
@@ -183,14 +180,10 @@ const OrgsResultSchema = z
183
180
  .object({
184
181
  configured: z.boolean(),
185
182
  agentAppSlug: z.string().nullable().optional(),
186
- agentAppReason: z
187
- .string()
188
- .nullable()
189
- .optional()
190
- .openapi({
191
- description:
192
- "Why the agent's App cannot be installed through the enterprise API (private App with no stored GH_APP_CLIENT_ID, or no App at all). Null when it can; present only with agentId.",
193
- }),
183
+ agentAppReason: z.string().nullable().optional().openapi({
184
+ description:
185
+ "Why the agent's App cannot be installed through the enterprise API (private App with no stored GH_APP_CLIENT_ID, or no App at all). Null when it can; present only with agentId.",
186
+ }),
194
187
  orgs: z.array(
195
188
  z.object({
196
189
  id: z.number(),
@@ -199,12 +192,9 @@ const OrgsResultSchema = z
199
192
  .boolean()
200
193
  .nullable()
201
194
  .openapi({ description: "Null when no lookup App is configured." }),
202
- agentAppInstalled: z
203
- .boolean()
204
- .nullable()
205
- .openapi({
206
- description: "Null when no agentId (or no slug) was given.",
207
- }),
195
+ agentAppInstalled: z.boolean().nullable().openapi({
196
+ description: "Null when no agentId (or no slug) was given.",
197
+ }),
208
198
  }),
209
199
  ),
210
200
  })
@@ -500,6 +490,63 @@ export function createGithubAccessPreview(
500
490
  };
501
491
  }
502
492
 
493
+ /** Backs AdminPlatformServices.githubLookup (SCR-1.7). */
494
+ export function createGithubLookupService(
495
+ deps: Pick<
496
+ GithubEnterpriseApiDeps,
497
+ "appService" | "fetchFn" | "apiBase" | "now"
498
+ > & {
499
+ /** Test seam: replaces the clients built from the stored Apps. */
500
+ clients?: {
501
+ installer: LookupInstallerPort;
502
+ lookup: LookupRepositoriesPort;
503
+ };
504
+ },
505
+ ): GithubLookupService {
506
+ return {
507
+ async listRepositories() {
508
+ let clients = deps.clients;
509
+ if (!clients) {
510
+ const [installer, lookup] = await Promise.all([
511
+ deps.appService.get("installer"),
512
+ deps.appService.get("lookup"),
513
+ ]);
514
+ if (!installer || !lookup || !installer.enterpriseSlug) {
515
+ return { configured: false, repos: [] };
516
+ }
517
+ const [installerKey, lookupKey] = await Promise.all([
518
+ deps.appService.getPrivateKey("installer"),
519
+ deps.appService.getPrivateKey("lookup"),
520
+ ]);
521
+ if (!installerKey || !lookupKey)
522
+ return { configured: false, repos: [] };
523
+ const common = {
524
+ apiBase: deps.apiBase,
525
+ fetchFn: deps.fetchFn,
526
+ now: deps.now,
527
+ };
528
+ clients = {
529
+ installer: new GithubEnterpriseClient({
530
+ appId: installer.appId,
531
+ enterprise: installer.enterpriseSlug,
532
+ privateKey: installerKey,
533
+ ...common,
534
+ }),
535
+ lookup: new GithubLookupClient({
536
+ appId: lookup.appId,
537
+ privateKey: lookupKey,
538
+ ...common,
539
+ }),
540
+ };
541
+ }
542
+ return {
543
+ configured: true,
544
+ repos: await listLookupRepositories(clients.installer, clients.lookup),
545
+ };
546
+ },
547
+ };
548
+ }
549
+
503
550
  // ─── App ──────────────────────────────────────────────────────────────────────
504
551
 
505
552
  export function createGithubEnterpriseApp(
@@ -0,0 +1,178 @@
1
+ /**
2
+ * admin/src/github-lookup-repositories.integration.test.ts
3
+ * The AdminPlatformServices.githubLookup lister over a real GithubLookupClient
4
+ * replaying hand-authored responses through an injected fetchFn (no global
5
+ * fetch override). The installer side is a stub org list. RSA key generated
6
+ * in-test.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { generateKeyPairSync } from "node:crypto";
11
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
12
+ import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
13
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
14
+ import { GithubLookupClient } from "./github-lookup-client.ts";
15
+
16
+ const { privateKey } = generateKeyPairSync("rsa", {
17
+ modulusLength: 2048,
18
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
19
+ publicKeyEncoding: { type: "spki", format: "pem" },
20
+ });
21
+
22
+ const NOW = new Date("2026-11-09T12:00:00Z");
23
+ const INSTALLATIONS: Record<string, number> = { acme: 1, beta: 2 };
24
+
25
+ const repo = (owner: string, name: string, archived = false, id = 1) => ({
26
+ id,
27
+ name,
28
+ full_name: `${owner}/${name}`,
29
+ private: true,
30
+ archived,
31
+ });
32
+
33
+ type Handler = (url: URL, installId?: number) => Response;
34
+
35
+ /** Replays the org-installation, token and repository-list endpoints. */
36
+ function replay(repos: Handler) {
37
+ return (async (input: RequestInfo | URL, init?: RequestInit) => {
38
+ const u = new URL(input.toString());
39
+ const method = init?.method ?? "GET";
40
+ const inst = u.pathname.match(/^\/orgs\/([^/]+)\/installation$/);
41
+ if (inst) {
42
+ const id = INSTALLATIONS[inst[1]];
43
+ return id
44
+ ? Response.json({ id, repository_selection: "all" })
45
+ : Response.json({ message: "Not Found" }, { status: 404 });
46
+ }
47
+ const mint = u.pathname.match(
48
+ /^\/app\/installations\/(\d+)\/access_tokens$/,
49
+ );
50
+ if (mint && method === "POST") {
51
+ return Response.json({
52
+ token: `ghs_tok${mint[1]}`,
53
+ expires_at: "2026-11-09T13:00:00Z",
54
+ });
55
+ }
56
+ if (u.pathname === "/installation/repositories") {
57
+ const bearer = String(new Headers(init?.headers).get("authorization"));
58
+ return repos(u, Number(bearer.replace(/\D/g, "")));
59
+ }
60
+ return Response.json({ message: "Not Found" }, { status: 404 });
61
+ }) as unknown as typeof fetch;
62
+ }
63
+
64
+ function service(orgs: string[], fetchFn: typeof fetch) {
65
+ return createGithubLookupService({
66
+ appService: {} as never,
67
+ clients: {
68
+ installer: {
69
+ listInstallableOrganizations: async () =>
70
+ orgs.map((login) => ({ login })),
71
+ },
72
+ lookup: new GithubLookupClient({
73
+ appId: "555",
74
+ privateKey,
75
+ fetchFn,
76
+ now: () => NOW,
77
+ }),
78
+ },
79
+ });
80
+ }
81
+
82
+ describe("githubLookup.listRepositories", () => {
83
+ it("lists repos across multiple orgs, carrying archived", async () => {
84
+ const svc = service(
85
+ ["acme", "beta"],
86
+ replay((_u, id) =>
87
+ Response.json({
88
+ repositories:
89
+ id === 1
90
+ ? [repo("acme", "api", false, 10), repo("acme", "old", true, 11)]
91
+ : [repo("beta", "web", false, 20)],
92
+ }),
93
+ ),
94
+ );
95
+ expect(await svc.listRepositories()).toEqual({
96
+ configured: true,
97
+ repos: [
98
+ { fullName: "acme/api", archived: false },
99
+ { fullName: "acme/old", archived: true },
100
+ { fullName: "beta/web", archived: false },
101
+ ],
102
+ });
103
+ });
104
+
105
+ it("follows pagination within an org", async () => {
106
+ const page1 = Array.from({ length: 100 }, (_, i) =>
107
+ repo("acme", `r${i}`, false, i),
108
+ );
109
+ const svc = service(
110
+ ["acme"],
111
+ replay((u) =>
112
+ u.searchParams.get("page") === "1"
113
+ ? Response.json(
114
+ { repositories: page1 },
115
+ { headers: { link: '<https://x/?page=2>; rel="next"' } },
116
+ )
117
+ : Response.json({ repositories: [repo("acme", "last", false, 999)] }),
118
+ ),
119
+ );
120
+ const out = await svc.listRepositories();
121
+ expect(out.repos).toHaveLength(101);
122
+ expect(out.repos.at(-1)).toEqual({
123
+ fullName: "acme/last",
124
+ archived: false,
125
+ });
126
+ });
127
+
128
+ it("skips an org without the lookup App installed", async () => {
129
+ const svc = service(
130
+ ["ghost", "acme"],
131
+ replay(() => Response.json({ repositories: [repo("acme", "api")] })),
132
+ );
133
+ expect((await svc.listRepositories()).repos).toEqual([
134
+ { fullName: "acme/api", archived: false },
135
+ ]);
136
+ });
137
+
138
+ it("returns configured:false with no repos when the Apps are not set", async () => {
139
+ const svc = createGithubLookupService({
140
+ appService: {
141
+ get: async () => null,
142
+ getPrivateKey: async () => null,
143
+ } as unknown as GitHubEnterpriseAppService,
144
+ });
145
+ expect(await svc.listRepositories()).toEqual({
146
+ configured: false,
147
+ repos: [],
148
+ });
149
+ });
150
+
151
+ it("rejects on a GitHub error instead of returning an empty list", async () => {
152
+ const svc = service(
153
+ ["acme"],
154
+ replay(() => Response.json({ message: "boom" }, { status: 500 })),
155
+ );
156
+ const err = await svc.listRepositories().then(
157
+ () => null,
158
+ (e) => e,
159
+ );
160
+ expect(err).toBeInstanceOf(GithubEnterpriseError);
161
+ expect((err as GithubEnterpriseError).kind).toBe("server");
162
+ });
163
+
164
+ it("rejects when listing installable organizations fails", async () => {
165
+ const svc = createGithubLookupService({
166
+ appService: {} as never,
167
+ clients: {
168
+ installer: {
169
+ listInstallableOrganizations: async () => {
170
+ throw new GithubEnterpriseError("rate_limit", "limited");
171
+ },
172
+ },
173
+ lookup: { listInstallationRepositories: async () => [] },
174
+ },
175
+ });
176
+ await expect(svc.listRepositories()).rejects.toThrow("limited");
177
+ });
178
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * admin/src/github-lookup-repositories.ts
3
+ * The lookup-App repository lister exposed to extensions as
4
+ * AdminPlatformServices.githubLookup: every repository the lookup App can see,
5
+ * across the organizations the installer App can reach.
6
+ *
7
+ * A GitHub failure rejects; it is never reported as an empty list. An org
8
+ * without the lookup App installed (not_found) is skipped. The stored-App
9
+ * wiring (key-bearing) lives in github-enterprise-api.ts.
10
+ */
11
+
12
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
13
+ import type { LookupRepository } from "./github-lookup-client.ts";
14
+
15
+ export interface GithubLookupRepository {
16
+ fullName: string;
17
+ archived: boolean;
18
+ }
19
+
20
+ export interface GithubLookupRepositories {
21
+ configured: boolean;
22
+ repos: GithubLookupRepository[];
23
+ }
24
+
25
+ /** The extension-facing lister (optional member of AdminPlatformServices). */
26
+ export interface GithubLookupService {
27
+ listRepositories(): Promise<GithubLookupRepositories>;
28
+ }
29
+
30
+ /** The installer-side client surface the lister needs. */
31
+ export interface LookupInstallerPort {
32
+ listInstallableOrganizations(): Promise<{ login: string }[]>;
33
+ }
34
+
35
+ /** The lookup-side client surface the lister needs. */
36
+ export interface LookupRepositoriesPort {
37
+ listInstallationRepositories(org: string): Promise<LookupRepository[]>;
38
+ }
39
+
40
+ export async function listLookupRepositories(
41
+ installer: LookupInstallerPort,
42
+ lookup: LookupRepositoriesPort,
43
+ ): Promise<GithubLookupRepository[]> {
44
+ const repos = new Map<string, GithubLookupRepository>();
45
+ for (const { login } of await installer.listInstallableOrganizations()) {
46
+ let rows: LookupRepository[];
47
+ try {
48
+ rows = await lookup.listInstallationRepositories(login);
49
+ } catch (e) {
50
+ // No lookup App installation on this org: nothing to list.
51
+ if (e instanceof GithubEnterpriseError && e.kind === "not_found")
52
+ continue;
53
+ throw e;
54
+ }
55
+ for (const r of rows) {
56
+ repos.set(r.fullName, { fullName: r.fullName, archived: r.archived });
57
+ }
58
+ }
59
+ return [...repos.values()];
60
+ }