@app-vitals/agent-admin 1.36.0 → 1.36.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.36.0",
3
+ "version": "1.36.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.36.0",
45
+ "@app-vitals/agent-lib": "1.36.2",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -88,7 +88,7 @@ export const NO_USERNAME_REASON =
88
88
  "No GitHub username is bound to this agent, so there is nothing to sync against. Bind one under Owner and identities.";
89
89
 
90
90
  export const APP_ID_MISMATCH_MESSAGE =
91
- "No installation matches the GH_APP_ID of this agent, although the Installations card matches an installation by App slug. GH_APP_ID is probably set to the wrong numeric App id; correct it in the agent env.";
91
+ "No installation of the agent GitHub App was found on any org the installer can reach, although the Installations card lists one. The App is matched by client id or slug: check the App installation and the agent GH_APP_CLIENT_ID / GH_APP_SLUG.";
92
92
 
93
93
  /** JSON body of GET /agents/:id/github-sync/preview. */
94
94
  export interface GithubSyncPreviewView {
@@ -314,6 +314,17 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
314
314
  expect(html).not.toContain("github-sync-confirm-btn");
315
315
  });
316
316
 
317
+ it("shows the no-installation reason, never 'Already in sync'", async () => {
318
+ const reason = "No installation of the agent GitHub App was found";
319
+ const { app } = setup({
320
+ agentsApi: () => json({ status: "skipped", reason }),
321
+ });
322
+ const html = await (await get(app, "/github-sync/confirm")).text();
323
+ expect(html).toContain('data-sync="skipped"');
324
+ expect(html).toContain("No installation of the agent GitHub App");
325
+ expect(html).not.toContain("Already in sync");
326
+ });
327
+
317
328
  it("surfaces an API failure on the confirm step", async () => {
318
329
  const { app } = setup({
319
330
  agentsApi: () => json({ error: "GitHub Apps are not configured" }, 503),
package/src/agents-api.ts CHANGED
@@ -3251,6 +3251,10 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3251
3251
  const svc = installationReposService(c);
3252
3252
  const { id: agentId } = c.req.valid("param");
3253
3253
  const result = await svc.list(agentId);
3254
+ if (result.status === "skipped") {
3255
+ // No installation matched: the listing stays empty (additive shape).
3256
+ return c.json({ appId: result.appId, orgs: [] }, 200);
3257
+ }
3254
3258
  if (result.status !== "ok") return installationFailure(agentId, result);
3255
3259
  return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3256
3260
  });
@@ -0,0 +1,26 @@
1
+ [
2
+ {
3
+ "id": 1000001,
4
+ "app_slug": "example-agent-app",
5
+ "client_id": "Iv1.0000000000000000",
6
+ "account": { "login": "example-org" },
7
+ "repository_selection": "selected",
8
+ "repositories_url": "https://api.github.com/enterprises/example-ent/apps/organizations/example-org/installations/1000001/repositories",
9
+ "permissions": { "contents": "write", "metadata": "read" },
10
+ "events": ["push"],
11
+ "created_at": "2026-01-01T00:00:00Z",
12
+ "updated_at": "2026-01-02T00:00:00Z"
13
+ },
14
+ {
15
+ "id": 1000002,
16
+ "app_slug": "example-other-app",
17
+ "client_id": "Iv1.1111111111111111",
18
+ "account": { "login": "example-org" },
19
+ "repository_selection": "all",
20
+ "repositories_url": "https://api.github.com/enterprises/example-ent/apps/organizations/example-org/installations/1000002/repositories",
21
+ "permissions": { "metadata": "read" },
22
+ "events": [],
23
+ "created_at": "2026-01-01T00:00:00Z",
24
+ "updated_at": "2026-01-02T00:00:00Z"
25
+ }
26
+ ]
@@ -16,6 +16,7 @@
16
16
  * Auth: admin key or admin session (every other caller class gets 403).
17
17
  */
18
18
 
19
+ import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
19
20
  import { createPrivateKey } from "node:crypto";
20
21
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
21
22
  import { HTTPException } from "hono/http-exception";
@@ -84,9 +85,6 @@ const REQUIRED_PERMISSION: Record<
84
85
  lookup: { name: "metadata", levels: ["read", "write"] },
85
86
  };
86
87
 
87
- const SLUG_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
88
- /** GitHub App client ids look like Iv1.<hex> / Iv23li<alnum>; no path or query chars. */
89
- const CLIENT_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
90
88
  const ORG_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
91
89
 
92
90
  // ─── Schemas ──────────────────────────────────────────────────────────────────
@@ -142,7 +142,12 @@ export interface InstallableOrganization {
142
142
 
143
143
  export interface AppInstallation {
144
144
  id: number;
145
- appId: number;
145
+ /**
146
+ * GitHub's enterprise-organization-installation schema omits app_id, so this
147
+ * is undefined for installations listed through the enterprise API; match by
148
+ * clientId or appSlug instead.
149
+ */
150
+ appId?: number;
146
151
  appSlug: string;
147
152
  clientId?: string;
148
153
  accountLogin: string;
@@ -504,7 +509,7 @@ export class GithubEnterpriseClient {
504
509
 
505
510
  interface RawInstallation {
506
511
  id: number;
507
- app_id: number;
512
+ app_id?: number;
508
513
  app_slug: string;
509
514
  client_id?: string;
510
515
  account?: { login?: string } | null;
@@ -521,10 +526,10 @@ function toRepository(r: RawRepository): AccessibleRepository {
521
526
  return { id: r.id, name: r.name, fullName: r.full_name };
522
527
  }
523
528
 
524
- function toInstallation(r: RawInstallation): AppInstallation {
529
+ export function toInstallation(r: RawInstallation): AppInstallation {
525
530
  return {
526
531
  id: r.id,
527
- appId: r.app_id,
532
+ ...(r.app_id === undefined ? {} : { appId: r.app_id }),
528
533
  appSlug: r.app_slug,
529
534
  ...(r.client_id ? { clientId: r.client_id } : {}),
530
535
  accountLogin: r.account?.login ?? "",
@@ -23,7 +23,7 @@ const portWith = (
23
23
  },
24
24
  listInstalled: async (appId) => {
25
25
  seen.push(appId);
26
- return [{ org: "acme", repos }];
26
+ return { status: "found", orgs: [{ org: "acme", repos }] };
27
27
  },
28
28
  addRepos: async () => {},
29
29
  removeRepos: async () => {},
@@ -25,7 +25,11 @@
25
25
  */
26
26
 
27
27
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
28
- import type { InstallationReposPort } from "./installation-repos-service.ts";
28
+ import {
29
+ identityOf,
30
+ type InstallationReposPort,
31
+ NO_INSTALLATION_REASON,
32
+ } from "./installation-repos-service.ts";
29
33
  import {
30
34
  MAX_UNCONFIRMED_REMOVALS,
31
35
  MISSING_APP_ID_REASON,
@@ -317,17 +321,18 @@ export class GithubSyncService {
317
321
  }
318
322
 
319
323
  const appId = agent.appId as number;
324
+ const identity = identityOf(agent);
320
325
  const added: string[] = [];
321
326
  const removed: string[] = [];
322
327
  let configDone = false;
323
328
  let error: string | undefined;
324
329
  try {
325
330
  for (const [org, repos] of groupByOrg(plan.appAdds)) {
326
- await this.deps.installation.addRepos(appId, org, repos);
331
+ await this.deps.installation.addRepos(appId, org, repos, identity);
327
332
  added.push(...repos);
328
333
  }
329
334
  for (const [org, repos] of groupByOrg(plan.appRemoves)) {
330
- await this.deps.installation.removeRepos(appId, org, repos);
335
+ await this.deps.installation.removeRepos(appId, org, repos, identity);
331
336
  removed.push(...repos);
332
337
  }
333
338
  if (plan.agentRemoves.length > 0) {
@@ -385,13 +390,17 @@ export class GithubSyncService {
385
390
  const skip = accessSkipReason(username, preview.access);
386
391
  if (skip) return skippedPlan(skip);
387
392
  if (agent.appId === undefined) return skippedPlan(MISSING_APP_ID_REASON);
388
- const installed = await this.deps.installation.listInstalled(agent.appId);
393
+ const installed = await this.deps.installation.listInstalled(
394
+ agent.appId,
395
+ identityOf(agent),
396
+ );
397
+ if (installed.status === "none") return skippedPlan(NO_INSTALLATION_REASON);
389
398
  return planGithubSync({
390
399
  username,
391
400
  access: preview.access,
392
401
  agentRepos: agent.repos,
393
402
  installationRepos: Object.fromEntries(
394
- installed.map(({ org, repos }) => [org, repos]),
403
+ installed.orgs.map(({ org, repos }) => [org, repos]),
395
404
  ),
396
405
  ...(requested
397
406
  ? {
@@ -13,7 +13,10 @@ import type {
13
13
  InstallationAgentRecord,
14
14
  InstallationAuditEntry,
15
15
  } from "./installation-ports.ts";
16
- import type { InstallationReposPort } from "./installation-repos-service.ts";
16
+ import {
17
+ type InstallationReposPort,
18
+ NO_INSTALLATION_REASON,
19
+ } from "./installation-repos-service.ts";
17
20
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
18
21
  import { repoLostAccessBlockReason } from "./repo-removal-open-work.ts";
19
22
  import {
@@ -249,6 +252,7 @@ function harness(
249
252
  agent?: Partial<InstallationAgentRecord> | null;
250
253
  access?: Awaited<ReturnType<GithubAccessPreviewFn>>;
251
254
  installed?: { org: string; repos: string[] }[];
255
+ noInstallation?: boolean;
252
256
  removeFails?: boolean;
253
257
  openWork?: Partial<OpenWorkPort> | null;
254
258
  } = {},
@@ -269,7 +273,9 @@ function harness(
269
273
  > = {
270
274
  listInstalled: async (appId) => {
271
275
  calls.push(["listInstalled", appId]);
272
- return installed;
276
+ return opts.noInstallation
277
+ ? { status: "none" }
278
+ : { status: "found", orgs: installed };
273
279
  },
274
280
  addRepos: async (appId, o, r) => {
275
281
  calls.push(["addRepos", appId, o, [...r]]);
@@ -339,6 +345,33 @@ const applyInput = (
339
345
  ...extra,
340
346
  });
341
347
 
348
+ describe("GithubSyncService with no installation", () => {
349
+ it("preview is skipped with the no-installation reason", async () => {
350
+ const { svc } = harness({ noInstallation: true });
351
+ expect(await svc.preview("ag")).toEqual({
352
+ status: "skipped",
353
+ reason: NO_INSTALLATION_REASON,
354
+ });
355
+ });
356
+
357
+ it("apply is skipped, not noop, and changes nothing", async () => {
358
+ const { svc, calls, audits } = harness({ noInstallation: true });
359
+ expect(await svc.apply(applyInput({}))).toEqual({
360
+ status: "skipped",
361
+ reason: NO_INSTALLATION_REASON,
362
+ });
363
+ expect(calls.map((c) => c[0])).toEqual(["listInstalled"]);
364
+ expect(audits).toEqual([]);
365
+ });
366
+
367
+ it("an App matched to an org with nothing to change still returns noop", async () => {
368
+ const { svc } = harness({
369
+ installed: [{ org: "acme", repos: ["acme/a", "acme/b"] }],
370
+ });
371
+ expect((await svc.apply(applyInput({}))).status).toBe("noop");
372
+ });
373
+ });
374
+
342
375
  describe("GithubSyncService.preview", () => {
343
376
  it("returns all three lists plus the open work removals block, changing nothing", async () => {
344
377
  const { svc, calls, audits } = harness();
@@ -0,0 +1,79 @@
1
+ /**
2
+ * admin/src/installation-ports-fixture.integration.test.ts
3
+ * Installation ports driven by the synthetic enterprise-organization-installation
4
+ * fixture (no app_id), mapped through the real client mapper. No network, no DB.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { toInstallation } from "./github-enterprise-client.ts";
9
+ import enterpriseOrgInstallations from "./fixtures/enterprise-org-installations.json";
10
+ import { createInstallationReposPort } from "./installation-repos-service.ts";
11
+ import {
12
+ AppNotInstalledError,
13
+ createInstallationPort,
14
+ } from "./installation-ports.ts";
15
+
16
+ const ORG = "example-org";
17
+ const CLIENT_ID = "Iv1.0000000000000000";
18
+ const SLUG = "example-agent-app";
19
+
20
+ function harness() {
21
+ const calls: string[] = [];
22
+ const port = createInstallationPort({
23
+ listOrgInstallations: async () =>
24
+ enterpriseOrgInstallations.map((r) =>
25
+ toInstallation(r as Parameters<typeof toInstallation>[0]),
26
+ ),
27
+ listInstallationRepositories: async (_o, id) => {
28
+ calls.push(`list:${id}`);
29
+ return [{ fullName: `${ORG}/repo-a` }];
30
+ },
31
+ addRepositories: async (_o, id, names) => {
32
+ calls.push(`add:${id}:${names.join(",")}`);
33
+ },
34
+ removeRepositories: async (_o, id, names) => {
35
+ calls.push(`rm:${id}:${names.join(",")}`);
36
+ },
37
+ });
38
+ const reposPort = createInstallationReposPort(port, {
39
+ listInstallableOrganizations: async () => [{ login: ORG }],
40
+ });
41
+ return { calls, port, reposPort };
42
+ }
43
+
44
+ describe("installation ports with the no-app_id fixture", () => {
45
+ for (const [label, identity] of [
46
+ ["client id", { clientId: CLIENT_ID }],
47
+ ["slug", { slug: SLUG.toUpperCase() }],
48
+ ] as const) {
49
+ it(`finds the installation by ${label}`, async () => {
50
+ const { calls, port, reposPort } = harness();
51
+ expect(await port.listRepos(7, [ORG], identity)).toEqual({
52
+ [ORG]: [`${ORG}/repo-a`],
53
+ });
54
+ await port.addRepos(7, ORG, [`${ORG}/repo-b`], identity);
55
+ await port.removeRepos(7, ORG, [`${ORG}/repo-c`], identity);
56
+ expect(await reposPort.listInstalled(7, identity)).toEqual({
57
+ status: "found",
58
+ orgs: [{ org: ORG, repos: [`${ORG}/repo-a`] }],
59
+ });
60
+ expect(calls).toEqual([
61
+ "list:1000001",
62
+ "add:1000001:repo-b",
63
+ "rm:1000001:repo-c",
64
+ "list:1000001",
65
+ ]);
66
+ });
67
+ }
68
+
69
+ it("lists no orgs and throws for an agent with no identifier", async () => {
70
+ const { port, reposPort } = harness();
71
+ await expect(port.listRepos(7, [ORG])).rejects.toBeInstanceOf(
72
+ AppNotInstalledError,
73
+ );
74
+ await expect(
75
+ port.addRepos(7, ORG, [`${ORG}/x`], {}),
76
+ ).rejects.toBeInstanceOf(AppNotInstalledError);
77
+ expect(await reposPort.listInstalled(7)).toEqual({ status: "none" });
78
+ });
79
+ });
@@ -15,6 +15,17 @@ function parseAppId(raw: string | undefined): number | undefined {
15
15
  return Number.isInteger(n) && n > 0 ? n : undefined;
16
16
  }
17
17
 
18
+ /** GitHub App slug shape (also validates a stored GH_APP_SLUG). */
19
+ export const SLUG_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
20
+ /** GitHub App client ids look like Iv1.<hex> / Iv23li<alnum>; no path or query chars. */
21
+ export const CLIENT_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
22
+
23
+ /** A stored env value that passes `re` (trimmed), else undefined. */
24
+ function validEnv(raw: string | undefined, re: RegExp): string | undefined {
25
+ const v = raw?.trim();
26
+ return v && re.test(v) ? v : undefined;
27
+ }
28
+
18
29
  /** More removals than this need confirmRemovals. */
19
30
  export const MAX_UNCONFIRMED_REMOVALS = 10;
20
31
 
@@ -24,6 +35,19 @@ export interface InstallationAgentRecord {
24
35
  githubUsername: string | null;
25
36
  /** The agent's own GitHub App id (its stored GH_APP_ID); undefined when unset or not numeric. */
26
37
  appId?: number;
38
+ /** The agent App's client id (stored GH_APP_CLIENT_ID); undefined when unset or malformed. */
39
+ clientId?: string;
40
+ /** The agent App's slug (stored GH_APP_SLUG); undefined when unset or malformed. */
41
+ slug?: string;
42
+ }
43
+
44
+ /**
45
+ * How an installation is matched to the agent's App when the enterprise API
46
+ * omits `app_id`: by client id, then slug (case-insensitive), then appId.
47
+ */
48
+ export interface AppIdentity {
49
+ clientId?: string;
50
+ slug?: string;
27
51
  }
28
52
 
29
53
  export interface InstallationAgentsPort {
@@ -40,13 +64,20 @@ export interface AppInstallationPort {
40
64
  listRepos(
41
65
  appId: number,
42
66
  orgs: readonly string[],
67
+ identity?: AppIdentity,
43
68
  ): Promise<Record<string, string[]>>;
44
69
  /** Grant the installation access to repos (owner/repo, all in `org`). */
45
- addRepos(appId: number, org: string, repos: readonly string[]): Promise<void>;
70
+ addRepos(
71
+ appId: number,
72
+ org: string,
73
+ repos: readonly string[],
74
+ identity?: AppIdentity,
75
+ ): Promise<void>;
46
76
  removeRepos(
47
77
  appId: number,
48
78
  org: string,
49
79
  repos: readonly string[],
80
+ identity?: AppIdentity,
50
81
  ): Promise<void>;
51
82
  }
52
83
 
@@ -111,9 +142,17 @@ export class PrismaInstallationAgents implements InstallationAgentsPort {
111
142
  select: { id: true, repos: true, githubUsername: true },
112
143
  });
113
144
  if (!agent) return null;
114
- const raw = (await this.env.getConfigBundle(agentId))?.env.GH_APP_ID;
145
+ const env = (await this.env.getConfigBundle(agentId))?.env;
146
+ const raw = env?.GH_APP_ID;
115
147
  const appId = parseAppId(raw);
116
- return appId === undefined ? agent : { ...agent, appId };
148
+ const clientId = validEnv(env?.GH_APP_CLIENT_ID, CLIENT_ID_RE);
149
+ const slug = validEnv(env?.GH_APP_SLUG, SLUG_RE);
150
+ return {
151
+ ...agent,
152
+ ...(appId === undefined ? {} : { appId }),
153
+ ...(clientId === undefined ? {} : { clientId }),
154
+ ...(slug === undefined ? {} : { slug }),
155
+ };
117
156
  }
118
157
 
119
158
  async setRepos(agentId: string, repos: string[]): Promise<void> {
@@ -126,7 +165,15 @@ export class PrismaInstallationAgents implements InstallationAgentsPort {
126
165
 
127
166
  /** The slice of GithubEnterpriseClient the installation port needs. */
128
167
  export interface InstallationRepoClient {
129
- listOrgInstallations(org: string): Promise<{ id: number; appId: number }[]>;
168
+ listOrgInstallations(org: string): Promise<
169
+ {
170
+ id: number;
171
+ /** Absent on the enterprise-organization-installation schema. */
172
+ appId?: number;
173
+ appSlug?: string;
174
+ clientId?: string;
175
+ }[]
176
+ >;
130
177
  listInstallationRepositories(
131
178
  org: string,
132
179
  installationId: number,
@@ -156,6 +203,27 @@ export class AppNotInstalledError extends Error {
156
203
  }
157
204
  }
158
205
 
206
+ /**
207
+ * Pick the agent App's installation: client id, then slug (case-insensitive),
208
+ * then appId. Each key only counts when both sides carry it.
209
+ */
210
+ export function matchInstallation<
211
+ T extends { appId?: number; appSlug?: string; clientId?: string },
212
+ >(
213
+ installs: readonly T[],
214
+ appId: number,
215
+ identity?: AppIdentity,
216
+ ): T | undefined {
217
+ const { clientId, slug } = identity ?? {};
218
+ return (
219
+ (clientId ? installs.find((i) => i.clientId === clientId) : undefined) ??
220
+ (slug
221
+ ? installs.find((i) => i.appSlug?.toLowerCase() === slug.toLowerCase())
222
+ : undefined) ??
223
+ installs.find((i) => i.appId !== undefined && i.appId === appId)
224
+ );
225
+ }
226
+
159
227
  const baseName = (fullName: string): string => fullName.split("/")[1] ?? "";
160
228
 
161
229
  /**
@@ -168,9 +236,12 @@ export function createInstallationPort(
168
236
  const installationId = async (
169
237
  appId: number,
170
238
  org: string,
239
+ identity?: AppIdentity,
171
240
  ): Promise<number> => {
172
- const found = (await client.listOrgInstallations(org)).find(
173
- (i) => i.appId === appId,
241
+ const found = matchInstallation(
242
+ await client.listOrgInstallations(org),
243
+ appId,
244
+ identity,
174
245
  );
175
246
  if (!found) {
176
247
  throw new AppNotInstalledError(appId, org);
@@ -178,28 +249,28 @@ export function createInstallationPort(
178
249
  return found.id;
179
250
  };
180
251
  return {
181
- async listRepos(appId, orgs) {
252
+ async listRepos(appId, orgs, identity) {
182
253
  const out: Record<string, string[]> = {};
183
254
  for (const org of orgs) {
184
255
  const repos = await client.listInstallationRepositories(
185
256
  org,
186
- await installationId(appId, org),
257
+ await installationId(appId, org, identity),
187
258
  );
188
259
  out[org] = repos.map((r) => r.fullName);
189
260
  }
190
261
  return out;
191
262
  },
192
- async addRepos(appId, org, repos) {
263
+ async addRepos(appId, org, repos, identity) {
193
264
  await client.addRepositories(
194
265
  org,
195
- await installationId(appId, org),
266
+ await installationId(appId, org, identity),
196
267
  repos.map(baseName),
197
268
  );
198
269
  },
199
- async removeRepos(appId, org, repos) {
270
+ async removeRepos(appId, org, repos, identity) {
200
271
  await client.removeRepositories(
201
272
  org,
202
- await installationId(appId, org),
273
+ await installationId(appId, org, identity),
203
274
  repos.map(baseName),
204
275
  );
205
276
  },
@@ -4,18 +4,67 @@
4
4
  */
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
+ import enterpriseOrgInstallations from "./fixtures/enterprise-org-installations.json";
7
8
  import {
8
9
  AppNotInstalledError,
9
10
  createInstallationPort,
11
+ matchInstallation,
10
12
  } from "./installation-ports.ts";
11
13
 
14
+ describe("enterprise-org-installations fixture", () => {
15
+ it("has no app_id on any row (GitHub's schema omits it)", () => {
16
+ expect(enterpriseOrgInstallations.length).toBeGreaterThan(0);
17
+ for (const row of enterpriseOrgInstallations) {
18
+ expect("app_id" in row).toBe(false);
19
+ expect(typeof row.app_slug).toBe("string");
20
+ expect(typeof row.client_id).toBe("string");
21
+ }
22
+ });
23
+ });
24
+
25
+ describe("matchInstallation", () => {
26
+ const installs = [
27
+ { id: 1, appId: 10, appSlug: "slug-one", clientId: "Iv1.aaa" },
28
+ { id: 2, appId: 20, appSlug: "Slug-Two", clientId: "Iv1.bbb" },
29
+ { id: 3, appSlug: "slug-three" },
30
+ ];
31
+
32
+ it("prefers client id over slug over appId", () => {
33
+ expect(
34
+ matchInstallation(installs, 10, { clientId: "Iv1.bbb", slug: "slug-one" })
35
+ ?.id,
36
+ ).toBe(2);
37
+ expect(matchInstallation(installs, 10, { slug: "slug-three" })?.id).toBe(3);
38
+ expect(matchInstallation(installs, 20)?.id).toBe(2);
39
+ });
40
+
41
+ it("falls through to the next key when one does not match", () => {
42
+ expect(
43
+ matchInstallation(installs, 10, { clientId: "Iv1.zzz", slug: "SLUG-TWO" })
44
+ ?.id,
45
+ ).toBe(2);
46
+ expect(
47
+ matchInstallation(installs, 20, { clientId: "Iv1.zzz", slug: "nope" })
48
+ ?.id,
49
+ ).toBe(2);
50
+ });
51
+
52
+ it("matches the slug case-insensitively", () => {
53
+ expect(matchInstallation(installs, 99, { slug: "SLUG-ONE" })?.id).toBe(1);
54
+ });
55
+
56
+ it("never matches an installation without appId on appId alone", () => {
57
+ expect(matchInstallation([{}], 0)).toBeUndefined();
58
+ expect(matchInstallation(installs, 99, {})).toBeUndefined();
59
+ });
60
+ });
61
+
12
62
  describe("createInstallationPort", () => {
13
- it("scopes to the given App's installation per call and sends simple names", async () => {
14
- const seen: string[] = [];
15
- const port = createInstallationPort({
63
+ const fake = (seen: string[]) =>
64
+ createInstallationPort({
16
65
  listOrgInstallations: async () => [
17
- { id: 1, appId: 10 },
18
- { id: 2, appId: 20 },
66
+ { id: 1, appSlug: "app-one" },
67
+ { id: 2, appSlug: "app-two" },
19
68
  ],
20
69
  listInstallationRepositories: async (_o, id) => {
21
70
  seen.push(`list:${id}`);
@@ -28,19 +77,22 @@ describe("createInstallationPort", () => {
28
77
  seen.push(`rm:${id}:${names.join(",")}`);
29
78
  },
30
79
  });
31
- expect(await port.listRepos(20, ["acme"])).toEqual({ acme: ["acme/a"] });
32
- await port.addRepos(20, "acme", ["acme/b"]);
33
- await port.removeRepos(10, "acme", ["acme/c", "acme/d"]);
80
+
81
+ it("scopes to the identified App's installation per call and sends simple names", async () => {
82
+ const seen: string[] = [];
83
+ const port = fake(seen);
84
+ expect(await port.listRepos(0, ["acme"], { slug: "app-two" })).toEqual({
85
+ acme: ["acme/a"],
86
+ });
87
+ await port.addRepos(0, "acme", ["acme/b"], { slug: "APP-TWO" });
88
+ await port.removeRepos(0, "acme", ["acme/c", "acme/d"], {
89
+ slug: "app-one",
90
+ });
34
91
  expect(seen).toEqual(["list:2", "add:2:b", "rm:1:c,d"]);
35
92
  });
36
93
 
37
94
  it("names the org when the App is not installed there", async () => {
38
- const port = createInstallationPort({
39
- listOrgInstallations: async () => [{ id: 1, appId: 10 }],
40
- listInstallationRepositories: async () => [],
41
- addRepositories: async () => {},
42
- removeRepositories: async () => {},
43
- });
95
+ const port = fake([]);
44
96
  await expect(port.listRepos(99, ["acme"])).rejects.toThrow(
45
97
  /99.*not installed on org acme/,
46
98
  );
@@ -9,6 +9,7 @@ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
9
9
  import {
10
10
  AppNotInstalledError,
11
11
  MISSING_APP_ID_REASON,
12
+ type AppIdentity,
12
13
  type InstallationAgentsPort,
13
14
  type AppInstallationPort,
14
15
  } from "./installation-ports.ts";
@@ -17,11 +18,25 @@ import type {
17
18
  UserRepoAccessResult,
18
19
  } from "./user-repo-access-resolver.ts";
19
20
 
21
+ /**
22
+ * The orgs the agent App is installed on, or "none" when the App matched no
23
+ * org the installer can reach (distinct from an installation with no changes).
24
+ */
25
+ export type InstalledOrgsResult =
26
+ | { status: "found"; orgs: { org: string; repos: string[] }[] }
27
+ | { status: "none" };
28
+
20
29
  /** Installation port plus discovery of the orgs the agent App is installed on. */
21
30
  export interface InstallationReposPort extends AppInstallationPort {
22
- listInstalled(appId: number): Promise<{ org: string; repos: string[] }[]>;
31
+ listInstalled(
32
+ appId: number,
33
+ identity?: AppIdentity,
34
+ ): Promise<InstalledOrgsResult>;
23
35
  }
24
36
 
37
+ export const NO_INSTALLATION_REASON =
38
+ "No installation of the agent GitHub App was found on any org the installer can reach (matched by client id or slug). Check the App installation and the agent GH_APP_CLIENT_ID / GH_APP_SLUG.";
39
+
25
40
  export interface InstallationRepoView {
26
41
  fullName: string;
27
42
  /** Present only when the bound user's access to this repo is known. */
@@ -36,6 +51,7 @@ export interface InstallationOrgView {
36
51
  export type InstallationListResult =
37
52
  | { status: "agent_not_found" }
38
53
  | { status: "no_app_id"; reason: string }
54
+ | { status: "skipped"; appId: number; reason: string }
39
55
  | { status: "ok"; appId: number; orgs: InstallationOrgView[] };
40
56
 
41
57
  export interface InstallationReposDeps {
@@ -44,6 +60,17 @@ export interface InstallationReposDeps {
44
60
  installation: InstallationReposPort;
45
61
  }
46
62
 
63
+ /** The agent's App identity keys (client id, slug), when stored. */
64
+ export function identityOf(agent: {
65
+ clientId?: string;
66
+ slug?: string;
67
+ }): AppIdentity {
68
+ return {
69
+ ...(agent.clientId ? { clientId: agent.clientId } : {}),
70
+ ...(agent.slug ? { slug: agent.slug } : {}),
71
+ };
72
+ }
73
+
47
74
  const orgKey = (org: string): string => org.toLowerCase();
48
75
 
49
76
  /**
@@ -88,7 +115,17 @@ export class InstallationReposService {
88
115
  if (agent.appId === undefined) {
89
116
  return { status: "no_app_id", reason: MISSING_APP_ID_REASON };
90
117
  }
91
- const installed = await this.deps.installation.listInstalled(agent.appId);
118
+ const installed = await this.deps.installation.listInstalled(
119
+ agent.appId,
120
+ identityOf(agent),
121
+ );
122
+ if (installed.status === "none") {
123
+ return {
124
+ status: "skipped",
125
+ appId: agent.appId,
126
+ reason: NO_INSTALLATION_REASON,
127
+ };
128
+ }
92
129
  const username = agent.githubUsername?.trim();
93
130
  let access: UserRepoAccessResult | undefined;
94
131
  if (username) {
@@ -102,7 +139,7 @@ export class InstallationReposService {
102
139
  return {
103
140
  status: "ok",
104
141
  appId: agent.appId,
105
- orgs: installed.map(({ org, repos }) => ({
142
+ orgs: installed.orgs.map(({ org, repos }) => ({
106
143
  org,
107
144
  repos: userPushHints(access, org, repos),
108
145
  })),
@@ -125,18 +162,20 @@ export function createInstallationReposPort(
125
162
  ): InstallationReposPort {
126
163
  return {
127
164
  ...base,
128
- async listInstalled(appId) {
165
+ async listInstalled(appId, identity) {
129
166
  const out: { org: string; repos: string[] }[] = [];
130
167
  for (const { login } of await client.listInstallableOrganizations()) {
131
168
  try {
132
- const repos = await base.listRepos(appId, [login]);
169
+ const repos = await base.listRepos(appId, [login], identity);
133
170
  out.push({ org: login, repos: repos[login] ?? [] });
134
171
  } catch (err) {
135
172
  if (err instanceof AppNotInstalledError) continue;
136
173
  throw err;
137
174
  }
138
175
  }
139
- return out;
176
+ return out.length === 0
177
+ ? { status: "none" }
178
+ : { status: "found", orgs: out };
140
179
  },
141
180
  };
142
181
  }
@@ -7,6 +7,7 @@
7
7
  import { describe, expect, it } from "bun:test";
8
8
  import {
9
9
  InstallationReposService,
10
+ NO_INSTALLATION_REASON,
10
11
  type InstallationReposPort,
11
12
  userPushHints,
12
13
  } from "./installation-repos-service.ts";
@@ -103,6 +104,7 @@ function noHint(r: { userCanPush?: boolean }): boolean {
103
104
  function build(
104
105
  opts: {
105
106
  agent?: { githubUsername: string | null; appId?: number } | null;
107
+ noInstallation?: boolean;
106
108
  access?: () => Promise<
107
109
  | { status: "unconfigured" }
108
110
  | { status: "ok"; access: UserRepoAccessResult }
@@ -110,9 +112,13 @@ function build(
110
112
  } = {},
111
113
  ) {
112
114
  const installation: InstallationReposPort = {
113
- listInstalled: async () => [
114
- { org: "acme", repos: ["acme/push", "acme/unlisted"] },
115
- ],
115
+ listInstalled: async () =>
116
+ opts.noInstallation
117
+ ? { status: "none" }
118
+ : {
119
+ status: "found",
120
+ orgs: [{ org: "acme", repos: ["acme/push", "acme/unlisted"] }],
121
+ },
116
122
  listRepos: async () => ({}),
117
123
  addRepos: async () => {},
118
124
  removeRepos: async () => {},
@@ -175,6 +181,15 @@ describe("InstallationReposService.list", () => {
175
181
  }
176
182
  });
177
183
 
184
+ it("is skipped with a reason when the App matches no installation", async () => {
185
+ const r = await build({ noInstallation: true }).svc.list("a1");
186
+ expect(r).toEqual({
187
+ status: "skipped",
188
+ appId: 42,
189
+ reason: NO_INSTALLATION_REASON,
190
+ });
191
+ });
192
+
178
193
  it("reports unknown agent and a missing GH_APP_ID distinctly", async () => {
179
194
  expect(await build({ agent: null }).svc.list("x")).toEqual({
180
195
  status: "agent_not_found",