@app-vitals/agent-admin 1.86.1 → 1.88.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.
Files changed (33) hide show
  1. package/openapi.json +2 -2
  2. package/openapi.platform.json +30 -2
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -0
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
  7. package/prisma/client/models/GitHubRepoSnapshot.ts +33 -1
  8. package/prisma/migrations/20261125000000_add_github_snapshot_repository_selection/migration.sql +2 -0
  9. package/prisma/schema/schema.prisma +2 -0
  10. package/src/admin-ui-github-identity-pages.ts +22 -4
  11. package/src/admin-ui-github-identity-pages.unit.test.ts +87 -0
  12. package/src/admin-ui-installation-repos-pages.ts +29 -7
  13. package/src/admin-ui-installation-repos-pages.unit.test.ts +83 -0
  14. package/src/admin-ui-installation-repos.smoke.test.ts +77 -9
  15. package/src/admin-ui-pages.ts +15 -2
  16. package/src/admin-ui.ts +23 -17
  17. package/src/agents-api.smoke.test.ts +237 -2
  18. package/src/agents-api.ts +27 -4
  19. package/src/github-access-preview.integration.test.ts +38 -3
  20. package/src/github-access-preview.ts +1 -1
  21. package/src/github-agent-installation-crawler.ts +27 -8
  22. package/src/github-agent-installation-crawler.unit.test.ts +76 -1
  23. package/src/github-apps-state.ts +31 -0
  24. package/src/github-cache-roundtrip.integration.test.ts +405 -0
  25. package/src/github-enterprise-api.ts +24 -18
  26. package/src/github-installation-selection.integration.test.ts +91 -0
  27. package/src/github-installation-wiring.ts +35 -0
  28. package/src/github-repo-cache.ts +8 -0
  29. package/src/github-sync.ts +38 -4
  30. package/src/installation-ports.ts +2 -0
  31. package/src/installation-repos-service.ts +24 -1
  32. package/src/user-repo-access-resolver.ts +26 -5
  33. package/src/user-repo-access-resolver.unit.test.ts +80 -0
