@app-vitals/agent-admin 1.77.0 → 1.79.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,351 @@
1
+ /**
2
+ * admin/src/github-access-backfill.unit.test.ts
3
+ * Ordering, definitive-vs-error, backoff cap, terminal state and rate-limit
4
+ * stop of backfillAccess (GLC-1.3), against in-memory ports.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
9
+ import {
10
+ type AccessBackfillStore,
11
+ type AccessProbe,
12
+ type AccessRow,
13
+ backfillAccess,
14
+ buildWorkList,
15
+ defaultAccessBackoffMs,
16
+ } from "./github-access-backfill.ts";
17
+ import {
18
+ GithubLookupRateLimitError,
19
+ type LookupRateLimit,
20
+ type RepoRole,
21
+ } from "./github-lookup-client.ts";
22
+ import type { AccessInput } from "./github-repo-cache.ts";
23
+
24
+ const T0 = new Date("2026-11-20T12:00:00Z");
25
+ const DAY = 86_400_000;
26
+ const noLimit: LookupRateLimit = {
27
+ remaining: 4000,
28
+ resetAt: null,
29
+ retryAfterSeconds: null,
30
+ };
31
+ const snapshotKey = {
32
+ accountId: "acc",
33
+ appKind: "lookup" as const,
34
+ appRef: "555",
35
+ org: "acme",
36
+ };
37
+
38
+ function makeStore(initial: AccessRow[] = [], user = "octocat") {
39
+ const rows = new Map<
40
+ string,
41
+ AccessRow & { canPush?: boolean; level?: string | null }
42
+ >();
43
+ for (const r of initial) rows.set(`${user}/${r.repo}`, r);
44
+ let snap: { rateLimitResetAt: Date | null } | null = null;
45
+ const writes: AccessInput[] = [];
46
+ const store: AccessBackfillStore = {
47
+ async getAccessRows(q) {
48
+ return q.repos.flatMap((r) => {
49
+ const row = rows.get(`${q.username}/${r}`);
50
+ return row ? [row] : [];
51
+ });
52
+ },
53
+ async upsertAccess(i) {
54
+ writes.push(i);
55
+ rows.set(`${i.username}/${i.repo}`, {
56
+ repo: i.repo,
57
+ status: i.status,
58
+ checkedAt: T0,
59
+ attempts: i.attempts ?? 0,
60
+ nextAttemptAt: i.nextAttemptAt ?? null,
61
+ canPush: i.canPush,
62
+ level: i.level,
63
+ });
64
+ },
65
+ async getSnapshot() {
66
+ return snap;
67
+ },
68
+ async upsertSnapshot(_k, p) {
69
+ snap = { rateLimitResetAt: p?.rateLimitResetAt ?? null };
70
+ return snap;
71
+ },
72
+ };
73
+ return { store, rows, writes, snap: () => snap };
74
+ }
75
+
76
+ function probeOf(
77
+ fn: (repo: string, user: string) => RepoRole | Error,
78
+ calls: string[] = [],
79
+ ): AccessProbe {
80
+ return {
81
+ async getCollaboratorPermissionWithRateLimit(_o, repo, user) {
82
+ calls.push(`${user}/${repo}`);
83
+ const out = fn(repo, user);
84
+ if (out instanceof Error) throw out;
85
+ return { role: out, rateLimit: noLimit };
86
+ },
87
+ };
88
+ }
89
+
90
+ const run = (
91
+ h: ReturnType<typeof makeStore>,
92
+ probe: AccessProbe,
93
+ extra: Partial<Parameters<typeof backfillAccess>[0]> = {},
94
+ now = T0,
95
+ ) =>
96
+ backfillAccess({
97
+ accountId: "acc",
98
+ org: "acme",
99
+ snapshotKey,
100
+ repos: ["a", "b", "c"],
101
+ users: [{ username: "octocat" }],
102
+ probe,
103
+ store: h.store,
104
+ clock: { now: () => now },
105
+ maxAgeMs: DAY,
106
+ ...extra,
107
+ });
108
+
109
+ const row = (repo: string, over: Partial<AccessRow> = {}): AccessRow => ({
110
+ repo,
111
+ status: "ok",
112
+ checkedAt: T0,
113
+ attempts: 0,
114
+ nextAttemptAt: null,
115
+ ...over,
116
+ });
117
+
118
+ describe("buildWorkList ordering", () => {
119
+ it("puts missing before expired, and configured repos first within each", () => {
120
+ const { work, unanswered } = buildWorkList({
121
+ username: "u",
122
+ repos: ["a", "b", "c", "d", "e"],
123
+ configuredRepos: ["e", "b"],
124
+ rows: [
125
+ row("a", { checkedAt: new Date(T0.getTime() - 2 * DAY) }), // expired
126
+ row("b", { checkedAt: new Date(T0.getTime() - 2 * DAY) }), // expired, configured
127
+ row("c"), // fresh
128
+ ],
129
+ now: T0,
130
+ maxAgeMs: DAY,
131
+ });
132
+ expect(work.map((w) => `${w.kind}:${w.repo}`)).toEqual([
133
+ "missing:e",
134
+ "missing:d",
135
+ "expired:b",
136
+ "expired:a",
137
+ ]);
138
+ expect(unanswered).toBe(2);
139
+ });
140
+
141
+ it("skips terminal rows and rows still backing off, but counts backing-off as unanswered", () => {
142
+ const { work, unanswered } = buildWorkList({
143
+ username: "u",
144
+ repos: ["a", "b", "c"],
145
+ configuredRepos: [],
146
+ rows: [
147
+ row("a", { status: "terminal", attempts: 5 }),
148
+ row("b", {
149
+ status: "error",
150
+ attempts: 1,
151
+ nextAttemptAt: new Date(T0.getTime() + 1000),
152
+ }),
153
+ row("c", {
154
+ status: "error",
155
+ attempts: 1,
156
+ nextAttemptAt: new Date(T0.getTime() - 1000),
157
+ }),
158
+ ],
159
+ now: T0,
160
+ maxAgeMs: DAY,
161
+ });
162
+ expect(work.map((w) => w.repo)).toEqual(["c"]);
163
+ expect(unanswered).toBe(2);
164
+ });
165
+ });
166
+
167
+ describe("backfillAccess", () => {
168
+ it("stores a real no-access as ok/none and a 404 the same way", async () => {
169
+ const h = makeStore();
170
+ const out = await run(
171
+ h,
172
+ probeOf((repo) =>
173
+ repo === "a"
174
+ ? "none"
175
+ : repo === "b"
176
+ ? new GithubEnterpriseError("not_found", "nf", { status: 404 })
177
+ : "write",
178
+ ),
179
+ );
180
+ expect(out).toMatchObject({
181
+ outcome: "complete",
182
+ recorded: 3,
183
+ failed: 0,
184
+ missing: 0,
185
+ });
186
+ const by = Object.fromEntries(h.writes.map((w) => [w.repo, w]));
187
+ expect(by.a).toMatchObject({ status: "ok", canPush: false, level: "none" });
188
+ expect(by.b).toMatchObject({ status: "ok", canPush: false, level: "none" });
189
+ expect(by.c).toMatchObject({ status: "ok", canPush: true, level: "write" });
190
+ });
191
+
192
+ it("never writes an access answer for an error; pair stays missing with backoff", async () => {
193
+ const h = makeStore();
194
+ const err = new GithubEnterpriseError("server", "boom", { status: 503 });
195
+ const out = await run(
196
+ h,
197
+ probeOf((r) => (r === "a" ? err : "read")),
198
+ );
199
+ expect(out).toMatchObject({
200
+ outcome: "in_progress",
201
+ recorded: 2,
202
+ failed: 1,
203
+ missing: 1,
204
+ });
205
+ const w = h.writes.find((x) => x.repo === "a");
206
+ expect(w).toMatchObject({
207
+ status: "error",
208
+ canPush: false,
209
+ level: null,
210
+ attempts: 1,
211
+ });
212
+ expect(w?.nextAttemptAt).toEqual(new Date(T0.getTime() + 60_000));
213
+ });
214
+
215
+ it("caps backoff and turns the pair terminal at maxAttempts, which stops blocking completion", async () => {
216
+ expect(defaultAccessBackoffMs(1)).toBe(60_000);
217
+ expect(defaultAccessBackoffMs(2)).toBe(120_000);
218
+ expect(defaultAccessBackoffMs(40)).toBe(3_600_000);
219
+
220
+ const h = makeStore();
221
+ const err = new GithubEnterpriseError("server", "boom", { status: 500 });
222
+ let now = T0;
223
+ const probe = probeOf((r) => (r === "a" ? err : "read"));
224
+ const results = [];
225
+ for (let i = 0; i < 3; i++) {
226
+ results.push(
227
+ await run(h, probe, { maxAttempts: 3, repos: ["a", "b"] }, now),
228
+ );
229
+ now = new Date(now.getTime() + 3_600_001);
230
+ }
231
+ expect(results.map((r) => r.outcome)).toEqual([
232
+ "in_progress",
233
+ "in_progress",
234
+ "complete",
235
+ ]);
236
+ expect(results[2]).toMatchObject({ terminal: 1, missing: 0 });
237
+ expect(h.rows.get("octocat/a")?.status).toBe("terminal");
238
+
239
+ const calls: string[] = [];
240
+ const again = await run(
241
+ h,
242
+ probeOf(() => "read", calls),
243
+ { maxAttempts: 3, repos: ["a", "b"] },
244
+ now,
245
+ );
246
+ expect(calls).toEqual([]);
247
+ expect(again).toMatchObject({ outcome: "complete", probed: 0, missing: 0 });
248
+ });
249
+
250
+ it("does not call for pairs still backing off", async () => {
251
+ const h = makeStore();
252
+ const calls: string[] = [];
253
+ const err = new GithubEnterpriseError("network", "down");
254
+ await run(
255
+ h,
256
+ probeOf(() => err, calls),
257
+ { repos: ["a"] },
258
+ );
259
+ await run(
260
+ h,
261
+ probeOf(() => "read", calls),
262
+ { repos: ["a"] },
263
+ new Date(T0.getTime() + 1000),
264
+ );
265
+ expect(calls).toEqual(["octocat/a"]);
266
+ });
267
+
268
+ it("probes missing before expired, configured first, and shares rows across agents with one user", async () => {
269
+ const h = makeStore([
270
+ row("a", { checkedAt: new Date(T0.getTime() - 2 * DAY) }),
271
+ ]);
272
+ const calls: string[] = [];
273
+ await run(
274
+ h,
275
+ probeOf(() => "read", calls),
276
+ {
277
+ repos: ["a", "b", "c"],
278
+ users: [
279
+ { username: "OctoCat", configuredRepos: ["c"] },
280
+ { username: "octocat", configuredRepos: [] },
281
+ ],
282
+ },
283
+ );
284
+ expect(calls).toEqual(["octocat/c", "octocat/b", "octocat/a"]);
285
+ });
286
+
287
+ it("stops cleanly on a rate limit, writes no row for it, and resumes without redoing finished pairs", async () => {
288
+ const h = makeStore();
289
+ const reset = new Date(T0.getTime() + 600_000);
290
+ const limited = new GithubLookupRateLimitError(
291
+ new GithubEnterpriseError("rate_limit", "slow down", { status: 429 }),
292
+ reset,
293
+ );
294
+ const first = await run(
295
+ h,
296
+ probeOf((r) => (r === "b" ? limited : "read")),
297
+ );
298
+ expect(first).toMatchObject({
299
+ outcome: "rate_limited",
300
+ recorded: 1,
301
+ failed: 0,
302
+ rateLimitResetAt: reset,
303
+ });
304
+ expect(h.rows.has("octocat/b")).toBe(false);
305
+ expect(h.snap()?.rateLimitResetAt).toEqual(reset);
306
+
307
+ const calls: string[] = [];
308
+ const early = await run(
309
+ h,
310
+ probeOf(() => "read", calls),
311
+ {},
312
+ new Date(T0.getTime() + 1000),
313
+ );
314
+ expect(early).toMatchObject({
315
+ outcome: "rate_limited",
316
+ probed: 0,
317
+ missing: 2,
318
+ });
319
+ expect(calls).toEqual([]);
320
+
321
+ const later = await run(
322
+ h,
323
+ probeOf(() => "read", calls),
324
+ {},
325
+ new Date(reset.getTime() + 1),
326
+ );
327
+ expect(calls).toEqual(["octocat/b", "octocat/c"]);
328
+ expect(later).toMatchObject({ outcome: "complete", recorded: 2 });
329
+ });
330
+
331
+ it("stops after an answer when X-RateLimit-Remaining is low", async () => {
332
+ const h = makeStore();
333
+ const resetAt = new Date(T0.getTime() + 300_000);
334
+ const probe: AccessProbe = {
335
+ async getCollaboratorPermissionWithRateLimit() {
336
+ return {
337
+ role: "read",
338
+ rateLimit: { remaining: 3, resetAt, retryAfterSeconds: null },
339
+ };
340
+ },
341
+ };
342
+ const out = await run(h, probe);
343
+ expect(out).toMatchObject({
344
+ outcome: "rate_limited",
345
+ probed: 1,
346
+ recorded: 1,
347
+ missing: 2,
348
+ rateLimitResetAt: resetAt,
349
+ });
350
+ });
351
+ });
@@ -0,0 +1,262 @@
1
+ /**
2
+ * admin/src/github-agent-installation-crawler.integration.test.ts
3
+ * The agent-installation crawl end to end through the installer client that
4
+ * backs the installation port (lazyInstallerClient -> GithubEnterpriseClient),
5
+ * replaying hand-authored cassettes (fixtures/github-agent-installation-cassette.json;
6
+ * nothing recorded live) through an INJECTED fetchFn (no global fetch
7
+ * override, no mock.module()). The repo list pages are generated here; the
8
+ * cassette carries routes, headers and status codes. Persistence is an
9
+ * in-memory CrawlStore (no database needed).
10
+ */
11
+
12
+ import { describe, expect, it } from "bun:test";
13
+ import { generateKeyPairSync } from "node:crypto";
14
+ import { readFileSync } from "node:fs";
15
+ import {
16
+ crawlAgentInstallation,
17
+ } from "./github-agent-installation-crawler.ts";
18
+ import { lazyInstallerClient } from "./github-installation-wiring.ts";
19
+ import type {
20
+ CachedRepoInput,
21
+ SnapshotKey,
22
+ SnapshotProgress,
23
+ } from "./github-repo-cache.ts";
24
+ import type { CrawlSnapshot, CrawlStore } from "./github-repo-crawler.ts";
25
+
26
+ interface CassetteEntry {
27
+ status: number;
28
+ headers?: Record<string, string>;
29
+ body: unknown;
30
+ }
31
+
32
+ const cassette: Record<string, CassetteEntry> = JSON.parse(
33
+ readFileSync(
34
+ new URL("./fixtures/github-agent-installation-cassette.json", import.meta.url)
35
+ .pathname,
36
+ "utf-8",
37
+ ),
38
+ );
39
+
40
+ const { privateKey } = generateKeyPairSync("rsa", {
41
+ modulusLength: 2048,
42
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
43
+ publicKeyEncoding: { type: "spki", format: "pem" },
44
+ });
45
+
46
+ const NOW = new Date("2026-11-20T12:00:00Z");
47
+ const clock = { now: () => new Date(NOW) };
48
+ const ENT = "/enterprises/acme-ent";
49
+ const REPOS_501 = `${ENT}/apps/organizations/acme-eng/installations/501/repositories`;
50
+
51
+ class MemoryStore implements CrawlStore {
52
+ snap: CrawlSnapshot | null = null;
53
+ key: SnapshotKey | null = null;
54
+ rows = new Map<number, { fullName: string; seenAt: Date }>();
55
+ async getSnapshot(_k: SnapshotKey) {
56
+ return this.snap ? { ...this.snap } : null;
57
+ }
58
+ async upsertSnapshot(k: SnapshotKey, p: SnapshotProgress = {}) {
59
+ this.key = k;
60
+ const next = {
61
+ ...(this.snap ?? {
62
+ id: "s1",
63
+ crawlPage: 0,
64
+ crawlStartedAt: null,
65
+ completedAt: null,
66
+ totalCount: null,
67
+ lastError: null,
68
+ attempts: 0,
69
+ nextAttemptAt: null,
70
+ rateLimitResetAt: null,
71
+ lastTickAt: null,
72
+ }),
73
+ } as Record<string, unknown>;
74
+ for (const [f, v] of Object.entries(p)) if (v !== undefined) next[f] = v;
75
+ this.snap = next as unknown as CrawlSnapshot;
76
+ return { ...this.snap };
77
+ }
78
+ async upsertRepos(_id: string, repos: CachedRepoInput[], seenAt: Date) {
79
+ for (const r of repos) {
80
+ this.rows.set(Number(r.githubId), { fullName: r.fullName, seenAt });
81
+ }
82
+ return repos.length;
83
+ }
84
+ async countReposSeenSince(_id: string, since: Date) {
85
+ return [...this.rows.values()].filter((r) => r.seenAt >= since).length;
86
+ }
87
+ async sweepGeneration(_id: string) {
88
+ const since = this.snap?.crawlStartedAt;
89
+ let n = 0;
90
+ for (const [id, r] of this.rows) {
91
+ if (since && r.seenAt < since) {
92
+ this.rows.delete(id);
93
+ n++;
94
+ }
95
+ }
96
+ return n;
97
+ }
98
+ }
99
+
100
+ /** `total` repos served in full pages of 100 with GitHub-style Link headers. */
101
+ function repoPage(total: number, page: number): CassetteEntry {
102
+ const start = (page - 1) * 100;
103
+ const n = Math.max(0, Math.min(100, total - start));
104
+ const hasNext = start + 100 < total;
105
+ return {
106
+ status: 200,
107
+ ...(hasNext
108
+ ? { headers: { link: `<https://ghe.test/x?page=${page + 1}>; rel="next"` } }
109
+ : {}),
110
+ body: Array.from({ length: n }, (_, i) => ({
111
+ id: start + i + 1,
112
+ name: `r${start + i + 1}`,
113
+ full_name: `acme-eng/r${start + i + 1}`,
114
+ archived: (start + i + 1) % 50 === 0,
115
+ })),
116
+ };
117
+ }
118
+
119
+ function setup(opts: {
120
+ installs: string;
121
+ total?: number;
122
+ repoOverride?: (page: number) => CassetteEntry | undefined;
123
+ }) {
124
+ const paths: string[] = [];
125
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
126
+ const u = new URL(input.toString());
127
+ const method = init?.method ?? "GET";
128
+ paths.push(`${method} ${u.pathname}${u.search}`);
129
+ let entry: CassetteEntry | undefined;
130
+ if (u.pathname === `${ENT}/installation`) entry = cassette.enterprise_installation;
131
+ else if (u.pathname === "/app/installations/4242/access_tokens") entry = cassette.installer_token;
132
+ else if (u.pathname === `${ENT}/apps/organizations/acme-eng/installations` || u.pathname === `${ENT}/apps/organizations/beta-eng/installations`)
133
+ entry = cassette[opts.installs];
134
+ else if (u.pathname === REPOS_501) {
135
+ const page = Number(u.searchParams.get("page"));
136
+ entry = opts.repoOverride?.(page) ?? repoPage(opts.total ?? 0, page);
137
+ }
138
+ if (!entry) throw new Error(`no route for ${method} ${u.pathname}`);
139
+ return new Response(JSON.stringify(entry.body), {
140
+ status: entry.status,
141
+ headers: { "Content-Type": "application/json", ...(entry.headers ?? {}) },
142
+ });
143
+ }) as typeof fetch;
144
+ const client = lazyInstallerClient({
145
+ appService: {
146
+ get: async () =>
147
+ ({ appId: "12345", enterpriseSlug: "acme-ent" }) as never,
148
+ getPrivateKey: async () => privateKey,
149
+ },
150
+ fetchFn,
151
+ apiBase: "https://ghe.test",
152
+ now: () => NOW,
153
+ });
154
+ return { client, paths, store: new MemoryStore() };
155
+ }
156
+
157
+ const agent = {
158
+ accountId: "acc",
159
+ appId: 777,
160
+ clientId: "Iv1.agentapp0001",
161
+ slug: "doc-agent",
162
+ };
163
+
164
+ describe("crawlAgentInstallation through the installer client (integration)", () => {
165
+ it("crawls a multi-page installation to a complete snapshot", async () => {
166
+ const { client, store, paths } = setup({
167
+ installs: "org_installations_agent",
168
+ total: 230,
169
+ });
170
+ const res = await crawlAgentInstallation({
171
+ agent,
172
+ org: "acme-eng",
173
+ client,
174
+ store,
175
+ clock,
176
+ });
177
+ expect(res).toMatchObject({ outcome: "complete", pagesFetched: 3 });
178
+ expect(store.rows.size).toBe(230);
179
+ expect(store.snap).toMatchObject({ totalCount: 230, lastError: null });
180
+ expect(store.snap?.completedAt).toEqual(NOW);
181
+ expect(store.key).toEqual({
182
+ accountId: "acc",
183
+ appKind: "agent",
184
+ appRef: "777",
185
+ org: "acme-eng",
186
+ });
187
+ expect(paths.filter((p) => p.includes("/repositories"))).toEqual([
188
+ `GET ${REPOS_501}?per_page=100&page=1`,
189
+ `GET ${REPOS_501}?per_page=100&page=2`,
190
+ `GET ${REPOS_501}?per_page=100&page=3`,
191
+ ]);
192
+ });
193
+
194
+ it("handles an exact multiple of the page size (last page full, no next)", async () => {
195
+ const { client, store } = setup({
196
+ installs: "org_installations_agent",
197
+ total: 200,
198
+ });
199
+ const res = await crawlAgentInstallation({
200
+ agent,
201
+ org: "acme-eng",
202
+ client,
203
+ store,
204
+ clock,
205
+ });
206
+ expect(res.outcome).toBe("complete");
207
+ expect(store.rows.size).toBe(200);
208
+ });
209
+
210
+ it("records an org without the agent App as not installed, sweeping stale rows", async () => {
211
+ const { client, store, paths } = setup({
212
+ installs: "org_installations_no_agent",
213
+ });
214
+ store.rows.set(1, { fullName: "beta-eng/old", seenAt: new Date(0) });
215
+ const res = await crawlAgentInstallation({
216
+ agent,
217
+ org: "beta-eng",
218
+ client,
219
+ store,
220
+ clock,
221
+ });
222
+ expect(res).toEqual({ outcome: "not_installed", pagesFetched: 0, swept: 1 });
223
+ expect(store.snap?.lastError).toBeNull();
224
+ expect(store.snap?.completedAt).toEqual(NOW);
225
+ expect(paths.some((p) => p.includes("/repositories"))).toBe(false);
226
+ });
227
+
228
+ it("never crawls an agent without GH_APP_ID", async () => {
229
+ const { client, store, paths } = setup({ installs: "org_installations_agent" });
230
+ const res = await crawlAgentInstallation({
231
+ agent: { accountId: "acc" },
232
+ org: "acme-eng",
233
+ client,
234
+ store,
235
+ clock,
236
+ });
237
+ expect(res.outcome).toBe("skipped_no_app_id");
238
+ expect(paths).toEqual([]);
239
+ expect(store.snap).toBeNull();
240
+ });
241
+
242
+ it("ends the run on a 429 with the retry-after reset recorded", async () => {
243
+ const { client, store } = setup({
244
+ installs: "org_installations_agent",
245
+ total: 230,
246
+ repoOverride: (page) =>
247
+ page === 2 ? cassette.repos_rate_limited : undefined,
248
+ });
249
+ const res = await crawlAgentInstallation({
250
+ agent,
251
+ org: "acme-eng",
252
+ client,
253
+ store,
254
+ clock,
255
+ });
256
+ expect(res.outcome).toBe("rate_limited");
257
+ expect(res.pagesFetched).toBe(1);
258
+ expect(store.snap?.rateLimitResetAt).toEqual(new Date(NOW.getTime() + 30_000));
259
+ expect(store.snap?.attempts).toBe(0);
260
+ expect(store.snap?.completedAt).toBeNull();
261
+ });
262
+ });