@app-vitals/agent-admin 1.78.0 → 1.80.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.78.0",
3
+ "version": "1.80.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@anthropic-ai/sdk": "0.137.0",
46
- "@app-vitals/agent-lib": "1.78.0",
46
+ "@app-vitals/agent-lib": "1.80.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -115,6 +115,7 @@ import {
115
115
  createGithubSync,
116
116
  } from "./github-installation-wiring.ts";
117
117
 
118
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
118
119
  import { PrincipalLookupService } from "./principal-lookup.ts";
119
120
  import { createPrincipalsApp } from "./principals-api.ts";
120
121
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
@@ -422,6 +423,7 @@ export async function startAdmin(
422
423
  provisioner,
423
424
  githubLookup: createGithubLookupService({
424
425
  appService: githubEnterpriseAppService,
426
+ cache: new GitHubRepoCacheService(prisma),
425
427
  }),
426
428
  },
427
429
  };
@@ -0,0 +1,208 @@
1
+ /**
2
+ * admin/src/github-access-backfill.integration.test.ts
3
+ * backfillAccess end to end: GithubLookupClient replaying recorded cassettes
4
+ * (fixtures/github-lookup-cassette.json) through an INJECTED fetchFn, persisting
5
+ * through GitHubRepoCacheService into a real PostgreSQL DB. Covers a 404, a 5xx
6
+ * and a rate limit mid-run.
7
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import { generateKeyPairSync } from "node:crypto";
12
+ import { readFileSync } from "node:fs";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { backfillAccess } from "./github-access-backfill.ts";
15
+ import { GithubLookupClient } from "./github-lookup-client.ts";
16
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
17
+ import { createAdminPrismaClient } from "./prisma-client.ts";
18
+
19
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
21
+
22
+ interface CassetteEntry {
23
+ status: number;
24
+ headers?: Record<string, string>;
25
+ body: unknown;
26
+ }
27
+
28
+ const cassette: Record<string, CassetteEntry> = JSON.parse(
29
+ readFileSync(
30
+ new URL("./fixtures/github-lookup-cassette.json", import.meta.url).pathname,
31
+ "utf-8",
32
+ ),
33
+ );
34
+
35
+ const { privateKey } = generateKeyPairSync("rsa", {
36
+ modulusLength: 2048,
37
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
38
+ publicKeyEncoding: { type: "spki", format: "pem" },
39
+ });
40
+
41
+ const T0 = new Date("2026-11-20T12:00:00Z");
42
+ const snapshotKey = {
43
+ accountId: "acc",
44
+ appKind: "lookup" as const,
45
+ appRef: "555",
46
+ org: "acme-eng",
47
+ };
48
+
49
+ describeOrSkip(
50
+ "backfillAccess through GithubLookupClient (integration)",
51
+ () => {
52
+ let prisma: PrismaClient;
53
+ let now: Date;
54
+ let svc: GitHubRepoCacheService;
55
+ let client: GithubLookupClient;
56
+ /** Permission cassette per repo name. */
57
+ let perms: Record<string, string>;
58
+ let calls: string[];
59
+
60
+ const clock = { now: () => new Date(now) };
61
+ const run = (repos = ["api", "web", "infra"]) =>
62
+ backfillAccess({
63
+ accountId: "acc",
64
+ org: "acme-eng",
65
+ snapshotKey,
66
+ repos,
67
+ users: [{ username: "octocat", configuredRepos: ["infra"] }],
68
+ probe: client,
69
+ store: svc,
70
+ clock,
71
+ maxAgeMs: 86_400_000,
72
+ maxAttempts: 2,
73
+ });
74
+ const accessRows = async () =>
75
+ Object.fromEntries(
76
+ (await prisma.gitHubRepoAccess.findMany()).map((r) => [r.repo, r]),
77
+ );
78
+
79
+ beforeEach(async () => {
80
+ prisma = createAdminPrismaClient(TEST_DB as string);
81
+ await prisma.gitHubRepoAccess.deleteMany();
82
+ await prisma.gitHubCachedRepo.deleteMany();
83
+ await prisma.gitHubRepoSnapshot.deleteMany();
84
+ now = T0;
85
+ svc = new GitHubRepoCacheService(prisma, clock);
86
+ await svc.upsertSnapshot(snapshotKey);
87
+ perms = {};
88
+ calls = [];
89
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
90
+ const u = new URL(input.toString());
91
+ const route = `${init?.method ?? "GET"} ${u.pathname}`;
92
+ let name: string | undefined;
93
+ if (route === "GET /orgs/acme-eng/installation") {
94
+ name = "org_installation_success";
95
+ } else if (route === "POST /app/installations/7001/access_tokens") {
96
+ name = "lookup_token_success";
97
+ } else {
98
+ const m = u.pathname.match(
99
+ /^\/repos\/acme-eng\/([^/]+)\/collaborators\/octocat\/permission$/,
100
+ );
101
+ if (m) {
102
+ calls.push(m[1] as string);
103
+ name = perms[m[1] as string];
104
+ }
105
+ }
106
+ const entry = name ? cassette[name] : undefined;
107
+ if (!entry) throw new Error(`no cassette for ${route}`);
108
+ return new Response(JSON.stringify(entry.body), {
109
+ status: entry.status,
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ ...(entry.headers ?? {}),
113
+ },
114
+ });
115
+ }) as typeof fetch;
116
+ client = new GithubLookupClient({
117
+ appId: "555",
118
+ privateKey,
119
+ apiBase: "https://ghe.test",
120
+ fetchFn,
121
+ now: clock.now,
122
+ });
123
+ });
124
+
125
+ afterEach(async () => {
126
+ await prisma.$disconnect();
127
+ });
128
+
129
+ it("records a 404 as no-access and a 5xx as an error with no answer", async () => {
130
+ perms = {
131
+ infra: "permission_write",
132
+ api: "permission_404",
133
+ web: "permission_500",
134
+ };
135
+ const out = await run();
136
+ expect(out).toMatchObject({
137
+ outcome: "in_progress",
138
+ recorded: 2,
139
+ failed: 1,
140
+ missing: 1,
141
+ });
142
+ expect(calls).toEqual(["infra", "api", "web"]);
143
+ const rows = await accessRows();
144
+ expect(rows.infra).toMatchObject({
145
+ status: "ok",
146
+ canPush: true,
147
+ level: "write",
148
+ });
149
+ expect(rows.api).toMatchObject({
150
+ status: "ok",
151
+ canPush: false,
152
+ level: "none",
153
+ });
154
+ expect(rows.web).toMatchObject({
155
+ status: "error",
156
+ canPush: false,
157
+ level: null,
158
+ attempts: 1,
159
+ });
160
+ expect(rows.web?.nextAttemptAt).not.toBeNull();
161
+ });
162
+
163
+ it("goes terminal after the attempts cap, then completes without blocking on it", async () => {
164
+ perms = { api: "permission_read", web: "permission_503" };
165
+ await run(["api", "web"]);
166
+ now = new Date(T0.getTime() + 2 * 3_600_000);
167
+ const out = await run(["api", "web"]);
168
+ expect(out).toMatchObject({
169
+ outcome: "complete",
170
+ terminal: 1,
171
+ missing: 0,
172
+ });
173
+ expect((await accessRows()).web?.status).toBe("terminal");
174
+ calls = [];
175
+ now = new Date(T0.getTime() + 3 * 3_600_000);
176
+ await run(["api", "web"]);
177
+ expect(calls).toEqual([]);
178
+ });
179
+
180
+ it("stops on a mid-run rate limit and resumes after the reset without redoing finished pairs", async () => {
181
+ perms = {
182
+ infra: "permission_read",
183
+ api: "permission_429",
184
+ web: "permission_read",
185
+ };
186
+ const first = await run();
187
+ expect(first).toMatchObject({
188
+ outcome: "rate_limited",
189
+ recorded: 1,
190
+ failed: 0,
191
+ });
192
+ expect(Object.keys(await accessRows())).toEqual(["infra"]);
193
+ const snap = await svc.getSnapshot(snapshotKey);
194
+ expect(snap?.rateLimitResetAt).toEqual(first.rateLimitResetAt as Date);
195
+
196
+ calls = [];
197
+ perms.api = "permission_read";
198
+ const early = await run();
199
+ expect(early).toMatchObject({ outcome: "rate_limited", probed: 0 });
200
+ expect(calls).toEqual([]);
201
+
202
+ now = new Date((first.rateLimitResetAt as Date).getTime() + 1000);
203
+ const resumed = await run();
204
+ expect(calls).toEqual(["api", "web"]);
205
+ expect(resumed).toMatchObject({ outcome: "complete", recorded: 2 });
206
+ });
207
+ },
208
+ );
@@ -0,0 +1,356 @@
1
+ /**
2
+ * admin/src/github-access-backfill.ts
3
+ * Backfill of per-user repo access into the access table (GLC-1.3).
4
+ *
5
+ * Rows are keyed (account, org, repo, username), so agents that share a GitHub
6
+ * user share rows: users are deduplicated before any call is made.
7
+ *
8
+ * Work list per user: repos with no usable answer ("missing": no row, or an
9
+ * error row whose nextAttemptAt has passed) come before repos whose ok row is
10
+ * older than maxAgeMs ("expired"). Within each group the agent's configured
11
+ * repos come first. Terminal rows and error rows still backing off are skipped.
12
+ *
13
+ * Only a definitive answer is stored as an access answer (status ok): a role,
14
+ * including "none", or a 404 (user or repo not visible to the user, which
15
+ * means no access). A timeout, 5xx, 403, unknown role or any other failure
16
+ * stores no answer: the row becomes status error with attempts + 1 and a
17
+ * capped-backoff nextAttemptAt, and once attempts reaches maxAttempts it
18
+ * becomes terminal (never retried, never counted as missing). A rate limit
19
+ * writes no row at all; it records rateLimitResetAt on the snapshot and ends
20
+ * the run, and later runs before that time make no calls.
21
+ */
22
+
23
+ import type { Clock } from "./clock.ts";
24
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
25
+ import {
26
+ GithubLookupRateLimitError,
27
+ type LookupRateLimit,
28
+ rateLimitResetAt,
29
+ type RepoRole,
30
+ } from "./github-lookup-client.ts";
31
+ import type {
32
+ AccessInput,
33
+ SnapshotKey,
34
+ SnapshotProgress,
35
+ } from "./github-repo-cache.ts";
36
+ import { canPushForRole } from "./user-repo-access-resolver.ts";
37
+
38
+ /** Port: one per-repo permission check (GithubLookupClient satisfies it). */
39
+ export interface AccessProbe {
40
+ getCollaboratorPermissionWithRateLimit(
41
+ owner: string,
42
+ repo: string,
43
+ username: string,
44
+ ): Promise<{ role: RepoRole; rateLimit: LookupRateLimit }>;
45
+ }
46
+
47
+ export interface AccessRow {
48
+ repo: string;
49
+ status: string;
50
+ checkedAt: Date;
51
+ attempts: number;
52
+ nextAttemptAt: Date | null;
53
+ }
54
+
55
+ /** Port: GitHubRepoCacheService satisfies it. */
56
+ export interface AccessBackfillStore {
57
+ getAccessRows(query: {
58
+ accountId: string;
59
+ org: string;
60
+ username: string;
61
+ repos: string[];
62
+ }): Promise<AccessRow[]>;
63
+ upsertAccess(input: AccessInput): Promise<unknown>;
64
+ getSnapshot(
65
+ key: SnapshotKey,
66
+ ): Promise<{ rateLimitResetAt: Date | null } | null>;
67
+ upsertSnapshot(
68
+ key: SnapshotKey,
69
+ progress?: SnapshotProgress,
70
+ ): Promise<unknown>;
71
+ }
72
+
73
+ export interface BackfillUser {
74
+ /** GitHub login; compared case-insensitively. */
75
+ username: string;
76
+ /** Repo names (without org) the agent(s) bound to this user are set up for. */
77
+ configuredRepos?: string[];
78
+ }
79
+
80
+ export interface BackfillOptions {
81
+ accountId: string;
82
+ org: string;
83
+ /** Snapshot that carries rateLimitResetAt (the org's lookup snapshot). */
84
+ snapshotKey: SnapshotKey;
85
+ /** Repo names (without org) in the org's repo cache. */
86
+ repos: string[];
87
+ users: BackfillUser[];
88
+ probe: AccessProbe;
89
+ store: AccessBackfillStore;
90
+ clock: Clock;
91
+ /** An ok row older than this is expired. */
92
+ maxAgeMs: number;
93
+ /** Failures before a pair becomes terminal. Default 5. */
94
+ maxAttempts?: number;
95
+ /** Delay before retrying after the n-th failure; default capped exponential. */
96
+ backoffMs?: (attempts: number) => number;
97
+ /** Stop when X-RateLimit-Remaining falls to this or below. Default 10. */
98
+ lowRemaining?: number;
99
+ /** Most probes in this run. Default 500. */
100
+ maxProbes?: number;
101
+ }
102
+
103
+ export type BackfillOutcome = "complete" | "in_progress" | "rate_limited";
104
+
105
+ export interface BackfillResult {
106
+ outcome: BackfillOutcome;
107
+ /** Permission calls made this run. */
108
+ probed: number;
109
+ recorded: number;
110
+ failed: number;
111
+ terminal: number;
112
+ /** Pairs with no ok answer that are not terminal (blocks completion). */
113
+ missing: number;
114
+ rateLimitResetAt?: Date;
115
+ }
116
+
117
+ export interface WorkItem {
118
+ username: string;
119
+ repo: string;
120
+ kind: "missing" | "expired";
121
+ }
122
+
123
+ const MAX_ERROR_LENGTH = 500;
124
+ export const DEFAULT_ACCESS_MAX_ATTEMPTS = 5;
125
+
126
+ /** 1m, 2m, 4m, ... capped at 1h. */
127
+ export function defaultAccessBackoffMs(attempts: number): number {
128
+ return Math.min(60_000 * 2 ** Math.max(0, attempts - 1), 3_600_000);
129
+ }
130
+
131
+ /**
132
+ * Order the pairs still needing a check for one user: missing before expired,
133
+ * configured repos first within each. `rows` are the user's existing rows.
134
+ * Also returns how many pairs have no ok answer and are not terminal.
135
+ */
136
+ export function buildWorkList(args: {
137
+ username: string;
138
+ repos: string[];
139
+ configuredRepos: string[];
140
+ rows: AccessRow[];
141
+ now: Date;
142
+ maxAgeMs: number;
143
+ }): { work: WorkItem[]; unanswered: number } {
144
+ const byRepo = new Map(args.rows.map((r) => [r.repo, r]));
145
+ const configured = new Set(args.configuredRepos);
146
+ const staleBefore = args.now.getTime() - args.maxAgeMs;
147
+ const items: (WorkItem & { index: number })[] = [];
148
+ let unanswered = 0;
149
+ args.repos.forEach((repo, index) => {
150
+ const row = byRepo.get(repo);
151
+ if (row?.status === "terminal") return;
152
+ if (row?.status === "ok") {
153
+ if (row.checkedAt.getTime() < staleBefore) {
154
+ items.push({ username: args.username, repo, kind: "expired", index });
155
+ }
156
+ return;
157
+ }
158
+ unanswered++;
159
+ const backingOff =
160
+ row?.status === "error" &&
161
+ row.nextAttemptAt !== null &&
162
+ row.nextAttemptAt > args.now;
163
+ if (!backingOff) {
164
+ items.push({ username: args.username, repo, kind: "missing", index });
165
+ }
166
+ });
167
+ items.sort(
168
+ (a, b) =>
169
+ Number(a.kind === "expired") - Number(b.kind === "expired") ||
170
+ Number(!configured.has(a.repo)) - Number(!configured.has(b.repo)) ||
171
+ a.index - b.index,
172
+ );
173
+ return {
174
+ work: items.map(({ index: _i, ...item }) => item),
175
+ unanswered,
176
+ };
177
+ }
178
+
179
+ export async function backfillAccess(
180
+ opts: BackfillOptions,
181
+ ): Promise<BackfillResult> {
182
+ const { store, clock, probe } = opts;
183
+ const maxAttempts = opts.maxAttempts ?? DEFAULT_ACCESS_MAX_ATTEMPTS;
184
+ const backoffMs = opts.backoffMs ?? defaultAccessBackoffMs;
185
+ const lowRemaining = opts.lowRemaining ?? 10;
186
+ const maxProbes = opts.maxProbes ?? 500;
187
+ const result: BackfillResult = {
188
+ outcome: "complete",
189
+ probed: 0,
190
+ recorded: 0,
191
+ failed: 0,
192
+ terminal: 0,
193
+ missing: 0,
194
+ };
195
+
196
+ // Agents sharing a user share rows: merge by lower-cased login.
197
+ const users = new Map<string, Set<string>>();
198
+ for (const u of opts.users) {
199
+ const name = u.username.trim().toLowerCase();
200
+ if (!name) continue;
201
+ const set = users.get(name) ?? new Set<string>();
202
+ for (const r of u.configuredRepos ?? []) set.add(r);
203
+ users.set(name, set);
204
+ }
205
+
206
+ const snap = await store.getSnapshot(opts.snapshotKey);
207
+ const gate = snap?.rateLimitResetAt ?? null;
208
+ if (gate && gate.getTime() > clock.now().getTime()) {
209
+ result.outcome = "rate_limited";
210
+ result.rateLimitResetAt = gate;
211
+ result.missing = await countMissing();
212
+ return result;
213
+ }
214
+
215
+ const rowsByKey = new Map<string, AccessRow>();
216
+ const work: WorkItem[] = [];
217
+ for (const [username, configured] of users) {
218
+ const rows = await store.getAccessRows({
219
+ accountId: opts.accountId,
220
+ org: opts.org,
221
+ username,
222
+ repos: opts.repos,
223
+ });
224
+ for (const r of rows) rowsByKey.set(`${username}/${r.repo}`, r);
225
+ const list = buildWorkList({
226
+ username,
227
+ repos: opts.repos,
228
+ configuredRepos: [...configured],
229
+ rows,
230
+ now: clock.now(),
231
+ maxAgeMs: opts.maxAgeMs,
232
+ });
233
+ result.missing += list.unanswered;
234
+ work.push(...list.work);
235
+ }
236
+ // All missing pairs before any expired one; each user's list is already
237
+ // configured-first and Array.sort is stable.
238
+ const queue = work.sort(
239
+ (a, b) => Number(a.kind === "expired") - Number(b.kind === "expired"),
240
+ );
241
+
242
+ for (const item of queue) {
243
+ if (result.probed >= maxProbes) {
244
+ result.outcome = "in_progress";
245
+ return result;
246
+ }
247
+ const key = `${item.username}/${item.repo}`;
248
+ result.probed++;
249
+ try {
250
+ const { role, rateLimit } =
251
+ await probe.getCollaboratorPermissionWithRateLimit(
252
+ opts.org,
253
+ item.repo,
254
+ item.username,
255
+ );
256
+ await record(item, role);
257
+ if (item.kind === "missing") result.missing--;
258
+ if (rateLimit.remaining !== null && rateLimit.remaining <= lowRemaining) {
259
+ return await stopForRateLimit(rateLimit);
260
+ }
261
+ } catch (err) {
262
+ if (err instanceof GithubEnterpriseError && err.kind === "rate_limit") {
263
+ return await stopForRateLimit({
264
+ remaining: 0,
265
+ resetAt:
266
+ err instanceof GithubLookupRateLimitError ? err.resetAt : null,
267
+ retryAfterSeconds: err.retryAfterSeconds ?? null,
268
+ });
269
+ }
270
+ if (err instanceof GithubEnterpriseError && err.kind === "not_found") {
271
+ await record(item, "none");
272
+ if (item.kind === "missing") result.missing--;
273
+ continue;
274
+ }
275
+ await fail(item, key, err);
276
+ }
277
+ }
278
+ result.outcome = result.missing === 0 ? "complete" : "in_progress";
279
+ return result;
280
+
281
+ async function record(item: WorkItem, role: RepoRole) {
282
+ await store.upsertAccess({
283
+ accountId: opts.accountId,
284
+ org: opts.org,
285
+ repo: item.repo,
286
+ username: item.username,
287
+ canPush: canPushForRole(role),
288
+ level: role,
289
+ status: "ok",
290
+ });
291
+ result.recorded++;
292
+ }
293
+
294
+ async function fail(item: WorkItem, key: string, err: unknown) {
295
+ const prev = rowsByKey.get(key);
296
+ // An expired ok row's attempts do not count toward the cap.
297
+ const n = (prev?.status === "error" ? prev.attempts : 0) + 1;
298
+ const now = clock.now();
299
+ const terminal = n >= maxAttempts;
300
+ const lastError = (err instanceof Error ? err.message : String(err)).slice(
301
+ 0,
302
+ MAX_ERROR_LENGTH,
303
+ );
304
+ await store.upsertAccess({
305
+ accountId: opts.accountId,
306
+ org: opts.org,
307
+ repo: item.repo,
308
+ username: item.username,
309
+ canPush: false,
310
+ level: null,
311
+ status: terminal ? "terminal" : "error",
312
+ attempts: n,
313
+ nextAttemptAt: terminal ? null : new Date(now.getTime() + backoffMs(n)),
314
+ lastError,
315
+ });
316
+ result.failed++;
317
+ if (terminal) {
318
+ result.terminal++;
319
+ if (item.kind === "missing" || prev?.status === "error") result.missing--;
320
+ } else if (item.kind === "expired") {
321
+ // The old ok answer was overwritten by an error row: now unanswered.
322
+ result.missing++;
323
+ }
324
+ }
325
+
326
+ async function stopForRateLimit(
327
+ rl: LookupRateLimit,
328
+ ): Promise<BackfillResult> {
329
+ const at = rateLimitResetAt(rl, clock.now());
330
+ await store.upsertSnapshot(opts.snapshotKey, { rateLimitResetAt: at });
331
+ result.outcome = "rate_limited";
332
+ result.rateLimitResetAt = at;
333
+ return result;
334
+ }
335
+
336
+ async function countMissing(): Promise<number> {
337
+ let n = 0;
338
+ for (const [username, configured] of users) {
339
+ const rows = await store.getAccessRows({
340
+ accountId: opts.accountId,
341
+ org: opts.org,
342
+ username,
343
+ repos: opts.repos,
344
+ });
345
+ n += buildWorkList({
346
+ username,
347
+ repos: opts.repos,
348
+ configuredRepos: [...configured],
349
+ rows,
350
+ now: clock.now(),
351
+ maxAgeMs: opts.maxAgeMs,
352
+ }).unanswered;
353
+ }
354
+ return n;
355
+ }
356
+ }