@app-vitals/agent-admin 1.30.0 → 1.32.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.
@@ -7,6 +7,8 @@
7
7
  */
8
8
 
9
9
  import { beforeAll, describe, expect, it, spyOn } from "bun:test";
10
+ import { generateKeyPairSync } from "node:crypto";
11
+ import { readFileSync } from "node:fs";
10
12
  import { sign } from "hono/jwt";
11
13
  import type { Prisma } from "../prisma/client/client.ts";
12
14
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
@@ -22,6 +24,16 @@ import type { AgentTokenService } from "./agent-tokens.ts";
22
24
  import type { AdminDeps } from "./agents-api.ts";
23
25
  import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
24
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
27
+ import {
28
+ createGithubInstallationRepos,
29
+ createGithubReconcile,
30
+ } from "./github-reconcile-wiring.ts";
31
+ import {
32
+ accessFor,
33
+ envWith,
34
+ fakeOpenWork,
35
+ fakePrisma,
36
+ } from "./github-reconcile-wiring.unit.test.ts";
25
37
  import type { SpecialtyType } from "./specialty-types.ts";
26
38
  import { identityCrypto } from "./token-crypto.ts";
27
39
 
@@ -7178,3 +7190,369 @@ describe("admin API — GitHub reconcile routes (GHE-3.4)", () => {
7178
7190
  expect((await post(app, "apply", asAdmin, {})).status).toBe(400);
7179
7191
  });
7180
7192
  });
