@app-vitals/agent-admin 1.31.0 → 1.33.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.
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { PrismaClient } from "../prisma/client/client.ts";
15
+ import type { AgentEnvService } from "./agent-envs.ts";
15
16
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
16
17
  import {
17
18
  type OpenWorkItem,
@@ -25,6 +26,12 @@ import {
25
26
  repoOrg,
26
27
  } from "./reconcile-planner.ts";
27
28
 
29
+ /** Parses a stored GH_APP_ID; unset or non-numeric -> undefined. */
30
+ function parseAppId(raw: string | undefined): number | undefined {
31
+ const n = Number(raw?.trim());
32
+ return Number.isInteger(n) && n > 0 ? n : undefined;
33
+ }
34
+
28
35
  /** More removals than this need confirmRemovals. */
29
36
  export const MAX_UNCONFIRMED_REMOVALS = 10;
30
37
 
@@ -32,6 +39,8 @@ export interface ReconcileAgentRecord {
32
39
  id: string;
33
40
  repos: string[];
34
41
  githubUsername: string | null;
42
+ /** The agent's own GitHub App id (its stored GH_APP_ID); undefined when unset or not numeric. */
43
+ appId?: number;
35
44
  }
36
45
 
37
46
  export interface ReconcileAgentsPort {
@@ -39,13 +48,23 @@ export interface ReconcileAgentsPort {
39
48
  setRepos(agentId: string, repos: string[]): Promise<void>;
40
49
  }
41
50
 
42
- /** Repo access on the agent App's installations, per org login. */
51
+ /**
52
+ * Repo access on an agent App's installations, per org login. Each agent has
53
+ * its own App, so every call names the App (`appId`) whose installation is used.
54
+ */
43
55
  export interface ReconcileInstallationPort {
44
56
  /** Repos the agent App covers in each org; only the named orgs are needed. */
45
- listRepos(orgs: readonly string[]): Promise<Record<string, string[]>>;
57
+ listRepos(
58
+ appId: number,
59
+ orgs: readonly string[],
60
+ ): Promise<Record<string, string[]>>;
46
61
  /** Grant the installation access to repos (owner/repo, all in `org`). */
47
- addRepos(org: string, repos: readonly string[]): Promise<void>;
48
- removeRepos(org: string, repos: readonly string[]): Promise<void>;
62
+ addRepos(appId: number, org: string, repos: readonly string[]): Promise<void>;
63
+ removeRepos(
64
+ appId: number,
65
+ org: string,
66
+ repos: readonly string[],
67
+ ): Promise<void>;
49
68
  }
50
69
 
51
70
  export interface ReconcileAuditEntry {
@@ -104,6 +123,10 @@ export type ReconcileApplyResult =
104
123
  error: string;
105
124
  };
106
125
 
126
+ /** Skip reason when the agent has no usable GH_APP_ID in its stored env. */
127
+ export const MISSING_APP_ID_REASON =
128
+ "agent has no GH_APP_ID in its stored env (its own GitHub App is not set up)";
129
+
107
130
  const orgsOf = (repos: readonly string[]): string[] =>
108
131
  [...new Set(repos.map(repoOrg))].sort();
109
132
 
@@ -176,7 +199,17 @@ export class ReconcileApplyService {
176
199
  ? { ...plan, skipReason: "GitHub Apps are not configured" }
177
200
  : plan;
178
201
  }
202
+ if (agent.appId === undefined) {
203
+ const plan = planReconcile({
204
+ username,
205
+ access: null,
206
+ agentRepos: agent.repos,
207
+ installationRepos: {},
208
+ });
209
+ return { ...plan, skipReason: MISSING_APP_ID_REASON };
210
+ }
179
211
  const installationRepos = await this.deps.installation.listRepos(
212
+ agent.appId,
180
213
  orgsOf([...agent.repos, ...(namedAdds ?? [])]),
181
214
  );
182
215
  return planReconcile({
@@ -209,7 +242,7 @@ export class ReconcileApplyService {
209
242
  diff: plan.diff,
210
243
  };
211
244
  try {
212
- await this.applyInstallation(plan.diff);
245
+ await this.applyInstallation(agent, plan.diff);
213
246
  await this.applyConfig(agent, plan.diff);
214
247
  } catch (err) {
215
248
  const error = err instanceof Error ? err.message : String(err);
@@ -230,13 +263,22 @@ export class ReconcileApplyService {
230
263
  return { status: "applied", plan, auditId, warnings };
231
264
  }
232
265
 
233
- private async applyInstallation(diff: ReconcileDiff): Promise<void> {
266
+ private async applyInstallation(
267
+ agent: ReconcileAgentRecord,
268
+ diff: ReconcileDiff,
269
+ ): Promise<void> {
234
270
  const { installation } = this.deps;
271
+ const hasChanges =
272
+ diff.installationAdds.length + diff.installationRemoves.length > 0;
273
+ if (agent.appId === undefined) {
274
+ if (hasChanges) throw new Error(MISSING_APP_ID_REASON);
275
+ return;
276
+ }
235
277
  for (const [org, repos] of groupByOrg(diff.installationAdds)) {
236
- await installation.addRepos(org, repos);
278
+ await installation.addRepos(agent.appId, org, repos);
237
279
  }
238
280
  for (const [org, repos] of groupByOrg(diff.installationRemoves)) {
239
- await installation.removeRepos(org, repos);
281
+ await installation.removeRepos(agent.appId, org, repos);
240
282
  }
241
283
  }
242
284
 
@@ -290,13 +332,20 @@ export class PrismaReconcileAudit implements ReconcileAuditPort {
290
332
 
291
333
  /** Prisma-backed agent reads/writes for the reconcile. */
292
334
  export class PrismaReconcileAgents implements ReconcileAgentsPort {
293
- constructor(private readonly prisma: PrismaClient) {}
335
+ constructor(
336
+ private readonly prisma: PrismaClient,
337
+ private readonly env: Pick<AgentEnvService, "getConfigBundle">,
338
+ ) {}
294
339
 
295
340
  async get(agentId: string): Promise<ReconcileAgentRecord | null> {
296
- return this.prisma.agent.findUnique({
341
+ const agent = await this.prisma.agent.findUnique({
297
342
  where: { id: agentId },
298
343
  select: { id: true, repos: true, githubUsername: true },
299
344
  });
345
+ if (!agent) return null;
346
+ const raw = (await this.env.getConfigBundle(agentId))?.env.GH_APP_ID;
347
+ const appId = parseAppId(raw);
348
+ return appId === undefined ? agent : { ...agent, appId };
300
349
  }
301
350
 
302
351
  async setRepos(agentId: string, repos: string[]): Promise<void> {
@@ -326,46 +375,63 @@ export interface InstallationRepoClient {
326
375
  ): Promise<unknown>;
327
376
  }
328
377
 
378
+ /** The agent App has no installation on the org (distinct from a GitHub failure). */
379
+ export class AppNotInstalledError extends Error {
380
+ constructor(
381
+ readonly appId: number,
382
+ readonly org: string,
383
+ ) {
384
+ super(
385
+ `agent App ${appId} (the agent's GH_APP_ID) is not installed on org ${org}`,
386
+ );
387
+ this.name = "AppNotInstalledError";
388
+ }
389
+ }
390
+
329
391
  const baseName = (fullName: string): string => fullName.split("/")[1] ?? "";
330
392
 
331
393
  /**
332
- * ReconcileInstallationPort over GithubEnterpriseClient (GHE-3.1), scoped to
333
- * the agent App's installation (`agentAppId`) on each org.
394
+ * ReconcileInstallationPort over GithubEnterpriseClient (GHE-3.1). Each call
395
+ * is scoped to the named agent App's installation on the org.
334
396
  */
335
397
  export function createInstallationPort(
336
398
  client: InstallationRepoClient,
337
- agentAppId: number,
338
399
  ): ReconcileInstallationPort {
339
- const installationId = async (org: string): Promise<number> => {
400
+ const installationId = async (
401
+ appId: number,
402
+ org: string,
403
+ ): Promise<number> => {
340
404
  const found = (await client.listOrgInstallations(org)).find(
341
- (i) => i.appId === agentAppId,
405
+ (i) => i.appId === appId,
342
406
  );
343
- if (!found) throw new Error(`agent App is not installed on ${org}`);
407
+ if (!found) {
408
+ throw new AppNotInstalledError(appId, org);
409
+ }
344
410
  return found.id;
345
411
  };
346
412
  return {
347
- async listRepos(orgs) {
413
+ async listRepos(appId, orgs) {
348
414
  const out: Record<string, string[]> = {};
349
415
  for (const org of orgs) {
350
416
  const repos = await client.listInstallationRepositories(
351
417
  org,
352
- await installationId(org),
418
+ await installationId(appId, org),
353
419
  );
354
420
  out[org] = repos.map((r) => r.fullName);
355
421
  }
356
422
  return out;
357
423
  },
358
- async addRepos(org, repos) {
424
+ async addRepos(appId, org, repos) {
359
425
  await client.addRepositories(
360
426
  org,
361
- await installationId(org),
427
+ await installationId(appId, org),
362
428
  repos.map(baseName),
363
429
  );
364
430
  },
365
- async removeRepos(org, repos) {
431
+ async removeRepos(appId, org, repos) {
366
432
  await client.removeRepositories(
367
433
  org,
368
- await installationId(org),
434
+ await installationId(appId, org),
369
435
  repos.map(baseName),
370
436
  );
371
437
  },
@@ -37,6 +37,7 @@ function access(pushable: string[]): UserRepoAccessResult {
37
37
  }
38
38
 
39
39
  function build(opts: {
40
+ appId?: number | null;
40
41
  repos: string[];
41
42
  pushable: string[];
42
43
  installed?: string[];
@@ -52,6 +53,7 @@ function build(opts: {
52
53
  id: "a1",
53
54
  repos: state.repos,
54
55
  githubUsername: "dev",
56
+ ...(opts.appId === null ? {} : { appId: opts.appId ?? 42 }),
55
57
  }),
56
58
  setRepos: async (_id, repos) => {
57
59
  calls.push("config");
@@ -61,8 +63,10 @@ function build(opts: {
61
63
  access: async () =>
62
64
  opts.preview ?? { status: "ok", access: access(opts.pushable) },
63
65
  installation: {
64
- listRepos: async () => ({ acme: opts.installed ?? opts.repos }),
65
- addRepos: async () => {
66
+ listRepos: async (_app, _orgs) => ({
67
+ acme: opts.installed ?? opts.repos,
68
+ }),
69
+ addRepos: async (_app) => {
66
70
  calls.push("inst-add");
67
71
  },
68
72
  removeRepos: async () => {
@@ -148,6 +152,39 @@ describe("ReconcileApplyService (unit)", () => {
148
152
  );
149
153
  });
150
154
 
155
+ it("agent without GH_APP_ID is skipped with a reason naming GH_APP_ID", async () => {
156
+ const { svc, calls } = build({
157
+ appId: null,
158
+ repos: ["acme/a"],
159
+ pushable: ["acme/a"],
160
+ });
161
+ const plan = await svc.plan("a1");
162
+ expect(plan.skipped).toBe(true);
163
+ expect(plan.skipReason).toContain("GH_APP_ID");
164
+ expect(plan.skipReason).not.toContain("not configured");
165
+ const res = await svc.apply({ agentId: "a1", caller: "c", planHash: "x" });
166
+ expect(res.status).toBe("skipped");
167
+ expect(calls).toEqual([]);
168
+ });
169
+
170
+ it("passes the agent's own App id to the installation port", async () => {
171
+ const seen: number[] = [];
172
+ const { svc } = build({
173
+ appId: 77,
174
+ repos: ["acme/a"],
175
+ pushable: ["acme/a"],
176
+ });
177
+ // @ts-expect-error reach into deps to spy
178
+ const inst = svc.deps.installation;
179
+ const orig = inst.listRepos;
180
+ inst.listRepos = async (app: number, orgs: readonly string[]) => {
181
+ seen.push(app);
182
+ return orig(app, orgs);
183
+ };
184
+ await svc.plan("a1");
185
+ expect(seen).toEqual([77]);
186
+ });
187
+
151
188
  it("skipped plan (unconfigured) changes nothing and writes no audit", async () => {
152
189
  const { svc, calls, audits } = build({
153
190
  repos: ["acme/a"],
@@ -162,31 +199,40 @@ describe("ReconcileApplyService (unit)", () => {
162
199
  });
163
200
 
164
201
  describe("createInstallationPort (unit)", () => {
165
- it("scopes to the agent App installation and sends simple names", async () => {
202
+ it("scopes to the given App's installation per call and sends simple names", async () => {
166
203
  const seen: string[] = [];
167
- const port = createInstallationPort(
168
- {
169
- listOrgInstallations: async () => [
170
- { id: 1, appId: 10 },
171
- { id: 2, appId: 20 },
172
- ],
173
- listInstallationRepositories: async (_o, id) => {
174
- seen.push(`list:${id}`);
175
- return [{ fullName: "acme/a" }];
176
- },
177
- addRepositories: async (_o, id, names) => {
178
- seen.push(`add:${id}:${names.join(",")}`);
179
- },
180
- removeRepositories: async (_o, id, names) => {
181
- seen.push(`rm:${id}:${names.join(",")}`);
182
- },
204
+ const port = createInstallationPort({
205
+ listOrgInstallations: async () => [
206
+ { id: 1, appId: 10 },
207
+ { id: 2, appId: 20 },
208
+ ],
209
+ listInstallationRepositories: async (_o, id) => {
210
+ seen.push(`list:${id}`);
211
+ return [{ fullName: "acme/a" }];
183
212
  },
184
- 20,
213
+ addRepositories: async (_o, id, names) => {
214
+ seen.push(`add:${id}:${names.join(",")}`);
215
+ },
216
+ removeRepositories: async (_o, id, names) => {
217
+ seen.push(`rm:${id}:${names.join(",")}`);
218
+ },
219
+ });
220
+ expect(await port.listRepos(20, ["acme"])).toEqual({ acme: ["acme/a"] });
221
+ await port.addRepos(20, "acme", ["acme/b"]);
222
+ await port.removeRepos(10, "acme", ["acme/c", "acme/d"]);
223
+ expect(seen).toEqual(["list:2", "add:2:b", "rm:1:c,d"]);
224
+ });
225
+
226
+ it("names the org when the App is not installed there", async () => {
227
+ const port = createInstallationPort({
228
+ listOrgInstallations: async () => [{ id: 1, appId: 10 }],
229
+ listInstallationRepositories: async () => [],
230
+ addRepositories: async () => {},
231
+ removeRepositories: async () => {},
232
+ });
233
+ await expect(port.listRepos(99, ["acme"])).rejects.toThrow(
234
+ /99.*not installed on org acme/,
185
235
  );
186
- expect(await port.listRepos(["acme"])).toEqual({ acme: ["acme/a"] });
187
- await port.addRepos("acme", ["acme/b"]);
188
- await port.removeRepos("acme", ["acme/c", "acme/d"]);
189
- expect(seen).toEqual(["list:2", "add:2:b", "rm:2:c,d"]);
190
236
  });
191
237
  });
192
238
 
@@ -0,0 +1,59 @@
1
+ /**
2
+ * admin/src/repo-removal-open-work.ts
3
+ * Shared preview + block logic for open work on a repo removed from an agent's
4
+ * own repos (IRM-1.7; reused by IRM-1.3). Both helpers are no-ops without a
5
+ * port, and a port failure is returned as a warning, never thrown, so the
6
+ * removal itself always succeeds. Re-adding a repo never unblocks anything.
7
+ */
8
+
9
+ import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
10
+
11
+ export function repoRemovedFromAgentBlockReason(repo: string): string {
12
+ return `repo ${repo} was removed from the agent's repos`;
13
+ }
14
+
15
+ export interface RepoRemovalPreview {
16
+ openWork: OpenWorkItem[];
17
+ warnings: string[];
18
+ }
19
+
20
+ /** Read-only: the open work that removing `repos` would block. */
21
+ export async function previewRepoRemovalWork(
22
+ port: OpenWorkPort | undefined,
23
+ agentId: string,
24
+ repos: readonly string[],
25
+ ): Promise<RepoRemovalPreview> {
26
+ if (!port || repos.length === 0) return { openWork: [], warnings: [] };
27
+ try {
28
+ return { openWork: await port.listOpenWork(agentId, repos), warnings: [] };
29
+ } catch (err) {
30
+ const msg = err instanceof Error ? err.message : String(err);
31
+ return {
32
+ openWork: [],
33
+ warnings: [`open work could not be listed: ${msg}`],
34
+ };
35
+ }
36
+ }
37
+
38
+ /** Blocks the agent's open work on each removed repo; returns warnings. */
39
+ export async function blockRepoRemovalWork(
40
+ port: OpenWorkPort | undefined,
41
+ agentId: string,
42
+ repos: readonly string[],
43
+ ): Promise<string[]> {
44
+ if (!port) return [];
45
+ const warnings: string[] = [];
46
+ for (const repo of repos) {
47
+ try {
48
+ await port.blockOpenWork(
49
+ agentId,
50
+ [repo],
51
+ repoRemovedFromAgentBlockReason(repo),
52
+ );
53
+ } catch (err) {
54
+ const msg = err instanceof Error ? err.message : String(err);
55
+ warnings.push(`open work for ${repo} was not blocked: ${msg}`);
56
+ }
57
+ }
58
+ return warnings;
59
+ }
@@ -0,0 +1,81 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
3
+ import {
4
+ blockRepoRemovalWork,
5
+ previewRepoRemovalWork,
6
+ repoRemovedFromAgentBlockReason,
7
+ } from "./repo-removal-open-work.ts";
8
+
9
+ const ITEMS = [{ id: "T-1", repo: "a/one", title: "t" }];
10
+
11
+ function port(over: Partial<OpenWorkPort> = {}) {
12
+ const calls: unknown[][] = [];
13
+ const p: OpenWorkPort = {
14
+ listOpenWork: async (...a) => {
15
+ calls.push(["list", ...a]);
16
+ return ITEMS;
17
+ },
18
+ blockOpenWork: async (...a) => {
19
+ calls.push(["block", ...a]);
20
+ },
21
+ ...over,
22
+ };
23
+ return { p, calls };
24
+ }
25
+
26
+ describe("previewRepoRemovalWork", () => {
27
+ it("lists open work from the port", async () => {
28
+ const { p } = port();
29
+ expect(await previewRepoRemovalWork(p, "ag", ["a/one"])).toEqual({
30
+ openWork: ITEMS,
31
+ warnings: [],
32
+ });
33
+ });
34
+ it("is empty without a port", async () => {
35
+ expect(await previewRepoRemovalWork(undefined, "ag", ["a/one"])).toEqual({
36
+ openWork: [],
37
+ warnings: [],
38
+ });
39
+ });
40
+ it("turns a port failure into a warning", async () => {
41
+ const { p } = port({
42
+ listOpenWork: async () => {
43
+ throw new Error("down");
44
+ },
45
+ });
46
+ const r = await previewRepoRemovalWork(p, "ag", ["a/one"]);
47
+ expect(r.openWork).toEqual([]);
48
+ expect(r.warnings[0]).toContain("down");
49
+ });
50
+ it("never blocks", async () => {
51
+ const { p, calls } = port();
52
+ await previewRepoRemovalWork(p, "ag", ["a/one"]);
53
+ expect(calls.some((c) => c[0] === "block")).toBe(false);
54
+ });
55
+ });
56
+
57
+ describe("blockRepoRemovalWork", () => {
58
+ it("blocks each repo with a reason naming it", async () => {
59
+ const { p, calls } = port();
60
+ expect(await blockRepoRemovalWork(p, "ag", ["a/one", "b/two"])).toEqual([]);
61
+ expect(calls).toEqual([
62
+ ["block", "ag", ["a/one"], repoRemovedFromAgentBlockReason("a/one")],
63
+ ["block", "ag", ["b/two"], repoRemovedFromAgentBlockReason("b/two")],
64
+ ]);
65
+ expect(repoRemovedFromAgentBlockReason("a/one")).toContain("a/one");
66
+ });
67
+ it("does nothing without a port", async () => {
68
+ expect(await blockRepoRemovalWork(undefined, "ag", ["a/one"])).toEqual([]);
69
+ });
70
+ it("warns on port failure and continues with the next repo", async () => {
71
+ let n = 0;
72
+ const { p } = port({
73
+ blockOpenWork: async () => {
74
+ if (n++ === 0) throw new Error("boom");
75
+ },
76
+ });
77
+ const w = await blockRepoRemovalWork(p, "ag", ["a/one", "b/two"]);
78
+ expect(w).toHaveLength(1);
79
+ expect(w[0]).toContain("a/one");
80
+ });
81
+ });