@@ -0,0 +1,91 @@
1
+ /**
2
+ * admin/src/github-installation-selection.integration.test.ts
3
+ * Real-database test (GIS-1.1): the agent installation crawl records whether
4
+ * the agent App's installation is on "all" or "selected" repositories on the
5
+ * cached snapshot, and listAgentSnapshots exposes it. A missing value stays
6
+ * null (unknown), never "all".
7
+ *
8
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
12
+ import type { PrismaClient } from "../prisma/client/client.ts";
13
+ import {
14
+ type AgentInstallationClient,
15
+ crawlAgentInstallation,
16
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
17
+ } from "./github-agent-installation-crawler.ts";
18
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
19
+ import { createAdminPrismaClient } from "./prisma-client.ts";
20
+
21
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
22
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
23
+
24
+ const T0 = new Date("2026-11-25T12:00:00Z");
25
+ const clock = { now: () => new Date(T0) };
26
+ const APP_ID = 4242;
27
+
28
+ type Selection = "all" | "selected" | "none" | undefined;
29
+
30
+ function client(selection: Selection): AgentInstallationClient {
31
+ return {
32
+ async listOrgInstallations() {
33
+ return [{ id: 900, appId: APP_ID, repositorySelection: selection }];
34
+ },
35
+ async listInstallationRepositoriesPage() {
36
+ return {
37
+ repos: [{ id: 1, fullName: "acme/a" }],
38
+ hasNext: false,
39
+ perPage: 10,
40
+ };
41
+ },
42
+ };
43
+ }
44
+
45
+ describeOrSkip("agent installation repository selection (integration)", () => {
46
+ let prisma: PrismaClient;
47
+ let cache: GitHubRepoCacheService;
48
+
49
+ const clean = async () => {
50
+ await prisma.gitHubCachedRepo.deleteMany();
51
+ await prisma.gitHubRepoSnapshot.deleteMany();
52
+ };
53
+ const crawl = (selection: Selection) =>
54
+ crawlAgentInstallation({
55
+ agent: { accountId: null, appId: APP_ID },
56
+ org: "acme",
57
+ client: client(selection),
58
+ store: cache,
59
+ clock,
60
+ });
61
+ const stored = async () =>
62
+ (
63
+ await cache.listAgentSnapshots(DEPLOYMENT_WIDE_ACCOUNT_KEY, String(APP_ID))
64
+ )[0]?.repositorySelection;
65
+
66
+ beforeEach(async () => {
67
+ prisma = createAdminPrismaClient(TEST_DB as string);
68
+ cache = new GitHubRepoCacheService(prisma, clock);
69
+ await clean();
70
+ });
71
+ afterEach(async () => {
72
+ await clean();
73
+ await prisma.$disconnect();
74
+ });
75
+
76
+ it("stores 'all', then 'selected' on a later crawl", async () => {
77
+ expect((await crawl("all")).outcome).toBe("complete");
78
+ expect(await stored()).toBe("all");
79
+ await crawl("selected");
80
+ expect(await stored()).toBe("selected");
81
+ });
82
+
83
+ it("leaves a missing value null, and resets a previous value to null", async () => {
84
+ await crawl(undefined);
85
+ expect(await stored()).toBeNull();
86
+ await crawl("all");
87
+ expect(await stored()).toBe("all");
88
+ await crawl(undefined);
89
+ expect(await stored()).toBeNull();
90
+ });
91
+ });
@@ -9,6 +9,10 @@
9
9
 
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import type {
13
+ GithubAppsState,
14
+ GithubAppsStateFn,
15
+ } from "./github-apps-state.ts";
12
16
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
13
17
  import type { Clock } from "./clock.ts";
14
18
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
@@ -93,6 +97,35 @@ export function lazyInstallerClient(
93
97
  };
94
98
  }
95
99
 
100
+ /**
101
+ * Which Apps are usable for an account: the lookup App needs metadata and its
102
+ * key; the installer App also needs its enterprise slug (same test as
103
+ * lazyInstallerClient). Probed per call so config changes are picked up.
104
+ */
105
+ export function githubAppsStateProbe(
106
+ deps: Pick<GithubInstallationWiringDeps, "appService">,
107
+ ): GithubAppsStateFn {
108
+ return async (accountId): Promise<GithubAppsState> => {
109
+ const [lookup, lookupKey, installer, installerKey] = await Promise.all([
110
+ deps.appService.get("lookup", accountId),
111
+ deps.appService.getPrivateKey("lookup", accountId),
112
+ deps.appService.get("installer", accountId),
113
+ deps.appService.getPrivateKey("installer", accountId),
114
+ ]);
115
+ if (!lookup || !lookupKey) return "lookup_missing";
116
+ return installer?.enterpriseSlug && installerKey ? "both" : "lookup_only";
117
+ };
118
+ }
119
+
120
+ /** The probe only guards the real installer-backed port; a replaced port has no installer to probe. */
121
+ function appsStateDep(
122
+ deps: Pick<InstallationReposWiringDeps, "appService" | "installationRepos">,
123
+ ): { appsState?: GithubAppsStateFn } {
124
+ return deps.installationRepos
125
+ ? {}
126
+ : { appsState: githubAppsStateProbe(deps) };
127
+ }
128
+
96
129
  export interface InstallationReposWiringDeps
97
130
  extends GithubInstallationWiringDeps {
98
131
  /** Test seam: replaces the installer-App-backed port. */
@@ -116,6 +149,7 @@ export function createGithubInstallationRepos(
116
149
  deps.installationRepos ??
117
150
  createInstallationReposPort(createInstallationPort(client), client),
118
151
  cache: new GitHubRepoCacheService(deps.prisma),
152
+ ...appsStateDep(deps),
119
153
  });
120
154
  }
121
155
 
@@ -194,6 +228,7 @@ export function createGithubSync(
194
228
  deps.installationRepos ??
195
229
  createInstallationReposPort(createInstallationPort(client), client),
196
230
  audit: new PrismaInstallationAudit(deps.prisma),
231
+ ...appsStateDep(deps),
197
232
  ...(deps.openWork ? { openWork: deps.openWork } : {}),
198
233
  });
199
234
  }
