@app-vitals/agent-admin 1.31.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.
@@ -0,0 +1,270 @@
1
+ /**
2
+ * admin/src/installation-repos-service.unit.test.ts
3
+ * IRM-1.2: the user-can-push hint logic and the list/add/remove service, with
4
+ * in-memory ports.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import {
9
+ InstallationReposService,
10
+ type InstallationReposPort,
11
+ userPushHints,
12
+ } from "./installation-repos-service.ts";
13
+ import {
14
+ AppNotInstalledError,
15
+ type ReconcileAuditEntry,
16
+ } from "./reconcile-apply-service.ts";
17
+ import type {
18
+ OrgAccessResult,
19
+ UserRepoAccessResult,
20
+ } from "./user-repo-access-resolver.ts";
21
+
22
+ const orgResult = (over: Partial<OrgAccessResult> = {}): OrgAccessResult => ({
23
+ org: "acme",
24
+ status: "ok",
25
+ unresolved: 0,
26
+ repos: [
27
+ { fullName: "acme/push", level: "write", canPush: true },
28
+ { fullName: "acme/readonly", level: "read", canPush: false },
29
+ ],
30
+ ...over,
31
+ });
32
+
33
+ const accessOf = (
34
+ orgs: OrgAccessResult[],
35
+ over: Partial<UserRepoAccessResult> = {},
36
+ ): UserRepoAccessResult => ({
37
+ username: "dev",
38
+ outcome: "ok",
39
+ userVerified: true,
40
+ orgs,
41
+ unresolved: 0,
42
+ complete: true,
43
+ checkedAt: "2026-11-11T00:00:00.000Z",
44
+ ...over,
45
+ });
46
+
47
+ describe("userPushHints", () => {
48
+ const repos = ["acme/push", "acme/readonly", "acme/unlisted"];
49
+
50
+ it("reports true/false for listed repos and omits unlisted ones", () => {
51
+ expect(userPushHints(accessOf([orgResult()]), "acme", repos)).toEqual([
52
+ { fullName: "acme/push", userCanPush: true },
53
+ { fullName: "acme/readonly", userCanPush: false },
54
+ { fullName: "acme/unlisted" },
55
+ ]);
56
+ });
57
+
58
+ it("matches org and repo names case-insensitively", () => {
59
+ expect(
60
+ userPushHints(accessOf([orgResult()]), "ACME", ["Acme/Push"]),
61
+ ).toEqual([{ fullName: "Acme/Push", userCanPush: true }]);
62
+ });
63
+
64
+ it("omits every hint when there is no access result", () => {
65
+ expect(userPushHints(undefined, "acme", repos).every(noHint)).toBe(true);
66
+ });
67
+
68
+ it("omits every hint when the org's result is partial, errored, unresolved or missing", () => {
69
+ for (const o of [
70
+ orgResult({ status: "partial" }),
71
+ orgResult({ status: "error" }),
72
+ orgResult({ status: "rate_limited" }),
73
+ orgResult({ status: "lookup_app_not_installed" }),
74
+ orgResult({ unresolved: 2 }),
75
+ ]) {
76
+ expect(userPushHints(accessOf([o]), "acme", repos).every(noHint)).toBe(
77
+ true,
78
+ );
79
+ }
80
+ expect(
81
+ userPushHints(accessOf([orgResult()]), "other", repos).every(noHint),
82
+ ).toBe(true);
83
+ });
84
+
85
+ it("omits hints for an unverified or missing user", () => {
86
+ expect(
87
+ userPushHints(
88
+ accessOf([orgResult()], { userVerified: false }),
89
+ "acme",
90
+ repos,
91
+ ).every(noHint),
92
+ ).toBe(true);
93
+ expect(
94
+ userPushHints(
95
+ accessOf([orgResult()], { outcome: "user_not_found" }),
96
+ "acme",
97
+ repos,
98
+ ).every(noHint),
99
+ ).toBe(true);
100
+ });
101
+ });
102
+
103
+ function noHint(r: { userCanPush?: boolean }): boolean {
104
+ return r.userCanPush === undefined;
105
+ }
106
+
107
+ function build(
108
+ opts: {
109
+ agent?: { githubUsername: string | null; appId?: number } | null;
110
+ access?: () => Promise<
111
+ | { status: "unconfigured" }
112
+ | { status: "ok"; access: UserRepoAccessResult }
113
+ >;
114
+ failAdd?: boolean;
115
+ notInstalled?: string;
116
+ } = {},
117
+ ) {
118
+ const audits: ReconcileAuditEntry[] = [];
119
+ const calls: string[] = [];
120
+ const installation: InstallationReposPort = {
121
+ listInstalled: async () => [
122
+ { org: "acme", repos: ["acme/push", "acme/unlisted"] },
123
+ ],
124
+ listRepos: async (appId, orgs) => {
125
+ if (opts.notInstalled && orgs.includes(opts.notInstalled)) {
126
+ throw new AppNotInstalledError(appId, opts.notInstalled);
127
+ }
128
+ return {};
129
+ },
130
+ addRepos: async (_a, org, repos) => {
131
+ if (opts.failAdd && org === "beta") throw new Error("boom");
132
+ calls.push(`add ${org} ${repos.join(",")}`);
133
+ },
134
+ removeRepos: async (_a, org, repos) => {
135
+ calls.push(`remove ${org} ${repos.join(",")}`);
136
+ },
137
+ };
138
+ const agent =
139
+ opts.agent === undefined
140
+ ? { id: "a1", repos: [], githubUsername: "dev", appId: 42 }
141
+ : opts.agent && { id: "a1", repos: [], ...opts.agent };
142
+ const svc = new InstallationReposService({
143
+ agents: { get: async () => agent },
144
+ access:
145
+ opts.access ??
146
+ (async () => ({ status: "ok", access: accessOf([orgResult()]) })),
147
+ installation,
148
+ audit: {
149
+ write: async (e) => {
150
+ audits.push(e);
151
+ return `audit-${audits.length}`;
152
+ },
153
+ },
154
+ });
155
+ return { svc, audits, calls };
156
+ }
157
+
158
+ describe("InstallationReposService.list", () => {
159
+ it("returns repos per org with hints for a bound user", async () => {
160
+ const { svc } = build();
161
+ expect(await svc.list("a1")).toEqual({
162
+ status: "ok",
163
+ appId: 42,
164
+ orgs: [
165
+ {
166
+ org: "acme",
167
+ repos: [
168
+ { fullName: "acme/push", userCanPush: true },
169
+ { fullName: "acme/unlisted" },
170
+ ],
171
+ },
172
+ ],
173
+ });
174
+ });
175
+
176
+ it("omits hints for an unbound agent without calling access", async () => {
177
+ let called = false;
178
+ const { svc } = build({
179
+ agent: { githubUsername: null, appId: 42 },
180
+ access: async () => {
181
+ called = true;
182
+ return { status: "unconfigured" };
183
+ },
184
+ });
185
+ const r = await svc.list("a1");
186
+ expect(called).toBe(false);
187
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
188
+ });
189
+
190
+ it("omits hints when access is unconfigured or the lookup throws", async () => {
191
+ for (const access of [
192
+ async () => ({ status: "unconfigured" as const }),
193
+ async () => {
194
+ throw new Error("502");
195
+ },
196
+ ]) {
197
+ const r = await build({ access }).svc.list("a1");
198
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
199
+ }
200
+ });
201
+
202
+ it("reports unknown agent and a missing GH_APP_ID distinctly", async () => {
203
+ expect(await build({ agent: null }).svc.list("x")).toEqual({
204
+ status: "agent_not_found",
205
+ });
206
+ const r = await build({ agent: { githubUsername: "dev" } }).svc.list("a1");
207
+ expect(r.status).toBe("no_app_id");
208
+ });
209
+ });
210
+
211
+ describe("InstallationReposService.add/remove", () => {
212
+ it("adds per org, dedupes, and writes one audit entry with the caller", async () => {
213
+ const { svc, audits, calls } = build();
214
+ const r = await svc.add("a1", "root", ["acme/a", "acme/a", "beta/b"]);
215
+ expect(r).toEqual({
216
+ status: "applied",
217
+ auditId: "audit-1",
218
+ repos: ["acme/a", "beta/b"],
219
+ });
220
+ expect(calls).toEqual(["add acme acme/a", "add beta beta/b"]);
221
+ expect(audits).toHaveLength(1);
222
+ expect(audits[0]).toMatchObject({
223
+ agentId: "a1",
224
+ caller: "root",
225
+ planHash: "direct:add",
226
+ diff: {
227
+ installationAdds: ["acme/a", "beta/b"],
228
+ installationRemoves: [],
229
+ configAdds: [],
230
+ configRemoves: [],
231
+ },
232
+ result: { status: "applied" },
233
+ });
234
+ });
235
+
236
+ it("remove records installationRemoves", async () => {
237
+ const { svc, audits } = build();
238
+ await svc.remove("a1", "root", ["acme/a"]);
239
+ expect(audits[0]?.diff.installationRemoves).toEqual(["acme/a"]);
240
+ expect(audits[0]?.planHash).toBe("direct:remove");
241
+ });
242
+
243
+ it("not installed: distinct status, nothing changed or audited", async () => {
244
+ const { svc, audits, calls } = build({ notInstalled: "beta" });
245
+ const r = await svc.add("a1", "root", ["acme/a", "beta/b"]);
246
+ expect(r).toMatchObject({ status: "not_installed", org: "beta" });
247
+ expect(calls).toEqual([]);
248
+ expect(audits).toEqual([]);
249
+ });
250
+
251
+ it("a mid-way GitHub failure audits a failed entry with only the repos that landed", async () => {
252
+ const { svc, audits } = build({ failAdd: true });
253
+ const r = await svc.add("a1", "root", ["acme/a", "beta/b"]);
254
+ expect(r).toEqual({ status: "failed", auditId: "audit-1", error: "boom" });
255
+ expect(audits[0]?.diff.installationAdds).toEqual(["acme/a"]);
256
+ expect(audits[0]?.result).toEqual({ status: "failed", error: "boom" });
257
+ });
258
+
259
+ it("unknown agent and no GH_APP_ID write nothing", async () => {
260
+ const a = build({ agent: null });
261
+ expect((await a.svc.add("x", "root", ["acme/a"])).status).toBe(
262
+ "agent_not_found",
263
+ );
264
+ const b = build({ agent: { githubUsername: null } });
265
+ expect((await b.svc.remove("a1", "root", ["acme/a"])).status).toBe(
266
+ "no_app_id",
267
+ );
268
+ expect(a.audits.concat(b.audits)).toEqual([]);
269
+ });
270
+ });
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import { AgentEnvService } from "./agent-envs.ts";
11
12
  import type { GithubAccessPreview } from "./github-access-preview.ts";
12
13
  import { createAdminPrismaClient } from "./prisma-client.ts";
13
14
  import {
@@ -15,6 +16,7 @@ import {
15
16
  PrismaReconcileAudit,
16
17
  ReconcileApplyService,
17
18
  } from "./reconcile-apply-service.ts";
19
+ import { identityCrypto } from "./token-crypto.ts";
18
20
 
19
21
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
22
  const describeOrSkip = TEST_DB ? describe : describe.skip;
@@ -55,10 +57,13 @@ describeOrSkip("ReconcileApplyService (integration)", () => {
55
57
  const service = (): ReconcileApplyService =>
56
58
  new ReconcileApplyService({
57
59
  agents: {
58
- get: (id) => new PrismaReconcileAgents(prisma).get(id),
60
+ get: (id) => new PrismaReconcileAgents(prisma, envService()).get(id),
59
61
  setRepos: async (id, repos) => {
60
62
  calls.push("config");
61
- await new PrismaReconcileAgents(prisma).setRepos(id, repos);
63
+ await new PrismaReconcileAgents(prisma, envService()).setRepos(
64
+ id,
65
+ repos,
66
+ );
62
67
  },
63
68
  },
64
69
  access: async () =>
@@ -77,6 +82,8 @@ describeOrSkip("ReconcileApplyService (integration)", () => {
77
82
  audit: new PrismaReconcileAudit(prisma),
78
83
  });
79
84
 
85
+ const envService = () => new AgentEnvService(prisma, identityCrypto);
86
+
80
87
  async function makeAgent(
81
88
  repos: string[],
82
89
  githubUsername: string | null = "dev",
@@ -84,6 +91,7 @@ describeOrSkip("ReconcileApplyService (integration)", () => {
84
91
  const a = await prisma.agent.create({
85
92
  data: { name: "A", repos, githubUsername },
86
93
  });
94
+ await envService().patch(a.id, { GH_APP_ID: "42" });
87
95
  installed = [...repos];
88
96
  return a.id;
89
97
  }
@@ -238,7 +246,7 @@ describeOrSkip("ReconcileApplyService (integration)", () => {
238
246
  const base = service();
239
247
  const plan = await base.plan(id);
240
248
  const failing = new ReconcileApplyService({
241
- agents: new PrismaReconcileAgents(prisma),
249
+ agents: new PrismaReconcileAgents(prisma, envService()),
242
250
  access: async () => accessFor(pushable),
243
251
  installation: {
244
252
  listRepos: async () => ({ acme: [...installed] }),
@@ -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