@app-vitals/agent-admin 1.129.0 → 1.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/package.json +2 -2
  2. package/src/admin-boot.ts +2 -0
  3. package/src/admin-ui-pages.ts +20 -6
  4. package/src/admin-ui-pages.unit.test.ts +23 -0
  5. package/src/admin-ui.ts +36 -2
  6. package/src/agent-github-apps-api.smoke.test.ts +155 -0
  7. package/src/agent-github-apps.integration.test.ts +168 -0
  8. package/src/agent-github-apps.ts +157 -0
  9. package/src/agent-github-apps.unit.test.ts +34 -0
  10. package/src/agents-api.smoke.test.ts +103 -0
  11. package/src/agents-api.ts +76 -1
  12. package/src/github-agent-installation-crawler.integration.test.ts +182 -11
  13. package/src/github-agent-installation-crawler.ts +41 -1
  14. package/src/github-agent-installation-crawler.unit.test.ts +155 -0
  15. package/src/github-enterprise-api.ts +14 -1
  16. package/src/github-installation-wiring.ts +7 -5
  17. package/src/github-installation.fixtures.ts +2 -0
  18. package/src/github-provisioning-service.integration.test.ts +189 -0
  19. package/src/github-provisioning-service.ts +66 -29
  20. package/src/github-provisioning-service.unit.test.ts +114 -6
  21. package/src/github-repo-refresh-discovery.ts +41 -31
  22. package/src/github-repo-refresh-discovery.unit.test.ts +86 -0
  23. package/src/github-sync-multi-app.integration.test.ts +122 -0
  24. package/src/github-sync-multi-app.unit.test.ts +156 -0
  25. package/src/github-sync.ts +59 -14
  26. package/src/installation-ports.integration.test.ts +79 -3
  27. package/src/installation-ports.ts +87 -12
  28. package/src/installation-ports.unit.test.ts +23 -0
  29. package/src/installation-repos-service.ts +40 -5
  30. package/src/installation-repos-service.unit.test.ts +100 -0
@@ -325,6 +325,49 @@ export function planGitHubAppBackfill(
325
325
  };
326
326
  }
327
327
 
328
+ /** The GH_APP_* keys a reader consumes that are not key material. */
329
+ export type GitHubAppEnvView = Partial<
330
+ Record<
331
+ "GH_APP_ID" | "GH_APP_SLUG" | "GH_APP_CLIENT_ID" | "GH_APP_INSTALLATION_ID",
332
+ string
333
+ >
334
+ >;
335
+
336
+ /** The non-secret fields of an app that readers overlay onto env. */
337
+ export type GitHubAppEnvSource = Pick<
338
+ AgentGitHubAppView,
339
+ "appId" | "slug" | "clientId" | "installationId"
340
+ >;
341
+
342
+ /**
343
+ * Overlay the agent's primary table app (lowest priority) onto its env map,
344
+ * for readers that still branch on GH_APP_* keys. When the agent has a table
345
+ * row the table is authoritative for the four non-secret keys (a null column
346
+ * removes the key); with no row the env map is returned unchanged, so an
347
+ * agent the backfill has not reached behaves as before. Returns a new object.
348
+ */
349
+ export function overlayGitHubAppEnv<T extends Record<string, string>>(
350
+ env: T,
351
+ primary: GitHubAppEnvSource | null,
352
+ ): Record<string, string> {
353
+ const out: Record<string, string> = { ...env };
354
+ if (!primary) return out;
355
+ const set = (key: string, value: string | null) => {
356
+ if (value === null) delete out[key];
357
+ else out[key] = value;
358
+ };
359
+ set("GH_APP_ID", primary.appId);
360
+ set("GH_APP_SLUG", primary.slug);
361
+ set("GH_APP_CLIENT_ID", primary.clientId);
362
+ set("GH_APP_INSTALLATION_ID", primary.installationId);
363
+ return out;
364
+ }
365
+
366
+ /** A legacy GH_APP_* env patch, as the provisioning and env writers carry it. */
367
+ export type LegacyGitHubAppEnvPatch = Partial<
368
+ Record<(typeof GH_APP_ENV_KEYS)[number], string>
369
+ >;
370
+
328
371
  // ─── Validation ───────────────────────────────────────────────────────────────
