@app-vitals/agent-admin 1.35.1 → 1.36.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.
@@ -26,7 +26,7 @@ import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
26
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
27
27
  import {
28
28
  createGithubInstallationRepos,
29
- createGithubLostAccessRemoval,
29
+ createGithubSync,
30
30
  } from "./github-installation-wiring.ts";
31
31
  import { accessFor, envWith } from "./github-installation.fixtures.ts";
32
32
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
@@ -7131,9 +7131,9 @@ describe("admin API — GET /agents/:id/github-access (GHE-2.4)", () => {
7131
7131
  });
7132
7132
  });
7133
7133
 
7134
- // ─── IRM-1.2: /agents/:id/github-installation/repos ───────────────────────────
7134
+ // ─── IRM-1.2 / IRM-3.1: installation repos list and GitHub Sync ───────────────
7135
7135
 
7136
- describe("admin API — agent App installation repos (IRM-1.2)", () => {
7136
+ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, IRM-3.1)", () => {
7137
7137
  const OPS = "irm-ops-token";
7138
7138
  const READER = "irm-read-token";
7139
7139
  const AGENT_KEY = "irm-agent-token";
@@ -7150,7 +7150,8 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7150
7150
  "utf-8",
7151
7151
  ),
7152
7152
  );
7153
- // The recorded org installation belongs to App 777 (installation 501).
7153
+ // The recorded org installation belongs to App 777 (installation 501) and
7154
+ // covers acme-eng/repo-1 and repo-2.
7154
7155
  const INST = "/enterprises/acme/apps/organizations/acme-eng/installations";
