@app-vitals/agent-admin 1.80.0 → 1.82.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 (30) hide show
  1. package/openapi.platform.json +48 -2
  2. package/package.json +2 -2
  3. package/src/admin-boot.boot-order.unit.test.ts +11 -0
  4. package/src/admin-boot.ts +42 -2
  5. package/src/admin-ui-installation-repos-pages.ts +89 -25
  6. package/src/admin-ui-installation-repos.smoke.test.ts +71 -0
  7. package/src/admin-ui-pages.ts +13 -1
  8. package/src/admin-ui.ts +16 -4
  9. package/src/agents-api.smoke.test.ts +85 -5
  10. package/src/agents-api.ts +32 -3
  11. package/src/github-access-backfill.ts +9 -1
  12. package/src/github-access-backfill.unit.test.ts +16 -0
  13. package/src/github-agent-installation-crawler.ts +4 -1
  14. package/src/github-agent-installation-crawler.unit.test.ts +14 -0
  15. package/src/github-enterprise-apps.integration.test.ts +11 -0
  16. package/src/github-enterprise-apps.ts +10 -0
  17. package/src/github-installation-wiring.ts +86 -4
  18. package/src/github-installation-wiring.unit.test.ts +8 -4
  19. package/src/github-installation.fixtures.ts +12 -1
  20. package/src/github-repo-cache.integration.test.ts +14 -0
  21. package/src/github-repo-cache.ts +30 -0
  22. package/src/github-repo-crawler.ts +6 -0
  23. package/src/github-repo-crawler.unit.test.ts +36 -0
  24. package/src/github-repo-refresh-discovery.ts +241 -0
  25. package/src/github-repo-refresh-discovery.unit.test.ts +237 -0
  26. package/src/github-repo-refresher.integration.test.ts +179 -0
  27. package/src/github-repo-refresher.ts +640 -0
  28. package/src/github-repo-refresher.unit.test.ts +735 -0
  29. package/src/installation-repos-service.ts +174 -50
  30. package/src/installation-repos-service.unit.test.ts +157 -52
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * admin/src/installation-repos-service.ts
3
3
  * Read-only listing of the repos on an agent's own GitHub App installation
4
- * (IRM-1.2), with the bound user's push hint. Changes go through the Sync flow
5
- * (github-sync.ts, IRM-3.1). Uses the installer App through the installation port.
4
+ * (IRM-1.2), with the bound user's push hint. list() reads only the repo/access
5
+ * cache (GLC-2.2): no GitHub call, sync detail alongside. Changes go through
6
+ * the Sync flow (github-sync.ts, IRM-3.1), which still uses the installer App
7
+ * through the installation port.
6
8
  */
7
9
 
8
10
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
11
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
9
12
  import {
10
- AppNotInstalledError,
11
- MISSING_APP_ID_REASON,
12
13
  type AppIdentity,
13
- type InstallationAgentsPort,
14
14
  type AppInstallationPort,
15
+ AppNotInstalledError,
16
+ type InstallationAgentsPort,
17
+ MISSING_APP_ID_REASON,
15
18
  } from "./installation-ports.ts";
