@app-vitals/agent-admin 1.79.0 → 1.80.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.79.0",
3
+ "version": "1.80.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@anthropic-ai/sdk": "0.137.0",
46
- "@app-vitals/agent-lib": "1.79.0",
46
+ "@app-vitals/agent-lib": "1.80.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -115,6 +115,7 @@ import {
115
115
  createGithubSync,
116
116
  } from "./github-installation-wiring.ts";
117
117
 
118
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
118
119
  import { PrincipalLookupService } from "./principal-lookup.ts";
119
120
  import { createPrincipalsApp } from "./principals-api.ts";
120
121
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
@@ -422,6 +423,7 @@ export async function startAdmin(
422
423
  provisioner,
423
424
  githubLookup: createGithubLookupService({
424
425
  appService: githubEnterpriseAppService,
426
+ cache: new GitHubRepoCacheService(prisma),
425
427
  }),
426
428
  },
427
429
  };
@@ -53,10 +53,9 @@ import { resolveValidation } from "./github-enterprise-warnings.ts";
53
53
  import { GithubLookupClient } from "./github-lookup-client.ts";
54
54
  import {
55
55
  type GithubLookupService,
56
- type LookupInstallerPort,
57
- type LookupRepositoriesPort,
58
- listLookupRepositories,
56
+ summarizeLookupSnapshots,
59
57
  } from "./github-lookup-repositories.ts";
58
+ import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
60
59
  import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
61
60
  import { ErrorSchema } from "./openapi-schemas.ts";
62
61
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
@@ -509,67 +508,41 @@ export function createGithubAccessPreview(
509
508
  };
510
509
  }
511
510
 
