@app-vitals/agent-admin 1.129.0 → 1.129.1

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.129.0",
3
+ "version": "1.129.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.129.0",
47
+ "@app-vitals/agent-lib": "1.129.1",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -7553,6 +7553,8 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7553
7553
  state.repos = args.data.repos;
7554
7554
  },
7555
7555
  },
7556
+ // No AgentGitHubApp rows: the App comes from the stored GH_APP_ID.
7557
+ agentGitHubApp: { findMany: async () => [] },
7556
7558
  gitHubRepoSnapshot: {
7557
7559
  findMany: async () => opts.snapshots ?? defaultSnapshots,
7558
7560
  },
@@ -6,20 +6,30 @@
6
6
  * nothing recorded live) through an INJECTED fetchFn (no global fetch
7
7
  * override, no mock.module()). The repo list pages are generated here; the
8
8
  * cassette carries routes, headers and status codes. Persistence is an
9
- * in-memory CrawlStore (no database needed).
9
+ * in-memory CrawlStore, except the per-app suite at the end, which crawls an
10
+ * agent's table-backed Apps into the real repo cache (DATABASE_URL_ADMIN_TEST;
11
+ * skips without it).
10
12
  */
11
13
 
12
- import { describe, expect, it } from "bun:test";
14
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
13
15
  import { generateKeyPairSync } from "node:crypto";
14
16
  import { readFileSync } from "node:fs";
15
- import { crawlAgentInstallation } from "./github-agent-installation-crawler.ts";
17
+ import type { PrismaClient } from "../prisma/client/client.ts";
18
+ import {
19
+ crawlAgentInstallation,
20
+ crawlAgentInstallations,
21
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
22
+ } from "./github-agent-installation-crawler.ts";
16
23
  import { lazyInstallerClient } from "./github-installation-wiring.ts";