@@ -33,6 +33,8 @@ export type SnapshotProgress = Partial<{
33
33
  crawlStartedAt: Date | null;
34
34
  completedAt: Date | null;
35
35
  totalCount: number | null;
36
+ /** Agent snapshots: the App installation's repository selection; null = unknown. */
37
+ repositorySelection: "all" | "selected" | null;
36
38
  lastError: string | null;
37
39
  attempts: number;
38
40
  nextAttemptAt: Date | null;
@@ -71,6 +73,11 @@ export interface AccessQuery {
71
73
 
72
74
  const REPO_BATCH_SIZE = 500;
73
75
 
76
+ /** A stored selection narrowed to the known values; anything else is unknown (null). */
77
+ function asSelection(raw: string | null): "all" | "selected" | null {
78
+ return raw === "all" || raw === "selected" ? raw : null;
79
+ }
80
+
74
81
  function requireNonEmpty(name: string, value: unknown): void {
75
82
  if (typeof value !== "string" || value.trim() === "") {
76
83
  throw new BadRequestError(`${name} is required`);
@@ -178,6 +185,7 @@ export class GitHubRepoCacheService {
178
185
  totalCount: r.totalCount,
179
186
  lastError: r.lastError,
180
187
  rateLimitResetAt: r.rateLimitResetAt,
188
+ repositorySelection: asSelection(r.repositorySelection),
181
189
  attempts: r.attempts,
182
190
  nextAttemptAt: r.nextAttemptAt,
183
191
  leaseHolder: r.leaseHolder,
@@ -25,6 +25,11 @@
25
25
  */
26
26
 
27
27
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
28
+ import {
29
+ GITHUB_APPS_STATE_REASONS,
30
+ type GithubAppsState,
31
+ type GithubAppsStateFn,
32
+ } from "./github-apps-state.ts";
28
33
  import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
29
34
  import { DEFAULT_REFRESH_STALENESS_CAP_MS } from "./github-repo-refresher.ts";
30
35
  import {
@@ -104,6 +109,8 @@ export interface NotAppliedRepo {
104
109
  export interface GithubSyncPlan {
105
110
  skipped: boolean;
106
111
  skipReason?: string;
112
+ /** Set when the skip is because an App role is missing (additive). */
113
+ appsState?: Exclude<GithubAppsState, "both">;
107
114
  appAdds: string[];
108
115
  appRemoves: string[];
109
116
  agentRemoves: string[];
@@ -291,11 +298,17 @@ export interface GithubSyncDeps {
291
298
  audit: InstallationAuditPort;
292
299
  /** Optional: with none, nothing is listed or blocked. */
293
300
  openWork?: OpenWorkPort;
301
+ /** Optional: which Apps are usable; without both, Sync is skipped with a specific reason. */
302
+ appsState?: GithubAppsStateFn;
294
303
  }
295
304
 
296
305
  export type GithubSyncPreviewResult =
297
306
  | { status: "agent_not_found" }
298
- | { status: "skipped"; reason: string }
307
+ | {
308
+ status: "skipped";
309
+ reason: string;
310
+ appsState?: Exclude<GithubAppsState, "both">;
311
+ }
299
312
  | {
300
313
  status: "previewed";
301
314
  plan: GithubSyncPlan;
@@ -312,7 +325,11 @@ export interface GithubSyncApplyInput extends SyncLists {
312
325
 
313
326
  export type GithubSyncApplyResult =
314
327
  | { status: "agent_not_found" }
315
- | { status: "skipped"; reason: string }
328
+ | {
329
+ status: "skipped";
330
+ reason: string;
331
+ appsState?: Exclude<GithubAppsState, "both">;
332
+ }
316
333
  | { status: "noop"; plan: GithubSyncPlan }
317
334
  | { status: "removal_cap"; plan: GithubSyncPlan; removals: number }
318
335
  | {
@@ -341,7 +358,11 @@ export class GithubSyncService {
341
358
  if (!agent) return { status: "agent_not_found" };
342
359
  const plan = await this.planFor(agent);
343
360
  if (plan.skipped) {
344
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
361
+ return {
362
+ status: "skipped",
363
+ reason: plan.skipReason ?? "skipped",
364
+ ...(plan.appsState ? { appsState: plan.appsState } : {}),
365
+ };
345
366
  }
346
367
  const work = await previewRepoRemovalWork(
347
368
  this.deps.openWork,
@@ -361,7 +382,11 @@ export class GithubSyncService {
361
382
  if (!agent) return { status: "agent_not_found" };
362
383
  let plan = await this.planFor(agent, input);
363
384
  if (plan.skipped) {
364
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
385
+ return {
386
+ status: "skipped",
387
+ reason: plan.skipReason ?? "skipped",
388
+ ...(plan.appsState ? { appsState: plan.appsState } : {}),
389
+ };
365
390
  }
366
391
  plan = await this.reverifyRemovals(plan, agent);
367
392
  if (plan.appAdds.length + plan.removedRepos.length === 0) {
@@ -568,6 +593,15 @@ export class GithubSyncService {
568
593
  if (!username) {
569
594
  return skippedPlan(accessSkipReason(username, null) as string);
570
595
  }
596
+ if (this.deps.appsState) {
597
+ const state = await this.deps.appsState(agent.accountId);
598
+ if (state !== "both") {
599
+ return {
600
+ ...skippedPlan(GITHUB_APPS_STATE_REASONS[state]),
601
+ appsState: state,
602
+ };
603
+ }
604
+ }
571
605
  let liveAccess: UserRepoAccessResult | null = null;
572
606
  if (!this.deps.cache) {
573
607
  const preview = await this.deps.access(username, agent.accountId);
@@ -179,6 +179,8 @@ export interface InstallationRepoClient {
179
179
  appId?: number;
180
180
  appSlug?: string;
181
181
  clientId?: string;
182
+ /** "all" | "selected" | "none"; absent when the listing does not say. */
183
+ repositorySelection?: "all" | "selected" | "none";
182
184
  }[]
183
185
  >;
184
186
  listInstallationRepositories(
@@ -7,6 +7,11 @@
7
7
  * through the installation port.
8
8
  */
9
9
 
10
+ import {
11
+ GITHUB_APPS_STATE_REASONS,
12
+ type GithubAppsState,
13
+ type GithubAppsStateFn,
14
+ } from "./github-apps-state.ts";
10
15
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
11
16
  import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
12
17
  import {
@@ -87,6 +92,8 @@ export interface InstallationSnapshotRow {
87
92
  totalCount: number | null;
88
93
  lastError: string | null;
89
94
  rateLimitResetAt: Date | null;
95
+ /** The agent App's installation on the org; absent or null = unknown (never 'all'). */
96
+ repositorySelection?: "all" | "selected" | null;
90
97
  attempts?: number;
91
98
  nextAttemptAt?: Date | null;
92
99
  leaseHolder?: string | null;
@@ -128,6 +135,9 @@ export type InstallationListResult =
128
135
  status: "ok";
129
136
  appId: number;
130
137
  orgs: InstallationOrgView[];
138
+ /** Set when an App role is missing; the listing is the cached crawl only (additive). */
139
+ appsState?: Exclude<GithubAppsState, "both">;
140
+ reason?: string;
131
141
  } & InstallationSyncDetail);
132
142
 
133
143
  export interface InstallationReposDeps {
@@ -137,6 +147,8 @@ export interface InstallationReposDeps {
137
147
  installation: InstallationReposPort;
138
148
  /** The repo/access cache list() reads. Without it list() reports nothing synced. */
139
149
  cache?: InstallationCachePort;
150
+ /** Optional: which Apps are usable; without both, list() says why (additive fields). */
151
+ appsState?: GithubAppsStateFn;
140
152
  }
141
153
 
142
154
  /** The agent's App identity keys (client id, slug), when stored. */
@@ -338,7 +350,18 @@ export class InstallationReposService {
338
350
  ...(s.lastTickAt ? { lastTickAt: iso(s.lastTickAt) } : {}),
339
351
  });
340
352
  }
341
- return { status: "ok", appId: agent.appId, orgs, ...summarize(orgs) };
353
+ const state = this.deps.appsState
354
+ ? await this.deps.appsState(agent.accountId)
355
+ : "both";
356
+ return {
357
+ status: "ok",
358
+ appId: agent.appId,
359
+ orgs,
360
+ ...summarize(orgs),
361
+ ...(state !== "both"
362
+ ? { appsState: state, reason: GITHUB_APPS_STATE_REASONS[state] }
363
+ : {}),
364
+ };
342
365
  }
343
366
  }
344
367
 
@@ -123,8 +123,16 @@ export interface LookupPort {
123
123
  ): Promise<RepoRole>;
124
124
  }
125
125
 
126
+ /** Lookup-App org source: GithubLookupClient satisfies this. */
127
+ export interface LookupInstallationsPort {
128
+ listInstallations(): Promise<{ login: string }[]>;
129
+ }
130
+
126
131
  export interface UserRepoAccessResolverOptions {
127
- installer: InstallerPort;
132
+ /** Org source when configured: the orgs the installer App can install on. */
133
+ installer?: InstallerPort;
134
+ /** Org source when no installer is configured: the lookup App's own installations. */
135
+ lookupInstallations?: LookupInstallationsPort;
128
136
  lookup: LookupPort;
129
137
  now?: () => Date;
130
138
  /** Max concurrent per-repo permission calls (default 5). */
@@ -149,13 +157,15 @@ function kindOf(e: unknown): string | undefined {
149
157
  }
150
158
 
151
159
  export class UserRepoAccessResolver {
152
- private readonly installer: InstallerPort;
160
+ private readonly installer?: InstallerPort;
161
+ private readonly lookupInstallations?: LookupInstallationsPort;
153
162
  private readonly lookup: LookupPort;
154
163
  private readonly now: () => Date;
155
164
  private readonly concurrency: number;
156
165
 
157
166
  constructor(opts: UserRepoAccessResolverOptions) {
158
167
  this.installer = opts.installer;
168
+ this.lookupInstallations = opts.lookupInstallations;
159
169
  this.lookup = opts.lookup;
160
170
  this.now = opts.now ?? (() => new Date());
161
171
  this.concurrency = Math.max(
@@ -165,9 +175,7 @@ export class UserRepoAccessResolver {
165
175
  }
166
176
 
167
177
  async resolve(username: string): Promise<UserRepoAccessResult> {
168
- const candidates = (
169
- await this.installer.listInstallableOrganizations()
170
- ).map((o) => o.login);
178
+ const candidates = await this.listOrgs();
171
179
  const verdict = await this.verifyUser(candidates, username);
172
180
  if (verdict === "not_found") {
173
181
  return this.result(username, "user_not_found", true, []);
@@ -179,6 +187,19 @@ export class UserRepoAccessResolver {
179
187
  return this.result(username, "ok", verdict === "verified", orgs);
180
188
  }
181
189
 
190
+ /** The installer's installable orgs when configured, else the lookup App's installations. */
191
+ private async listOrgs(): Promise<string[]> {
192
+ const source = this.installer
193
+ ? await this.installer.listInstallableOrganizations()
194
+ : await this.lookupInstallations?.listInstallations();
195
+ if (!source) {
196
+ throw new Error(
197
+ "UserRepoAccessResolver needs an org source: installer or lookupInstallations",
198
+ );
199
+ }
200
+ return source.map((o) => o.login);
201
+ }
202
+
182
203
  /** One getUser check up front, on the first org that can mint a token. */
183
204
  private async verifyUser(
184
205
  orgs: string[],
@@ -103,6 +103,86 @@ describe("selected-repositories installation", () => {
103
103
  });
104
104
  });
105
105
 
106
+ describe("org source", () => {
107
+ function build(opts: {
108
+ installer?: string[];
109
+ lookupInstallations?: string[];
110
+ }) {
111
+ const calls: string[] = [];
112
+ const repos = { one: ["a"], two: ["b"], three: ["c"] } as Record<
113
+ string,
114
+ string[]
115
+ >;
116
+ const lookup: LookupPort = {
117
+ getOrgToken: async () => ({
118
+ token: "t",
119
+ expiresAt: "x",
120
+ installationId: 1,
121
+ }),
122
+ getUser: async (_o, login) => ({ id: 1, login, type: "User" }),
123
+ listInstallationRepositories: async (org) =>
124
+ (repos[org] ?? []).map((n) => repo(org, n)),
125
+ getCollaboratorPermission: async () => "write",
126
+ };
127
+ return {
128
+ calls,
129
+ resolver: new UserRepoAccessResolver({
130
+ ...(opts.installer
131
+ ? {
132
+ installer: {
133
+ listInstallableOrganizations: async () => {
134
+ calls.push("installer");
135
+ return (opts.installer ?? []).map((login, id) => ({
136
+ id,
137
+ login,
138
+ }));
139
+ },
140
+ },
141
+ }
142
+ : {}),
143
+ ...(opts.lookupInstallations
144
+ ? {
145
+ lookupInstallations: {
146
+ listInstallations: async () => {
147
+ calls.push("lookup");
148
+ return (opts.lookupInstallations ?? []).map((login, id) => ({
149
+ id,
150
+ login,
151
+ }));
152
+ },
153
+ },
154
+ }
155
+ : {}),
156
+ lookup,
157
+ now: () => NOW,
158
+ }),
159
+ };
160
+ }
161
+
162
+ it("lookup-only: orgs come from the lookup App installations", async () => {
163
+ const { resolver, calls } = build({ lookupInstallations: ["one", "two"] });
164
+ const res = await resolver.resolve("octocat");
165
+ expect(res.orgs.map((o) => o.org)).toEqual(["one", "two"]);
166
+ expect(res.outcome).toBe("ok");
167
+ expect(calls).toEqual(["lookup"]);
168
+ });
169
+
170
+ it("installer configured: the installer's orgs win and lookup is not listed", async () => {
171
+ const { resolver, calls } = build({
172
+ installer: ["three"],
173
+ lookupInstallations: ["one", "two"],
174
+ });
175
+ const res = await resolver.resolve("octocat");
176
+ expect(res.orgs.map((o) => o.org)).toEqual(["three"]);
177
+ expect(calls).toEqual(["installer"]);
178
+ });
179
+
180
+ it("no org source at all fails loudly", async () => {
181
+ const { resolver } = build({});
182
+ await expect(resolver.resolve("octocat")).rejects.toThrow(/org source/);
183
+ });
184
+ });
185
+
106
186
  describe("canPushForRole", () => {
107
187
  const cases: Array<[RepoRole, boolean]> = [
108
188
  ["admin", true],