@app-vitals/agent-admin 1.129.1 → 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.
@@ -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,
@@ -8276,3 +8277,103 @@ describe("admin API — accountId filter on the agent list and stats", () => {
8276
8277
  }
8277
8278
  });
8278
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
 
@@ -20,6 +20,10 @@ import { createPrivateKey } from "node:crypto";
20
20
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
21
21
  import { HTTPException } from "hono/http-exception";
22
22
  import type { AgentEnvService } from "./agent-envs.ts";
23
+ import {
24
+ type AgentGitHubAppService,
25
+ overlayGitHubAppEnv,
26
+ } from "./agent-github-apps.ts";
23
27
  import type { AgentTokenService } from "./agent-tokens.ts";
24
28
  import type { AgentService } from "./agents.ts";
25
29
  import {
@@ -87,6 +91,12 @@ export interface GithubEnterpriseApiDeps {
87
91
  >;
88
92
  agentService: Pick<AgentService, "getSummary">;
89
93
  agentEnvService: Pick<AgentEnvService, "getByAgentId">;
94
+ /**
95
+ * multi-github-apps 1.5: the agent's App is read from the AgentGitHubApp
96
+ * table (primary app), falling back to its GH_APP_* env when the agent has no
97
+ * row. Optional so existing wiring stays valid.
98
+ */
99
+ agentGitHubAppService?: Pick<AgentGitHubAppService, "getPrimary">;
90
100
  sessionSecret: string;
91
101
  adminApiKeys?: Map<string, AdminApiKey>;
92
102
  agentTokenService: Pick<AgentTokenService, "validate">;
@@ -776,7 +786,10 @@ export function createGithubEnterpriseApp(
776
786
  if (!(await deps.agentService.getSummary(agentId))) {
777
787
  throw new NotFoundError(`agent ${agentId} not found`);
778
788
  }
779
- const env = (await deps.agentEnvService.getByAgentId(agentId))?.env;
789
+ const primary = await deps.agentGitHubAppService?.getPrimary(agentId);
790
+ const env = primary
791
+ ? overlayGitHubAppEnv({}, primary)
792
+ : (await deps.agentEnvService.getByAgentId(agentId))?.env;
780
793
  const storedClientId = env?.GH_APP_CLIENT_ID?.trim();
781
794
  const clientId =
782
795
  storedClientId && CLIENT_ID_RE.test(storedClientId)
@@ -0,0 +1,189 @@
1
+ /**
2
+ * admin/src/github-provisioning-service.integration.test.ts
3
+ * GithubProvisioningService against a real PostgreSQL DB with the real
4
+ * AgentGitHubAppService and AgentEnvService (multi-github-apps 1.5): App
5
+ * writes land in the table and the env mirror, reads prefer the table, and
6
+ * single-app behavior (overwrite, installation id kept) is unchanged.
7
+ *
8
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
12
+ import { sign } from "hono/jwt";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { AgentEnvService } from "./agent-envs.ts";
15
+ import { AgentGitHubAppService } from "./agent-github-apps.ts";
16
+ import { GithubProvisioningService } from "./github-provisioning-service.ts";
17
+ import { createAdminPrismaClient } from "./prisma-client.ts";
18
+ import { makeTokenCrypto } from "./token-crypto.ts";
19
+
20
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
21
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
22
+
23
+ const TEST_KEY =
24
+ "0000000000000000000000000000000000000000000000000000000000000001";
25
+ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
26
+ const PEM =
27
+ "-----BEGIN RSA PRIVATE KEY-----\nMIIfakeKeyProv\n-----END RSA PRIVATE KEY-----";
28
+ const SECRETS = new Set(["GH_APP_PRIVATE_KEY", "GH_APP_CLIENT_SECRET"]);
29
+
30
+ describeOrSkip("GithubProvisioningService (integration)", () => {
31
+ let prisma: PrismaClient;
32
+ let apps: AgentGitHubAppService;
33
+ let envs: AgentEnvService;
34
+ let service: GithubProvisioningService;
35
+ let agentId: string;
36
+ let exchange: { appId: string; slug: string };
37
+
38
+ const stateCookie = () => {
39
+ const now = Math.floor(Date.now() / 1000);
40
+ return sign(
41
+ { agentId, githubOrg: "my-org", iat: now, exp: now + 300 },
42
+ SESSION_SECRET,
43
+ "HS256",
44
+ );
45
+ };
46
+
47
+ beforeEach(async () => {
48
+ prisma = createAdminPrismaClient(TEST_DB as string);
49
+ await prisma.agentGitHubApp.deleteMany();
50
+ await prisma.agentToken.deleteMany();
51
+ await prisma.agentCronJob.deleteMany();
52
+ await prisma.agentTool.deleteMany();
53
+ await prisma.agentEnv.deleteMany();
54
+ await prisma.agent.deleteMany();
55
+ const crypto = makeTokenCrypto(TEST_KEY);
56
+ apps = new AgentGitHubAppService(prisma, crypto);
57
+ envs = new AgentEnvService(prisma, crypto);
58
+ exchange = { appId: "5001", slug: "example-prov-app" };
59
+ service = new GithubProvisioningService({
60
+ githubAppClient: {
61
+ exchangeManifestCode: async () => ({
62
+ ...exchange,
63
+ pem: PEM,
64
+ clientId: "Iv1.provclient",
65
+ clientSecret: "prov-secret",
66
+ }),
67
+ } as never,
68
+ agentService: { getDetail: async (id: string) => ({ id }) } as never,
69
+ agentEnvService: envs,
70
+ agentGitHubAppService: apps,
71
+ agentCronJobService: {
72
+ reconcileSystemCrons: async () => ({
73
+ created: 0,
74
+ updated: 0,
75
+ deleted: 0,
76
+ }),
77
+ } as never,
78
+ sessionSecret: SESSION_SECRET,
79
+ appBaseUrl: "https://example.com",
80
+ secretEnvVars: SECRETS,
81
+ });
82
+ agentId = (await prisma.agent.create({ data: { name: "Prov Agent" } })).id;
83
+ });
84
+
85
+ afterEach(async () => {
86
+ await prisma.$disconnect();
87
+ });
88
+
89
+ it("manifest flow then install: table row complete, env mirrored, installation id kept on a second install", async () => {
90
+ const connect = await service.completeConnect(
91
+ await stateCookie(),
92
+ "code",
93
+ agentId,
94
+ );
95
+ expect(connect.outcome).toBe("success");
96
+
97
+ let row = await apps.getPrimary(agentId);
98
+ expect(row).toMatchObject({
99
+ appId: "5001",
100
+ slug: "example-prov-app",
101
+ clientId: "Iv1.provclient",
102
+ installationId: null,
103
+ hasPrivateKey: true,
104
+ hasClientSecret: true,
105
+ });
106
+ const creds = await apps.listCredentials(agentId);
107
+ expect(creds[0]?.privateKey).toBe(PEM);
108
+
109
+ const installed = await service.completeInstalled(
110
+ await stateCookie(),
111
+ "90001",
112
+ agentId,
113
+ );
114
+ expect(installed).toMatchObject({
115
+ outcome: "success",
116
+ alreadyStored: false,
117
+ });
118
+ row = await apps.getPrimary(agentId);
119
+ expect(row?.installationId).toBe("90001");
120
+
121
+ // Additional-org install: no cookie, stored id wins, nothing rewritten.
122
+ const again = await service.completeInstalled(undefined, "90002", agentId);
123
+ expect(again).toMatchObject({ outcome: "success", alreadyStored: true });
124
+ expect((await apps.getPrimary(agentId))?.installationId).toBe("90001");
125
+
126
+ // Env mirror (runtime still reads env until 1.3/1.11).
127
+ const env = (await envs.getByAgentId(agentId))?.env ?? {};
128
+ expect(env).toMatchObject({
129
+ GH_APP_ID: "5001",
130
+ GH_APP_SLUG: "example-prov-app",
131
+ GH_APP_CLIENT_ID: "Iv1.provclient",
132
+ GH_APP_INSTALLATION_ID: "90001",
133
+ });
134
+ expect(await prisma.agentGitHubApp.count({ where: { agentId } })).toBe(1);
135
+ });
136
+
137
+ it("manual paste writes table and env; re-pasting a new app replaces the single app", async () => {
138
+ const first = await service.startAppManualConnect(agentId, {
139
+ ghAppId: "6001",
140
+ ghAppInstallationId: "70001",
141
+ ghAppPrivateKey: PEM,
142
+ });
143
+ expect(first.ok).toBe(true);
144
+ expect(await apps.getPrimary(agentId)).toMatchObject({
145
+ appId: "6001",
146
+ installationId: "70001",
147
+ slug: null,
148
+ });
149
+
150
+ await service.startAppManualConnect(agentId, {
151
+ ghAppId: "6002",
152
+ ghAppInstallationId: "70002",
153
+ ghAppPrivateKey: PEM,
154
+ });
155
+ const rows = await apps.list(agentId);
156
+ expect(rows).toHaveLength(1);
157
+ expect(rows[0]).toMatchObject({ appId: "6002", installationId: "70002" });
158
+ expect((await envs.getByAgentId(agentId))?.env.GH_APP_ID).toBe("6002");
159
+ });
160
+
161
+ it("getAddOrgUrl reads the slug from the table, and falls back to env for an unbackfilled agent", async () => {
162
+ await apps.create(agentId, {
163
+ appId: "6003",
164
+ slug: "table-slug",
165
+ privateKey: PEM,
166
+ });
167
+ expect(await service.getAddOrgUrl(agentId)).toEqual({
168
+ ok: true,
169
+ url: "https://github.com/apps/table-slug/installations/new",
170
+ });
171
+
172
+ const other = (await prisma.agent.create({ data: { name: "Env Only" } }))
173
+ .id;
174
+ await envs.patch(other, { GH_APP_ID: "1", GH_APP_SLUG: "env-slug" });
175
+ expect(await service.getAddOrgUrl(other)).toEqual({
176
+ ok: true,
177
+ url: "https://github.com/apps/env-slug/installations/new",
178
+ });
179
+ });
180
+
181
+ it("env-only agent: a stored env installation id is honoured (no table row to read)", async () => {
182
+ await envs.patch(agentId, { GH_APP_ID: "1", GH_APP_INSTALLATION_ID: "55" });
183
+ const result = await service.completeInstalled(undefined, "99", agentId);
184
+ expect(result).toMatchObject({ outcome: "success", alreadyStored: true });
185
+ expect((await envs.getByAgentId(agentId))?.env.GH_APP_INSTALLATION_ID).toBe(
186
+ "55",
187
+ );
188
+ });
189
+ });