512
- /** Backs AdminPlatformServices.githubLookup (SCR-1.7). */
511
+ /** Backs AdminPlatformServices.githubLookup: reads the repo cache, never GitHub. */
513
512
  export function createGithubLookupService(
514
- deps: Pick<
515
- GithubEnterpriseApiDeps,
516
- "appService" | "fetchFn" | "apiBase" | "now"
517
- > & {
518
- /** Test seam: replaces the clients built from the stored Apps. */
519
- clients?: {
520
- installer?: LookupInstallerPort;
521
- lookup: LookupRepositoriesPort;
522
- };
513
+ deps: Pick<GithubEnterpriseApiDeps, "appService" | "now"> & {
514
+ cache: Pick<GitHubRepoCacheService, "listLookupSnapshots">;
515
+ /** Age past which a completed crawl reads as stale. */
516
+ ttlMs?: number;
523
517
  },
524
518
  ): GithubLookupService {
525
519
  return {
526
520
  async listRepositories(accountId) {
527
- let clients = deps.clients;
528
- if (!clients) {
529
- const [installer, lookup] = await Promise.all([
530
- deps.appService.get("installer", accountId),
531
- deps.appService.get("lookup", accountId),
532
- ]);
533
- if (!lookup) return { configured: false, repos: [] };
534
- const lookupKey = await deps.appService.getPrivateKey(
535
- "lookup",
536
- accountId,
537
- );
538
- if (!lookupKey) return { configured: false, repos: [] };
539
- const common = {
540
- apiBase: deps.apiBase,
541
- fetchFn: deps.fetchFn,
542
- now: deps.now,
543
- };
544
- // An installer with an enterprise slug supplies the org list; without
545
- // one the lookup App lists the orgs it is installed on.
546
- const installerKey = installer?.enterpriseSlug
547
- ? await deps.appService.getPrivateKey("installer", accountId)
548
- : null;
549
- if (installer?.enterpriseSlug && !installerKey) {
550
- return { configured: false, repos: [] };
551
- }
552
- clients = {
553
- installer:
554
- installer?.enterpriseSlug && installerKey
555
- ? new GithubEnterpriseClient({
556
- appId: installer.appId,
557
- enterprise: installer.enterpriseSlug,
558
- privateKey: installerKey,
559
- ...common,
560
- })
561
- : undefined,
562
- lookup: new GithubLookupClient({
563
- appId: lookup.appId,
564
- privateKey: lookupKey,
565
- ...common,
566
- }),
567
- };
521
+ const [installer, lookup] = await Promise.all([
522
+ deps.appService.get("installer", accountId),
523
+ deps.appService.get("lookup", accountId),
524
+ ]);
525
+ if (!lookup) return { configured: false, repos: [] };
526
+ const [lookupKey, installerKey] = await Promise.all([
527
+ deps.appService.getPrivateKey("lookup", accountId),
528
+ installer?.enterpriseSlug
529
+ ? deps.appService.getPrivateKey("installer", accountId)
530
+ : null,
531
+ ]);
532
+ if (!lookupKey || (installer?.enterpriseSlug && !installerKey)) {
533
+ return { configured: false, repos: [] };
568
534
  }
569
- return {
570
- configured: true,
571
- repos: await listLookupRepositories(clients.installer, clients.lookup),
572
- };
535
+ // The crawler files a deployment-wide App's snapshots under accountId "".
536
+ const accountIds = accountId ? [accountId, ""] : [""];
537
+ const snapshots = await deps.cache.listLookupSnapshots(
538
+ accountIds,
539
+ lookup.appId,
540
+ );
541
+ return summarizeLookupSnapshots(
542
+ snapshots,
543
+ (deps.now ?? (() => new Date()))(),
544
+ deps.ttlMs,
545
+ );
573
546
  },
574
547
  };
575
548
  }
@@ -1,391 +1,86 @@
1
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.
2
+ * Integration: githubLookup.listRepositories over a real repo cache. Requires
3
+ * DATABASE_URL_ADMIN_TEST; skips otherwise. A throwing fetch proves no GitHub
4
+ * call is made.
7
5
  */
8
6
 
9
- import { describe, expect, it } from "bun:test";
10
- import { generateKeyPairSync } from "node:crypto";
7
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
9
  import { createGithubLookupService } from "./github-enterprise-api.ts";
12
10
  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,
11
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
12
+ import { createAdminPrismaClient } from "./prisma-client.ts";
13
+
14
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
15
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
16
+
17
+ const NOW = new Date("2026-11-20T12:00:00Z");
18
+ const key = (org: string) => ({
19
+ accountId: "acct",
20
+ appKind: "lookup" as const,
21
+ appRef: "555",
22
+ org,
31
23
  });
32
24
 
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 === "/app/installations") {
57
- return Response.json(
58
- Object.entries(INSTALLATIONS).map(([login, id]) => ({
59
- id,
60
- account: { login, type: "Organization" },
61
- })),
62
- );
63
- }
64
- if (u.pathname === "/installation/repositories") {
65
- const bearer = String(new Headers(init?.headers).get("authorization"));
66
- return repos(u, Number(bearer.replace(/\D/g, "")));
67
- }
68
- return Response.json({ message: "Not Found" }, { status: 404 });
69
- }) as unknown as typeof fetch;
70
- }
71
-
72
- function service(orgs: string[], fetchFn: typeof fetch) {
73
- return createGithubLookupService({
74
- appService: {} as never,
75
- clients: {
76
- installer: {
77
- listInstallableOrganizations: async () =>
78
- orgs.map((login) => ({ login })),
79
- },
80
- lookup: new GithubLookupClient({
81
- appId: "555",
82
- privateKey,
83
- fetchFn,
84
- now: () => NOW,
85
- }),
86
- },
87
- });
88
- }
89
-
90
- describe("githubLookup.listRepositories", () => {
91
- it("lists repos across multiple orgs, carrying archived", async () => {
92
- const svc = service(
93
- ["acme", "beta"],
94
- replay((_u, id) =>
95
- Response.json({
96
- repositories:
97
- id === 1
98
- ? [repo("acme", "api", false, 10), repo("acme", "old", true, 11)]
99
- : [repo("beta", "web", false, 20)],
100
- }),
101
- ),
102
- );
103
- expect(await svc.listRepositories()).toEqual({
104
- configured: true,
105
- repos: [
106
- { fullName: "acme/api", archived: false },
107
- { fullName: "acme/old", archived: true },
108
- { fullName: "beta/web", archived: false },
109
- ],
110
- });
111
- });
112
-
113
- it("follows pagination within an org", async () => {
114
- const page1 = Array.from({ length: 100 }, (_, i) =>
115
- repo("acme", `r${i}`, false, i),
116
- );
117
- const svc = service(
118
- ["acme"],
119
- replay((u) =>
120
- u.searchParams.get("page") === "1"
121
- ? Response.json(
122
- { repositories: page1 },
123
- { headers: { link: '<https://x/?page=2>; rel="next"' } },
124
- )
125
- : Response.json({ repositories: [repo("acme", "last", false, 999)] }),
126
- ),
127
- );
128
- const out = await svc.listRepositories();
129
- expect(out.repos).toHaveLength(101);
130
- expect(out.repos.at(-1)).toEqual({
131
- fullName: "acme/last",
132
- archived: false,
133
- });
134
- });
25
+ describeOrSkip("githubLookup.listRepositories (cache, integration)", () => {
26
+ let prisma: PrismaClient;
27
+ let cache: GitHubRepoCacheService;
28
+ const realFetch = globalThis.fetch;
135
29
 
136
- it("skips an org without the lookup App installed", async () => {
137
- const svc = service(
138
- ["ghost", "acme"],
139
- replay(() => Response.json({ repositories: [repo("acme", "api")] })),
140
- );
141
- expect((await svc.listRepositories()).repos).toEqual([
142
- { fullName: "acme/api", archived: false },
143
- ]);
144
- });
145
-
146
- it("returns configured:false with no repos when the Apps are not set", async () => {
147
- const svc = createGithubLookupService({
30
+ const svc = () =>
31
+ createGithubLookupService({
148
32
  appService: {
149
- get: async () => null,
150
- getPrivateKey: async () => null,
33
+ get: async (role: string) =>
34
+ role === "lookup" ? { appId: "555", enterpriseSlug: null } : null,
35
+ getPrivateKey: async (role: string) =>
36
+ role === "lookup" ? "pem" : null,
151
37
  } as unknown as GitHubEnterpriseAppService,
152
- });
153
- expect(await svc.listRepositories()).toEqual({
154
- configured: false,
155
- repos: [],
156
- });
157
- });
158
-
159
- it("rejects on a GitHub error instead of returning an empty list", async () => {
160
- const svc = service(
161
- ["acme"],
162
- replay(() => Response.json({ message: "boom" }, { status: 500 })),
163
- );
164
- const err = await svc.listRepositories().then(
165
- () => null,
166
- (e) => e,
167
- );
168
- expect(err).toBeInstanceOf(GithubEnterpriseError);
169
- expect((err as GithubEnterpriseError).kind).toBe("server");
170
- });
171
-
172
- it("rejects when listing installable organizations fails", async () => {
173
- const svc = createGithubLookupService({
174
- appService: {} as never,
175
- clients: {
176
- installer: {
177
- listInstallableOrganizations: async () => {
178
- throw new GithubEnterpriseError("rate_limit", "limited");
179
- },
180
- },
181
- lookup: { listInstallationRepositories: async () => [] },
182
- },
183
- });
184
- await expect(svc.listRepositories()).rejects.toThrow("limited");
185
- });
186
-
187
- describe("without an installer", () => {
188
- const lookupApp = { appId: "555", enterpriseSlug: null };
189
- const stored = (installer: unknown) =>
190
- ({
191
- get: async (kind: string) =>
192
- kind === "lookup" ? lookupApp : installer,
193
- getPrivateKey: async (kind: string) =>
194
- kind === "lookup" || installer ? privateKey : null,
195
- }) as unknown as GitHubEnterpriseAppService;
196
-
197
- it("lists repos from every org the lookup App is installed on", async () => {
198
- const svc = createGithubLookupService({
199
- appService: stored(null),
200
- fetchFn: replay((_u, id) =>
201
- Response.json({
202
- repositories:
203
- id === 1
204
- ? [repo("acme", "api", false, 10)]
205
- : [repo("beta", "web", false, 20)],
206
- }),
207
- ),
208
- now: () => NOW,
209
- });
210
- expect(await svc.listRepositories()).toEqual({
211
- configured: true,
212
- repos: [
213
- { fullName: "acme/api", archived: false },
214
- { fullName: "beta/web", archived: false },
215
- ],
216
- });
217
- });
218
-
219
- it("lists only the selected repos of a selected-scope installation", async () => {
220
- const svc = createGithubLookupService({
221
- appService: stored(null),
222
- fetchFn: replay((_u, id) =>
223
- Response.json({
224
- repositories: id === 1 ? [repo("acme", "only-this")] : [],
225
- }),
226
- ),
227
- now: () => NOW,
228
- });
229
- expect((await svc.listRepositories()).repos).toEqual([
230
- { fullName: "acme/only-this", archived: false },
231
- ]);
232
- });
233
-
234
- it("rejects on a GitHub failure instead of returning an empty list", async () => {
235
- const svc = createGithubLookupService({
236
- appService: stored(null),
237
- fetchFn: (async () =>
238
- Response.json(
239
- { message: "boom" },
240
- { status: 500 },
241
- )) as unknown as typeof fetch,
242
- now: () => NOW,
243
- });
244
- await expect(svc.listRepositories()).rejects.toBeInstanceOf(
245
- GithubEnterpriseError,
246
- );
247
- });
248
-
249
- it("an installer with a slug but no key stays unconfigured", async () => {
250
- const svc = createGithubLookupService({
251
- appService: {
252
- get: async (kind: string) =>
253
- kind === "lookup"
254
- ? lookupApp
255
- : { appId: "1", enterpriseSlug: "ent" },
256
- getPrivateKey: async (kind: string) =>
257
- kind === "lookup" ? privateKey : null,
258
- } as unknown as GitHubEnterpriseAppService,
259
- });
260
- expect(await svc.listRepositories()).toEqual({
261
- configured: false,
262
- repos: [],
263
- });
38
+ cache,
39
+ now: () => NOW,
264
40
  });
265
41
 
266
- it("with an installer configured the org list still comes from it", async () => {
267
- const svc = service(
268
- ["acme"],
269
- replay(() => Response.json({ repositories: [repo("acme", "api")] })),
270
- );
271
- expect((await svc.listRepositories()).repos).toEqual([
272
- { fullName: "acme/api", archived: false },
273
- ]);
274
- });
42
+ beforeEach(async () => {
43
+ prisma = createAdminPrismaClient(TEST_DB as string);
44
+ await prisma.gitHubCachedRepo.deleteMany();
45
+ await prisma.gitHubRepoSnapshot.deleteMany();
46
+ cache = new GitHubRepoCacheService(prisma, { now: () => NOW });
47
+ globalThis.fetch = (() => {
48
+ throw new Error("GitHub must not be called");
49
+ }) as unknown as typeof fetch;
275
50
  });
276
- });
277
-
278
- describe("githubLookup.listRepositories(accountId)", () => {
279
- type Row = { appId: string; enterpriseSlug: string | null };
280
- /** In-memory app service with the real account-then-deployment-wide fallback. */
281
- function scopedApps(rows: Record<string, Row | undefined>) {
282
- const key = (role: string, accountId?: string | null) =>
283
- `${accountId ?? ""}:${role}`;
284
- const resolve = (role: string, accountId?: string | null) =>
285
- (accountId ? rows[key(role, accountId)] : undefined) ??
286
- rows[key(role, null)];
287
- return {
288
- get: async (role: string, accountId?: string | null) =>
289
- resolve(role, accountId) ?? null,
290
- getPrivateKey: async (role: string, accountId?: string | null) =>
291
- resolve(role, accountId) ? privateKey : null,
292
- } as unknown as GitHubEnterpriseAppService;
293
- }
294
51
 
295
- /** The lookup App id (JWT iss) decides which org installation it sees. */
296
- const byApp: typeof fetch = (async (
297
- input: RequestInfo | URL,
298
- init?: RequestInit,
299
- ) => {
300
- const u = new URL(input.toString());
301
- const bearer = String(new Headers(init?.headers).get("authorization"));
302
- const jwt = bearer.replace(/^Bearer /, "");
303
- if (u.pathname === "/app/installations") {
304
- const iss = JSON.parse(
305
- Buffer.from(jwt.split(".")[1], "base64url").toString(),
306
- ).iss;
307
- const org = String(iss) === "777" ? "gamma" : "acme";
308
- return Response.json([
309
- {
310
- id: org === "gamma" ? 3 : 1,
311
- account: { login: org, type: "Organization" },
312
- },
313
- ]);
314
- }
315
- const inst = u.pathname.match(/^\/orgs\/([^/]+)\/installation$/);
316
- if (inst) {
317
- return Response.json({
318
- id: inst[1] === "gamma" ? 3 : 1,
319
- repository_selection: "all",
320
- });
321
- }
322
- if (u.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/)) {
323
- const id = u.pathname.match(/installations\/(\d+)/)?.[1];
324
- return Response.json({
325
- token: `ghs_tok${id}`,
326
- expires_at: "2026-11-09T13:00:00Z",
327
- });
328
- }
329
- if (u.pathname === "/installation/repositories") {
330
- return Response.json({
331
- repositories: bearer.endsWith("tok3")
332
- ? [repo("gamma", "tenant", false, 30)]
333
- : [repo("acme", "shared", false, 10)],
334
- });
335
- }
336
- return Response.json({ message: "Not Found" }, { status: 404 });
337
- }) as unknown as typeof fetch;
338
-
339
- const lookup = (appId: string): Row => ({ appId, enterpriseSlug: null });
340
-
341
- it("lists through the account's own lookup App", async () => {
342
- const svc = createGithubLookupService({
343
- appService: scopedApps({
344
- ":lookup": lookup("555"),
345
- "acct-1:lookup": lookup("777"),
346
- }),
347
- fetchFn: byApp,
348
- now: () => NOW,
349
- });
350
- expect((await svc.listRepositories("acct-1")).repos).toEqual([
351
- { fullName: "gamma/tenant", archived: false },
352
- ]);
52
+ afterEach(async () => {
53
+ globalThis.fetch = realFetch;
54
+ await prisma.$disconnect();
353
55
  });
354
56
 
355
- it("falls back to the deployment-wide pair when the account has none", async () => {
356
- const svc = createGithubLookupService({
357
- appService: scopedApps({ ":lookup": lookup("555") }),
358
- fetchFn: byApp,
359
- now: () => NOW,
57
+ it("cold start returns an empty syncing result", async () => {
58
+ expect(await svc().listRepositories("acct")).toEqual({
59
+ configured: true,
60
+ repos: [],
61
+ syncState: "syncing",
360
62
  });
361
- expect((await svc.listRepositories("acct-2")).repos).toEqual([
362
- { fullName: "acme/shared", archived: false },
363
- ]);
364
63
  });
365
64
 
366
- it("with no argument uses the deployment-wide pair, ignoring account rows", async () => {
367
- const svc = createGithubLookupService({
368
- appService: scopedApps({
369
- ":lookup": lookup("555"),
370
- "acct-1:lookup": lookup("777"),
371
- }),
372
- fetchFn: byApp,
373
- now: () => NOW,
65
+ it("serves a partial crawl with progress, then a completed one as ready", async () => {
66
+ const snap = await cache.upsertSnapshot(key("acme"), {
67
+ crawlPage: 1,
68
+ crawlStartedAt: NOW,
69
+ totalCount: 2,
374
70
  });
375
- expect((await svc.listRepositories()).repos).toEqual([
376
- { fullName: "acme/shared", archived: false },
71
+ await cache.upsertRepos(snap.id, [{ githubId: 1, fullName: "acme/a" }]);
72
+ const partial = await svc().listRepositories("acct");
73
+ expect(partial.syncState).toBe("syncing");
74
+ expect(partial.repos).toEqual([{ fullName: "acme/a", archived: false }]);
75
+ expect(partial.progress).toEqual({ reposSeen: 1, totalCount: 2 });
76
+
77
+ await cache.upsertRepos(snap.id, [
78
+ { githubId: 2, fullName: "acme/b", archived: true },
377
79
  ]);
378
- });
379
-
380
- it("is unconfigured when neither the account nor the deployment has a lookup App", async () => {
381
- const svc = createGithubLookupService({
382
- appService: scopedApps({}),
383
- fetchFn: byApp,
384
- now: () => NOW,
385
- });
386
- expect(await svc.listRepositories("acct-1")).toEqual({
387
- configured: false,
388
- repos: [],
389
- });
80
+ await cache.upsertSnapshot(key("acme"), { completedAt: NOW });
81
+ const done = await svc().listRepositories("acct");
82
+ expect(done.syncState).toBe("ready");
83
+ expect(done.repos).toHaveLength(2);
84
+ expect(done.fetchedAt).toEqual(NOW);
390
85
  });
391
86
  });
@@ -1,26 +1,37 @@
1
1
  /**
2
2
  * admin/src/github-lookup-repositories.ts
3
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, or, with no
6
- * installer configured, the organizations the lookup App is installed on.
4
+ * AdminPlatformServices.githubLookup. It reads the cached crawl snapshots
5
+ * (GLC-1.2 crawler) and never calls GitHub, so a GitHub outage or rate limit
6
+ * cannot fail it; the crawl state is reported in optional fields instead.
7
7
  *
8
- * A GitHub failure rejects; it is never reported as an empty list. An org
9
- * without the lookup App installed (not_found) is skipped. The stored-App
10
- * wiring (key-bearing) lives in github-enterprise-api.ts.
8
+ * A configured account with no snapshot yet returns an empty list with
9
+ * syncState "syncing" (older consumers treat that as their existing empty-list
10
+ * path). The stored-App wiring lives in github-enterprise-api.ts.
11
11
  */
12
12
 
13
- import { GithubEnterpriseError } from "./github-enterprise-client.ts";
14
- import type { LookupRepository } from "./github-lookup-client.ts";
15
-
16
13
  export interface GithubLookupRepository {
17
14
  fullName: string;
18
15
  archived: boolean;
19
16
  }
20
17
 
18
+ /** syncing: a crawl is incomplete; ready: complete and fresh; stale: complete but past the TTL; failed: the last crawl errored. */
19
+ export type GithubLookupSyncState = "syncing" | "ready" | "stale" | "failed";
20
+
21
+ export interface GithubLookupProgress {
22
+ reposSeen: number;
23
+ /** Sum of GitHub's total_count across orgs; absent until every org reports one. */
24
+ totalCount?: number;
25
+ }
26
+
21
27
  export interface GithubLookupRepositories {
22
28
  configured: boolean;
23
29
  repos: GithubLookupRepository[];
30
+ /** Optional: consumers that predate the cache ignore these. */
31
+ syncState?: GithubLookupSyncState;
32
+ /** Oldest completed crawl across orgs; absent until one has completed. */
33
+ fetchedAt?: Date;
34
+ progress?: GithubLookupProgress;
24
35
  }
25
36
 
26
37
  /** The extension-facing lister (optional member of AdminPlatformServices). */
@@ -31,48 +42,65 @@ export interface GithubLookupService {
31
42
  ): Promise<GithubLookupRepositories>;
32
43
  }
33
44
 
34
- /** The installer-side client surface the lister needs. */
35
- export interface LookupInstallerPort {
36
- listInstallableOrganizations(): Promise<{ login: string }[]>;
45
+ /** One org's cached snapshot with its repos. */
46
+ export interface LookupSnapshotView {
47
+ completedAt: Date | null;
48
+ totalCount: number | null;
49
+ lastError: string | null;
50
+ repos: GithubLookupRepository[];
37
51
  }
38
52
 
39
- /** The lookup-side client surface the lister needs. */
40
- export interface LookupRepositoriesPort {
41
- listInstallationRepositories(org: string): Promise<LookupRepository[]>;
42
- /** Required only when no installer is configured (the App lists its own orgs). */
43
- listInstallations?(): Promise<{ login: string }[]>;
44
- }
53
+ /** Default age after which a completed crawl is reported stale (hourly refresh). */
54
+ export const DEFAULT_LOOKUP_TTL_MS = 3_600_000;
45
55
 
46
- export async function listLookupRepositories(
47
- installer: LookupInstallerPort | undefined,
48
- lookup: LookupRepositoriesPort,
49
- ): Promise<GithubLookupRepository[]> {
56
+ /** Folds per-org snapshots into one result: failed > syncing > stale > ready. */
57
+ export function summarizeLookupSnapshots(
58
+ snapshots: LookupSnapshotView[],
59
+ now: Date,
60
+ ttlMs: number = DEFAULT_LOOKUP_TTL_MS,
61
+ ): GithubLookupRepositories {
62
+ if (snapshots.length === 0) {
63
+ return { configured: true, repos: [], syncState: "syncing" };
64
+ }
50
65
  const repos = new Map<string, GithubLookupRepository>();
51
- const orgs = installer
52
- ? await installer.listInstallableOrganizations()
53
- : await listOwnInstallations(lookup);
54
- for (const { login } of orgs) {
55
- let rows: LookupRepository[];
56
- try {
57
- rows = await lookup.listInstallationRepositories(login);
58
- } catch (e) {
59
- // No lookup App installation on this org: nothing to list.
60
- if (e instanceof GithubEnterpriseError && e.kind === "not_found")
61
- continue;
62
- throw e;
63
- }
64
- for (const r of rows) {
66
+ let reposSeen = 0;
67
+ let totalCount: number | undefined = 0;
68
+ let failed = false;
69
+ let incomplete = false;
70
+ let oldest: Date | undefined;
71
+ for (const s of snapshots) {
72
+ for (const r of s.repos) {
65
73
  repos.set(r.fullName, { fullName: r.fullName, archived: r.archived });
66
74
  }
75
+ reposSeen += s.repos.length;
76
+ totalCount =
77
+ totalCount === undefined || s.totalCount === null
78
+ ? undefined
79
+ : totalCount + s.totalCount;
80
+ if (s.completedAt) {
81
+ if (!oldest || s.completedAt < oldest) oldest = s.completedAt;
82
+ } else {
83
+ incomplete = true;
84
+ if (s.lastError) failed = true;
85
+ }
67
86
  }
68
- return [...repos.values()];
69
- }
70
-
71
- async function listOwnInstallations(
72
- lookup: LookupRepositoriesPort,
73
- ): Promise<{ login: string }[]> {
74
- if (!lookup.listInstallations) {
75
- throw new Error("lookup client cannot list its own installations");
76
- }
77
- return lookup.listInstallations();
87
+ const stale =
88
+ oldest !== undefined && now.getTime() - oldest.getTime() > ttlMs;
89
+ const syncState: GithubLookupSyncState = failed
90
+ ? "failed"
91
+ : incomplete
92
+ ? "syncing"
93
+ : stale
94
+ ? "stale"
95
+ : "ready";
96
+ return {
97
+ configured: true,
98
+ repos: [...repos.values()],
99
+ syncState,
100
+ ...(oldest && !incomplete ? { fetchedAt: oldest } : {}),
101
+ progress: {
102
+ reposSeen,
103
+ ...(totalCount === undefined ? {} : { totalCount }),
104
+ },
105
+ };
78
106
  }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * admin/src/github-lookup-repositories.unit.test.ts
3
+ * Cache-backed githubLookup: syncState derivation, the unconfigured cases and
4
+ * the guarantee that no GitHub call is made.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
9
+ import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
10
+ import {
11
+ type LookupSnapshotView,
12
+ summarizeLookupSnapshots,
13
+ } from "./github-lookup-repositories.ts";
14
+
15
+ const NOW = new Date("2026-11-20T12:00:00Z");
16
+ const ago = (ms: number) => new Date(NOW.getTime() - ms);
17
+ const MIN = 60_000;
18
+
19
+ const snap = (o: Partial<LookupSnapshotView> = {}): LookupSnapshotView => ({
20
+ completedAt: ago(10 * MIN),
21
+ totalCount: 2,
22
+ lastError: null,
23
+ repos: [
24
+ { fullName: "acme/a", archived: false },
25
+ { fullName: "acme/b", archived: true },
26
+ ],
27
+ ...o,
28
+ });
29
+
30
+ describe("summarizeLookupSnapshots", () => {
31
+ it("no snapshot yet: configured, empty, syncing", () => {
32
+ expect(summarizeLookupSnapshots([], NOW)).toEqual({
33
+ configured: true,
34
+ repos: [],
35
+ syncState: "syncing",
36
+ });
37
+ });
38
+
39
+ it("complete and fresh: ready with fetchedAt and progress", () => {
40
+ const r = summarizeLookupSnapshots([snap()], NOW);
41
+ expect(r.syncState).toBe("ready");
42
+ expect(r.fetchedAt).toEqual(ago(10 * MIN));
43
+ expect(r.progress).toEqual({ reposSeen: 2, totalCount: 2 });
44
+ expect(r.repos).toEqual([
45
+ { fullName: "acme/a", archived: false },
46
+ { fullName: "acme/b", archived: true },
47
+ ]);
48
+ });
49
+
50
+ it("complete but older than the TTL: stale, repos still served", () => {
51
+ const r = summarizeLookupSnapshots(
52
+ [snap({ completedAt: ago(61 * MIN) })],
53
+ NOW,
54
+ );
55
+ expect(r.syncState).toBe("stale");
56
+ expect(r.repos).toHaveLength(2);
57
+ });
58
+
59
+ it("honours a custom TTL", () => {
60
+ const r = summarizeLookupSnapshots([snap()], NOW, 5 * MIN);
61
+ expect(r.syncState).toBe("stale");
62
+ });
63
+
64
+ it("in-progress crawl: partial repos, syncing, progress, no fetchedAt", () => {
65
+ const r = summarizeLookupSnapshots(
66
+ [
67
+ snap({
68
+ completedAt: null,
69
+ totalCount: 10,
70
+ repos: [{ fullName: "acme/a", archived: false }],
71
+ }),
72
+ ],
73
+ NOW,
74
+ );
75
+ expect(r.syncState).toBe("syncing");
76
+ expect(r.repos).toEqual([{ fullName: "acme/a", archived: false }]);
77
+ expect(r.progress).toEqual({ reposSeen: 1, totalCount: 10 });
78
+ expect(r.fetchedAt).toBeUndefined();
79
+ });
80
+
81
+ it("incomplete crawl with an error: failed", () => {
82
+ const r = summarizeLookupSnapshots(
83
+ [snap({ completedAt: null, lastError: "boom" })],
84
+ NOW,
85
+ );
86
+ expect(r.syncState).toBe("failed");
87
+ });
88
+
89
+ it("omits totalCount while any org has not reported one", () => {
90
+ const r = summarizeLookupSnapshots(
91
+ [snap(), snap({ completedAt: null, totalCount: null, repos: [] })],
92
+ NOW,
93
+ );
94
+ expect(r.progress).toEqual({ reposSeen: 2 });
95
+ });
96
+
97
+ it("merges orgs: syncing beats stale, failed beats syncing, dedupes repos", () => {
98
+ const orgA = snap({ completedAt: ago(90 * MIN) });
99
+ const orgB = snap({
100
+ completedAt: null,
101
+ repos: [{ fullName: "acme/a", archived: false }],
102
+ });
103
+ const mixed = summarizeLookupSnapshots([orgA, orgB], NOW);
104
+ expect(mixed.syncState).toBe("syncing");
105
+ expect(mixed.repos.map((r) => r.fullName).sort()).toEqual([
106
+ "acme/a",
107
+ "acme/b",
108
+ ]);
109
+ const failed = summarizeLookupSnapshots(
110
+ [orgA, { ...orgB, lastError: "x" }],
111
+ NOW,
112
+ );
113
+ expect(failed.syncState).toBe("failed");
114
+ });
115
+
116
+ it("fetchedAt is the oldest completion across orgs", () => {
117
+ const r = summarizeLookupSnapshots(
118
+ [
119
+ snap({ completedAt: ago(5 * MIN) }),
120
+ snap({ completedAt: ago(30 * MIN) }),
121
+ ],
122
+ NOW,
123
+ );
124
+ expect(r.fetchedAt).toEqual(ago(30 * MIN));
125
+ });
126
+ });
127
+
128
+ describe("createGithubLookupService", () => {
129
+ type Row = { appId: string; enterpriseSlug: string | null };
130
+ function apps(rows: Record<string, Row | undefined>, withKey = true) {
131
+ return {
132
+ get: async (role: string) => rows[role] ?? null,
133
+ getPrivateKey: async (role: string) =>
134
+ rows[role] && withKey ? "pem" : null,
135
+ } as unknown as GitHubEnterpriseAppService;
136
+ }
137
+ const lookupRow = { appId: "555", enterpriseSlug: null };
138
+
139
+ function build(
140
+ rows: Record<string, Row | undefined>,
141
+ snapshots: LookupSnapshotView[] = [],
142
+ withKey = true,
143
+ ) {
144
+ const calls: unknown[][] = [];
145
+ const svc = createGithubLookupService({
146
+ appService: apps(rows, withKey),
147
+ now: () => NOW,
148
+ cache: {
149
+ listLookupSnapshots: async (...args: unknown[]) => {
150
+ calls.push(args);
151
+ return snapshots;
152
+ },
153
+ },
154
+ });
155
+ return { svc, calls };
156
+ }
157
+
158
+ it("unconfigured when no lookup App: configured:false, cache untouched", async () => {
159
+ const { svc, calls } = build({});
160
+ expect(await svc.listRepositories("acct")).toEqual({
161
+ configured: false,
162
+ repos: [],
163
+ });
164
+ expect(calls).toHaveLength(0);
165
+ });
166
+
167
+ it("unconfigured when the lookup App has no key", async () => {
168
+ const { svc } = build({ lookup: lookupRow }, [], false);
169
+ expect((await svc.listRepositories()).configured).toBe(false);
170
+ });
171
+
172
+ it("unconfigured when an installer with a slug has no key", async () => {
173
+ const rows = {
174
+ lookup: lookupRow,
175
+ installer: { appId: "1", enterpriseSlug: "ent" },
176
+ };
177
+ const svc = createGithubLookupService({
178
+ appService: {
179
+ get: async (role: string) => (rows as Record<string, Row>)[role],
180
+ getPrivateKey: async (role: string) =>
181
+ role === "lookup" ? "pem" : null,
182
+ } as unknown as GitHubEnterpriseAppService,
183
+ cache: { listLookupSnapshots: async () => [] },
184
+ });
185
+ expect((await svc.listRepositories()).configured).toBe(false);
186
+ });
187
+
188
+ it("cold start: configured, empty, syncing", async () => {
189
+ const { svc } = build({ lookup: lookupRow });
190
+ expect(await svc.listRepositories("acct")).toEqual({
191
+ configured: true,
192
+ repos: [],
193
+ syncState: "syncing",
194
+ });
195
+ });
196
+
197
+ it("queries the account and deployment-wide scopes by lookup App id", async () => {
198
+ const { svc, calls } = build({ lookup: lookupRow }, [snap()]);
199
+ const r = await svc.listRepositories("acct");
200
+ expect(r.syncState).toBe("ready");
201
+ expect(calls[0]).toEqual([["acct", ""], "555"]);
202
+ await svc.listRepositories();
203
+ expect(calls[1]).toEqual([[""], "555"]);
204
+ });
205
+ });
@@ -128,6 +128,24 @@ export class GitHubRepoCacheService {
128
128
  });
129
129
  }
130
130
 
131
+ /** Lookup-App snapshots (with their repos) for the account scopes and App id. Reads only the cache. */
132
+ async listLookupSnapshots(accountIds: string[], appRef: string) {
133
+ requireNonEmpty("appRef", appRef);
134
+ const rows = await this.prisma.gitHubRepoSnapshot.findMany({
135
+ where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
136
+ include: {
137
+ repos: { select: { fullName: true, archived: true } },
138
+ },
139
+ orderBy: { org: "asc" },
140
+ });
141
+ return rows.map((r) => ({
142
+ completedAt: r.completedAt,
143
+ totalCount: r.totalCount,
144
+ lastError: r.lastError,
145
+ repos: r.repos,
146
+ }));
147
+ }
148
+
131
149
  /** Upsert repos for a snapshot in batches, stamping each with `seenAt`. */
132
150
  async upsertRepos(
133
151
  snapshotId: string,