7193
+
7194
+ describe("admin API — reconcile open-work seam, in-process composition (GHE-3.9)", () => {
7195
+ const compose = (
7196
+ openWork?: ReturnType<typeof fakeOpenWork>["port"],
7197
+ env: Record<string, string> | undefined = { GH_APP_ID: "42" },
7198
+ ) => {
7199
+ const { prisma, state } = fakePrisma(["acme/old"]);
7200
+ const githubReconcile = createGithubReconcile({
7201
+ prisma,
7202
+ appService: { get: async () => null, getPrivateKey: async () => null },
7203
+ access: accessFor(["acme/api"]),
7204
+ agentEnv: envWith(env),
7205
+ installation: {
7206
+ listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
7207
+ addRepos: async () => {},
7208
+ removeRepos: async () => {},
7209
+ },
7210
+ openWork,
7211
+ });
7212
+ const app = createAdminApp({
7213
+ ...makeMockDeps(),
7214
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7215
+ githubReconcile,
7216
+ });
7217
+ const plan = () =>
7218
+ app.request(`/agents/${AGENT_ID}/github-reconcile/plan`, {
7219
+ method: "POST",
7220
+ headers: { Authorization: `Bearer ${ADMIN_API_KEY}` },
7221
+ });
7222
+ return { plan, state };
7223
+ };
7224
+
7225
+ it("plan returns the port's items and retires nothing", async () => {
7226
+ const { port, calls } = fakeOpenWork();
7227
+ const { plan, state } = compose(port);
7228
+ const res = await plan();
7229
+ expect(res.status).toBe(200);
7230
+ const body = (await res.json()) as { affectedOpenWork: unknown[] };
7231
+ expect(body.affectedOpenWork).toEqual([
7232
+ { id: "T-1", repo: "acme/old", title: "fix it" },
7233
+ ]);
7234
+ expect(calls.map((c) => c.fn)).toEqual(["list"]);
7235
+ expect(state.repos).toEqual(["acme/old"]);
7236
+ });
7237
+
7238
+ it("plans for an agent whose GH_APP_ID is in its stored env", async () => {
7239
+ const res = await compose(undefined, { GH_APP_ID: "42" }).plan();
7240
+ expect(res.status).toBe(200);
7241
+ expect(await res.json()).toMatchObject({ status: "planned" });
7242
+ });
7243
+
7244
+ it("reports skipped naming GH_APP_ID for an agent without one", async () => {
7245
+ const res = await compose(undefined, {}).plan();
7246
+ expect(res.status).toBe(200);
7247
+ const body = (await res.json()) as { status: string; reason?: string };
7248
+ expect(body.status).toBe("skipped");
7249
+ expect(body.reason).toContain("GH_APP_ID");
7250
+ });
7251
+
7252
+ it("without a port plan lists nothing", async () => {
7253
+ const res = await compose().plan();
7254
+ expect(res.status).toBe(200);
7255
+ const body = (await res.json()) as { affectedOpenWork: unknown[] };
7256
+ expect(body.affectedOpenWork).toEqual([]);
7257
+ });
7258
+ });
7259
+
7260
+ // ─── IRM-1.2: /agents/:id/github-installation/repos ───────────────────────────
7261
+
7262
+ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7263
+ const OPS = "irm-ops-token";
7264
+ const READER = "irm-read-token";
7265
+ const AGENT_KEY = "irm-agent-token";
7266
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
7267
+ modulusLength: 2048,
7268
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
7269
+ publicKeyEncoding: { type: "spki", format: "pem" },
7270
+ });
7271
+ const cassette: Record<string, { status: number; body: unknown }> =
7272
+ JSON.parse(
7273
+ readFileSync(
7274
+ new URL("./fixtures/github-enterprise-cassette.json", import.meta.url)
7275
+ .pathname,
7276
+ "utf-8",
7277
+ ),
7278
+ );
7279
+ // The recorded org installation belongs to App 777 (installation 501).
7280
+ const INST = "/enterprises/acme/apps/organizations/acme-eng/installations";
7281
+ const routes: Record<string, string | unknown> = {
7282
+ "GET /enterprises/acme/installation": "enterprise_installation_success",
7283
+ "POST /app/installations/4242/access_tokens": "access_token_success",
7284
+ "GET /enterprises/acme/apps/installable_organizations":
7285
+ "installable_orgs_success",
7286
+ [`GET ${INST}`]: "org_installations_success",
7287
+ [`GET ${INST}/501/repositories`]: "install_repos_success",
7288
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_success",
7289
+ [`PATCH ${INST}/501/repositories/remove`]: "install_repos_remove_success",
7290
+ };
7291
+
7292
+ function setup(
7293
+ opts: {
7294
+ env?: Record<string, string>;
7295
+ username?: string | null;
7296
+ known?: boolean;
7297
+ override?: Record<string, string>;
7298
+ } = {},
7299
+ ) {
7300
+ const audits: Array<Record<string, unknown>> = [];
7301
+ const gh: string[] = [];
7302
+ const table = { ...routes, ...(opts.override ?? {}) };
7303
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
7304
+ const u = new URL(input.toString());
7305
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
7306
+ gh.push(key);
7307
+ // The recorded installable orgs are org-1/org-2; this agent's App lives on acme-eng.
7308
+ if (key === "GET /enterprises/acme/apps/installable_organizations") {
7309
+ return new Response(JSON.stringify([{ id: 5010, login: "acme-eng" }]), {
7310
+ status: 200,
7311
+ });
7312
+ }
7313
+ const name = table[key] as string | undefined;
7314
+ if (!name) throw new Error(`no route for ${key}`);
7315
+ const entry = cassette[name];
7316
+ if (!entry) throw new Error(`no cassette entry ${name}`);
7317
+ return new Response(JSON.stringify(entry.body), {
7318
+ status: entry.status,
7319
+ headers: { "Content-Type": "application/json" },
7320
+ });
7321
+ }) as typeof fetch;
7322
+ const prisma = {
7323
+ agent: {
7324
+ findUnique: async () =>
7325
+ opts.known === false
7326
+ ? null
7327
+ : {
7328
+ id: AGENT_ID,
7329
+ repos: [],
7330
+ githubUsername:
7331
+ opts.username === undefined ? "dev" : opts.username,
7332
+ },
7333
+ },
7334
+ gitHubReconcileAudit: {
7335
+ create: async (args: { data: Record<string, unknown> }) => {
7336
+ audits.push(args.data);
7337
+ return { id: `audit-${audits.length}` };
7338
+ },
7339
+ },
7340
+ } as unknown as Parameters<
7341
+ typeof createGithubInstallationRepos
7342
+ >[0]["prisma"];
7343
+ const githubInstallationRepos = createGithubInstallationRepos({
7344
+ prisma,
7345
+ appService: {
7346
+ get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
7347
+ getPrivateKey: async () => PEM,
7348
+ },
7349
+ access: async (username) => {
7350
+ const base = await accessFor(["acme-eng/repo-1"])(username);
7351
+ if (base.status === "unconfigured") return base;
7352
+ const [org] = base.access.orgs;
7353
+ return {
7354
+ ...base,
7355
+ access: {
7356
+ ...base.access,
7357
+ orgs: org ? [{ ...org, org: "acme-eng" }] : [],
7358
+ },
7359
+ };
7360
+ },
7361
+ agentEnv: envWith(opts.env ?? { GH_APP_ID: "777" }),
7362
+ fetchFn,
7363
+ });
7364
+ const base = makeMockDeps();
7365
+ const app = createAdminApp({
7366
+ ...base,
7367
+ adminApiKeys: parseAdminApiKeys(
7368
+ `root:${ADMIN_API_KEY}:*,operator:${OPS}:platform.ops,reader:${READER}:platform.read`,
7369
+ ),
7370
+ agentTokenService: {
7371
+ ...base.agentTokenService,
7372
+ validate: async (t: string) =>
7373
+ t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7374
+ },
7375
+ githubInstallationRepos,
7376
+ });
7377
+ return { app, audits, gh };
7378
+ }
7379
+
7380
+ const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
7381
+ const url = (suffix = "", id = AGENT_ID) =>
7382
+ `/agents/${id}/github-installation/repos${suffix}`;
7383
+ const send = (
7384
+ app: ReturnType<typeof createAdminApp>,
7385
+ path: string,
7386
+ headers: Record<string, string>,
7387
+ body: unknown = { repos: ["acme-eng/repo-3"] },
7388
+ ) =>
7389
+ app.request(path, {
7390
+ method: "POST",
7391
+ headers: { "Content-Type": "application/json", ...headers },
7392
+ body: JSON.stringify(body),
7393
+ });
7394
+
7395
+ it("GET lists repos per org with push hints from the access lookup", async () => {
7396
+ const { app } = setup();
7397
+ const res = await app.request(url(), { headers: asAdmin });
7398
+ expect(res.status).toBe(200);
7399
+ expect(await res.json()).toEqual({
7400
+ appId: 777,
7401
+ orgs: [
7402
+ {
7403
+ org: "acme-eng",
7404
+ repos: [
7405
+ { fullName: "acme-eng/repo-1", userCanPush: true },
7406
+ { fullName: "acme-eng/repo-2" },
7407
+ ],
7408
+ },
7409
+ ],
7410
+ });
7411
+ });
7412
+
7413
+ it("GET omits the hint entirely for an agent with no bound username", async () => {
7414
+ const { app } = setup({ username: null });
7415
+ const body = (await (
7416
+ await app.request(url(), { headers: asAdmin })
7417
+ ).json()) as {
7418
+ orgs: { repos: Record<string, unknown>[] }[];
7419
+ };
7420
+ expect(body.orgs[0]?.repos.map((r) => "userCanPush" in r)).toEqual([
7421
+ false,
7422
+ false,
7423
+ ]);
7424
+ });
7425
+
7426
+ it("403 for ops, read and agent keys on every route; no GitHub call, no audit", async () => {
7427
+ const { app, audits, gh } = setup();
7428
+ for (const key of [OPS, READER, AGENT_KEY]) {
7429
+ const h = { Authorization: `Bearer ${key}` };
7430
+ expect((await app.request(url(), { headers: h })).status).toBe(403);
7431
+ expect((await send(app, url(), h)).status).toBe(403);
7432
+ expect((await send(app, url("/remove"), h)).status).toBe(403);
7433
+ }
7434
+ expect(audits).toEqual([]);
7435
+ expect(gh).toEqual([]);
7436
+ });
7437
+
7438
+ it("403 for a non-admin session member", async () => {
7439
+ const { app } = setup();
7440
+ const cookie = await sign(
7441
+ {
7442
+ isAdmin: false,
7443
+ userId: "user-acct",
7444
+ email: "owner@acct-a.example.com",
7445
+ iat: Math.floor(Date.now() / 1000),
7446
+ exp: Math.floor(Date.now() / 1000) + 3600,
7447
+ },
7448
+ SESSION_SECRET,
7449
+ "HS256",
7450
+ );
7451
+ const memberApp = createAdminApp({
7452
+ ...makeMockDeps(),
7453
+ callerScopeResolver: async () => ({
7454
+ kind: "scoped",
7455
+ accountId: "acct-a",
7456
+ agentIds: [AGENT_ID],
7457
+ }),
7458
+ });
7459
+ const res = await memberApp.request(url(), {
7460
+ headers: { Cookie: `admin_session=${cookie}` },
7461
+ });
7462
+ expect(res.status).toBe(403);
7463
+ void app;
7464
+ });
7465
+
7466
+ it("404 for an unknown agent on every route", async () => {
7467
+ const { app, audits } = setup({ known: false });
7468
+ expect((await app.request(url(), { headers: asAdmin })).status).toBe(404);
7469
+ expect((await send(app, url(), asAdmin)).status).toBe(404);
7470
+ expect((await send(app, url("/remove"), asAdmin)).status).toBe(404);
7471
+ expect(audits).toEqual([]);
7472
+ });
7473
+
7474
+ it("422 naming GH_APP_ID when the agent has none", async () => {
7475
+ const { app, audits } = setup({ env: {} });
7476
+ const res = await app.request(url(), { headers: asAdmin });
7477
+ expect(res.status).toBe(422);
7478
+ expect(JSON.stringify(await res.json())).toContain("GH_APP_ID");
7479
+ expect((await send(app, url(), asAdmin)).status).toBe(422);
7480
+ expect(audits).toEqual([]);
7481
+ });
7482
+
7483
+ it("409 when the agent's App is not installed on the org; nothing audited", async () => {
7484
+ // App 999 has no recorded installation on acme-eng.
7485
+ const { app, audits, gh } = setup({ env: { GH_APP_ID: "999" } });
7486
+ const res = await send(app, url(), asAdmin);
7487
+ expect(res.status).toBe(409);
7488
+ expect(JSON.stringify(await res.json())).toContain("not installed");
7489
+ expect(audits).toEqual([]);
7490
+ expect(gh.some((k) => k.startsWith("PATCH"))).toBe(false);
7491
+ });
7492
+
7493
+ it("POST add changes the installation and writes one audit entry with the caller", async () => {
7494
+ const { app, audits, gh } = setup();
7495
+ const res = await send(app, url(), asAdmin, {
7496
+ repos: ["acme-eng/repo-3"],
7497
+ });
7498
+ expect(res.status).toBe(200);
7499
+ expect(await res.json()).toEqual({
7500
+ status: "applied",
7501
+ auditId: "audit-1",
7502
+ repos: ["acme-eng/repo-3"],
7503
+ });
7504
+ expect(gh).toContain(`PATCH ${INST}/501/repositories/add`);
7505
+ expect(audits).toHaveLength(1);
7506
+ expect(audits[0]).toMatchObject({
7507
+ agentId: AGENT_ID,
7508
+ caller: "root",
7509
+ planHash: "direct:add",
7510
+ diff: { installationAdds: ["acme-eng/repo-3"], installationRemoves: [] },
7511
+ result: { status: "applied" },
7512
+ });
7513
+ });
7514
+
7515
+ it("POST remove changes the installation and writes one audit entry", async () => {
7516
+ const { app, audits, gh } = setup();
7517
+ const res = await send(app, url("/remove"), asAdmin, {
7518
+ repos: ["acme-eng/repo-2"],
7519
+ });
7520
+ expect(res.status).toBe(200);
7521
+ expect(gh).toContain(`PATCH ${INST}/501/repositories/remove`);
7522
+ expect(audits).toHaveLength(1);
7523
+ expect(audits[0]).toMatchObject({
7524
+ caller: "root",
7525
+ planHash: "direct:remove",
7526
+ diff: { installationRemoves: ["acme-eng/repo-2"], installationAdds: [] },
7527
+ });
7528
+ });
7529
+
7530
+ it("502 and a failed audit entry when GitHub refuses the change", async () => {
7531
+ const { app, audits } = setup({
7532
+ override: {
7533
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_403",
7534
+ },
7535
+ });
7536
+ const res = await send(app, url(), asAdmin);
7537
+ expect(res.status).toBe(502);
7538
+ expect(audits).toHaveLength(1);
7539
+ expect(audits[0]?.result).toMatchObject({ status: "failed" });
7540
+ });
7541
+
7542
+ it("400 for a body that is not owner/repo names", async () => {
7543
+ const { app, audits } = setup();
7544
+ expect((await send(app, url(), asAdmin, { repos: ["nope"] })).status).toBe(
7545
+ 400,
7546
+ );
7547
+ expect((await send(app, url(), asAdmin, { repos: [] })).status).toBe(400);
7548
+ expect(audits).toEqual([]);
7549
+ });
7550
+
7551
+ it("503 when the Apps are not wired", async () => {
7552
+ const app = createAdminApp({
7553
+ ...makeMockDeps(),
7554
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7555
+ });
7556
+ expect((await app.request(url(), { headers: asAdmin })).status).toBe(503);
7557
+ });
7558
+ });
package/src/agents-api.ts CHANGED
@@ -101,6 +101,7 @@ import {
101
101
  } from "./cron-run-transcripts.ts";
