@app-vitals/agent-admin 1.86.0 → 1.87.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.
@@ -0,0 +1,405 @@
1
+ /**
2
+ * admin/src/github-cache-roundtrip.integration.test.ts
3
+ * Real-database round trip for the GitHub repo cache (GFU-1.1). The real
4
+ * refresher, discovery and crawlers write snapshots and access rows through
5
+ * GitHubRepoCacheService into PostgreSQL, and every reader reads them back:
6
+ * githubLookup.listRepositories, GitHub Sync preview (lookupRepos plus
7
+ * cachedAccess) and the installation repos list.
8
+ *
9
+ * Earlier tests stubbed lookupRepos or the cache, which hid readers that
10
+ * looked under the wrong account key (GSF-1.1, GSF-4.1). Only the GitHub
11
+ * ports are faked here (lookup client, installer client); time is an injected
12
+ * Clock. Two scopes: a deployment-wide (null-account) lookup App, filed under
13
+ * DEPLOYMENT_WIDE_ACCOUNT_KEY, and an account-scoped App, read through its own
14
+ * account key plus the deployment key (lookupAccountKeys).
15
+ *
16
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
17
+ */
18
+
19
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
20
+ import type { PrismaClient } from "../prisma/client/client.ts";
21
+ import type { AgentEnvService } from "./agent-envs.ts";
22
+ import type { Clock } from "./clock.ts";
23
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
24
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
25
+ import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
26
+ import {
27
+ createGithubInstallationRepos,
28
+ createGithubSync,
29
+ } from "./github-installation-wiring.ts";
30
+ import {
31
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
32
+ lookupAccountKeys,
33
+ } from "./github-agent-installation-crawler.ts";
34
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
35
+ import {
36
+ createRefreshDiscovery,
37
+ type LookupAppClient,
38
+ } from "./github-repo-refresh-discovery.ts";
39
+ import { GithubRepoRefresher } from "./github-repo-refresher.ts";
40
+ import {
41
+ createInstallationPort,
42
+ type InstallationRepoClient,
43
+ PrismaInstallationAgents,
44
+ } from "./installation-ports.ts";
45
+ import { createInstallationReposPort } from "./installation-repos-service.ts";
46
+ import { createAdminPrismaClient } from "./prisma-client.ts";
47
+
48
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
49
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
50
+
51
+ const T0 = new Date("2026-11-20T12:00:00Z");
52
+ const MINUTE = 60_000;
53
+ const HOUR = 3_600_000;
54
+ const LOOKUP_APP_ID = "555";
55
+ const AGENT_APP_ID = 42;
56
+ const USERNAME = "octocat";
57
+
58
+ /** Repos per org: three, listed over two pages (two per page). */
59
+ const reposOf = (org: string) => ["a", "b", "c"].map((n) => `${org}/${n}`);
60
+
61
+ /** Fake lookup App client: the GitHub port the crawl and access backfill use. */
62
+ function fakeLookupClient(orgs: string[]): LookupAppClient {
63
+ return {
64
+ async listInstallations() {
65
+ return orgs.map((login, i) => ({
66
+ id: i + 1,
67
+ login,
68
+ })) as unknown as Awaited<
69
+ ReturnType<LookupAppClient["listInstallations"]>
70
+ >;
71
+ },
72
+ async listInstallationRepositoriesPage(org, page) {
73
+ const all = reposOf(org);
74
+ const slice = all.slice((page - 1) * 2, page * 2);
75
+ return {
76
+ repositories: slice.map((fullName) => ({
77
+ id: org.length * 1000 + all.indexOf(fullName) + 1,
78
+ fullName,
79
+ archived: false,
80
+ })),
81
+ totalCount: all.length,
82
+ hasNext: page * 2 < all.length,
83
+ rateLimit: { remaining: 4000, resetAt: null, retryAfterSeconds: null },
84
+ } as unknown as Awaited<
85
+ ReturnType<LookupAppClient["listInstallationRepositoriesPage"]>
86
+ >;
87
+ },
88
+ async getCollaboratorPermissionWithRateLimit(_org, repo) {
89
+ return {
90
+ role: repo === "a" ? "write" : "read",
91
+ rateLimit: { remaining: 4000, resetAt: null, retryAfterSeconds: null },
92
+ };
93
+ },
94
+ };
95
+ }
96
+
97
+ type InstallerClient = InstallationRepoClient &
98
+ Required<Pick<InstallationRepoClient, "listInstallationRepositoriesPage">> & {
99
+ listInstallableOrganizations(): Promise<{ login: string }[]>;
100
+ };
101
+
102
+ /** Fake installer client: the agent App has installation 900 on org `acme`. */
103
+ function fakeInstaller(): InstallerClient {
104
+ const repos = (org: string) =>
105
+ reposOf(org).map((fullName, i) => ({
106
+ id: 9000 + i,
107
+ fullName,
108
+ archived: false,
109
+ }));
110
+ return {
111
+ async listInstallableOrganizations() {
112
+ return [{ login: "acme" }];
113
+ },
114
+ async listOrgInstallations() {
115
+ return [{ id: 900, appId: AGENT_APP_ID }];
116
+ },
117
+ async listInstallationRepositories(org: string) {
118
+ return repos(org);
119
+ },
120
+ async listInstallationRepositoriesPage(
121
+ org: string,
122
+ _id: number,
123
+ page: number,
124
+ ) {
125
+ const all = repos(org);
126
+ const slice = all.slice((page - 1) * 2, page * 2);
127
+ return {
128
+ repos: slice,
129
+ perPage: 2,
130
+ hasNext: page * 2 < all.length,
131
+ };
132
+ },
133
+ async addRepositories() {},
134
+ async removeRepositories() {},
135
+ } as unknown as InstallerClient;
136
+ }
137
+
138
+ describeOrSkip("GitHub repo cache round trip (integration)", () => {
139
+ let prisma: PrismaClient;
140
+ let now: Date;
141
+ let cache: GitHubRepoCacheService;
142
+ const accountIds: string[] = [];
143
+ const agentIds: string[] = [];
144
+
145
+ const clock: Clock = { now: () => new Date(now) };
146
+
147
+ const agentEnv = {
148
+ getConfigBundle: async () => ({ env: { GH_APP_ID: String(AGENT_APP_ID) } }),
149
+ } as unknown as Pick<AgentEnvService, "getConfigBundle">;
150
+
151
+ /** Resolves a lookup App per scope, as the stored-App wiring would. */
152
+ interface Apps {
153
+ /** scope (null = deployment-wide) -> the App row that scope resolves to. */
154
+ byScope: Map<
155
+ string | null,
156
+ { ownerAccountId: string | null; orgs: string[] }
157
+ >;
158
+ }
159
+
160
+ const appService = (apps: Apps) =>
161
+ ({
162
+ get: async (role: string, scope?: string | null) => {
163
+ if (role !== "lookup") return null;
164
+ const found = apps.byScope.get(scope ?? null);
165
+ if (!found) return null;
166
+ return {
167
+ appId: LOOKUP_APP_ID,
168
+ accountId: found.ownerAccountId,
169
+ enterpriseSlug: null,
170
+ updatedAt: T0,
171
+ };
172
+ },
173
+ getPrivateKey: async (role: string, scope?: string | null) =>
174
+ role === "lookup" && apps.byScope.has(scope ?? null) ? "pem" : null,
175
+ }) as unknown as GitHubEnterpriseAppService;
176
+
177
+ /** Run the real refresher until every target is crawled and backfilled. */
178
+ async function refresh(apps: Apps, agentScope: string | null) {
179
+ const installer = fakeInstaller();
180
+ const agentsPort = new PrismaInstallationAgents(prisma, agentEnv);
181
+ const discovery = createRefreshDiscovery({
182
+ listAppScopes: async () =>
183
+ [...apps.byScope.keys()].filter((s): s is string => s !== null),
184
+ async listAgents() {
185
+ const out = [];
186
+ for (const id of agentIds) {
187
+ const rec = await agentsPort.get(id);
188
+ if (rec) out.push(rec);
189
+ }
190
+ return out;
191
+ },
192
+ async lookupApp(scope) {
193
+ const found = apps.byScope.get(scope);
194
+ if (!found) return null;
195
+ return {
196
+ accountId: found.ownerAccountId,
197
+ appId: LOOKUP_APP_ID,
198
+ client: fakeLookupClient(found.orgs),
199
+ };
200
+ },
201
+ // Only the agent's own scope has an installer; the others fall back to
202
+ // the lookup App's own installations for their orgs.
203
+ installerOrgs: async (scope) => (scope === agentScope ? ["acme"] : null),
204
+ installer,
205
+ store: cache,
206
+ clock,
207
+ log: () => {},
208
+ });
209
+ const refresher = new GithubRepoRefresher({
210
+ discovery,
211
+ store: cache,
212
+ clock,
213
+ holder: "roundtrip",
214
+ config: {
215
+ intervalMs: MINUTE,
216
+ ttlMs: HOUR,
217
+ stalenessCapMs: 6 * HOUR,
218
+ timeBudgetMs: 45_000,
219
+ },
220
+ log: () => {},
221
+ });
222
+ const result = await refresher.tick();
223
+ expect(result.targets.every((t) => t.state === "worked")).toBe(true);
224
+ // Readers run a little later, still inside the freshness window.
225
+ now = new Date(T0.getTime() + MINUTE);
226
+ return installer;
227
+ }
228
+
229
+ async function makeAgent(accountId: string | null) {
230
+ const agent = await prisma.agent.create({
231
+ data: {
232
+ name: `roundtrip-${agentIds.length}`,
233
+ githubUsername: USERNAME,
234
+ repos: ["acme/a"],
235
+ ...(accountId ? { accountId } : {}),
236
+ },
237
+ });
238
+ agentIds.push(agent.id);
239
+ return agent.id;
240
+ }
241
+
242
+ async function makeAccount(name: string) {
243
+ const acct = await prisma.account.create({ data: { name } });
244
+ accountIds.push(acct.id);
245
+ return acct.id;
246
+ }
247
+
248
+ const lister = (apps: Apps) =>
249
+ createGithubLookupService({
250
+ appService: appService(apps),
251
+ cache,
252
+ now: () => clock.now(),
253
+ });
254
+
255
+ const noLiveAccess: GithubAccessPreviewFn = async () => {
256
+ throw new Error("the live access resolver must not be consulted");
257
+ };
258
+
259
+ const wiring = (apps: Apps, installer: InstallerClient) => {
260
+ const installationRepos = createInstallationReposPort(
261
+ createInstallationPort(installer),
262
+ installer,
263
+ );
264
+ return {
265
+ prisma,
266
+ appService: appService(apps),
267
+ access: noLiveAccess,
268
+ agentEnv,
269
+ installationRepos,
270
+ now: () => clock.now(),
271
+ };
272
+ };
273
+
274
+ beforeEach(async () => {
275
+ prisma = createAdminPrismaClient(TEST_DB as string);
276
+ await prisma.gitHubRepoAccess.deleteMany();
277
+ await prisma.gitHubCachedRepo.deleteMany();
278
+ await prisma.gitHubRepoSnapshot.deleteMany();
279
+ now = T0;
280
+ cache = new GitHubRepoCacheService(prisma, clock);
281
+ accountIds.length = 0;
282
+ agentIds.length = 0;
283
+ });
284
+
285
+ afterEach(async () => {
286
+ await prisma.gitHubRepoAccess.deleteMany();
287
+ await prisma.gitHubCachedRepo.deleteMany();
288
+ await prisma.gitHubRepoSnapshot.deleteMany();
289
+ if (agentIds.length > 0) {
290
+ await prisma.agent.deleteMany({ where: { id: { in: agentIds } } });
291
+ }
292
+ if (accountIds.length > 0) {
293
+ await prisma.account.deleteMany({ where: { id: { in: accountIds } } });
294
+ }
295
+ await prisma.$disconnect();
296
+ });
297
+
298
+ it("null-account lookup App: every reader reads the deployment-keyed snapshots", async () => {
299
+ const agentId = await makeAgent(null);
300
+ const apps: Apps = {
301
+ byScope: new Map([[null, { ownerAccountId: null, orgs: ["acme"] }]]),
302
+ };
303
+ const installer = await refresh(apps, null);
304
+
305
+ // The writers filed everything under the deployment key.
306
+ const snaps = await prisma.gitHubRepoSnapshot.findMany();
307
+ expect(snaps.map((s) => [s.appKind, s.accountId, s.org]).sort()).toEqual([
308
+ ["agent", DEPLOYMENT_WIDE_ACCOUNT_KEY, "acme"],
309
+ ["lookup", DEPLOYMENT_WIDE_ACCOUNT_KEY, "acme"],
310
+ ]);
311
+
312
+ // 1. githubLookup.listRepositories
313
+ const listed = await lister(apps).listRepositories(null);
314
+ expect(listed.configured).toBe(true);
315
+ expect(listed.syncState).toBe("ready");
316
+ expect(listed.repos.map((r) => r.fullName).sort()).toEqual(reposOf("acme"));
317
+
318
+ // 2. Sync preview: lookupRepos + cachedAccess over the real cache.
319
+ const sync = createGithubSync(wiring(apps, installer));
320
+ const preview = await sync.preview(agentId);
321
+ if (preview.status !== "previewed") throw new Error(preview.status);
322
+ expect(preview.plan.skippedOrgs).toEqual([]);
323
+ expect(preview.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
324
+
325
+ // 3. Installation list: the agent App snapshot.
326
+ const list = await createGithubInstallationRepos(
327
+ wiring(apps, installer),
328
+ ).list(agentId);
329
+ if (list.status !== "ok") throw new Error(list.status);
330
+ expect(list.appId).toBe(AGENT_APP_ID);
331
+ expect(list.orgs).toHaveLength(1);
332
+ expect(list.orgs[0]?.org).toBe("acme");
333
+ expect(list.orgs[0]?.complete).toBe(true);
334
+ expect(list.orgs[0]?.repos.map((r) => r.fullName).sort()).toEqual(
335
+ reposOf("acme"),
336
+ );
337
+ });
338
+
339
+ it("account-scoped App: readers use the own account key plus the deployment key, never another account's", async () => {
340
+ const acct = await makeAccount("roundtrip-own");
341
+ const other = await makeAccount("roundtrip-other");
342
+ const agentId = await makeAgent(acct);
343
+ const apps: Apps = {
344
+ byScope: new Map([
345
+ // The account's own App covers `acme`; the deployment-wide App `beta`.
346
+ [acct, { ownerAccountId: acct, orgs: ["acme"] }],
347
+ [null, { ownerAccountId: null, orgs: ["beta"] }],
348
+ // Another account's App, same App id, must never be read.
349
+ [other, { ownerAccountId: other, orgs: ["evil"] }],
350
+ ]),
351
+ };
352
+ const installer = await refresh(apps, acct);
353
+
354
+ expect(lookupAccountKeys(acct)).toEqual([
355
+ acct,
356
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
357
+ ]);
358
+ const lookupSnaps = await prisma.gitHubRepoSnapshot.findMany({
359
+ where: { appKind: "lookup" },
360
+ });
361
+ expect(lookupSnaps.map((s) => [s.accountId, s.org]).sort()).toEqual(
362
+ [
363
+ [acct, "acme"],
364
+ [DEPLOYMENT_WIDE_ACCOUNT_KEY, "beta"],
365
+ [other, "evil"],
366
+ ].sort(),
367
+ );
368
+
369
+ // 1. Lister: own account's acme plus the deployment-wide beta, no evil.
370
+ const listed = await lister(apps).listRepositories(acct);
371
+ expect(listed.configured).toBe(true);
372
+ expect(listed.syncState).toBe("ready");
373
+ expect(listed.repos.map((r) => r.fullName).sort()).toEqual(
374
+ [...reposOf("acme"), ...reposOf("beta")].sort(),
375
+ );
376
+ expect(listed.repos.some((r) => r.fullName.startsWith("evil/"))).toBe(
377
+ false,
378
+ );
379
+
380
+ // The other account's lister sees its own org plus the deployment key only.
381
+ const otherListed = await lister(apps).listRepositories(other);
382
+ expect(otherListed.repos.map((r) => r.fullName).sort()).toEqual(
383
+ [...reposOf("evil"), ...reposOf("beta")].sort(),
384
+ );
385
+
386
+ // 2. Sync preview over the account's own access rows.
387
+ const sync = createGithubSync(wiring(apps, installer));
388
+ const preview = await sync.preview(agentId);
389
+ if (preview.status !== "previewed") throw new Error(preview.status);
390
+ expect(preview.plan.skippedOrgs).toEqual([]);
391
+ expect(preview.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
392
+
393
+ // 3. Installation list: the agent App snapshot under the account key.
394
+ const list = await createGithubInstallationRepos(
395
+ wiring(apps, installer),
396
+ ).list(agentId);
397
+ if (list.status !== "ok") throw new Error(list.status);
398
+ expect(list.orgs).toHaveLength(1);
399
+ expect(list.orgs[0]?.org).toBe("acme");
400
+ expect(list.orgs[0]?.complete).toBe(true);
401
+ expect(list.orgs[0]?.repos.map((r) => r.fullName).sort()).toEqual(
402
+ reposOf("acme"),
403
+ );
404
+ });
405
+ });
@@ -36,6 +36,7 @@ import {
36
36
  UnprocessableEntityError,
37
37
  } from "./errors.ts";
38
38
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
39
+ import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
39
40
  import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
40
41
  import {
41
42
  GITHUB_ENTERPRISE_APP_ROLES,
@@ -482,8 +483,8 @@ function serializeApp(m: GitHubEnterpriseAppMetadata) {
482
483
  // ─── Access preview (GHE-2.4) ─────────────────────────────────────────────────
483
484
 
484
485
  /**
485
- * Backs GET /agents/:id/github-access. Unconfigured (either App missing, or a
486
- * stored App without its key / enterprise slug) returns before any GitHub
486
+ * Backs GET /agents/:id/github-access. Unconfigured (the lookup App, or its
487
+ * key, missing) returns before any GitHub
487
488
  * call. A GitHub failure while listing orgs is rethrown as a 502 carrying only
488
489
  * the mapped, non-leaky message.
489
490
  */
@@ -498,32 +499,38 @@ export function createGithubAccessPreview(
498
499
  deps.appService.get("installer", accountId),
499
500
  deps.appService.get("lookup", accountId),
500
501
  ]);
501
- if (!installer || !lookup || !installer.enterpriseSlug) {
502
- return { status: "unconfigured" };
503
- }
502
+ if (!lookup) return { status: "unconfigured" };
504
503
  const [installerKey, lookupKey] = await Promise.all([
505
- deps.appService.getPrivateKey("installer", accountId),
504
+ installer ? deps.appService.getPrivateKey("installer", accountId) : null,
506
505
  deps.appService.getPrivateKey("lookup", accountId),
507
506
  ]);
508
- if (!installerKey || !lookupKey) return { status: "unconfigured" };
507
+ if (!lookupKey) return { status: "unconfigured" };
509
508
 
510
509
  const common = {
511
510
  apiBase: deps.apiBase,
512
511
  fetchFn: deps.fetchFn,
513
512
  now: deps.now,
514
513
  };
514
+ const lookupClient = new GithubLookupClient({
515
+ appId: lookup.appId,
516
+ privateKey: lookupKey,
517
+ ...common,
518
+ });
519
+ // The installer only widens the org list; without a usable one (no key or
520
+ // enterprise slug) the lookup App's own installations are the org source.
521
+ const installerClient =
522
+ installer?.enterpriseSlug && installerKey
523
+ ? new GithubEnterpriseClient({
524
+ appId: installer.appId,
525
+ enterprise: installer.enterpriseSlug,
526
+ privateKey: installerKey,
527
+ ...common,
528
+ })
529
+ : undefined;
515
530
  const resolver = new UserRepoAccessResolver({
516
- installer: new GithubEnterpriseClient({
517
- appId: installer.appId,
518
- enterprise: installer.enterpriseSlug,
519
- privateKey: installerKey,
520
- ...common,
521
- }),
522
- lookup: new GithubLookupClient({
523
- appId: lookup.appId,
524
- privateKey: lookupKey,
525
- ...common,
526
- }),
531
+ installer: installerClient,
532
+ lookupInstallations: lookupClient,
533
+ lookup: lookupClient,
527
534
  now: deps.now,
528
535
  });
529
536
  try {
@@ -563,10 +570,8 @@ export function createGithubLookupService(
563
570
  if (!lookupKey || (installer?.enterpriseSlug && !installerKey)) {
564
571
  return { configured: false, repos: [] };
565
572
  }
566
- // The crawler files a deployment-wide App's snapshots under accountId "".
567
- const accountIds = accountId ? [accountId, ""] : [""];
568
573
  const snapshots = await deps.cache.listLookupSnapshots(
569
- accountIds,
574
+ lookupAccountKeys(accountId),
570
575
  lookup.appId,
571
576
  );
572
577
  return summarizeLookupSnapshots(
@@ -9,11 +9,15 @@
9
9
 
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import type {
13
+ GithubAppsState,
14
+ GithubAppsStateFn,
15
+ } from "./github-apps-state.ts";
12
16
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
13
17
  import type { Clock } from "./clock.ts";
14
18
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
15
19
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
16
- import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
20
+ import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
17
21
  import { GithubLookupClient } from "./github-lookup-client.ts";
18
22
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
19
23
  import type { CrawlStore } from "./github-repo-crawler.ts";
@@ -93,6 +97,35 @@ export function lazyInstallerClient(
93
97
  };
94
98
  }
95
99
 
100
+ /**
101
+ * Which Apps are usable for an account: the lookup App needs metadata and its
102
+ * key; the installer App also needs its enterprise slug (same test as
103
+ * lazyInstallerClient). Probed per call so config changes are picked up.
104
+ */
105
+ export function githubAppsStateProbe(
106
+ deps: Pick<GithubInstallationWiringDeps, "appService">,
107
+ ): GithubAppsStateFn {
108
+ return async (accountId): Promise<GithubAppsState> => {
109
+ const [lookup, lookupKey, installer, installerKey] = await Promise.all([
110
+ deps.appService.get("lookup", accountId),
111
+ deps.appService.getPrivateKey("lookup", accountId),
112
+ deps.appService.get("installer", accountId),
113
+ deps.appService.getPrivateKey("installer", accountId),
114
+ ]);
115
+ if (!lookup || !lookupKey) return "lookup_missing";
116
+ return installer?.enterpriseSlug && installerKey ? "both" : "lookup_only";
117
+ };
118
+ }
119
+
120
+ /** The probe only guards the real installer-backed port; a replaced port has no installer to probe. */
121
+ function appsStateDep(
122
+ deps: Pick<InstallationReposWiringDeps, "appService" | "installationRepos">,
123
+ ): { appsState?: GithubAppsStateFn } {
124
+ return deps.installationRepos
125
+ ? {}
126
+ : { appsState: githubAppsStateProbe(deps) };
127
+ }
128
+
96
129
  export interface InstallationReposWiringDeps
97
130
  extends GithubInstallationWiringDeps {
98
131
  /** Test seam: replaces the installer-App-backed port. */
@@ -116,6 +149,7 @@ export function createGithubInstallationRepos(
116
149
  deps.installationRepos ??
117
150
  createInstallationReposPort(createInstallationPort(client), client),
118
151
  cache: new GitHubRepoCacheService(deps.prisma),
152
+ ...appsStateDep(deps),
119
153
  });
120
154
  }
121
155
 
@@ -159,15 +193,8 @@ export function createGithubSync(
159
193
  lookupRepos: async (accountId) => {
160
194
  const lookup = await lookupClient(accountId);
161
195
  if (!lookup) return [];
162
- // The crawler files a deployment-wide App's snapshots under
163
- // DEPLOYMENT_WIDE_ACCOUNT_KEY, so a null-account agent reads that key and
164
- // an account agent reads its own account plus that key.
165
- // Note: a real account literally named "deployment" would collide with
166
- // this fallback key; that is known and deliberately not fixed here.
167
196
  const snapshots = await cache.listLookupOrgSnapshots(
168
- accountId
169
- ? [accountId, DEPLOYMENT_WIDE_ACCOUNT_KEY]
170
- : [DEPLOYMENT_WIDE_ACCOUNT_KEY],
197
+ lookupAccountKeys(accountId),
171
198
  lookup.appId,
172
199
  );
173
200
  return snapshots.map((s) => ({
@@ -201,6 +228,7 @@ export function createGithubSync(
201
228
  deps.installationRepos ??
202
229
  createInstallationReposPort(createInstallationPort(client), client),
203
230
  audit: new PrismaInstallationAudit(deps.prisma),
231
+ ...appsStateDep(deps),
204
232
  ...(deps.openWork ? { openWork: deps.openWork } : {}),
205
233
  });
206
234
  }
@@ -83,4 +83,20 @@ describeOrSkip("githubLookup.listRepositories (cache, integration)", () => {
83
83
  expect(done.repos).toHaveLength(2);
84
84
  expect(done.fetchedAt).toEqual(NOW);
85
85
  });
86
+
87
+ it("null-account lookup reads a deployment-wide snapshot filed under 'deployment'", async () => {
88
+ const snap = await cache.upsertSnapshot(
89
+ { ...key("acme"), accountId: "deployment" },
90
+ { crawlPage: 1, crawlStartedAt: NOW, totalCount: 1 },
91
+ );
92
+ await cache.upsertRepos(snap.id, [{ githubId: 3, fullName: "acme/c" }]);
93
+ await cache.upsertSnapshot(
94
+ { ...key("acme"), accountId: "deployment" },
95
+ { completedAt: NOW },
96
+ );
97
+ const r = await svc().listRepositories(null);
98
+ expect(r.configured).toBe(true);
99
+ expect(r.syncState).toBe("ready");
100
+ expect(r.repos).toEqual([{ fullName: "acme/c", archived: false }]);
101
+ });
86
102
  });
@@ -198,8 +198,69 @@ describe("createGithubLookupService", () => {
198
198
  const { svc, calls } = build({ lookup: lookupRow }, [snap()]);
199
199
  const r = await svc.listRepositories("acct");
200
200
  expect(r.syncState).toBe("ready");
201
- expect(calls[0]).toEqual([["acct", ""], "555"]);
202
- await svc.listRepositories();
203
- expect(calls[1]).toEqual([[""], "555"]);
201
+ expect(calls[0]).toEqual([["acct", "deployment"], "555"]);
202
+ });
203
+
204
+ describe("against a cache seeded under the real keys", () => {
205
+ /** Fake cache that only returns snapshots filed under a requested accountId. */
206
+ function seededCache(seed: Record<string, LookupSnapshotView[]>) {
207
+ const calls: string[][] = [];
208
+ return {
209
+ calls,
210
+ cache: {
211
+ listLookupSnapshots: async (accountIds: string[]) => {
212
+ calls.push(accountIds);
213
+ return accountIds.flatMap((id) => seed[id] ?? []);
214
+ },
215
+ },
216
+ };
217
+ }
218
+ const deploymentApps = {
219
+ get: async (role: string) => (role === "lookup" ? lookupRow : null),
220
+ getPrivateKey: async (role: string) => (role === "lookup" ? "pem" : null),
221
+ } as unknown as GitHubEnterpriseAppService;
222
+
223
+ it("deployment-wide lookup App (null account) reads the 'deployment' key: ready", async () => {
224
+ const { cache, calls } = seededCache({
225
+ deployment: [snap({ completedAt: ago(5 * MIN) })],
226
+ });
227
+ const svc = createGithubLookupService({
228
+ appService: deploymentApps,
229
+ cache,
230
+ now: () => NOW,
231
+ });
232
+ const r = await svc.listRepositories(null);
233
+ expect(calls).toEqual([["deployment"]]);
234
+ expect(r.configured).toBe(true);
235
+ expect(r.syncState).toBe("ready");
236
+ expect(r.repos.map((x) => x.fullName)).toEqual(["acme/a", "acme/b"]);
237
+ });
238
+
239
+ it("account-scoped lookup also serves the deployment-wide snapshots", async () => {
240
+ const { cache, calls } = seededCache({
241
+ deployment: [snap({ completedAt: ago(5 * MIN) })],
242
+ });
243
+ const svc = createGithubLookupService({
244
+ appService: deploymentApps,
245
+ cache,
246
+ now: () => NOW,
247
+ });
248
+ const r = await svc.listRepositories("acct");
249
+ expect(calls).toEqual([["acct", "deployment"]]);
250
+ expect(r.syncState).toBe("ready");
251
+ expect(r.repos).toHaveLength(2);
252
+ });
253
+
254
+ it("never queries the empty-string key", async () => {
255
+ const { cache, calls } = seededCache({});
256
+ const svc = createGithubLookupService({
257
+ appService: deploymentApps,
258
+ cache,
259
+ now: () => NOW,
260
+ });
261
+ await svc.listRepositories();
262
+ await svc.listRepositories("acct");
263
+ expect(calls.flat()).not.toContain("");
264
+ });
204
265
  });
205
266
  });