7155
7156
  const routes: Record<string, string | unknown> = {
7156
7157
  "GET /enterprises/acme/installation": "enterprise_installation_success",
@@ -7162,6 +7163,7 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7162
7163
  [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_success",
7163
7164
  [`PATCH ${INST}/501/repositories/remove`]: "install_repos_remove_success",
7164
7165
  };
7166
+ const LIST = `GET ${INST}/501/repositories`;
7165
7167
 
7166
7168
  function setup(
7167
7169
  opts: {
@@ -7169,10 +7171,19 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7169
7171
  username?: string | null;
7170
7172
  known?: boolean;
7171
7173
  override?: Record<string, string>;
7174
+ agentRepos?: string[];
7175
+ pushable?: string[];
7176
+ openWork?: Partial<OpenWorkPort> | null;
7172
7177
  } = {},
7173
7178
  ) {
7174
7179
  const audits: Array<Record<string, unknown>> = [];
7175
7180
  const gh: string[] = [];
7181
+ const patches: Array<{ key: string; names: string[] }> = [];
7182
+ const events: unknown[][] = [];
7183
+ const state = {
7184
+ repos: [...(opts.agentRepos ?? ["acme-eng/repo-2"])],
7185
+ installed: ["acme-eng/repo-1", "acme-eng/repo-2"],
7186
+ };
7176
7187
  const table = { ...routes, ...(opts.override ?? {}) };
7177
7188
  const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
7178
7189
  const u = new URL(input.toString());
@@ -7188,6 +7199,33 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7188
7199
  if (!name) throw new Error(`no route for ${key}`);
7189
7200
  const entry = cassette[name];
7190
7201
  if (!entry) throw new Error(`no cassette entry ${name}`);
7202
+ // The installation's repo list follows the changes applied to it.
7203
+ if (key === LIST && name === "install_repos_success") {
7204
+ return new Response(
7205
+ JSON.stringify(
7206
+ state.installed.map((full_name, i) => ({
7207
+ id: i + 1,
7208
+ name: full_name.split("/")[1],
7209
+ full_name,
7210
+ })),
7211
+ ),
7212
+ { status: 200, headers: { "Content-Type": "application/json" } },
7213
+ );
7214
+ }
7215
+ if (key.startsWith("PATCH") && entry.status === 200) {
7216
+ const body = JSON.parse(String(init?.body ?? "{}")) as {
7217
+ repositories?: string[];
7218
+ };
7219
+ const names = body.repositories ?? [];
7220
+ patches.push({ key, names });
7221
+ events.push([key.endsWith("/add") ? "addRepos" : "removeRepos", names]);
7222
+ const full = names.map((n) =>
7223
+ `acme-eng/${n}`.replace("acme-eng/acme-eng/", "acme-eng/"),
7224
+ );
7225
+ state.installed = key.endsWith("/add")
7226
+ ? [...state.installed, ...full]
7227
+ : state.installed.filter((r) => !full.includes(r));
7228
+ }
7191
7229
  return new Response(JSON.stringify(entry.body), {
7192
7230
  status: entry.status,
7193
7231
  headers: { "Content-Type": "application/json" },
@@ -7200,13 +7238,18 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7200
7238
  ? null
7201
7239
  : {
7202
7240
  id: AGENT_ID,
7203
- repos: [],
7241
+ repos: [...state.repos],
7204
7242
  githubUsername:
7205
7243
  opts.username === undefined ? "dev" : opts.username,
7206
7244
  },
7245
+ update: async (args: { data: { repos: string[] } }) => {
7246
+ events.push(["setRepos", args.data.repos]);
7247
+ state.repos = args.data.repos;
7248
+ },
7207
7249
  },
7208
7250
  gitHubReconcileAudit: {
7209
7251
  create: async (args: { data: Record<string, unknown> }) => {
7252
+ events.push(["audit"]);
7210
7253
  audits.push(args.data);
7211
7254
  return { id: `audit-${audits.length}` };
7212
7255
  },
@@ -7214,14 +7257,29 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7214
7257
  } as unknown as Parameters<
7215
7258
  typeof createGithubInstallationRepos
7216
7259
  >[0]["prisma"];
7217
- const githubInstallationRepos = createGithubInstallationRepos({
7260
+ const openWork: OpenWorkPort | undefined =
7261
+ opts.openWork === null
7262
+ ? undefined
7263
+ : {
7264
+ listOpenWork: async (...a) => {
7265
+ events.push(["list", ...a]);
7266
+ return [{ id: "T-1", repo: "acme-eng/repo-2", title: "fix it" }];
7267
+ },
7268
+ blockOpenWork: async (...a) => {
7269
+ events.push(["block", ...a]);
7270
+ },
7271
+ ...opts.openWork,
7272
+ };
7273
+ const wiring = {
7218
7274
  prisma,
7219
7275
  appService: {
7220
7276
  get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
7221
7277
  getPrivateKey: async () => PEM,
7222
7278
  },
7223
- access: async (username) => {
7224
- const base = await accessFor(["acme-eng/repo-1"])(username);
7279
+ access: async (username: string) => {
7280
+ const base = await accessFor(
7281
+ opts.pushable ?? ["acme-eng/repo-1", "acme-eng/repo-3"],
7282
+ )(username);
7225
7283
  if (base.status === "unconfigured") return base;
7226
7284
  const [org] = base.access.orgs;
7227
7285
  return {
@@ -7234,6 +7292,11 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7234
7292
  },
7235
7293
  agentEnv: envWith(opts.env ?? { GH_APP_ID: "777" }),
7236
7294
  fetchFn,
7295
+ };
7296
+ const githubInstallationRepos = createGithubInstallationRepos(wiring);
7297
+ const githubSync = createGithubSync({
7298
+ ...wiring,
7299
+ ...(openWork ? { openWork } : {}),
7237
7300
  });
7238
7301
  const base = makeMockDeps();
7239
7302
  const app = createAdminApp({
@@ -7247,20 +7310,21 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7247
7310
  t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7248
7311
  },
7249
7312
  githubInstallationRepos,
7313
+ githubSync,
7250
7314
  });
7251
- return { app, audits, gh };
7315
+ return { app, audits, gh, patches, events, state };
7252
7316
  }
7253
7317
 
7254
7318
  const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
7255
- const url = (suffix = "", id = AGENT_ID) =>
7256
- `/agents/${id}/github-installation/repos${suffix}`;
7257
- const send = (
7319
+ const url = (id = AGENT_ID) => `/agents/${id}/github-installation/repos`;
7320
+ const previewUrl = `/agents/${AGENT_ID}/github-sync/preview`;
7321
+ const applyUrl = `/agents/${AGENT_ID}/github-sync/apply`;
7322
+ const apply = (
7258
7323
  app: ReturnType<typeof createAdminApp>,
7259
- path: string,
7260
- headers: Record<string, string>,
7261
- body: unknown = { repos: ["acme-eng/repo-3"] },
7324
+ body: unknown,
7325
+ headers: Record<string, string> = asAdmin,
7262
7326
  ) =>
7263
- app.request(path, {
7327
+ app.request(applyUrl, {
7264
7328
  method: "POST",
7265
7329
  headers: { "Content-Type": "application/json", ...headers },
7266
7330
  body: JSON.stringify(body),
@@ -7297,20 +7361,41 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7297
7361
  ]);
7298
7362
  });
7299
7363
 
7364
+ it("the direct add and remove routes are gone", async () => {
7365
+ const { app, audits, gh } = setup();
7366
+ for (const [method, path] of [
7367
+ ["POST", url()],
7368
+ ["POST", `${url()}/remove`],
7369
+ ["GET", `/agents/${AGENT_ID}/github-lost-access/preview`],
7370
+ ["POST", `/agents/${AGENT_ID}/github-lost-access/remove`],
7371
+ ] as const) {
7372
+ const res = await app.request(path, {
7373
+ method,
7374
+ headers: { "Content-Type": "application/json", ...asAdmin },
7375
+ body:
7376
+ method === "POST" ? JSON.stringify({ repos: ["a/b"] }) : undefined,
7377
+ });
7378
+ expect([404, 405]).toContain(res.status);
7379
+ }
7380
+ expect(audits).toEqual([]);
7381
+ expect(gh).toEqual([]);
7382
+ });
7383
+
7300
7384
  it("403 for ops, read and agent keys on every route; no GitHub call, no audit", async () => {
7301
7385
  const { app, audits, gh } = setup();
7302
7386
  for (const key of [OPS, READER, AGENT_KEY]) {
7303
7387
  const h = { Authorization: `Bearer ${key}` };
7304
7388
  expect((await app.request(url(), { headers: h })).status).toBe(403);
7305
- expect((await send(app, url(), h)).status).toBe(403);
7306
- expect((await send(app, url("/remove"), h)).status).toBe(403);
7389
+ expect((await app.request(previewUrl, { headers: h })).status).toBe(403);
7390
+ expect(
7391
+ (await apply(app, { appAdds: ["acme-eng/repo-3"] }, h)).status,
7392
+ ).toBe(403);
7307
7393
  }
7308
7394
  expect(audits).toEqual([]);
7309
7395
  expect(gh).toEqual([]);
7310
7396
  });
7311
7397
 
7312
7398
  it("403 for a non-admin session member", async () => {
7313
- const { app } = setup();
7314
7399
  const cookie = await sign(
7315
7400
  {
7316
7401
  isAdmin: false,
@@ -7334,91 +7419,27 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7334
7419
  headers: { Cookie: `admin_session=${cookie}` },
7335
7420
  });
7336
7421
  expect(res.status).toBe(403);
7337
- void app;
7338
7422
  });
7339
7423
 
7340
7424
  it("404 for an unknown agent on every route", async () => {
7341
7425
  const { app, audits } = setup({ known: false });
7342
7426
  expect((await app.request(url(), { headers: asAdmin })).status).toBe(404);
7343
- expect((await send(app, url(), asAdmin)).status).toBe(404);
7344
- expect((await send(app, url("/remove"), asAdmin)).status).toBe(404);
7427
+ expect((await app.request(previewUrl, { headers: asAdmin })).status).toBe(
7428
+ 404,
7429
+ );
7430
+ expect((await apply(app, { appAdds: ["acme-eng/repo-3"] })).status).toBe(
7431
+ 404,
7432
+ );
7345
7433
  expect(audits).toEqual([]);
7346
7434
  });
7347
7435
 
7348
- it("422 naming GH_APP_ID when the agent has none", async () => {
7436
+ it("422 naming GH_APP_ID when the agent has none on the list route; sync is skipped", async () => {
7349
7437
  const { app, audits } = setup({ env: {} });
7350
7438
  const res = await app.request(url(), { headers: asAdmin });
7351
7439
  expect(res.status).toBe(422);
7352
7440
  expect(JSON.stringify(await res.json())).toContain("GH_APP_ID");
7353
- expect((await send(app, url(), asAdmin)).status).toBe(422);
7354
- expect(audits).toEqual([]);
7355
- });
7356
-
7357
- it("409 when the agent's App is not installed on the org; nothing audited", async () => {
7358
- // App 999 has no recorded installation on acme-eng.
7359
- const { app, audits, gh } = setup({ env: { GH_APP_ID: "999" } });
7360
- const res = await send(app, url(), asAdmin);
7361
- expect(res.status).toBe(409);
7362
- expect(JSON.stringify(await res.json())).toContain("not installed");
7363
- expect(audits).toEqual([]);
7364
- expect(gh.some((k) => k.startsWith("PATCH"))).toBe(false);
7365
- });
7366
-
7367
- it("POST add changes the installation and writes one audit entry with the caller", async () => {
7368
- const { app, audits, gh } = setup();
7369
- const res = await send(app, url(), asAdmin, {
7370
- repos: ["acme-eng/repo-3"],
7371
- });
7372
- expect(res.status).toBe(200);
7373
- expect(await res.json()).toEqual({
7374
- status: "applied",
7375
- auditId: "audit-1",
7376
- repos: ["acme-eng/repo-3"],
7377
- });
7378
- expect(gh).toContain(`PATCH ${INST}/501/repositories/add`);
7379
- expect(audits).toHaveLength(1);
7380
- expect(audits[0]).toMatchObject({
7381
- agentId: AGENT_ID,
7382
- caller: "root",
7383
- planHash: "direct:add",
7384
- diff: { installationAdds: ["acme-eng/repo-3"], installationRemoves: [] },
7385
- result: { status: "applied" },
7386
- });
7387
- });
7388
-
7389
- it("POST remove changes the installation and writes one audit entry", async () => {
7390
- const { app, audits, gh } = setup();
7391
- const res = await send(app, url("/remove"), asAdmin, {
7392
- repos: ["acme-eng/repo-2"],
7393
- });
7394
- expect(res.status).toBe(200);
7395
- expect(gh).toContain(`PATCH ${INST}/501/repositories/remove`);
7396
- expect(audits).toHaveLength(1);
7397
- expect(audits[0]).toMatchObject({
7398
- caller: "root",
7399
- planHash: "direct:remove",
7400
- diff: { installationRemoves: ["acme-eng/repo-2"], installationAdds: [] },
7401
- });
7402
- });
7403
-
7404
- it("502 and a failed audit entry when GitHub refuses the change", async () => {
7405
- const { app, audits } = setup({
7406
- override: {
7407
- [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_403",
7408
- },
7409
- });
7410
- const res = await send(app, url(), asAdmin);
7411
- expect(res.status).toBe(502);
7412
- expect(audits).toHaveLength(1);
7413
- expect(audits[0]?.result).toMatchObject({ status: "failed" });
7414
- });
7415
-
7416
- it("400 for a body that is not owner/repo names", async () => {
7417
- const { app, audits } = setup();
7418
- expect((await send(app, url(), asAdmin, { repos: ["nope"] })).status).toBe(
7419
- 400,
7420
- );
7421
- expect((await send(app, url(), asAdmin, { repos: [] })).status).toBe(400);
7441
+ const pre = await app.request(previewUrl, { headers: asAdmin });
7442
+ expect(await pre.json()).toMatchObject({ status: "skipped" });
7422
7443
  expect(audits).toEqual([]);
7423
7444
  });
7424
7445
 
@@ -7428,137 +7449,34 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7428
7449
  adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7429
7450
  });
7430
7451
  expect((await app.request(url(), { headers: asAdmin })).status).toBe(503);
7452
+ expect((await app.request(previewUrl, { headers: asAdmin })).status).toBe(
7453
+ 503,
7454
+ );
7455
+ expect((await apply(app, { appAdds: ["acme-eng/repo-3"] })).status).toBe(
7456
+ 503,
7457
+ );
7431
7458
  });
7432
- });
7433
-
7434
- // ─── IRM-1.3: /agents/:id/github-lost-access ──────────────────────────────────
7435
-
7436
- describe("admin API — remove repos the bound user lost access to (IRM-1.3)", () => {
7437
- const OPS = "irm13-ops-token";
7438
- const AGENT_KEY = "irm13-agent-token";
7439
-
7440
- function setup(
7441
- opts: {
7442
- repos?: string[];
7443
- installed?: string[];
7444
- username?: string | null;
7445
- known?: boolean;
7446
- openWork?: Partial<OpenWorkPort> | null;
7447
- access?: AdminDeps["githubAccessPreview"];
7448
- } = {},
7449
- ) {
7450
- const state = {
7451
- repos: [...(opts.repos ?? ["acme/api", "acme/old"])],
7452
- installed: [...(opts.installed ?? ["acme/api", "acme/old", "acme/gone"])],
7453
- };
7454
- const audits: Array<Record<string, unknown>> = [];
7455
- const calls: unknown[][] = [];
7456
- const prisma = {
7457
- agent: {
7458
- findUnique: async () =>
7459
- opts.known === false
7460
- ? null
7461
- : {
7462
- id: AGENT_ID,
7463
- repos: [...state.repos],
7464
- githubUsername:
7465
- opts.username === undefined ? "dev" : opts.username,
7466
- },
7467
- update: async (args: { data: { repos: string[] } }) => {
7468
- calls.push(["setRepos", args.data.repos]);
7469
- state.repos = args.data.repos;
7470
- },
7471
- },
7472
- gitHubReconcileAudit: {
7473
- create: async (args: { data: Record<string, unknown> }) => {
7474
- calls.push(["audit"]);
7475
- audits.push(args.data);
7476
- return { id: `audit-${audits.length}` };
7477
- },
7478
- },
7479
- } as unknown as Parameters<
7480
- typeof createGithubLostAccessRemoval
7481
- >[0]["prisma"];
7482
- const openWork: OpenWorkPort | undefined =
7483
- opts.openWork === null
7484
- ? undefined
7485
- : {
7486
- listOpenWork: async (...a) => {
7487
- calls.push(["list", ...a]);
7488
- return [{ id: "T-1", repo: "acme/old", title: "fix it" }];
7489
- },
7490
- blockOpenWork: async (...a) => {
7491
- calls.push(["block", ...a]);
7492
- },
7493
- ...opts.openWork,
7494
- };
7495
- const githubLostAccessRemoval = createGithubLostAccessRemoval({
7496
- prisma,
7497
- appService: { get: async () => null, getPrivateKey: async () => null },
7498
- access: opts.access ?? accessFor(["acme/api"]),
7499
- agentEnv: envWith({ GH_APP_ID: "42" }),
7500
- installationRepos: {
7501
- listInstalled: async () => [
7502
- { org: "acme", repos: [...state.installed] },
7503
- ],
7504
- listRepos: async () => ({ acme: [...state.installed] }),
7505
- addRepos: async () => {},
7506
- removeRepos: async (_appId, org, repos) => {
7507
- calls.push(["removeRepos", org, [...repos]]);
7508
- state.installed = state.installed.filter((r) => !repos.includes(r));
7509
- },
7510
- },
7511
- ...(openWork ? { openWork } : {}),
7512
- });
7513
- const base = makeMockDeps();
7514
- const app = createAdminApp({
7515
- ...base,
7516
- adminApiKeys: parseAdminApiKeys(
7517
- `root:${ADMIN_API_KEY}:*,operator:${OPS}:platform.ops`,
7518
- ),
7519
- agentTokenService: {
7520
- ...base.agentTokenService,
7521
- validate: async (t: string) =>
7522
- t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7523
- },
7524
- githubLostAccessRemoval,
7525
- });
7526
- return { app, audits, calls, state };
7527
- }
7528
7459
 
7529
- const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
7530
- const previewUrl = `/agents/${AGENT_ID}/github-lost-access/preview`;
7531
- const removeUrl = `/agents/${AGENT_ID}/github-lost-access/remove`;
7532
- const remove = (
7533
- app: ReturnType<typeof createAdminApp>,
7534
- body: unknown,
7535
- headers: Record<string, string> = asAdmin,
7536
- ) =>
7537
- app.request(removeUrl, {
7538
- method: "POST",
7539
- headers: { "Content-Type": "application/json", ...headers },
7540
- body: JSON.stringify(body),
7541
- });
7542
-
7543
- it("preview lists the repos that would be removed and their open work, changing nothing", async () => {
7544
- const { app, audits, calls, state } = setup();
7460
+ it("sync preview lists app adds, app removes, agent removes and the open work, changing nothing", async () => {
7461
+ const { app, audits, patches, events, state } = setup();
7545
7462
  const res = await app.request(previewUrl, { headers: asAdmin });
7546
7463
  expect(res.status).toBe(200);
7547
7464
  expect(await res.json()).toEqual({
7548
7465
  status: "previewed",
7549
- repos: ["acme/gone", "acme/old"],
7550
- installationRemoves: ["acme/gone", "acme/old"],
7551
- configRemoves: ["acme/old"],
7466
+ appAdds: ["acme-eng/repo-3"],
7467
+ appRemoves: ["acme-eng/repo-2"],
7468
+ agentRemoves: ["acme-eng/repo-2"],
7552
7469
  skippedOrgs: [],
7553
- openWork: [{ id: "T-1", repo: "acme/old", title: "fix it" }],
7470
+ openWork: [{ id: "T-1", repo: "acme-eng/repo-2", title: "fix it" }],
7554
7471
  warnings: [],
7555
7472
  });
7556
7473
  expect(audits).toEqual([]);
7557
- expect(calls.map((c) => c[0])).toEqual(["list"]);
7558
- expect(state.repos).toEqual(["acme/api", "acme/old"]);
7474
+ expect(patches).toEqual([]);
7475
+ expect(events.map((e) => e[0])).toEqual(["list"]);
7476
+ expect(state.repos).toEqual(["acme-eng/repo-2"]);
7559
7477
  });
7560
7478
 
7561
- it("preview reports a failing open-work port as a warning", async () => {
7479
+ it("sync preview reports a failing open-work port as a warning", async () => {
7562
7480
  const { app } = setup({
7563
7481
  openWork: {
7564
7482
  listOpenWork: async () => {
@@ -7573,132 +7491,117 @@ describe("admin API — remove repos the bound user lost access to (IRM-1.3)", (
7573
7491
  expect(body.warnings.join()).toContain("store down");
7574
7492
  });
7575
7493
 
7576
- it("remove applies the confirmed repos in order, audits once, and blocks open work", async () => {
7577
- const { app, audits, calls, state } = setup();
7578
- const res = await remove(app, { repos: ["acme/old", "acme/api"] });
7494
+ it("sync apply changes the confirmed repos, audits once, blocks open work; a second preview has nothing to do", async () => {
7495
+ const { app, audits, events, state } = setup();
7496
+ const res = await apply(app, {
7497
+ appAdds: ["acme-eng/repo-3", "acme-eng/repo-1"],
7498
+ appRemoves: ["acme-eng/repo-2"],
7499
+ agentRemoves: ["acme-eng/repo-2"],
7500
+ });
7579
7501
  expect(res.status).toBe(200);
7580
7502
  expect(await res.json()).toEqual({
7581
7503
  status: "applied",
7582
7504
  auditId: "audit-1",
7583
- repos: ["acme/old"],
7584
- installationRemoves: ["acme/old"],
7585
- configRemoves: ["acme/old"],
7586
- notRemoved: [
7505
+ appAdds: ["acme-eng/repo-3"],
7506
+ appRemoves: ["acme-eng/repo-2"],
7507
+ agentRemoves: ["acme-eng/repo-2"],
7508
+ notApplied: [
7587
7509
  {
7588
- repo: "acme/api",
7589
- reason: "the bound user can still push to this repo",
7510
+ repo: "acme-eng/repo-1",
7511
+ reason: "already on the agent installation",
7590
7512
  },
7591
7513
  ],
7592
7514
  skippedOrgs: [],
7593
7515
  warnings: [],
7594
7516
  });
7595
- expect(calls).toEqual([
7596
- ["removeRepos", "acme", ["acme/old"]],
7597
- ["setRepos", ["acme/api"]],
7517
+ expect(events).toEqual([
7518
+ ["addRepos", ["repo-3"]],
7519
+ ["removeRepos", ["repo-2"]],
7520
+ ["setRepos", []],
7598
7521
  ["audit"],
7599
- ["block", AGENT_ID, ["acme/old"], repoLostAccessBlockReason("acme/old")],
7522
+ [
7523
+ "block",
7524
+ AGENT_ID,
7525
+ ["acme-eng/repo-2"],
7526
+ repoLostAccessBlockReason("acme-eng/repo-2"),
7527
+ ],
7600
7528
  ]);
7601
- expect(state.repos).toEqual(["acme/api"]);
7602
- expect(state.installed).toEqual(["acme/api", "acme/gone"]);
7603
7529
  expect(audits).toHaveLength(1);
7604
7530
  expect(audits[0]).toMatchObject({
7605
7531
  agentId: AGENT_ID,
7606
7532
  caller: "root",
7607
- planHash: "lost-access:remove",
7533
+ planHash: "sync:apply",
7608
7534
  result: { status: "applied" },
7609
7535
  });
7536
+ expect(state.repos).toEqual([]);
7537
+ const again = await app.request(previewUrl, { headers: asAdmin });
7538
+ expect(await again.json()).toMatchObject({
7539
+ status: "previewed",
7540
+ appAdds: [],
7541
+ appRemoves: [],
7542
+ agentRemoves: [],
7543
+ openWork: [],
7544
+ });
7610
7545
  });
7611
7546
 
7612
- it("a failing open-work port is a warning, not a failed call", async () => {
7613
- const { app, state, audits } = setup({
7547
+ it("sync apply: a failing open-work port is a warning, not a failed call", async () => {
7548
+ const { app, audits } = setup({
7614
7549
  openWork: {
7615
7550
  blockOpenWork: async () => {
7616
7551
  throw new Error("store down");
7617
7552
  },
7618
7553
  },
7619
7554
  });
7620
- const res = await remove(app, { repos: ["acme/old"] });
7555
+ const res = await apply(app, { agentRemoves: ["acme-eng/repo-2"] });
7621
7556
  expect(res.status).toBe(200);
7622
7557
  const body = (await res.json()) as { status: string; warnings: string[] };
7623
7558
  expect(body.status).toBe("applied");
7624
- expect(body.warnings[0]).toContain("acme/old");
7625
7559
  expect(body.warnings[0]).toContain("store down");
7626
- expect(state.repos).toEqual(["acme/api"]);
7627
7560
  expect(audits).toHaveLength(1);
7628
7561
  });
7629
7562
 
7630
- it("skipped for an unbound user: nothing changed, no audit", async () => {
7631
- const { app, audits, calls } = setup({ username: null });
7632
- const res = await remove(app, { repos: ["acme/old"] });
7633
- expect(res.status).toBe(200);
7634
- expect(await res.json()).toMatchObject({ status: "skipped" });
7635
- expect((await app.request(previewUrl, { headers: asAdmin })).status).toBe(
7636
- 200,
7637
- );
7638
- expect(audits).toEqual([]);
7639
- expect(calls).toEqual([]);
7640
- });
7641
-
7642
- it("skipped for an unverified user: nothing changed, no audit", async () => {
7643
- const verified = accessFor(["acme/api"]);
7644
- const { app, audits, calls } = setup({
7645
- access: async (u) => {
7646
- const r = await verified(u);
7647
- return r.status === "ok"
7648
- ? { ...r, access: { ...r.access, userVerified: false } }
7649
- : r;
7563
+ it("sync apply: 502 and a failed audit entry when GitHub refuses a change", async () => {
7564
+ const { app, audits, state } = setup({
7565
+ override: {
7566
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_403",
7650
7567
  },
7651
7568
  });
7652
- const res = await remove(app, { repos: ["acme/old"] });
7653
- const body = (await res.json()) as { status: string; reason: string };
7654
- expect(body.status).toBe("skipped");
7655
- expect(body.reason).toContain("verified");
7569
+ const res = await apply(app, {
7570
+ appAdds: ["acme-eng/repo-3"],
7571
+ agentRemoves: ["acme-eng/repo-2"],
7572
+ });
7573
+ expect(res.status).toBe(502);
7574
+ expect(audits).toHaveLength(1);
7575
+ expect(audits[0]?.result).toMatchObject({ status: "failed" });
7576
+ expect(state.repos).toEqual(["acme-eng/repo-2"]);
7577
+ });
7578
+
7579
+ it("sync apply: skipped for an unbound user, nothing changed, no audit", async () => {
7580
+ const { app, audits, gh } = setup({ username: null });
7581
+ const res = await apply(app, { appAdds: ["acme-eng/repo-3"] });
7582
+ expect(await res.json()).toMatchObject({ status: "skipped" });
7656
7583
  expect(audits).toEqual([]);
7657
- expect(calls).toEqual([]);
7584
+ expect(gh).toEqual([]);
7658
7585
  });
7659
7586
 
7660
- it("422 for more than 10 removals without confirmRemovals; nothing changed", async () => {
7661
- const many = Array.from({ length: 11 }, (_, i) => `acme/r${i}`);
7662
- const { app, audits, state } = setup({ repos: many, installed: many });
7663
- const res = await remove(app, { repos: many });
7587
+ it("sync apply: 422 for more than 10 removals without confirmRemovals; nothing changed", async () => {
7588
+ const many = Array.from({ length: 11 }, (_, i) => `acme-eng/r${i}`);
7589
+ const { app, audits, state } = setup({ agentRepos: many });
7590
+ const res = await apply(app, { agentRemoves: many });
7664
7591
  expect(res.status).toBe(422);
7665
7592
  expect(JSON.stringify(await res.json())).toContain("confirmRemovals");
7666
7593
  expect(audits).toEqual([]);
7667
7594
  expect(state.repos).toEqual(many);
7668
- const ok = await remove(app, { repos: many, confirmRemovals: true });
7595
+ const ok = await apply(app, { agentRemoves: many, confirmRemovals: true });
7669
7596
  expect(ok.status).toBe(200);
7670
7597
  expect(state.repos).toEqual([]);
7671
7598
  });
7672
7599
 
7673
- it("noop when nothing named still lacks access; no audit", async () => {
7674
- const { app, audits } = setup();
7675
- const res = await remove(app, { repos: ["acme/api"] });
7676
- expect(res.status).toBe(200);
7677
- expect(await res.json()).toMatchObject({ status: "noop", repos: [] });
7678
- expect(audits).toEqual([]);
7679
- });
7680
-
7681
- it("403 for ops and agent keys; 404 unknown agent; 400 bad body; 503 unwired", async () => {
7600
+ it("sync apply: noop when nothing confirmed still applies; 400 for bad names", async () => {
7682
7601
  const { app, audits } = setup();
7683
- for (const key of [OPS, AGENT_KEY]) {
7684
- const h = { Authorization: `Bearer ${key}` };
7685
- expect((await app.request(previewUrl, { headers: h })).status).toBe(403);
7686
- expect((await remove(app, { repos: ["acme/old"] }, h)).status).toBe(403);
7687
- }
7688
- expect((await remove(app, { repos: [] })).status).toBe(400);
7689
- expect((await remove(app, { repos: ["nope"] })).status).toBe(400);
7602
+ const res = await apply(app, { appRemoves: ["acme-eng/repo-1"] });
7603
+ expect(await res.json()).toMatchObject({ status: "noop" });
7604
+ expect((await apply(app, { appAdds: ["nope"] })).status).toBe(400);
7690
7605
  expect(audits).toEqual([]);
7691
- const unknown = setup({ known: false }).app;
7692
- expect(
7693
- (await unknown.request(previewUrl, { headers: asAdmin })).status,
7694
- ).toBe(404);
7695
- expect((await remove(unknown, { repos: ["acme/old"] })).status).toBe(404);
7696
- const unwired = createAdminApp({
7697
- ...makeMockDeps(),
7698
- adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7699
- });
7700
- expect(
7701
- (await unwired.request(previewUrl, { headers: asAdmin })).status,
7702
- ).toBe(503);
7703
7606
  });
7704
7607
  });