329
372
 
330
373
  function assertPositiveInt(field: string, value: string): void {
@@ -519,6 +562,120 @@ export class AgentGitHubAppService {
519
562
  return result.count > 0;
520
563
  }
521
564
 
565
+ /** The agent's primary app (lowest priority), or null when it has none. */
566
+ async getPrimary(agentId: string): Promise<AgentGitHubAppView | null> {
567
+ const [first] = await this.list(agentId);
568
+ return first ?? null;
569
+ }
570
+
571
+ /**
572
+ * Mirror a legacy GH_APP_* env write into the table (writers still write
573
+ * env until 1.11). The target row is the one matching GH_APP_ID when given,
574
+ * else the primary. An existing row is updated with the keys present; with
575
+ * no target, a row is created when both GH_APP_ID and GH_APP_PRIVATE_KEY are
576
+ * present (otherwise the patch is incomplete and ignored). A new GH_APP_ID on
577
+ * an agent with exactly one app replaces that app in place, matching the
578
+ * single-app overwrite semantics the env had. Returns the resulting view, or
579
+ * null when nothing was written.
580
+ */
581
+ async applyLegacyEnvPatch(
582
+ agentId: string,
583
+ patch: LegacyGitHubAppEnvPatch,
584
+ ): Promise<AgentGitHubAppView | null> {
585
+ const newAppId = patch.GH_APP_ID?.trim();
586
+ const rows = sortAgentGitHubApps(
587
+ await this.prisma.agentGitHubApp.findMany({ where: { agentId } }),
588
+ );
589
+ let target = newAppId
590
+ ? rows.find((r) => r.appId === newAppId)
591
+ : (rows[0] as AgentGitHubAppRow | undefined);
592
+ if (!target && newAppId && rows.length === 1 && rows[0]) {
593
+ assertPositiveInt("appId", newAppId);
594
+ await this.prisma.agentGitHubApp.update({
595
+ where: { id: rows[0].id },
596
+ data: { appId: newAppId, updatedAt: this.clock.now() },
597
+ });
598
+ target = { ...rows[0], appId: newAppId };
599
+ }
600
+ const fields: UpdateAgentGitHubAppInput = {};
601
+ if (patch.GH_APP_SLUG !== undefined) fields.slug = patch.GH_APP_SLUG;
602
+ if (patch.GH_APP_CLIENT_ID !== undefined) {
603
+ fields.clientId = patch.GH_APP_CLIENT_ID;
604
+ }
605
+ if (patch.GH_APP_CLIENT_SECRET !== undefined) {
606
+ fields.clientSecret = patch.GH_APP_CLIENT_SECRET;
607
+ }
608
+ if (patch.GH_APP_PRIVATE_KEY !== undefined) {
609
+ fields.privateKey = patch.GH_APP_PRIVATE_KEY;
610
+ }
611
+ if (patch.GH_APP_INSTALLATION_ID !== undefined) {
612
+ fields.installationId = patch.GH_APP_INSTALLATION_ID;
613
+ }
614
+ if (target) {
615
+ if (Object.keys(fields).length === 0) return toAgentGitHubAppView(target);
616
+ return this.update(agentId, target.id, fields);
617
+ }
618
+ if (!newAppId || !patch.GH_APP_PRIVATE_KEY) return null;
619
+ return this.create(agentId, {
620
+ appId: newAppId,
621
+ privateKey: patch.GH_APP_PRIVATE_KEY,
622
+ ...(patch.GH_APP_SLUG !== undefined && { slug: patch.GH_APP_SLUG }),
623
+ ...(patch.GH_APP_CLIENT_ID !== undefined && {
624
+ clientId: patch.GH_APP_CLIENT_ID,
625
+ }),
626
+ ...(patch.GH_APP_CLIENT_SECRET !== undefined && {
627
+ clientSecret: patch.GH_APP_CLIENT_SECRET,
628
+ }),
629
+ ...(patch.GH_APP_INSTALLATION_ID !== undefined && {
630
+ installationId: patch.GH_APP_INSTALLATION_ID,
631
+ }),
632
+ });
633
+ }
634
+
635
+ /**
636
+ * Mirror deleting one legacy GH_APP_* env key into the table: GH_APP_ID and
637
+ * GH_APP_PRIVATE_KEY remove the primary app (a row cannot exist without
638
+ * them); the optional keys clear their column. No primary: no-op.
639
+ */
640
+ async removeLegacyEnvKey(agentId: string, key: string): Promise<void> {
641
+ await this.removeLegacyEnvKeys(agentId, [key]);
642
+ }
643
+
644
+ /**
645
+ * Mirror deleting several legacy GH_APP_* env keys at once. The primary is
646
+ * resolved once and every key acts on that same row: deleting it for
647
+ * GH_APP_ID / GH_APP_PRIVATE_KEY must not promote the next app and let the
648
+ * remaining keys clear or delete it too. Other apps are never touched.
649
+ *
650
+ * `appId`, when given, targets the row with that GitHub App id instead of
651
+ * the primary — the same row `applyLegacyEnvPatch` wrote for a body naming
652
+ * that GH_APP_ID. No row with that id: no-op (the primary is not touched).
653
+ */
654
+ async removeLegacyEnvKeys(
655
+ agentId: string,
656
+ keys: readonly string[],
657
+ appId?: string,
658
+ ): Promise<void> {
659
+ if (keys.length === 0) return;
660
+ const targetAppId = appId?.trim();
661
+ const target = targetAppId
662
+ ? ((await this.list(agentId)).find((r) => r.appId === targetAppId) ??
663
+ null)
664
+ : await this.getPrimary(agentId);
665
+ if (!target) return;
666
+ if (keys.includes("GH_APP_ID") || keys.includes("GH_APP_PRIVATE_KEY")) {
667
+ await this.delete(agentId, target.id);
668
+ return;
669
+ }
670
+ const fields: UpdateAgentGitHubAppInput = {};
671
+ if (keys.includes("GH_APP_SLUG")) fields.slug = null;
672
+ if (keys.includes("GH_APP_CLIENT_ID")) fields.clientId = null;
673
+ if (keys.includes("GH_APP_CLIENT_SECRET")) fields.clientSecret = null;
674
+ if (keys.includes("GH_APP_INSTALLATION_ID")) fields.installationId = null;
675
+ if (Object.keys(fields).length === 0) return;
676
+ await this.update(agentId, target.id, fields);
677
+ }
678
+
522
679
  /**
523
680
  * Decrypted credentials for every app of the agent, in priority order.
524
681
  * Internal/runtime use only; never expose over a read API or log.
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it } from "bun:test";
2
2
  import { join } from "node:path";
3
3
  import {
4
+ overlayGitHubAppEnv,
4
5
  planGitHubAppBackfill,
5
6
  serializeAgentGitHubApp,
6
7
  sortAgentGitHubApps,
@@ -343,3 +344,36 @@ describe("toConfigBundleApps", () => {
343
344
  expect(apps[1]?.clientSecret).toBeNull();
344
345
  });
345
346
  });
347
+
348
+ describe("overlayGitHubAppEnv", () => {
349
+ const primary = {
350
+ appId: "42",
351
+ slug: null,
352
+ clientId: "Iv1.abc",
353
+ installationId: "7",
354
+ };
355
+
356
+ it("returns a copy of env unchanged when there is no table row", () => {
357
+ const env = { GH_APP_ID: "1", GH_APP_SLUG: "s", OTHER: "x" };
358
+ const out = overlayGitHubAppEnv(env, null);
359
+ expect(out).toEqual(env);
360
+ expect(out).not.toBe(env);
361
+ });
362
+
363
+ it("table wins for the four non-secret keys; a null column drops the key", () => {
364
+ const out = overlayGitHubAppEnv(
365
+ { GH_APP_ID: "1", GH_APP_SLUG: "stale", OTHER: "x" },
366
+ primary,
367
+ );
368
+ expect(out).toEqual({
369
+ GH_APP_ID: "42",
370
+ GH_APP_CLIENT_ID: "Iv1.abc",
371
+ GH_APP_INSTALLATION_ID: "7",
372
+ OTHER: "x",
373
+ });
374
+ });
375
+
376
+ it("an agent with a table row but no env rows still looks like it has an App", () => {
377
+ expect("GH_APP_ID" in overlayGitHubAppEnv({}, primary)).toBe(true);
378
+ });
379
+ });
@@ -29,6 +29,7 @@ import {
29
29
  createGithubInstallationRepos,
30
30
  createGithubSync,
31
31
  } from "./github-installation-wiring.ts";
32
+ import { GithubSyncService } from "./github-sync.ts";
32
33
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
33
34
  import {
34
35
  repoLostAccessBlockReason,
@@ -7553,6 +7554,8 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7553
7554
  state.repos = args.data.repos;
7554
7555
  },
7555
7556
  },
7557
+ // No AgentGitHubApp rows: the App comes from the stored GH_APP_ID.
7558
+ agentGitHubApp: { findMany: async () => [] },
7556
7559
  gitHubRepoSnapshot: {
7557
7560
  findMany: async () => opts.snapshots ?? defaultSnapshots,
7558
7561
  },
@@ -8274,3 +8277,103 @@ describe("admin API — accountId filter on the agent list and stats", () => {
8274
8277
  }
8275
8278
  });
8276
8279
  });
8280
+
8281
+ describe("GitHub Sync routes with several Apps", () => {
8282
+ const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
8283
+ const orgAccess = (org: string, repos: Record<string, boolean>) => ({
8284
+ org,
8285
+ status: "ok" as const,
8286
+ unresolved: 0,
8287
+ repos: Object.entries(repos).map(([n, canPush]) => ({
8288
+ fullName: `${org}/${n}`,
8289
+ level: canPush ? ("write" as const) : ("read" as const),
8290
+ canPush,
8291
+ })),
8292
+ });
8293
+
8294
+ function makeApp() {
8295
+ const calls: unknown[][] = [];
8296
+ const installs: Record<number, { org: string; repos: string[] }[]> = {
8297
+ 1: [{ org: "org-a", repos: ["org-a/keep", "org-a/lost"] }],
8298
+ 2: [{ org: "org-b", repos: ["org-b/keep", "org-b/lost"] }],
8299
+ };
8300
+ const githubSync = new GithubSyncService({
8301
+ agents: {
8302
+ get: async () => ({
8303
+ id: AGENT_ID,
8304
+ githubUsername: "octo",
8305
+ appId: 1,
8306
+ apps: [{ appId: 1 }, { appId: 2 }],
8307
+ repos: [],
8308
+ }),
8309
+ setRepos: async () => {},
8310
+ },
8311
+ access: async () => ({
8312
+ status: "ok",
8313
+ access: {
8314
+ username: "octo",
8315
+ outcome: "ok",
8316
+ userVerified: true,
8317
+ orgs: [
8318
+ orgAccess("org-a", { keep: true, lost: false, extra: true }),
8319
+ orgAccess("org-b", { keep: true, lost: false, extra: true }),
8320
+ ],
8321
+ unresolved: 0,
8322
+ complete: true,
8323
+ checkedAt: "2026-11-11T00:00:00.000Z",
8324
+ },
8325
+ }),
8326
+ installation: {
8327
+ listInstalled: async (appId) =>
8328
+ installs[appId]
8329
+ ? { status: "found", orgs: installs[appId] }
8330
+ : { status: "none" },
8331
+ addRepos: async (appId, org, repos) => {
8332
+ calls.push(["add", appId, org, [...repos]]);
8333
+ },
8334
+ removeRepos: async (appId, org, repos) => {
8335
+ calls.push(["remove", appId, org, [...repos]]);
8336
+ },
8337
+ },
8338
+ audit: { write: async () => "audit-1" },
8339
+ });
8340
+ const base = makeMockDeps();
8341
+ const app = createAdminApp({
8342
+ ...base,
8343
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
8344
+ githubSync,
8345
+ });
8346
+ return { app, calls };
8347
+ }
8348
+
8349
+ it("preview lists changes for orgs on different Apps; apply routes each to its App", async () => {
8350
+ const { app, calls } = makeApp();
8351
+ const prev = await app.request(`/agents/${AGENT_ID}/github-sync/preview`, {
8352
+ headers: asAdmin,
8353
+ });
8354
+ expect(prev.status).toBe(200);
8355
+ const body = (await prev.json()) as {
8356
+ appAdds: string[];
8357
+ appRemoves: string[];
8358
+ };
8359
+ expect(body.appAdds).toEqual(["org-a/extra", "org-b/extra"]);
8360
+ expect(body.appRemoves).toEqual(["org-a/lost", "org-b/lost"]);
8361
+
8362
+ const res = await app.request(`/agents/${AGENT_ID}/github-sync/apply`, {
8363
+ method: "POST",
8364
+ headers: { "Content-Type": "application/json", ...asAdmin },
8365
+ body: JSON.stringify({
8366
+ appAdds: body.appAdds,
8367
+ appRemoves: body.appRemoves,
8368
+ agentRemoves: [],
8369
+ }),
8370
+ });
8371
+ expect(res.status).toBe(200);
8372
+ expect(calls).toEqual([
8373
+ ["add", 1, "org-a", ["org-a/extra"]],
8374
+ ["add", 2, "org-b", ["org-b/extra"]],
8375
+ ["remove", 1, "org-a", ["org-a/lost"]],
8376
+ ["remove", 2, "org-b", ["org-b/lost"]],
8377
+ ]);
8378
+ });
8379
+ });
package/src/agents-api.ts CHANGED
@@ -62,6 +62,8 @@ import { deleteAgentFully } from "./agent-deletion.ts";
62
62
  import type { AgentEnvService } from "./agent-envs.ts";
63
63
  import {
64
64
  type AgentGitHubAppService,
65
+ GH_APP_ENV_KEYS,
66
+ type LegacyGitHubAppEnvPatch,
65
67
  serializeAgentGitHubApp,
66
68
  } from "./agent-github-apps.ts";
67
69
  import type { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
@@ -263,7 +265,12 @@ export interface AdminDeps {
263
265
  */
264
266
  agentGitHubAppService?: Pick<
265
267
  AgentGitHubAppService,
266
- "list" | "create" | "update" | "delete"
268
+ | "list"
269
+ | "create"
270
+ | "update"
271
+ | "delete"
272
+ | "applyLegacyEnvPatch"
273
+ | "removeLegacyEnvKeys"
267
274
  >;
268
275
  agentMemberService: Pick<
269
276
  AgentMemberService,
@@ -2905,11 +2912,75 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2905
2912
 
2906
2913
  // ─── Env vars ──────────────────────────────────────────────────────────────
2907
2914
 
2915
+ /**
2916
+ * multi-github-apps 1.5: GH_APP_* env writes are mirrored into the
2917
+ * AgentGitHubApp table, which readers prefer. The env write has already
2918
+ * succeeded and stays authoritative for the runtime until 1.11, so a table
2919
+ * failure (e.g. a malformed slug) is logged by name only, never fails the
2920
+ * request, and never echoes a value.
2921
+ */
2922
+ const mirrorGitHubAppEnv = async (
2923
+ agentId: string,
2924
+ env: Record<string, string>,
2925
+ ): Promise<void> => {
2926
+ const patch: LegacyGitHubAppEnvPatch = {};
2927
+ for (const key of GH_APP_ENV_KEYS) {
2928
+ const value = env[key];
2929
+ if (value !== undefined) patch[key] = value;
2930
+ }
2931
+ if (Object.keys(patch).length === 0) return;
2932
+ try {
2933
+ await deps.agentGitHubAppService?.applyLegacyEnvPatch(agentId, patch);
2934
+ } catch (err) {
2935
+ console.error(
2936
+ "[agents-api] could not mirror GH_APP_* env to the GitHub App table:",
2937
+ err instanceof Error ? err.name : "unknown error",
2938
+ );
2939
+ }
2940
+ };
2941
+ const isGitHubAppEnvKey = (key: string): boolean =>
2942
+ (GH_APP_ENV_KEYS as readonly string[]).includes(key);
2943
+ /**
2944
+ * Mirror removing GH_APP_* env keys into the table; same failure policy.
2945
+ * All keys go in one call so they act on the same row: the one matching
2946
+ * `appId` when given, else the primary.
2947
+ */
2948
+ const mirrorGitHubAppEnvRemoval = async (
2949
+ agentId: string,
2950
+ keys: readonly string[],
2951
+ appId?: string,
2952
+ ): Promise<void> => {
2953
+ if (keys.length === 0) return;
2954
+ try {
2955
+ await deps.agentGitHubAppService?.removeLegacyEnvKeys(
2956
+ agentId,
2957
+ keys,
2958
+ appId,
2959
+ );
2960
+ } catch (err) {
2961
+ console.error(
2962
+ `[agents-api] could not mirror ${keys.join(", ")} removal to the GitHub App table:`,
2963
+ err instanceof Error ? err.name : "unknown error",
2964
+ );
2965
+ }
2966
+ };
2967
+
2908
2968
  // POST /agents/:id/envs — replace all env vars (bulk upsert)
2909
2969
  app.openapi(upsertEnvsRoute, async (c) => {
2910
2970
  const { id: agentId } = c.req.valid("param");
2911
2971
  const body = c.req.valid("json");
2912
2972
  await agentEnvService.upsert(agentId, body);
2973
+ await mirrorGitHubAppEnv(agentId, body);
2974
+ // Replace-all drops every key the body omits, so omitted GH_APP_* keys
2975
+ // must leave the table too (readers prefer the table). One call, so the
2976
+ // target is resolved once and other apps are never touched. The target is
2977
+ // the row the body's GH_APP_ID names (the one mirrorGitHubAppEnv just
2978
+ // wrote), else the primary.
2979
+ await mirrorGitHubAppEnvRemoval(
2980
+ agentId,
2981
+ GH_APP_ENV_KEYS.filter((key) => body[key] === undefined),
2982
+ body.GH_APP_ID,
2983
+ );
2913
2984
  return c.json({ ok: true } as const, 201);
2914
2985
  });
2915
2986
 
@@ -2932,6 +3003,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2932
3003
  env,
2933
3004
  secretKeys ? new Set(secretKeys) : undefined,
2934
3005
  );
3006
+ await mirrorGitHubAppEnv(agentId, env);
2935
3007
  return c.json({ ok: true } as const, 200);
2936
3008
  });
2937
3009
 
@@ -2939,6 +3011,9 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2939
3011
  app.openapi(deleteEnvKeyRoute, async (c) => {
2940
3012
  const { id: agentId, key } = c.req.valid("param");
2941
3013
  await agentEnvService.deleteKey(agentId, key);
3014
+ if (isGitHubAppEnvKey(key)) {
3015
+ await mirrorGitHubAppEnvRemoval(agentId, [key]);
3016
+ }
2942
3017
  return c.body(null, 204);
2943
3018
  });
2944
3019
 
@@ -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
+ );