17
- import type {
18
- CachedRepoInput,
19
- SnapshotKey,
20
- SnapshotProgress,
24
+ import {
25
+ type CachedRepoInput,
26
+ GitHubRepoCacheService,
27
+ type SnapshotKey,
28
+ type SnapshotProgress,
21
29
  } from "./github-repo-cache.ts";
22
30
  import type { CrawlSnapshot, CrawlStore } from "./github-repo-crawler.ts";
31
+ import { PrismaInstallationAgents } from "./installation-ports.ts";
32
+ import { createAdminPrismaClient } from "./prisma-client.ts";
23
33
 
24
34
  interface CassetteEntry {
25
35
  status: number;
@@ -47,6 +57,8 @@ const NOW = new Date("2026-11-20T12:00:00Z");
47
57
  const clock = { now: () => new Date(NOW) };
48
58
  const ENT = "/enterprises/acme-ent";
49
59
  const REPOS_501 = `${ENT}/apps/organizations/acme-eng/installations/501/repositories`;
60
+ /** The other App's installation on acme-eng (app 111, "other-app"). */
61
+ const REPOS_900 = `${ENT}/apps/organizations/acme-eng/installations/900/repositories`;
50
62
 
51
63
  class MemoryStore implements CrawlStore {
52
64
  snap: CrawlSnapshot | null = null;
@@ -98,10 +110,10 @@ class MemoryStore implements CrawlStore {
98
110
  }
99
111
 
100
112
  /** `total` repos served in full pages of 100 with GitHub-style Link headers. */
101
- function repoPage(total: number, page: number): CassetteEntry {
102
- const start = (page - 1) * 100;
103
- const n = Math.max(0, Math.min(100, total - start));
104
- const hasNext = start + 100 < total;
113
+ function repoPage(total: number, page: number, idBase = 0): CassetteEntry {
114
+ const start = (page - 1) * 100 + idBase;
115
+ const n = Math.max(0, Math.min(100, total - (start - idBase)));
116
+ const hasNext = start - idBase + 100 < total;
105
117
  return {
106
118
  status: 200,
107
119
  ...(hasNext
@@ -123,6 +135,8 @@ function repoPage(total: number, page: number): CassetteEntry {
123
135
  function setup(opts: {
124
136
  installs: string;
125
137
  total?: number;
138
+ /** Repos on the other App's installation 900 (ids from 10001). */
139
+ total900?: number;
126
140
  repoOverride?: (page: number) => CassetteEntry | undefined;
127
141
  }) {
128
142
  const paths: string[] = [];
@@ -143,6 +157,9 @@ function setup(opts: {
143
157
  else if (u.pathname === REPOS_501) {
144
158
  const page = Number(u.searchParams.get("page"));
145
159
  entry = opts.repoOverride?.(page) ?? repoPage(opts.total ?? 0, page);
160
+ } else if (u.pathname === REPOS_900) {
161
+ const page = Number(u.searchParams.get("page"));
162
+ entry = repoPage(opts.total900 ?? 0, page, 10_000);
146
163
  }
147
164
  if (!entry) throw new Error(`no route for ${method} ${u.pathname}`);
148
165
  return new Response(JSON.stringify(entry.body), {
@@ -277,3 +294,157 @@ describe("crawlAgentInstallation through the installer client (integration)", ()
277
294
  expect(store.snap?.completedAt).toBeNull();
278
295
  });
279
296
  });
297
+
298
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
299
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
300
+
301
+ describeOrSkip(
302
+ "crawlAgentInstallations: every agent App into the real repo cache (integration)",
303
+ () => {
304
+ let prisma: PrismaClient;
305
+ let cache: GitHubRepoCacheService;
306
+ const agentIds: string[] = [];
307
+ const noEnv = { getConfigBundle: async () => ({ env: {} }) } as never;
308
+
309
+ beforeEach(async () => {
310
+ prisma = createAdminPrismaClient(TEST_DB as string);
311
+ await prisma.gitHubRepoAccess.deleteMany();
312
+ await prisma.gitHubCachedRepo.deleteMany();
313
+ await prisma.gitHubRepoSnapshot.deleteMany();
314
+ cache = new GitHubRepoCacheService(prisma, clock);
315
+ });
316
+
317
+ afterEach(async () => {
318
+ await prisma.gitHubCachedRepo.deleteMany();
319
+ await prisma.gitHubRepoSnapshot.deleteMany();
320
+ if (agentIds.length > 0) {
321
+ await prisma.agent.deleteMany({ where: { id: { in: agentIds } } });
322
+ agentIds.length = 0;
323
+ }
324
+ await prisma.$disconnect();
325
+ });
326
+
327
+ /** An agent whose AgentGitHubApp rows are the given apps (priority = index). */
328
+ async function agentWithApps(
329
+ apps: { appId: string; slug?: string; clientId?: string }[],
330
+ ) {
331
+ const agent = await prisma.agent.create({
332
+ data: { name: `per-app-${agentIds.length}`, repos: [] },
333
+ });
334
+ agentIds.push(agent.id);
335
+ for (const [priority, app] of apps.entries()) {
336
+ await prisma.agentGitHubApp.create({
337
+ data: {
338
+ agentId: agent.id,
339
+ appId: app.appId,
340
+ slug: app.slug ?? null,
341
+ clientId: app.clientId ?? null,
342
+ privateKeyEncrypted: "ciphertext",
343
+ priority,
344
+ },
345
+ });
346
+ }
347
+ const rec = await new PrismaInstallationAgents(prisma, noEnv).get(
348
+ agent.id,
349
+ );
350
+ if (!rec) throw new Error("agent not found");
351
+ return rec;
352
+ }
353
+
354
+ const snapshots = (appRef: string) =>
355
+ cache.listAgentSnapshots(DEPLOYMENT_WIDE_ACCOUNT_KEY, appRef);
356
+
357
+ it("records each App's installation, repos and repository selection in its own snapshot", async () => {
358
+ const agent = await agentWithApps([
359
+ { appId: "777", clientId: "Iv1.agentapp0001", slug: "doc-agent" },
360
+ { appId: "111", slug: "other-app" },
361
+ { appId: "333", slug: "absent-app" },
362
+ ]);
363
+ const { client } = setup({
364
+ installs: "org_installations_agent",
365
+ total: 3,
366
+ total900: 2,
367
+ });
368
+ const results = await crawlAgentInstallations({
369
+ agent,
370
+ org: "acme-eng",
371
+ client,
372
+ store: cache,
373
+ clock,
374
+ });
375
+ expect(results.map((r) => [r.appId, r.result.outcome])).toEqual([
376
+ [777, "complete"],
377
+ [111, "complete"],
378
+ [333, "not_installed"],
379
+ ]);
380
+
381
+ const [first] = await snapshots("777");
382
+ expect(first).toMatchObject({
383
+ org: "acme-eng",
384
+ repositorySelection: "selected",
385
+ totalCount: 3,
386
+ lastError: null,
387
+ });
388
+ expect(first?.repos).toHaveLength(3);
389
+
390
+ const [second] = await snapshots("111");
391
+ expect(second).toMatchObject({
392
+ org: "acme-eng",
393
+ repositorySelection: "all",
394
+ totalCount: 2,
395
+ });
396
+ expect(second?.repos.map((r) => r.fullName).sort()).toEqual([
397
+ "acme-eng/r10001",
398
+ "acme-eng/r10002",
399
+ ]);
400
+
401
+ const [absent] = await snapshots("333");
402
+ expect(absent).toMatchObject({
403
+ repositorySelection: null,
404
+ totalCount: 0,
405
+ repos: [],
406
+ });
407
+ expect(absent?.completedAt).toEqual(NOW);
408
+ });
409
+
410
+ it("an agent with one App writes the same cache rows as the single-App crawl", async () => {
411
+ const agent = await agentWithApps([
412
+ { appId: "777", clientId: "Iv1.agentapp0001", slug: "doc-agent" },
413
+ ]);
414
+ const shape = async () =>
415
+ (await snapshots("777")).map((s) => ({
416
+ org: s.org,
417
+ completedAt: s.completedAt,
418
+ totalCount: s.totalCount,
419
+ repositorySelection: s.repositorySelection,
420
+ repos: s.repos.map((r) => r.fullName).sort(),
421
+ }));
422
+
423
+ await crawlAgentInstallations({
424
+ agent,
425
+ org: "acme-eng",
426
+ client: setup({ installs: "org_installations_agent", total: 3 }).client,
427
+ store: cache,
428
+ clock,
429
+ });
430
+ const viaApps = await shape();
431
+
432
+ await prisma.gitHubCachedRepo.deleteMany();
433
+ await prisma.gitHubRepoSnapshot.deleteMany();
434
+ await crawlAgentInstallation({
435
+ agent: {
436
+ accountId: null,
437
+ appId: 777,
438
+ clientId: "Iv1.agentapp0001",
439
+ slug: "doc-agent",
440
+ },
441
+ org: "acme-eng",
442
+ client: setup({ installs: "org_installations_agent", total: 3 }).client,
443
+ store: cache,
444
+ clock,
445
+ });
446
+ expect(viaApps).toEqual(await shape());
447
+ expect(viaApps).toHaveLength(1);
448
+ });
449
+ },
450
+ );
@@ -4,7 +4,9 @@
4
4
  *
5
5
  * A PageSource over the installer client's single-page installation listing,
6
6
  * fed through the same resumable engine (crawlRepos) and completeness check as
7
- * the lookup crawl, under appKind "agent" and appRef = the agent's GH_APP_ID.
7
+ * the lookup crawl, under appKind "agent" and appRef = the App's id. An agent
8
+ * with several Apps is crawled once per App (crawlAgentInstallations), each
9
+ * into its own snapshot with its own repository selection.
8
10
  * Scheduling lives in github-repo-refresher.ts (GLC-1.4).
9
11
  */
10
12
 
@@ -20,6 +22,7 @@ import {
20
22
  import {
21
23
  type AppIdentity,
22
24
  AppNotInstalledError,
25
+ agentApps,
23
26
  type InstallationAgentRecord,
24
27
  type InstallationRepoClient,
25
28
  matchInstallation,
@@ -268,3 +271,40 @@ export async function crawlAgentInstallation(
268
271
  };
269
272
  }
270
273
  }
274
+
275
+ export interface CrawlAgentInstallationsOptions
276
+ extends Omit<CrawlAgentInstallationOptions, "agent"> {
277
+ agent: Pick<
278
+ InstallationAgentRecord,
279
+ "accountId" | "appId" | "clientId" | "slug" | "apps"
280
+ >;
281
+ }
282
+
283
+ /** One App's crawl result from crawlAgentInstallations. */
284
+ export interface AgentAppCrawlResult {
285
+ appId: number;
286
+ result: AgentInstallationCrawlResult;
287
+ }
288
+
289
+ /**
290
+ * Crawl every App of the agent (agentApps, priority order) on one org, one
291
+ * crawlAgentInstallation per App, so each App's installation and repository
292
+ * selection land in its own snapshot (appRef = that App's id). An agent with
293
+ * no App crawls nothing.
294
+ */
295
+ export async function crawlAgentInstallations(
296
+ opts: CrawlAgentInstallationsOptions,
297
+ ): Promise<AgentAppCrawlResult[]> {
298
+ const { agent, ...rest } = opts;
299
+ const out: AgentAppCrawlResult[] = [];
300
+ for (const app of agentApps(agent)) {
301
+ out.push({
302
+ appId: app.appId,
303
+ result: await crawlAgentInstallation({
304
+ ...rest,
305
+ agent: { accountId: agent.accountId, ...app },
306
+ }),
307
+ });
308
+ }
309
+ return out;
310
+ }
@@ -10,6 +10,7 @@ import {
10
10
  type AgentInstallationClient,
11
11
  agentInstallationPageSource,
12
12
  crawlAgentInstallation,
13
+ crawlAgentInstallations,
13
14
  DEPLOYMENT_WIDE_ACCOUNT_KEY,
14
15
  getAccessRowsAcrossKeys,
15
16
  lookupAccountKeys,
@@ -542,3 +543,157 @@ describe("getAccessRowsAcrossKeys", () => {
542
543
  expect(store.queried).toEqual([DEPLOYMENT_WIDE_ACCOUNT_KEY]);
543
544
  });
544
545
  });
546
+
547
+ /** A CrawlStore keyed by SnapshotKey, so several apps' snapshots coexist. */
548
+ class KeyedStore implements CrawlStore {
549
+ snaps = new Map<string, CrawlSnapshot>();
550
+ rows = new Map<string, Map<number, Date>>();
551
+ private k = (key: SnapshotKey) =>
552
+ `${key.accountId}|${key.appKind}|${key.appRef}|${key.org}`;
553
+ async getSnapshot(key: SnapshotKey) {
554
+ const s = this.snaps.get(this.k(key));
555
+ return s ? { ...s } : null;
556
+ }
557
+ async upsertSnapshot(key: SnapshotKey, progress: SnapshotProgress = {}) {
558
+ const id = this.k(key);
559
+ const next = {
560
+ ...(this.snaps.get(id) ?? {
561
+ id,
562
+ crawlPage: 0,
563
+ crawlStartedAt: null,
564
+ completedAt: null,
565
+ totalCount: null,
566
+ lastError: null,
567
+ attempts: 0,
568
+ nextAttemptAt: null,
569
+ rateLimitResetAt: null,
570
+ lastTickAt: null,
571
+ }),
572
+ } as Record<string, unknown>;
573
+ for (const [f, v] of Object.entries(progress)) {
574
+ if (v !== undefined) next[f] = v;
575
+ }
576
+ this.snaps.set(id, next as unknown as CrawlSnapshot);
577
+ return { ...(next as unknown as CrawlSnapshot) };
578
+ }
579
+ async upsertRepos(id: string, repos: CachedRepoInput[], seenAt: Date) {
580
+ const m = this.rows.get(id) ?? new Map<number, Date>();
581
+ for (const r of repos) m.set(Number(r.githubId), seenAt);
582
+ this.rows.set(id, m);
583
+ return repos.length;
584
+ }
585
+ async countReposSeenSince(id: string, since: Date) {
586
+ return [...(this.rows.get(id)?.values() ?? [])].filter((d) => d >= since)
587
+ .length;
588
+ }
589
+ async sweepGeneration() {
590
+ return 0;
591
+ }
592
+ selection(id: string) {
593
+ return (this.snaps.get(id) as unknown as Record<string, unknown>)
594
+ ?.repositorySelection;
595
+ }
596
+ }
597
+
598
+ describe("crawlAgentInstallations (one crawl per app)", () => {
599
+ /** Two apps installed on the org with different selections; app 3 is not. */
600
+ function multiClient() {
601
+ const pagesFor: number[] = [];
602
+ const client: AgentInstallationClient = {
603
+ async listOrgInstallations() {
604
+ return [
605
+ { id: 501, appId: 777, repositorySelection: "selected" as const },
606
+ {
607
+ id: 601,
608
+ appSlug: "second-app",
609
+ repositorySelection: "all" as const,
610
+ },
611
+ ];
612
+ },
613
+ async listInstallationRepositoriesPage(_org, installationId) {
614
+ pagesFor.push(installationId);
615
+ const base = installationId * 10;
616
+ return {
617
+ repos: [1, 2].map((i) => ({
618
+ id: base + i,
619
+ fullName: `acme/r${base + i}`,
620
+ })),
621
+ hasNext: false,
622
+ perPage: 100,
623
+ };
624
+ },
625
+ };
626
+ return { client, pagesFor };
627
+ }
628
+
629
+ it("crawls every app into its own snapshot and records each app's selection", async () => {
630
+ const store = new KeyedStore();
631
+ const { client, pagesFor } = multiClient();
632
+ const results = await crawlAgentInstallations({
633
+ agent: {
634
+ accountId: "acc",
635
+ appId: 777,
636
+ apps: [
637
+ { appId: 777 },
638
+ { appId: 888, slug: "second-app" },
639
+ { appId: 999, slug: "missing-app" },
640
+ ],
641
+ },
642
+ org: "acme",
643
+ client,
644
+ store,
645
+ clock,
646
+ });
647
+ expect(results.map((r) => [r.appId, r.result.outcome])).toEqual([
648
+ [777, "complete"],
649
+ [888, "complete"],
650
+ [999, "not_installed"],
651
+ ]);
652
+ expect(pagesFor).toEqual([501, 601]);
653
+ expect([...store.snaps.keys()]).toEqual([
654
+ "acc|agent|777|acme",
655
+ "acc|agent|888|acme",
656
+ "acc|agent|999|acme",
657
+ ]);
658
+ expect(store.selection("acc|agent|777|acme")).toBe("selected");
659
+ expect(store.selection("acc|agent|888|acme")).toBe("all");
660
+ expect(store.selection("acc|agent|999|acme")).toBeNull();
661
+ expect(store.rows.get("acc|agent|888|acme")?.size).toBe(2);
662
+ });
663
+
664
+ it("a single-app agent crawls exactly as crawlAgentInstallation does", async () => {
665
+ const viaMany = new KeyedStore();
666
+ const viaOne = new KeyedStore();
667
+ const single = { accountId: null, appId: 777 };
668
+ const many = await crawlAgentInstallations({
669
+ agent: single,
670
+ org: "acme",
671
+ client: multiClient().client,
672
+ store: viaMany,
673
+ clock,
674
+ });
675
+ const one = await crawlAgentInstallation({
676
+ agent: single,
677
+ org: "acme",
678
+ client: multiClient().client,
679
+ store: viaOne,
680
+ clock,
681
+ });
682
+ expect(many).toEqual([{ appId: 777, result: one }]);
683
+ expect([...viaMany.snaps.entries()]).toEqual([...viaOne.snaps.entries()]);
684
+ });
685
+
686
+ it("does nothing for an agent with no app", async () => {
687
+ const store = new KeyedStore();
688
+ expect(
689
+ await crawlAgentInstallations({
690
+ agent: { accountId: "acc" },
691
+ org: "acme",
692
+ client: multiClient().client,
693
+ store,
694
+ clock,
695
+ }),
696
+ ).toEqual([]);
697
+ expect(store.snaps.size).toBe(0);
698
+ });
699
+ });
@@ -3,8 +3,9 @@
3
3
  * Composition of the installation repos list and GitHub Sync services for
4
4
  * admin boot, from the stored installer App and an optional host-supplied
5
5
  * OpenWorkPort, plus the GitHub cache refresher's target discovery over the
6
- * stored Apps (GLC-1.4). The agent App id comes from each agent's own stored
7
- * GH_APP_ID; without an open-work port nothing is listed or blocked.
6
+ * stored Apps (GLC-1.4). The agent Apps come from each agent's AgentGitHubApp
7
+ * rows (else its stored GH_APP_ID); without an open-work port nothing is
8
+ * listed or blocked.
8
9
  */
9
10
 
10
11
  import type { PrismaClient } from "../prisma/client/client.ts";
@@ -12,7 +13,7 @@ import type { AgentEnvService } from "./agent-envs.ts";
12
13
  import type { Clock } from "./clock.ts";
13
14
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
14
15
  import {
15
- crawlAgentInstallation,
16
+ crawlAgentInstallations,
16
17
  DEPLOYMENT_WIDE_ACCOUNT_KEY,
17
18
  lookupKeysForApp,
18
19
  } from "./github-agent-installation-crawler.ts";
@@ -256,9 +257,10 @@ export function createGithubSync(
256
257
  return undefined;
257
258
  }
258
259
  },
259
- // Re-crawl just the changed org so the UI list is current after apply.
260
+ // Re-crawl just the changed org (every agent App) so the UI list is
261
+ // current after apply.
260
262
  refreshAgentSnapshot: async (agent, org) => {
261
- await crawlAgentInstallation({
263
+ await crawlAgentInstallations({
262
264
  agent,
263
265
  org,
264
266
  client,
@@ -91,6 +91,8 @@ export function fakePrisma(repos: string[], cache: FakeCache = {}) {
91
91
  state.repos = args.data.repos;
92
92
  },
93
93
  },
94
+ // No AgentGitHubApp rows: the agent's App comes from its stored GH_APP_ID.
95
+ agentGitHubApp: { findMany: async () => [] },
94
96
  gitHubRepoSnapshot: {
95
97
  findMany: async (args: unknown) => {
96
98
  state.snapshotQueries.push(args);
@@ -10,12 +10,14 @@
10
10
  * per org, keyed by the scope that owns the lookup App (accountId, or
11
11
  * DEPLOYMENT_WIDE_ACCOUNT_KEY). Orgs come from the resolved installer App when
12
12
  * it has an enterprise slug, else from the lookup App's own installations.
13
- * Agents with a GH_APP_ID and a GitHub username whose account resolves to that
14
- * lookup App supply the access-backfill users.
13
+ * Agents with at least one App and a GitHub username whose account resolves
14
+ * to that lookup App supply the access-backfill users; every App of theirs
15
+ * contributes an installation key.
15
16
  *
16
- * Each agent with a GH_APP_ID also gets one agent target per org its account's
17
- * installer can reach (keyed as GLC-1.5 keys it). No installer, no agent
18
- * targets.
17
+ * Each agent App (agentApps: the AgentGitHubApp rows, else the legacy
18
+ * GH_APP_ID) also gets one agent target per org its account's installer can
19
+ * reach (keyed as GLC-1.5 keys it, appRef = that App's id). An agent with one
20
+ * App gets exactly the targets it always did. No installer, no agent targets.
19
21
  *
20
22
  * Keys are deduplicated, and a scope or agent whose discovery fails is logged
21
23
  * and skipped without affecting the rest. The stored-App wiring (key-bearing)
@@ -44,7 +46,10 @@ import {
44
46
  type RefreshTarget,
45
47
  snapshotKeyString,
46
48
  } from "./github-repo-refresher.ts";
47
- import type { InstallationAgentRecord } from "./installation-ports.ts";
49
+ import {
50
+ agentApps,
51
+ type InstallationAgentRecord,
52
+ } from "./installation-ports.ts";
48
53
 
49
54
  /** The lookup-client surface discovery and its targets use. */
50
55
  export type LookupAppClient = AccessProbe &
@@ -145,7 +150,7 @@ export function createRefreshDiscovery(
145
150
  // Access users per lookup scope key: agents with an App and a user.
146
151
  const usersByScope = new Map<string, InstallationAgentRecord[]>();
147
152
  for (const a of agents) {
148
- if (a.appId === undefined || !a.githubUsername?.trim()) continue;
153
+ if (agentApps(a).length === 0 || !a.githubUsername?.trim()) continue;
149
154
  try {
150
155
  const lookup = await lookupFor(a.accountId ?? null);
151
156
  if (!lookup) continue;
@@ -194,13 +199,15 @@ export function createRefreshDiscovery(
194
199
  access: {
195
200
  probe: lookup.client,
196
201
  users,
197
- installationKeys: bound.map(
198
- (a): SnapshotKey => ({
199
- accountId: scopeKeyOf(a.accountId),
200
- appKind: "agent",
201
- appRef: String(a.appId),
202
- org,
203
- }),
202
+ installationKeys: bound.flatMap((a) =>
203
+ agentApps(a).map(
204
+ (app): SnapshotKey => ({
205
+ accountId: scopeKeyOf(a.accountId),
206
+ appKind: "agent",
207
+ appRef: String(app.appId),
208
+ org,
209
+ }),
210
+ ),
204
211
  ),
205
212
  },
206
213
  }
@@ -215,28 +222,31 @@ export function createRefreshDiscovery(
215
222
  }
216
223
 
217
224
  for (const a of agents) {
218
- if (a.appId === undefined) continue;
225
+ const apps = agentApps(a);
226
+ if (apps.length === 0) continue;
219
227
  try {
220
228
  const orgs = await installerOrgsFor(a.accountId ?? null);
221
229
  if (!orgs) continue;
222
230
  for (const org of orgs) {
223
- add({
224
- key: {
225
- accountId: scopeKeyOf(a.accountId),
226
- appKind: "agent",
227
- appRef: String(a.appId),
228
- org,
229
- },
230
- crawl: (ctx) =>
231
- crawlAgentInstallation({
232
- agent: a,
231
+ for (const app of apps) {
232
+ add({
233
+ key: {
234
+ accountId: scopeKeyOf(a.accountId),
235
+ appKind: "agent",
236
+ appRef: String(app.appId),
233
237
  org,
234
- client: installer,
235
- store,
236
- clock,
237
- shouldStop: ctx.shouldStop,
238
- }),
239
- });
238
+ },
239
+ crawl: (ctx) =>
240
+ crawlAgentInstallation({
241
+ agent: { accountId: a.accountId, ...app },
242
+ org,
243
+ client: installer,
244
+ store,
245
+ clock,
246
+ shouldStop: ctx.shouldStop,
247
+ }),
248
+ });
249
+ }
240
250
  }
241
251
  } catch (err) {
242
252
  log(
@@ -107,6 +107,92 @@ describe("createRefreshDiscovery", () => {
107
107
  expect(targets[2]?.access).toBeUndefined();
108
108
  });
109
109
 
110
+ it("emits one agent target per app per org, and every app's installation keys for access", async () => {
111
+ const d = createRefreshDiscovery(
112
+ ports({
113
+ listAgents: async () => [
114
+ agent({
115
+ id: "a1",
116
+ appId: 777,
117
+ apps: [{ appId: 777 }, { appId: 888, slug: "second-app" }],
118
+ githubUsername: "octocat",
119
+ }),
120
+ ],
121
+ }),
122
+ );
123
+ const targets = await d.listTargets();
124
+ expect(keys(targets)).toEqual([
125
+ "deployment|lookup|555|acme",
126
+ "deployment|lookup|555|beta",
127
+ "deployment|agent|777|acme",
128
+ "deployment|agent|888|acme",
129
+ "deployment|agent|777|beta",
130
+ "deployment|agent|888|beta",
131
+ ]);
132
+ expect(targets[0]?.access?.users).toEqual([
133
+ { username: "octocat", configuredRepos: [] },
134
+ ]);
135
+ expect(
136
+ targets[0]?.access?.installationKeys?.map((k) => `${k.appRef}|${k.org}`),
137
+ ).toEqual(["777|acme", "888|acme"]);
138
+ });
139
+
140
+ it("a single-app agent yields the same targets with or without the apps list", async () => {
141
+ const run = async (a: InstallationAgentRecord) =>
142
+ (
143
+ await createRefreshDiscovery(
144
+ ports({ listAgents: async () => [a] }),
145
+ ).listTargets()
146
+ ).map((t) => ({
147
+ key: t.key,
148
+ installationKeys: t.access?.installationKeys,
149
+ }));
150
+ const legacy = agent({ appId: 777, githubUsername: "octocat" });
151
+ expect(await run({ ...legacy, apps: [{ appId: 777 }] })).toEqual(
152
+ await run(legacy),
153
+ );
154
+ });
155
+
156
+ it("crawls each app's own installation for its target", async () => {
157
+ const seen: string[] = [];
158
+ const d = createRefreshDiscovery(
159
+ ports({
160
+ installerOrgs: async () => ["acme"],
161
+ installer: {
162
+ async listOrgInstallations() {
163
+ return [{ id: 601, appSlug: "second-app" }];
164
+ },
165
+ async listInstallationRepositoriesPage(_org, id) {
166
+ seen.push(`page:${id}`);
167
+ throw new Error("stop");
168
+ },
169
+ },
170
+ store: {
171
+ getSnapshot: async () => null,
172
+ upsertSnapshot: async (k: { appRef: string }) => {
173
+ seen.push(`snap:${k.appRef}`);
174
+ return { id: k.appRef } as never;
175
+ },
176
+ upsertRepos: async () => 0,
177
+ countReposSeenSince: async () => 0,
178
+ sweepGeneration: async () => 0,
179
+ } as unknown as DiscoveryPorts["store"],
180
+ listAgents: async () => [
181
+ agent({
182
+ appId: 777,
183
+ apps: [{ appId: 777 }, { appId: 888, slug: "second-app" }],
184
+ }),
185
+ ],
186
+ }),
187
+ );
188
+ const target = (await d.listTargets()).find(
189
+ (t) => t.key.appKind === "agent" && t.key.appRef === "888",
190
+ );
191
+ await target?.crawl({ shouldStop: () => false });
192
+ expect(seen).toContain("page:601");
193
+ expect(seen.every((s) => s === "page:601" || s === "snap:888")).toBe(true);
194
+ });
195
+
110
196
  it("uses the lookup App's own installations when no installer is configured, with no agent targets", async () => {
111
197
  const d = createRefreshDiscovery(
112
198
  ports({
@@ -36,6 +36,7 @@ describeOrSkip("installation ports (integration)", () => {
36
36
  await prisma.agentTool.deleteMany();
37
37
  await prisma.agentEnv.deleteMany();
38
38
  await prisma.agentMember.deleteMany();
39
+ await prisma.agentGitHubApp.deleteMany();
39
40
  await prisma.agent.deleteMany();
40
41
  });
41
42
 
@@ -43,24 +44,99 @@ describeOrSkip("installation ports (integration)", () => {
43
44
  await prisma.$disconnect();
44
45
  });
45
46
 
46
- it("reads the agent's own GH_APP_ID and writes its repos", async () => {
47
+ const addApp = (
48
+ agentId: string,
49
+ appId: string,
50
+ over: {
51
+ slug?: string | null;
52
+ clientId?: string | null;
53
+ priority?: number;
54
+ createdAt?: Date;
55
+ } = {},
56
+ ) =>
57
+ prisma.agentGitHubApp.create({
58
+ data: {
59
+ agentId,
60
+ appId,
61
+ privateKeyEncrypted: "ciphertext",
62
+ slug: over.slug ?? null,
63
+ clientId: over.clientId ?? null,
64
+ priority: over.priority ?? 0,
65
+ ...(over.createdAt ? { createdAt: over.createdAt } : {}),
66
+ },
67
+ });
68
+
69
+ it("falls back to the stored GH_APP_ID as a single app and writes repos", async () => {
47
70
  const a = await prisma.agent.create({
48
71
  data: { name: "A", repos: ["acme/a"], githubUsername: "dev" },
49
72
  });
50
73
  const agents = new PrismaInstallationAgents(prisma, env());
51
- expect((await agents.get(a.id))?.appId).toBeUndefined();
52
- await env().patch(a.id, { GH_APP_ID: "42" });
74
+ const none = await agents.get(a.id);
75
+ expect(none?.appId).toBeUndefined();
76
+ expect(none?.apps).toBeUndefined();
77
+ await env().patch(a.id, { GH_APP_ID: "42", GH_APP_SLUG: "env-app" });
53
78
  expect(await agents.get(a.id)).toMatchObject({
54
79
  id: a.id,
55
80
  repos: ["acme/a"],
56
81
  githubUsername: "dev",
57
82
  appId: 42,
83
+ slug: "env-app",
84
+ apps: [{ appId: 42, slug: "env-app" }],
58
85
  });
59
86
  await agents.setRepos(a.id, ["acme/b"]);
60
87
  expect((await agents.get(a.id))?.repos).toEqual(["acme/b"]);
61
88
  expect(await agents.get("missing")).toBeNull();
62
89
  });
63
90
 
91
+ it("resolves every app from the agent's GitHub apps table in priority order", async () => {
92
+ const a = await prisma.agent.create({ data: { name: "A", repos: [] } });
93
+ // The table is authoritative once it has rows: the env app is ignored.
94
+ await env().patch(a.id, { GH_APP_ID: "999" });
95
+ await addApp(a.id, "300", { priority: 2, slug: "third-app" });
96
+ await addApp(a.id, "100", {
97
+ priority: 0,
98
+ clientId: "Iv1.first",
99
+ slug: "first-app",
100
+ });
101
+ await addApp(a.id, "200", { priority: 1, clientId: "bad client/id" });
102
+ const rec = await new PrismaInstallationAgents(prisma, env()).get(a.id);
103
+ expect(rec?.apps).toEqual([
104
+ { appId: 100, clientId: "Iv1.first", slug: "first-app" },
105
+ // A malformed client id is dropped, like a malformed env value.
106
+ { appId: 200 },
107
+ { appId: 300, slug: "third-app" },
108
+ ]);
109
+ // The primary (highest-priority) app keeps the single-app fields.
110
+ expect(rec).toMatchObject({
111
+ appId: 100,
112
+ clientId: "Iv1.first",
113
+ slug: "first-app",
114
+ });
115
+ });
116
+
117
+ it("an agent with one table app resolves exactly as its GH_APP_ID did", async () => {
118
+ const viaEnv = await prisma.agent.create({
119
+ data: { name: "E", repos: [] },
120
+ });
121
+ await env().patch(viaEnv.id, {
122
+ GH_APP_ID: "42",
123
+ GH_APP_CLIENT_ID: "Iv1.one",
124
+ GH_APP_SLUG: "one-app",
125
+ });
126
+ const viaTable = await prisma.agent.create({
127
+ data: { name: "T", repos: [] },
128
+ });
129
+ await addApp(viaTable.id, "42", { clientId: "Iv1.one", slug: "one-app" });
130
+ const agents = new PrismaInstallationAgents(prisma, env());
131
+ const withoutId = async (id: string) => {
132
+ const rec = await agents.get(id);
133
+ return { ...rec, id: "" };
134
+ };
135
+ const fromEnv = await withoutId(viaEnv.id);
136
+ const fromTable = await withoutId(viaTable.id);
137
+ expect(fromTable).toEqual(fromEnv);
138
+ });
139
+
64
140
  it("writes one audit row per entry and returns its id", async () => {
65
141
  const a = await prisma.agent.create({ data: { name: "A", repos: [] } });
66
142
  const audit = new PrismaInstallationAudit(prisma);
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * admin/src/installation-ports.ts
3
3
  * Ports and Prisma/GitHub-backed adapters shared by the installation repos
4
- * service (IRM-1.2) and GitHub Sync (IRM-3.1): the agent record
5
- * with its own GH_APP_ID, installation list/add/remove scoped to that App, and
6
- * the audit table (GitHubReconcileAudit) every change is recorded in.
4
+ * service (IRM-1.2) and GitHub Sync (IRM-3.1): the agent record with all of
5
+ * its own GitHub Apps (the AgentGitHubApp table, else its legacy GH_APP_ID),
6
+ * installation list/add/remove scoped to one named App, and the audit table
7
+ * (GitHubReconcileAudit) every change is recorded in.
7
8
  */
8
9
 
9
10
  import type { PrismaClient } from "../prisma/client/client.ts";
10
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import { sortAgentGitHubApps } from "./agent-github-apps.ts";
11
13
 
12
14
  /** Parses a stored GH_APP_ID; unset or non-numeric -> undefined. */
13
15
  function parseAppId(raw: string | undefined): number | undefined {
@@ -29,6 +31,15 @@ function validEnv(raw: string | undefined, re: RegExp): string | undefined {
29
31
  /** More removals than this need confirmRemovals. */
30
32
  export const MAX_UNCONFIRMED_REMOVALS = 10;
31
33
 
34
+ /** One of an agent's own GitHub Apps, as the installation code matches it. */
35
+ export interface AgentAppRef {
36
+ appId: number;
37
+ /** Omitted when unset or malformed. */
38
+ clientId?: string;
39
+ /** Omitted when unset or malformed. */
40
+ slug?: string;
41
+ }
42
+
32
43
  export interface InstallationAgentRecord {
33
44
  id: string;
34
45
  /** The agent's account; selects that account's GitHub App pair (null/absent: deployment-wide). */
@@ -41,6 +52,31 @@ export interface InstallationAgentRecord {
41
52
  clientId?: string;
42
53
  /** The agent App's slug (stored GH_APP_SLUG); undefined when unset or malformed. */
43
54
  slug?: string;
55
+ /**
56
+ * Every App of the agent in priority order (lowest priority first). The
57
+ * first is the primary App that appId/clientId/slug describe. Absent when
58
+ * the agent has no App; read through agentApps().
59
+ */
60
+ apps?: AgentAppRef[];
61
+ }
62
+
63
+ /**
64
+ * The agent's Apps in priority order: `apps` when set, else the single primary
65
+ * App (appId/clientId/slug), else none. Records built without `apps` keep
66
+ * their single-App behaviour.
67
+ */
68
+ export function agentApps(
69
+ agent: Pick<InstallationAgentRecord, "apps" | "appId" | "clientId" | "slug">,
70
+ ): AgentAppRef[] {
71
+ if (agent.apps && agent.apps.length > 0) return agent.apps;
72
+ if (agent.appId === undefined) return [];
73
+ return [
74
+ {
75
+ appId: agent.appId,
76
+ ...(agent.clientId === undefined ? {} : { clientId: agent.clientId }),
77
+ ...(agent.slug === undefined ? {} : { slug: agent.slug }),
78
+ },
79
+ ];
44
80
  }
45
81
 
46
82
  /**
@@ -135,7 +171,28 @@ export class PrismaInstallationAudit implements InstallationAuditPort {
135
171
  }
136
172
  }
137
173
 
138
- /** Prisma-backed agent reads/writes. */
174
+ /** An AgentAppRef from stored values; null when the app id is unusable. */
175
+ function appRef(
176
+ rawAppId: string | undefined,
177
+ rawClientId: string | null | undefined,
178
+ rawSlug: string | null | undefined,
179
+ ): AgentAppRef | null {
180
+ const appId = parseAppId(rawAppId);
181
+ if (appId === undefined) return null;
182
+ const clientId = validEnv(rawClientId ?? undefined, CLIENT_ID_RE);
183
+ const slug = validEnv(rawSlug ?? undefined, SLUG_RE);
184
+ return {
185
+ appId,
186
+ ...(clientId === undefined ? {} : { clientId }),
187
+ ...(slug === undefined ? {} : { slug }),
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Prisma-backed agent reads/writes. The agent's Apps come from the
193
+ * AgentGitHubApp table, which is authoritative once it has rows; an agent
194
+ * without rows falls back to its legacy GH_APP_* env as one App.
195
+ */
139
196
  export class PrismaInstallationAgents implements InstallationAgentsPort {
140
197
  constructor(
141
198
  private readonly prisma: PrismaClient,
@@ -148,19 +205,37 @@ export class PrismaInstallationAgents implements InstallationAgentsPort {
148
205
  select: { id: true, repos: true, githubUsername: true, accountId: true },
149
206
  });
150
207
  if (!agent) return null;
151
- const env = (await this.env.getConfigBundle(agentId))?.env;
152
- const raw = env?.GH_APP_ID;
153
- const appId = parseAppId(raw);
154
- const clientId = validEnv(env?.GH_APP_CLIENT_ID, CLIENT_ID_RE);
155
- const slug = validEnv(env?.GH_APP_SLUG, SLUG_RE);
208
+ const apps = await this.resolveApps(agentId);
209
+ const primary = apps[0];
156
210
  return {
157
211
  ...agent,
158
- ...(appId === undefined ? {} : { appId }),
159
- ...(clientId === undefined ? {} : { clientId }),
160
- ...(slug === undefined ? {} : { slug }),
212
+ ...(primary ?? {}),
213
+ ...(apps.length > 0 ? { apps } : {}),
161
214
  };
162
215
  }
163
216
 
217
+ private async resolveApps(agentId: string): Promise<AgentAppRef[]> {
218
+ const rows = await this.prisma.agentGitHubApp.findMany({
219
+ where: { agentId },
220
+ select: {
221
+ id: true,
222
+ appId: true,
223
+ slug: true,
224
+ clientId: true,
225
+ priority: true,
226
+ createdAt: true,
227
+ },
228
+ });
229
+ if (rows.length > 0) {
230
+ return sortAgentGitHubApps(rows)
231
+ .map((r) => appRef(r.appId, r.clientId, r.slug))
232
+ .filter((a): a is AgentAppRef => a !== null);
233
+ }
234
+ const env = (await this.env.getConfigBundle(agentId))?.env;
235
+ const app = appRef(env?.GH_APP_ID, env?.GH_APP_CLIENT_ID, env?.GH_APP_SLUG);
236
+ return app ? [app] : [];
237
+ }
238
+
164
239
  async setRepos(agentId: string, repos: string[]): Promise<void> {
165
240
  await this.prisma.agent.update({
166
241
  where: { id: agentId },
@@ -7,6 +7,7 @@ import { describe, expect, it } from "bun:test";
7
7
  import enterpriseOrgInstallations from "./fixtures/enterprise-org-installations.json";
8
8
  import {
9
9
  AppNotInstalledError,
10
+ agentApps,
10
11
  createInstallationPort,
11
12
  matchInstallation,
12
13
  } from "./installation-ports.ts";
@@ -101,3 +102,25 @@ describe("createInstallationPort", () => {
101
102
  );
102
103
  });
103
104
  });
105
+
106
+ describe("agentApps", () => {
107
+ it("returns every resolved app in priority order", () => {
108
+ const apps = [
109
+ { appId: 1, slug: "first-app" },
110
+ { appId: 2, clientId: "Iv1.second" },
111
+ ];
112
+ expect(agentApps({ appId: 1, slug: "first-app", apps })).toEqual(apps);
113
+ });
114
+
115
+ it("falls back to the single primary app when apps is absent or empty", () => {
116
+ expect(
117
+ agentApps({ appId: 42, clientId: "Iv1.aaa", slug: "app-one" }),
118
+ ).toEqual([{ appId: 42, clientId: "Iv1.aaa", slug: "app-one" }]);
119
+ expect(agentApps({ appId: 42, apps: [] })).toEqual([{ appId: 42 }]);
120
+ });
121
+
122
+ it("is empty for an agent with no app", () => {
123
+ expect(agentApps({})).toEqual([]);
124
+ expect(agentApps({ apps: [] })).toEqual([]);
125
+ });
126
+ });
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * admin/src/installation-repos-service.ts
3
- * Read-only listing of the repos on an agent's own GitHub App installation
4
- * (IRM-1.2), with the bound user's push hint. list() reads only the repo/access
3
+ * Read-only listing of the repos on an agent's own GitHub App installations
4
+ * (IRM-1.2), with the bound user's push hint. An agent with several Apps
5
+ * lists each org once, from the highest-priority App installed there. list() reads only the repo/access
5
6
  * cache (GLC-2.2): no GitHub call, sync detail alongside. Changes go through
6
7
  * the Sync flow (github-sync.ts, IRM-3.1), which still uses the installer App
7
8
  * through the installation port.
@@ -21,6 +22,7 @@ import {
21
22
  type AppIdentity,
22
23
  type AppInstallationPort,
23
24
  AppNotInstalledError,
25
+ agentApps,
24
26
  type InstallationAgentsPort,
25
27
  MISSING_APP_ID_REASON,
26
28
  } from "./installation-ports.ts";
@@ -245,6 +247,33 @@ function withAccessDetail(
245
247
  });
246
248
  }
247
249
 
250
+ /** True when the snapshot shows the App installed on its org. */
251
+ const installedOn = (s: InstallationSnapshotRow): boolean =>
252
+ (s.repositorySelection ?? null) !== null || s.repos.length > 0;
253
+
254
+ /**
255
+ * Merges each App's cached snapshots (lists in App priority order) into one
256
+ * snapshot per org: the highest-priority App installed on the org (a known
257
+ * repository selection or any cached repo), else the first App's snapshot. An
258
+ * App not installed on an org still records an empty snapshot for it, which
259
+ * must not hide a lower-priority App's installation. Orgs keep first-seen
260
+ * order; a single list is returned as is.
261
+ */
262
+ export function mergeAppSnapshots(
263
+ perApp: readonly (readonly InstallationSnapshotRow[])[],
264
+ ): InstallationSnapshotRow[] {
265
+ if (perApp.length === 1) return perApp[0] as InstallationSnapshotRow[];
266
+ const byOrg = new Map<string, InstallationSnapshotRow>();
267
+ for (const list of perApp) {
268
+ for (const s of list) {
269
+ const k = orgKey(s.org);
270
+ const held = byOrg.get(k);
271
+ if (!held || (!installedOn(held) && installedOn(s))) byOrg.set(k, s);
272
+ }
273
+ }
274
+ return [...byOrg.values()];
275
+ }
276
+
248
277
  const iso = (d: Date | null): string | undefined =>
249
278
  d ? d.toISOString() : undefined;
250
279
 
@@ -308,9 +337,15 @@ export class InstallationReposService {
308
337
  }
309
338
  const cache = this.deps.cache;
310
339
  const accountId = agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY;
311
- const snapshots = cache
312
- ? await cache.listAgentSnapshots(accountId, String(agent.appId))
313
- : [];
340
+ const perApp: InstallationSnapshotRow[][] = [];
341
+ if (cache) {
342
+ for (const app of agentApps(agent)) {
343
+ perApp.push(
344
+ await cache.listAgentSnapshots(accountId, String(app.appId)),
345
+ );
346
+ }
347
+ }
348
+ const snapshots = mergeAppSnapshots(perApp);
314
349
  const state = this.deps.appsState
315
350
  ? await this.deps.appsState(agent.accountId)
316
351
  : "both";
@@ -10,6 +10,7 @@ import {
10
10
  type InstallationCachePort,
11
11
  InstallationReposService,
12
12
  type InstallationSnapshotRow,
13
+ mergeAppSnapshots,
13
14
  userPushHints,
14
15
  } from "./installation-repos-service.ts";
15
16
  import type {
@@ -337,3 +338,102 @@ describe("InstallationReposService.list debug detail", () => {
337
338
  expect(r2.attempts).toBeUndefined();
338
339
  });
339
340
  });
341
+
342
+ describe("mergeAppSnapshots", () => {
343
+ const s = (
344
+ org: string,
345
+ over: Partial<InstallationSnapshotRow> = {},
346
+ ): InstallationSnapshotRow => ({
347
+ org,
348
+ completedAt: T0,
349
+ totalCount: 0,
350
+ lastError: null,
351
+ rateLimitResetAt: null,
352
+ repositorySelection: null,
353
+ repos: [],
354
+ ...over,
355
+ });
356
+
357
+ it("returns a single app's snapshots unchanged", () => {
358
+ const one = [s("acme"), s("beta", { repositorySelection: "all" })];
359
+ expect(mergeAppSnapshots([one])).toBe(one);
360
+ });
361
+
362
+ it("keeps one snapshot per org: the highest-priority app installed there", () => {
363
+ const first = [
364
+ s("acme", { repositorySelection: "selected" }),
365
+ // Not installed here (empty, no selection): the second app wins beta.
366
+ s("beta"),
367
+ ];
368
+ const second = [
369
+ s("acme", {
370
+ repositorySelection: "all",
371
+ repos: [{ fullName: "acme/x" }],
372
+ }),
373
+ s("Beta", {
374
+ repositorySelection: "all",
375
+ repos: [{ fullName: "Beta/y" }],
376
+ }),
377
+ s("gamma"),
378
+ ];
379
+ const merged = mergeAppSnapshots([first, second]);
380
+ expect(merged.map((m) => [m.org, m.repositorySelection])).toEqual([
381
+ ["acme", "selected"],
382
+ ["Beta", "all"],
383
+ ["gamma", null],
384
+ ]);
385
+ });
386
+
387
+ it("an org no app is installed on keeps the first app's snapshot", () => {
388
+ const a = s("acme", { lastError: "first" });
389
+ const b = s("acme", { lastError: "second" });
390
+ expect(mergeAppSnapshots([[a], [b]])).toEqual([a]);
391
+ });
392
+ });
393
+
394
+ describe("InstallationReposService.list with several apps", () => {
395
+ it("reads every app's snapshots and merges them per org", async () => {
396
+ const calls: string[] = [];
397
+ const byApp: Record<string, InstallationSnapshotRow[]> = {
398
+ "1": [snap({ org: "acme", repositorySelection: "selected" })],
399
+ "2": [
400
+ snap({
401
+ org: "beta",
402
+ repositorySelection: "all",
403
+ repos: [{ fullName: "beta/z" }],
404
+ totalCount: 1,
405
+ }),
406
+ ],
407
+ };
408
+ const svc = new InstallationReposService({
409
+ agents: {
410
+ get: async () => ({
411
+ id: "a1",
412
+ repos: [],
413
+ githubUsername: null,
414
+ accountId: "acct-1",
415
+ appId: 1,
416
+ apps: [{ appId: 1 }, { appId: 2, slug: "second-app" }],
417
+ }),
418
+ },
419
+ access: async () => ({ status: "unconfigured" }),
420
+ installation: {} as never,
421
+ cache: {
422
+ listAgentSnapshots: async (a, r) => {
423
+ calls.push(`${a}:${r}`);
424
+ return byApp[r] ?? [];
425
+ },
426
+ getAccessRows: async () => [],
427
+ },
428
+ });
429
+ const r = await svc.list("a1");
430
+ expect(calls).toEqual(["acct-1:1", "acct-1:2"]);
431
+ if (r.status !== "ok") throw new Error(r.status);
432
+ expect(r.appId).toBe(1);
433
+ expect(r.orgs.map((o) => [o.org, o.repos.length])).toEqual([
434
+ ["acme", 2],
435
+ ["beta", 1],
436
+ ]);
437
+ expect(r).toMatchObject({ reposSeen: 3, totalCount: 3, complete: true });
438
+ });
439
+ });