102
102
  import {
103
103
  ApiError,
104
+ BadGatewayError,
104
105
  BadRequestError,
105
106
  ConflictError,
106
107
  ForbiddenError,
@@ -164,6 +165,7 @@ import {
164
165
  UpsertAgentMarketplaceBodySchema,
165
166
  UpsertChatTokenDailyBodySchema,
166
167
  } from "./openapi-schemas.ts";
168
+ import type { InstallationReposService } from "./installation-repos-service.ts";
167
169
  import type { ReconcileApplyService } from "./reconcile-apply-service.ts";
168
170
  import type { SelfServeConfig } from "./self-serve-config.ts";
169
171
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
@@ -268,6 +270,15 @@ export interface AdminDeps {
268
270
  * `skipped`.
269
271
  */
270
272
  githubReconcile?: Pick<ReconcileApplyService, "planWithOpenWork" | "apply">;
273
+ /**
274
+ * IRM-1.2: backs the admin-only /agents/:id/github-installation/repos
275
+ * routes. Optional (additive); absent means the enterprise Apps are not
276
+ * wired and the routes answer 503.
277
+ */
278
+ githubInstallationRepos?: Pick<
279
+ InstallationReposService,
280
+ "list" | "add" | "remove"
281
+ >;
271
282
  /**
272
283
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
273
284
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -679,6 +690,43 @@ const GithubReconcileApplyResultSchema = z
679
690
  })
680
691
  .openapi("GithubReconcileApplyResult");
681
692
 
693
+ const InstallationReposBodySchema = z
694
+ .object({
695
+ repos: z.array(RepoFullNameSchema).min(1).max(100).openapi({
696
+ description:
697
+ "Repos (owner/repo) to change on the agent App's installation.",
698
+ }),
699
+ })
700
+ .openapi("GithubInstallationReposBody");
701
+
702
+ const GithubInstallationReposListSchema = z
703
+ .object({
704
+ appId: z.number().int(),
705
+ orgs: z.array(
706
+ z.object({
707
+ org: z.string(),
708
+ repos: z.array(
709
+ z.object({
710
+ fullName: z.string(),
711
+ userCanPush: z.boolean().optional().openapi({
712
+ description:
713
+ "Whether the agent's bound GitHub user can push. Omitted when no username is bound or the org's access lookup is incomplete; never reported as false for unknown.",
714
+ }),
715
+ }),
716
+ ),
717
+ }),
718
+ ),
719
+ })
720
+ .openapi("GithubInstallationReposList");
721
+
722
+ const GithubInstallationReposChangeSchema = z
723
+ .object({
724
+ status: z.enum(["applied"]),
725
+ auditId: z.string(),
726
+ repos: z.array(z.string()),
727
+ })
728
+ .openapi("GithubInstallationReposChange");
729
+
682
730
  // ─── Route definitions ──────────────────────────────────────────────────────────
683
731
 
684
732
  const reconcileAgentsRoute = createRoute({
@@ -1630,6 +1678,88 @@ const githubReconcileApplyRoute = createRoute({
1630
1678
  },
1631
1679
  });
1632
1680
 
1681
+ const installationReposErrors = {
1682
+ 401: { description: "Unauthorized", ...jsonError },
1683
+ 403: { description: "Platform admin required", ...jsonError },
1684
+ 404: { description: "Agent not found", ...jsonError },
1685
+ 422: {
1686
+ description: "Agent has no GH_APP_ID (its own GitHub App is not set up)",
1687
+ ...jsonError,
1688
+ },
1689
+ 503: { description: "GitHub Apps are not configured", ...jsonError },
1690
+ };
1691
+
1692
+ const listInstallationReposRoute = createRoute({
1693
+ method: "get",
1694
+ path: "/agents/{id}/github-installation/repos",
1695
+ summary: "List the repos on the agent App's installation",
1696
+ description:
1697
+ "Platform-admin only (session members, ops keys and agent keys get 403). Per org the agent's own GitHub App (its GH_APP_ID) is installed on, lists the installation's repos. When the agent has a bound githubUsername, each repo carries `userCanPush` from the access lookup only when that org's lookup result is complete; otherwise the field is omitted (never false). 404 for an unknown agent; 422 when the agent has no GH_APP_ID.",
1698
+ request: { params: AgentIdParamSchema },
1699
+ responses: {
1700
+ 200: {
1701
+ description: "Installation repos",
1702
+ content: {
1703
+ "application/json": { schema: GithubInstallationReposListSchema },
1704
+ },
1705
+ },
1706
+ ...installationReposErrors,
1707
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1708
+ },
1709
+ });
1710
+
1711
+ const addInstallationReposRoute = createRoute({
1712
+ method: "post",
1713
+ path: "/agents/{id}/github-installation/repos",
1714
+ summary: "Add repos to the agent App's installation",
1715
+ description:
1716
+ "Platform-admin only. Grants the agent's own GitHub App installation access to the named repos, with no plan step; the agent's configured repos are not changed. Writes one audit entry (GitHubReconcileAudit, planHash `direct:add`) recording the caller and repos. 404 unknown agent; 422 no GH_APP_ID; 409 when the App is not installed on a repo's org (nothing is changed or audited); 502 when GitHub refuses (a failed audit entry is written).",
1717
+ request: {
1718
+ params: AgentIdParamSchema,
1719
+ body: {
1720
+ required: true,
1721
+ content: { "application/json": { schema: InstallationReposBodySchema } },
1722
+ },
1723
+ },
1724
+ responses: {
1725
+ 200: {
1726
+ description: "Repos added",
1727
+ content: {
1728
+ "application/json": { schema: GithubInstallationReposChangeSchema },
1729
+ },
1730
+ },
1731
+ ...installationReposErrors,
1732
+ 409: { description: "Agent App not installed on the org", ...jsonError },
1733
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1734
+ },
1735
+ });
1736
+
1737
+ const removeInstallationReposRoute = createRoute({
1738
+ method: "post",
1739
+ path: "/agents/{id}/github-installation/repos/remove",
1740
+ summary: "Remove repos from the agent App's installation",
1741
+ description:
1742
+ "Platform-admin only. Revokes the agent's own GitHub App installation access to the named repos, with no plan step; the agent's configured repos are not changed. Writes one audit entry (GitHubReconcileAudit, planHash `direct:remove`) recording the caller and repos. Same errors as the add route.",
1743
+ request: {
1744
+ params: AgentIdParamSchema,
1745
+ body: {
1746
+ required: true,
1747
+ content: { "application/json": { schema: InstallationReposBodySchema } },
1748
+ },
1749
+ },
1750
+ responses: {
1751
+ 200: {
1752
+ description: "Repos removed",
1753
+ content: {
1754
+ "application/json": { schema: GithubInstallationReposChangeSchema },
1755
+ },
1756
+ },
1757
+ ...installationReposErrors,
1758
+ 409: { description: "Agent App not installed on the org", ...jsonError },
1759
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1760
+ },
1761
+ });
1762
+
1633
1763
  /** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
1634
1764
  export const cronRunStatsQuerySchema = z
1635
1765
  .object({
@@ -3207,6 +3337,100 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3207
3337
  }
3208
3338
  });
3209
3339
 
3340
+ // /agents/:id/github-installation/repos — IRM-1.2. Platform admin only;
3341
+ // responses carry repo names and ids, never tokens.
3342
+ const installationReposService = (c: {
3343
+ get(k: "isAdmin"): boolean | undefined;
3344
+ }) => {
3345
+ if (c.get("isAdmin") !== true) {
3346
+ throw new ForbiddenError(
3347
+ "Admin access required to manage installation repos",
3348
+ );
3349
+ }
3350
+ const svc = deps.githubInstallationRepos;
3351
+ if (!svc) throw new ApiError(503, GITHUB_RECONCILE_UNCONFIGURED);
3352
+ return svc;
3353
+ };
3354
+ const installationFailure = (
3355
+ agentId: string,
3356
+ result:
3357
+ | { status: "agent_not_found" }
3358
+ | { status: "no_app_id"; reason: string }
3359
+ | { status: "not_installed"; reason: string },
3360
+ ): never => {
3361
+ if (result.status === "agent_not_found") {
3362
+ throw new NotFoundError(`agent ${agentId} not found`);
3363
+ }
3364
+ if (result.status === "no_app_id") {
3365
+ throw new UnprocessableEntityError(result.reason);
3366
+ }
3367
+ throw new ConflictError(result.reason);
3368
+ };
3369
+
3370
+ app.openapi(listInstallationReposRoute, async (c) => {
3371
+ const svc = installationReposService(c);
3372
+ const { id: agentId } = c.req.valid("param");
3373
+ const result = await svc.list(agentId);
3374
+ if (result.status !== "ok") return installationFailure(agentId, result);
3375
+ return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3376
+ });
3377
+
3378
+ const changeInstallationRepos = async (
3379
+ kind: "add" | "remove",
3380
+ c: {
3381
+ get(k: "isAdmin"): boolean | undefined;
3382
+ get(k: "caller"): { name: string } | undefined;
3383
+ },
3384
+ agentId: string,
3385
+ repos: string[],
3386
+ ) => {
3387
+ const svc = installationReposService(c);
3388
+ const caller = c.get("caller")?.name ?? "anonymous";
3389
+ const result = await svc[kind](agentId, caller, repos);
3390
+ if (
3391
+ result.status === "agent_not_found" ||
3392
+ result.status === "no_app_id" ||
3393
+ result.status === "not_installed"
3394
+ ) {
3395
+ return installationFailure(agentId, result);
3396
+ }
3397
+ console.log(
3398
+ `[agents-api] github installation repos ${kind} ${result.status}: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3399
+ );
3400
+ if (result.status === "failed") {
3401
+ throw new BadGatewayError(
3402
+ `GitHub refused the ${kind}; audit ${result.auditId} records the failure: ${result.error}`,
3403
+ );
3404
+ }
3405
+ return {
3406
+ status: "applied" as const,
3407
+ auditId: result.auditId,
3408
+ repos: result.repos,
3409
+ };
3410
+ };
3411
+ app.openapi(addInstallationReposRoute, async (c) =>
3412
+ c.json(
3413
+ await changeInstallationRepos(
3414
+ "add",
3415
+ c,
3416
+ c.req.valid("param").id,
3417
+ c.req.valid("json").repos,
3418
+ ),
3419
+ 200,
3420
+ ),
3421
+ );
3422
+ app.openapi(removeInstallationReposRoute, async (c) =>
3423
+ c.json(
3424
+ await changeInstallationRepos(
3425
+ "remove",
3426
+ c,
3427
+ c.req.valid("param").id,
3428
+ c.req.valid("json").repos,
3429
+ ),
3430
+ 200,
3431
+ ),
3432
+ );
3433
+
3210
3434
  // GET /agents/:id/github-installations — latest snapshot, 404 if none yet
3211
3435
  app.openapi(getGitHubInstallationsRoute, async (c) => {
3212
3436
  const { id: agentId } = c.req.valid("param");
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * admin/src/github-enterprise-isolation.unit.test.ts
3
3
  * Isolation exception guard (GHE-1.3): the GitHub Enterprise App private key
4
- * is reachable only from the enterprise service, its admin API and the boot
5
- * wiring. Agent config bundle, agent-bearer routes and env serialization must
4
+ * is reachable only from the enterprise service, its admin API, the boot
5
+ * wiring and the reconcile wiring. Agent config bundle, agent-bearer routes and env serialization must
6
6
  * never import the service, touch its table or call getPrivateKey().
7
7
  */
8
8
 
@@ -17,6 +17,7 @@ const ALLOWED = new Set([
17
17
  "admin/src/github-enterprise-apps.ts",
18
18
  "admin/src/github-enterprise-api.ts",
19
19
  "admin/src/admin-boot.ts",
20
+ "admin/src/github-reconcile-wiring.ts",
20
21
  ]);
21
22
 
22
23
  function sources(dir: string, out: string[] = []): string[] {
@@ -66,13 +67,16 @@ describe("GitHub Enterprise key isolation", () => {
66
67
  expect(offenders).toEqual([]);
67
68
  });
68
69
 
69
- it("getPrivateKey() is only called by the enterprise API", () => {
70
+ it("getPrivateKey() is only called by the enterprise API and reconcile wiring", () => {
70
71
  const callers = files
71
72
  .map((f) => relative(REPO, f))
72
73
  .filter((rel) =>
73
74
  /\.getPrivateKey\(/.test(readFileSync(join(REPO, rel), "utf-8")),
74
75
  );
75
- expect(callers).toEqual(["admin/src/github-enterprise-api.ts"]);
76
+ expect(callers.sort()).toEqual([
77
+ "admin/src/github-enterprise-api.ts",
78
+ "admin/src/github-reconcile-wiring.ts",
79
+ ]);
76
80
  });
77
81
 
78
82
  it("the config bundle and env serializers never read the enterprise table", () => {