16
19
  import type {
17
20
  OrgAccessResult,
@@ -43,21 +46,74 @@ export interface InstallationRepoView {
43
46
  userCanPush?: boolean;
44
47
  }
45
48
 
46
- export interface InstallationOrgView {
49
+ /** Sync detail for one org's cached snapshot (all optional, additive). */
50
+ export interface InstallationSyncDetail {
51
+ /** True once the org's crawl completed. */
52
+ complete?: boolean;
53
+ /** ISO time of the completed crawl; absent until one completed. */
54
+ syncedAt?: string;
55
+ /** Repos in the cache for the org. */
56
+ reposSeen?: number;
57
+ /** GitHub's repo count for the org, when known ("N of M"). */
58
+ totalCount?: number;
59
+ lastError?: string;
60
+ /** ISO time the GitHub rate limit resets, while limited. */
61
+ rateLimitResetAt?: string;
62
+ }
63
+
64
+ export interface InstallationOrgView extends InstallationSyncDetail {
47
65
  org: string;
48
66
  repos: InstallationRepoView[];
49
67
  }
50
68
 
69
+ /** One cached agent-App snapshot with its repos (GitHubRepoCacheService.listAgentSnapshots). */
70
+ export interface InstallationSnapshotRow {
71
+ org: string;
72
+ completedAt: Date | null;
73
+ totalCount: number | null;
74
+ lastError: string | null;
75
+ rateLimitResetAt: Date | null;
76
+ repos: { fullName: string }[];
77
+ }
78
+
79
+ /** A cached per-user access row (repo is the name without the org). */
80
+ export interface CachedAccessRow {
81
+ repo: string;
82
+ status: string;
83
+ canPush: boolean;
84
+ }
85
+
86
+ /** The slice of GitHubRepoCacheService the list reads; never calls GitHub. */
87
+ export interface InstallationCachePort {
88
+ listAgentSnapshots(
89
+ accountId: string,
90
+ appRef: string,
91
+ ): Promise<InstallationSnapshotRow[]>;
92
+ getAccessRows(query: {
93
+ accountId: string;
94
+ org: string;
95
+ username: string;
96
+ repos: string[];
97
+ }): Promise<CachedAccessRow[]>;
98
+ }
99
+
51
100
  export type InstallationListResult =
52
101
  | { status: "agent_not_found" }
53
102
  | { status: "no_app_id"; reason: string }
54
103
  | { status: "skipped"; appId: number; reason: string }
55
- | { status: "ok"; appId: number; orgs: InstallationOrgView[] };
104
+ | ({
105
+ status: "ok";
106
+ appId: number;
107
+ orgs: InstallationOrgView[];
108
+ } & InstallationSyncDetail);
56
109
 
57
110
  export interface InstallationReposDeps {
58
111
  agents: Pick<InstallationAgentsPort, "get">;
112
+ /** Used by GitHub Sync, not by list(), which reads only the cache. */
59
113
  access: GithubAccessPreviewFn;
60
114
  installation: InstallationReposPort;
115
+ /** The repo/access cache list() reads. Without it list() reports nothing synced. */
116
+ cache?: InstallationCachePort;
61
117
  }
62
118
 
63
119
  /** The agent's App identity keys (client id, slug), when stored. */
@@ -75,31 +131,52 @@ export function identityOf(agent: {
75
131
 
76
132
  const orgKey = (org: string): string => org.toLowerCase();
77
133
 
134
+ /** Cached access rows for one org and user, as read from the access cache. */
135
+ export interface CachedAccessRows {
136
+ cachedRows: readonly CachedAccessRow[];
137
+ }
138
+
78
139
  /**
79
140
  * The user-can-push hint for one org: true/false per repo only when the bound
80
- * user is verified and this org's lookup result is complete ("ok", nothing
81
- * unresolved). A repo the lookup did not list is unknown, so it gets no hint
82
- * (never false).
141
+ * user is verified and this org's access data is complete (a live "ok" lookup
142
+ * with nothing unresolved, or cached rows with an "ok" row for every listed
143
+ * repo). Anything else is unknown, so it gets no hint (never false).
83
144
  */
84
145
  export function userPushHints(
85
- access: UserRepoAccessResult | undefined,
146
+ access: UserRepoAccessResult | CachedAccessRows | undefined,
86
147
  org: string,
87
148
  repos: readonly string[],
88
149
  ): InstallationRepoView[] {
89
- const orgResult: OrgAccessResult | undefined = access?.orgs.find(
90
- (o) => orgKey(o.org) === orgKey(org),
91
- );
92
- const complete =
93
- access !== undefined &&
94
- access.outcome === "ok" &&
95
- access.userVerified &&
96
- orgResult !== undefined &&
97
- orgResult.status === "ok" &&
98
- orgResult.unresolved === 0;
99
150
  const pushByName = new Map<string, boolean>();
100
- if (complete) {
101
- for (const r of orgResult.repos) {
102
- pushByName.set(r.fullName.toLowerCase(), r.canPush);
151
+ if (access && "cachedRows" in access) {
152
+ const byRepo = new Map<string, CachedAccessRow>();
153
+ for (const r of access.cachedRows) byRepo.set(r.repo.toLowerCase(), r);
154
+ const nameOf = (fullName: string) =>
155
+ fullName.slice(fullName.indexOf("/") + 1).toLowerCase();
156
+ const complete = repos.every((f) => byRepo.get(nameOf(f))?.status === "ok");
157
+ if (complete) {
158
+ for (const f of repos) {
159
+ pushByName.set(
160
+ f.toLowerCase(),
161
+ byRepo.get(nameOf(f))?.canPush ?? false,
162
+ );
163
+ }
164
+ }
165
+ } else {
166
+ const orgResult: OrgAccessResult | undefined = access?.orgs.find(
167
+ (o) => orgKey(o.org) === orgKey(org),
168
+ );
169
+ const complete =
170
+ access !== undefined &&
171
+ access.outcome === "ok" &&
172
+ access.userVerified &&
173
+ orgResult !== undefined &&
174
+ orgResult.status === "ok" &&
175
+ orgResult.unresolved === 0;
176
+ if (complete) {
177
+ for (const r of orgResult.repos) {
178
+ pushByName.set(r.fullName.toLowerCase(), r.canPush);
179
+ }
103
180
  }
104
181
  }
105
182
  return repos.map((fullName) => {
@@ -108,44 +185,91 @@ export function userPushHints(
108
185
  });
109
186
  }
110
187
 
188
+ const iso = (d: Date | null): string | undefined =>
189
+ d ? d.toISOString() : undefined;
190
+
191
+ /** Folds per-org sync detail into the page-level detail. */
192
+ function summarize(
193
+ orgs: readonly InstallationOrgView[],
194
+ ): InstallationSyncDetail {
195
+ const complete = orgs.length > 0 && orgs.every((o) => o.complete === true);
196
+ const synced = orgs
197
+ .map((o) => o.syncedAt)
198
+ .filter((d): d is string => d !== undefined)
199
+ .sort();
200
+ const totals = orgs.map((o) => o.totalCount);
201
+ const totalCount = totals.every((t) => t !== undefined)
202
+ ? totals.reduce<number>((a, t) => a + (t ?? 0), 0)
203
+ : undefined;
204
+ const lastError = orgs.find((o) => o.lastError)?.lastError;
205
+ const reset = orgs
206
+ .map((o) => o.rateLimitResetAt)
207
+ .filter((d): d is string => d !== undefined)
208
+ .sort()
209
+ .at(-1);
210
+ return {
211
+ complete,
212
+ reposSeen: orgs.reduce((a, o) => a + (o.reposSeen ?? 0), 0),
213
+ ...(complete && synced[0] ? { syncedAt: synced[0] } : {}),
214
+ ...(orgs.length > 0 && totalCount !== undefined ? { totalCount } : {}),
215
+ ...(lastError ? { lastError } : {}),
216
+ ...(reset ? { rateLimitResetAt: reset } : {}),
217
+ };
218
+ }
219
+
111
220
  export class InstallationReposService {
112
221
  constructor(private readonly deps: InstallationReposDeps) {}
113
222
 
223
+ /**
224
+ * Reads the agent-installation cache (crawled in the background) and the
225
+ * cached access rows; it never calls GitHub. A hint appears only when the
226
+ * org's snapshot is complete and every repo has an ok access row.
227
+ */
114
228
  async list(agentId: string): Promise<InstallationListResult> {
115
229
  const agent = await this.deps.agents.get(agentId);
116
230
  if (!agent) return { status: "agent_not_found" };
117
231
  if (agent.appId === undefined) {
118
232
  return { status: "no_app_id", reason: MISSING_APP_ID_REASON };
119
233
  }
120
- const installed = await this.deps.installation.listInstalled(
121
- agent.appId,
122
- identityOf(agent),
123
- );
124
- if (installed.status === "none") {
125
- return {
126
- status: "skipped",
127
- appId: agent.appId,
128
- reason: NO_INSTALLATION_REASON,
129
- };
130
- }
234
+ const cache = this.deps.cache;
235
+ const accountId = agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY;
236
+ const snapshots = cache
237
+ ? await cache.listAgentSnapshots(accountId, String(agent.appId))
238
+ : [];
131
239
  const username = agent.githubUsername?.trim();
132
- let access: UserRepoAccessResult | undefined;
133
- if (username) {
134
- try {
135
- const preview = await this.deps.access(username, agent.accountId);
136
- if (preview.status === "ok") access = preview.access;
137
- } catch {
138
- // The hint is advisory: a failed lookup omits it.
240
+ const orgs: InstallationOrgView[] = [];
241
+ for (const s of snapshots) {
242
+ const names = s.repos.map((r) => r.fullName);
243
+ let repos: InstallationRepoView[] = names.map((fullName) => ({
244
+ fullName,
245
+ }));
246
+ if (cache && username && s.completedAt && names.length > 0) {
247
+ try {
248
+ const rows = await cache.getAccessRows({
249
+ accountId,
250
+ org: s.org,
251
+ username,
252
+ repos: names.map((f) => f.slice(f.indexOf("/") + 1)),
253
+ });
254
+ repos = userPushHints({ cachedRows: rows }, s.org, names);
255
+ } catch {
256
+ // The hint is advisory: a failed cache read omits it.
257
+ }
139
258
  }
259
+ orgs.push({
260
+ org: s.org,
261
+ repos,
262
+ complete: s.completedAt !== null,
263
+ reposSeen: names.length,
264
+ ...(s.completedAt ? { syncedAt: iso(s.completedAt) } : {}),
265
+ ...(s.totalCount !== null ? { totalCount: s.totalCount } : {}),
266
+ ...(s.lastError ? { lastError: s.lastError } : {}),
267
+ ...(s.rateLimitResetAt
268
+ ? { rateLimitResetAt: iso(s.rateLimitResetAt) }
269
+ : {}),
270
+ });
140
271
  }
141
- return {
142
- status: "ok",
143
- appId: agent.appId,
144
- orgs: installed.orgs.map(({ org, repos }) => ({
145
- org,
146
- repos: userPushHints(access, org, repos),
147
- })),
148
- };
272
+ return { status: "ok", appId: agent.appId, orgs, ...summarize(orgs) };
149
273
  }
150
274
  }
151
275
 
@@ -6,9 +6,10 @@
6
6
 
7
7
  import { describe, expect, it } from "bun:test";
8
8
  import {
9
+ type CachedAccessRow,
10
+ type InstallationCachePort,
9
11
  InstallationReposService,
10
- NO_INSTALLATION_REASON,
11
- type InstallationReposPort,
12
+ type InstallationSnapshotRow,
12
13
  userPushHints,
13
14
  } from "./installation-repos-service.ts";
14
15
  import type {
@@ -101,93 +102,197 @@ function noHint(r: { userCanPush?: boolean }): boolean {
101
102
  return r.userCanPush === undefined;
102
103
  }
103
104
 
105
+ const row = (
106
+ repo: string,
107
+ status: string,
108
+ canPush = false,
109
+ ): CachedAccessRow => ({ repo, status, canPush });
110
+
111
+ describe("userPushHints from cached access rows", () => {
112
+ const repos = ["acme/push", "acme/readonly"];
113
+
114
+ it("reports true/false per repo when every repo has an ok row", () => {
115
+ const out = userPushHints(
116
+ { cachedRows: [row("push", "ok", true), row("ReadOnly", "ok", false)] },
117
+ "acme",
118
+ repos,
119
+ );
120
+ expect(out).toEqual([
121
+ { fullName: "acme/push", userCanPush: true },
122
+ { fullName: "acme/readonly", userCanPush: false },
123
+ ]);
124
+ });
125
+
126
+ it("omits every hint when any pair is missing, errored or terminal (never false)", () => {
127
+ for (const second of [
128
+ undefined,
129
+ row("readonly", "error", false),
130
+ row("readonly", "terminal", false),
131
+ ]) {
132
+ const rows = [row("push", "ok", true), ...(second ? [second] : [])];
133
+ expect(
134
+ userPushHints({ cachedRows: rows }, "acme", repos).every(noHint),
135
+ ).toBe(true);
136
+ }
137
+ });
138
+
139
+ it("omits hints with no rows at all", () => {
140
+ expect(userPushHints({ cachedRows: [] }, "acme", repos).every(noHint)).toBe(
141
+ true,
142
+ );
143
+ });
144
+ });
145
+
146
+ const T0 = new Date("2026-11-20T10:00:00Z");
147
+ const snap = (
148
+ over: Partial<InstallationSnapshotRow> = {},
149
+ ): InstallationSnapshotRow => ({
150
+ org: "acme",
151
+ completedAt: T0,
152
+ totalCount: 2,
153
+ lastError: null,
154
+ rateLimitResetAt: null,
155
+ repos: [{ fullName: "acme/push" }, { fullName: "acme/readonly" }],
156
+ ...over,
157
+ });
158
+
104
159
  function build(
105
160
  opts: {
106
161
  agent?: { githubUsername: string | null; appId?: number } | null;
107
- noInstallation?: boolean;
108
- access?: () => Promise<
109
- | { status: "unconfigured" }
110
- | { status: "ok"; access: UserRepoAccessResult }
111
- >;
162
+ snapshots?: InstallationSnapshotRow[];
163
+ rows?: CachedAccessRow[];
112
164
  } = {},
113
165
  ) {
114
- const installation: InstallationReposPort = {
115
- listInstalled: async () =>
116
- opts.noInstallation
117
- ? { status: "none" }
118
- : {
119
- status: "found",
120
- orgs: [{ org: "acme", repos: ["acme/push", "acme/unlisted"] }],
121
- },
122
- listRepos: async () => ({}),
123
- addRepos: async () => {},
124
- removeRepos: async () => {},
166
+ const calls: string[] = [];
167
+ const cache: InstallationCachePort = {
168
+ listAgentSnapshots: async (accountId, appRef) => {
169
+ calls.push(`snapshots:${accountId}:${appRef}`);
170
+ return opts.snapshots ?? [snap()];
171
+ },
172
+ getAccessRows: async (q) => {
173
+ calls.push(`rows:${q.accountId}:${q.org}:${q.username}`);
174
+ return opts.rows ?? [row("push", "ok", true), row("readonly", "ok")];
175
+ },
125
176
  };
126
177
  const agent =
127
178
  opts.agent === undefined
128
179
  ? { id: "a1", repos: [], githubUsername: "dev", appId: 42 }
129
180
  : opts.agent && { id: "a1", repos: [], ...opts.agent };
181
+ const boom = () => {
182
+ throw new Error("GitHub must not be called");
183
+ };
130
184
  const svc = new InstallationReposService({
131
185
  agents: { get: async () => agent },
132
- access:
133
- opts.access ??
134
- (async () => ({ status: "ok", access: accessOf([orgResult()]) })),
135
- installation,
186
+ access: boom,
187
+ installation: {
188
+ listInstalled: boom,
189
+ listRepos: boom,
190
+ addRepos: boom,
191
+ removeRepos: boom,
192
+ },
193
+ cache,
136
194
  });
137
- return { svc };
195
+ return { svc, calls };
138
196
  }
139
197
 
140
- describe("InstallationReposService.list", () => {
141
- it("returns repos per org with hints for a bound user", async () => {
142
- const { svc } = build();
143
- expect(await svc.list("a1")).toEqual({
198
+ describe("InstallationReposService.list (cache read)", () => {
199
+ it("returns cached repos with hints and sync detail for a complete snapshot", async () => {
200
+ const { svc, calls } = build();
201
+ const r = await svc.list("a1");
202
+ expect(r).toMatchObject({
144
203
  status: "ok",
145
204
  appId: 42,
205
+ complete: true,
206
+ syncedAt: T0.toISOString(),
207
+ reposSeen: 2,
208
+ totalCount: 2,
146
209
  orgs: [
147
210
  {
148
211
  org: "acme",
212
+ complete: true,
213
+ syncedAt: T0.toISOString(),
214
+ reposSeen: 2,
215
+ totalCount: 2,
149
216
  repos: [
150
217
  { fullName: "acme/push", userCanPush: true },
151
- { fullName: "acme/unlisted" },
218
+ { fullName: "acme/readonly", userCanPush: false },
152
219
  ],
153
220
  },
154
221
  ],
155
222
  });
223
+ expect(calls[0]).toBe("snapshots:deployment:42");
156
224
  });
157
225
 
158
- it("omits hints for an unbound agent without calling access", async () => {
159
- let called = false;
160
- const { svc } = build({
226
+ it("omits hints when an access pair is errored or missing", async () => {
227
+ const r = await build({
228
+ rows: [row("push", "ok", true), row("readonly", "error")],
229
+ }).svc.list("a1");
230
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
231
+ });
232
+
233
+ it("omits hints and skips the access read for an unbound agent", async () => {
234
+ const { svc, calls } = build({
161
235
  agent: { githubUsername: null, appId: 42 },
162
- access: async () => {
163
- called = true;
164
- return { status: "unconfigured" };
165
- },
166
236
  });
167
237
  const r = await svc.list("a1");
168
- expect(called).toBe(false);
238
+ expect(calls.some((c) => c.startsWith("rows:"))).toBe(false);
169
239
  expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
170
240
  });
171
241
 
172
- it("omits hints when access is unconfigured or the lookup throws", async () => {
173
- for (const access of [
174
- async () => ({ status: "unconfigured" as const }),
175
- async () => {
176
- throw new Error("502");
177
- },
178
- ]) {
179
- const r = await build({ access }).svc.list("a1");
180
- expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
181
- }
242
+ it("an incomplete snapshot is not complete and carries error and rate-limit detail", async () => {
243
+ const reset = new Date("2026-11-20T11:00:00Z");
244
+ const r = await build({
245
+ snapshots: [
246
+ snap({
247
+ completedAt: null,
248
+ totalCount: 5,
249
+ lastError: "boom",
250
+ rateLimitResetAt: reset,
251
+ repos: [{ fullName: "acme/push" }],
252
+ }),
253
+ ],
254
+ }).svc.list("a1");
255
+ expect(r).toMatchObject({
256
+ status: "ok",
257
+ complete: false,
258
+ reposSeen: 1,
259
+ totalCount: 5,
260
+ lastError: "boom",
261
+ rateLimitResetAt: reset.toISOString(),
262
+ });
263
+ expect(r.status === "ok" && r.syncedAt).toBeUndefined();
264
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
182
265
  });
183
266
 
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,
267
+ it("no snapshots yet: ok, empty, not complete", async () => {
268
+ const r = await build({ snapshots: [] }).svc.list("a1");
269
+ expect(r).toMatchObject({ status: "ok", orgs: [], complete: false });
270
+ });
271
+
272
+ it("uses the agent's account for the cache scope", async () => {
273
+ const calls: string[] = [];
274
+ const svc = new InstallationReposService({
275
+ agents: {
276
+ get: async () => ({
277
+ id: "a1",
278
+ repos: [],
279
+ githubUsername: null,
280
+ appId: 7,
281
+ accountId: "acct-1",
282
+ }),
283
+ },
284
+ access: async () => ({ status: "unconfigured" }),
285
+ installation: {} as never,
286
+ cache: {
287
+ listAgentSnapshots: async (a, r) => {
288
+ calls.push(`${a}:${r}`);
289
+ return [];
290
+ },
291
+ getAccessRows: async () => [],
292
+ },
190
293
  });
294
+ await svc.list("a1");
295
+ expect(calls).toEqual(["acct-1:7"]);
191
296
  });
192
297
 
193
298
  it("reports unknown agent and a missing GH_APP_ID distinctly", async () => {