@app-vitals/agent-admin 1.79.0 → 1.81.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,205 @@
1
+ /**
2
+ * admin/src/github-lookup-repositories.unit.test.ts
3
+ * Cache-backed githubLookup: syncState derivation, the unconfigured cases and
4
+ * the guarantee that no GitHub call is made.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
9
+ import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
10
+ import {
11
+ type LookupSnapshotView,
12
+ summarizeLookupSnapshots,
13
+ } from "./github-lookup-repositories.ts";
14
+
15
+ const NOW = new Date("2026-11-20T12:00:00Z");
16
+ const ago = (ms: number) => new Date(NOW.getTime() - ms);
17
+ const MIN = 60_000;
18
+
19
+ const snap = (o: Partial<LookupSnapshotView> = {}): LookupSnapshotView => ({
20
+ completedAt: ago(10 * MIN),
21
+ totalCount: 2,
22
+ lastError: null,
23
+ repos: [
24
+ { fullName: "acme/a", archived: false },
25
+ { fullName: "acme/b", archived: true },
26
+ ],
27
+ ...o,
28
+ });
29
+
30
+ describe("summarizeLookupSnapshots", () => {
31
+ it("no snapshot yet: configured, empty, syncing", () => {
32
+ expect(summarizeLookupSnapshots([], NOW)).toEqual({
33
+ configured: true,
34
+ repos: [],
35
+ syncState: "syncing",
36
+ });
37
+ });
38
+
39
+ it("complete and fresh: ready with fetchedAt and progress", () => {
40
+ const r = summarizeLookupSnapshots([snap()], NOW);
41
+ expect(r.syncState).toBe("ready");
42
+ expect(r.fetchedAt).toEqual(ago(10 * MIN));
43
+ expect(r.progress).toEqual({ reposSeen: 2, totalCount: 2 });
44
+ expect(r.repos).toEqual([
45
+ { fullName: "acme/a", archived: false },
46
+ { fullName: "acme/b", archived: true },
47
+ ]);
48
+ });
49
+
50
+ it("complete but older than the TTL: stale, repos still served", () => {
51
+ const r = summarizeLookupSnapshots(
52
+ [snap({ completedAt: ago(61 * MIN) })],
53
+ NOW,
54
+ );
55
+ expect(r.syncState).toBe("stale");
56
+ expect(r.repos).toHaveLength(2);
57
+ });
58
+
59
+ it("honours a custom TTL", () => {
60
+ const r = summarizeLookupSnapshots([snap()], NOW, 5 * MIN);
61
+ expect(r.syncState).toBe("stale");
62
+ });
63
+
64
+ it("in-progress crawl: partial repos, syncing, progress, no fetchedAt", () => {
65
+ const r = summarizeLookupSnapshots(
66
+ [
67
+ snap({
68
+ completedAt: null,
69
+ totalCount: 10,
70
+ repos: [{ fullName: "acme/a", archived: false }],
71
+ }),
72
+ ],
73
+ NOW,
74
+ );
75
+ expect(r.syncState).toBe("syncing");
76
+ expect(r.repos).toEqual([{ fullName: "acme/a", archived: false }]);
77
+ expect(r.progress).toEqual({ reposSeen: 1, totalCount: 10 });
78
+ expect(r.fetchedAt).toBeUndefined();
79
+ });
80
+
81
+ it("incomplete crawl with an error: failed", () => {
82
+ const r = summarizeLookupSnapshots(
83
+ [snap({ completedAt: null, lastError: "boom" })],
84
+ NOW,
85
+ );
86
+ expect(r.syncState).toBe("failed");
87
+ });
88
+
89
+ it("omits totalCount while any org has not reported one", () => {
90
+ const r = summarizeLookupSnapshots(
91
+ [snap(), snap({ completedAt: null, totalCount: null, repos: [] })],
92
+ NOW,
93
+ );
94
+ expect(r.progress).toEqual({ reposSeen: 2 });
95
+ });
96
+
97
+ it("merges orgs: syncing beats stale, failed beats syncing, dedupes repos", () => {
98
+ const orgA = snap({ completedAt: ago(90 * MIN) });
99
+ const orgB = snap({
100
+ completedAt: null,
101
+ repos: [{ fullName: "acme/a", archived: false }],
102
+ });
103
+ const mixed = summarizeLookupSnapshots([orgA, orgB], NOW);
104
+ expect(mixed.syncState).toBe("syncing");
105
+ expect(mixed.repos.map((r) => r.fullName).sort()).toEqual([
106
+ "acme/a",
107
+ "acme/b",
108
+ ]);
109
+ const failed = summarizeLookupSnapshots(
110
+ [orgA, { ...orgB, lastError: "x" }],
111
+ NOW,
112
+ );
113
+ expect(failed.syncState).toBe("failed");
114
+ });
115
+
116
+ it("fetchedAt is the oldest completion across orgs", () => {
117
+ const r = summarizeLookupSnapshots(
118
+ [
119
+ snap({ completedAt: ago(5 * MIN) }),
120
+ snap({ completedAt: ago(30 * MIN) }),
121
+ ],
122
+ NOW,
123
+ );
124
+ expect(r.fetchedAt).toEqual(ago(30 * MIN));
125
+ });
126
+ });
127
+
128
+ describe("createGithubLookupService", () => {
129
+ type Row = { appId: string; enterpriseSlug: string | null };
130
+ function apps(rows: Record<string, Row | undefined>, withKey = true) {
131
+ return {
132
+ get: async (role: string) => rows[role] ?? null,
133
+ getPrivateKey: async (role: string) =>
134
+ rows[role] && withKey ? "pem" : null,
135
+ } as unknown as GitHubEnterpriseAppService;
136
+ }
137
+ const lookupRow = { appId: "555", enterpriseSlug: null };
138
+
139
+ function build(
140
+ rows: Record<string, Row | undefined>,
141
+ snapshots: LookupSnapshotView[] = [],
142
+ withKey = true,
143
+ ) {
144
+ const calls: unknown[][] = [];
145
+ const svc = createGithubLookupService({
146
+ appService: apps(rows, withKey),
147
+ now: () => NOW,
148
+ cache: {
149
+ listLookupSnapshots: async (...args: unknown[]) => {
150
+ calls.push(args);
151
+ return snapshots;
152
+ },
153
+ },
154
+ });
155
+ return { svc, calls };
156
+ }
157
+
158
+ it("unconfigured when no lookup App: configured:false, cache untouched", async () => {
159
+ const { svc, calls } = build({});
160
+ expect(await svc.listRepositories("acct")).toEqual({
161
+ configured: false,
162
+ repos: [],
163
+ });
164
+ expect(calls).toHaveLength(0);
165
+ });
166
+
167
+ it("unconfigured when the lookup App has no key", async () => {
168
+ const { svc } = build({ lookup: lookupRow }, [], false);
169
+ expect((await svc.listRepositories()).configured).toBe(false);
170
+ });
171
+
172
+ it("unconfigured when an installer with a slug has no key", async () => {
173
+ const rows = {
174
+ lookup: lookupRow,
175
+ installer: { appId: "1", enterpriseSlug: "ent" },
176
+ };
177
+ const svc = createGithubLookupService({
178
+ appService: {
179
+ get: async (role: string) => (rows as Record<string, Row>)[role],
180
+ getPrivateKey: async (role: string) =>
181
+ role === "lookup" ? "pem" : null,
182
+ } as unknown as GitHubEnterpriseAppService,
183
+ cache: { listLookupSnapshots: async () => [] },
184
+ });
185
+ expect((await svc.listRepositories()).configured).toBe(false);
186
+ });
187
+
188
+ it("cold start: configured, empty, syncing", async () => {
189
+ const { svc } = build({ lookup: lookupRow });
190
+ expect(await svc.listRepositories("acct")).toEqual({
191
+ configured: true,
192
+ repos: [],
193
+ syncState: "syncing",
194
+ });
195
+ });
196
+
197
+ it("queries the account and deployment-wide scopes by lookup App id", async () => {
198
+ const { svc, calls } = build({ lookup: lookupRow }, [snap()]);
199
+ const r = await svc.listRepositories("acct");
200
+ expect(r.syncState).toBe("ready");
201
+ expect(calls[0]).toEqual([["acct", ""], "555"]);
202
+ await svc.listRepositories();
203
+ expect(calls[1]).toEqual([[""], "555"]);
204
+ });
205
+ });
@@ -68,6 +68,20 @@ describeOrSkip("GitHubRepoCacheService (integration)", () => {
68
68
  expect(r.archived).toBe(true);
69
69
  });
70
70
 
71
+ it("lists a snapshot's repo full names, sorted, and no other snapshot's", async () => {
72
+ const snap = await svc.upsertSnapshot(key);
73
+ const other = await svc.upsertSnapshot({ ...key, org: "other" });
74
+ await svc.upsertRepos(snap.id, [
75
+ { githubId: 2, fullName: "acme/web" },
76
+ { githubId: 1, fullName: "acme/api" },
77
+ ]);
78
+ await svc.upsertRepos(other.id, [{ githubId: 3, fullName: "other/x" }]);
79
+ expect(await svc.listRepoFullNames(snap.id)).toEqual([
80
+ "acme/api",
81
+ "acme/web",
82
+ ]);
83
+ });
84
+
71
85
  it("sweep deletes only rows seen before crawlStartedAt", async () => {
72
86
  const snap = await svc.upsertSnapshot(key, { crawlStartedAt: min(10) });
73
87
  await svc.upsertRepos(
@@ -128,6 +128,24 @@ export class GitHubRepoCacheService {
128
128
  });
129
129
  }
130
130
 
131
+ /** Lookup-App snapshots (with their repos) for the account scopes and App id. Reads only the cache. */
132
+ async listLookupSnapshots(accountIds: string[], appRef: string) {
133
+ requireNonEmpty("appRef", appRef);
134
+ const rows = await this.prisma.gitHubRepoSnapshot.findMany({
135
+ where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
136
+ include: {
137
+ repos: { select: { fullName: true, archived: true } },
138
+ },
139
+ orderBy: { org: "asc" },
140
+ });
141
+ return rows.map((r) => ({
142
+ completedAt: r.completedAt,
143
+ totalCount: r.totalCount,
144
+ lastError: r.lastError,
145
+ repos: r.repos,
146
+ }));
147
+ }
148
+
131
149
  /** Upsert repos for a snapshot in batches, stamping each with `seenAt`. */
132
150
  async upsertRepos(
133
151
  snapshotId: string,
@@ -176,6 +194,17 @@ export class GitHubRepoCacheService {
176
194
  });
177
195
  }
178
196
 
197
+ /** Full names (owner/repo) of every repo cached for the snapshot, sorted. */
198
+ async listRepoFullNames(snapshotId: string): Promise<string[]> {
199
+ requireNonEmpty("snapshotId", snapshotId);
200
+ const rows = await this.prisma.gitHubCachedRepo.findMany({
201
+ where: { snapshotId },
202
+ select: { fullName: true },
203
+ orderBy: { fullName: "asc" },
204
+ });
205
+ return rows.map((r) => r.fullName);
206
+ }
207
+
179
208
  /**
180
209
  * Delete repos last seen before the snapshot's crawlStartedAt. Returns the
181
210
  * number deleted; 0 (and deletes nothing) when no crawl has started.
@@ -114,6 +114,11 @@ export interface CrawlOptions {
114
114
  maxPages?: number;
115
115
  /** Delay before retrying after the n-th consecutive failure. */
116
116
  backoffMs?: (attempts: number) => number;
117
+ /**
118
+ * Checked before every page after the first; true ends the run as
119
+ * in_progress (the next run resumes). Lets a caller bound a run by time.
120
+ */
121
+ shouldStop?: () => boolean;
117
122
  }
118
123
 
119
124
  const DEFAULT_MAX_PAGES = 1000;
@@ -158,6 +163,7 @@ export async function crawlRepos(opts: CrawlOptions): Promise<CrawlResult> {
158
163
 
159
164
  let pagesFetched = 0;
160
165
  for (let page = startPage; pagesFetched < maxPages; page++) {
166
+ if (pagesFetched > 0 && opts.shouldStop?.()) break;
161
167
  let result: RepoPage;
162
168
  try {
163
169
  result = await source.fetchPage(page);
@@ -450,3 +450,39 @@ describe("crawlRepos: page budget", () => {
450
450
  expect(done.outcome).toBe("complete");
451
451
  });
452
452
  });
453
+
454
+ describe("crawlRepos: shouldStop (GLC-1.4 time budget)", () => {
455
+ it("fetches at least one page, then stops in_progress when asked and resumes later", async () => {
456
+ const source = new FakeSource([1, 2, 3, 4, 5, 6]);
457
+ let calls = 0;
458
+ const out = await crawlRepos({
459
+ key: KEY,
460
+ source,
461
+ store,
462
+ clock,
463
+ shouldStop: () => ++calls > 1,
464
+ });
465
+ expect(out.outcome).toBe("in_progress");
466
+ expect(source.fetched).toEqual([1, 2]);
467
+ expect(store.snap?.crawlPage).toBe(2);
468
+ expect(store.snap?.completedAt).toBeNull();
469
+
470
+ source.fetched = [];
471
+ const done = await run(source);
472
+ expect(done.outcome).toBe("complete");
473
+ expect(source.fetched).toEqual([1, 2, 3]);
474
+ });
475
+
476
+ it("is not consulted before the first page", async () => {
477
+ const source = new FakeSource([1, 2]);
478
+ const out = await crawlRepos({
479
+ key: KEY,
480
+ source,
481
+ store,
482
+ clock,
483
+ shouldStop: () => true,
484
+ });
485
+ expect(out.outcome).toBe("complete");
486
+ expect(source.fetched).toEqual([1]);
487
+ });
488
+ });
@@ -0,0 +1,241 @@
1
+ /**
2
+ * admin/src/github-repo-refresh-discovery.ts
3
+ * Target discovery for the refresh tick (GLC-1.4): which cache snapshots to
4
+ * keep current, from the stored GitHub Apps, the installer App's orgs and the
5
+ * agents.
6
+ *
7
+ * Scopes are the deployment-wide App pair plus every account with Apps of its
8
+ * own. Per scope, the resolved lookup App (the account's, else the
9
+ * deployment-wide one, as listRepositories resolves it) gets one lookup target
10
+ * per org, keyed by the scope that owns the lookup App (accountId, or
11
+ * DEPLOYMENT_WIDE_ACCOUNT_KEY). Orgs come from the resolved installer App when
12
+ * it has an enterprise slug, else from the lookup App's own installations.
13
+ * Agents with a GH_APP_ID and a GitHub username whose account resolves to that
14
+ * lookup App supply the access-backfill users.
15
+ *
16
+ * Each agent with a GH_APP_ID also gets one agent target per org its account's
17
+ * installer can reach (keyed as GLC-1.5 keys it). No installer, no agent
18
+ * targets.
19
+ *
20
+ * Keys are deduplicated, and a scope or agent whose discovery fails is logged
21
+ * and skipped without affecting the rest. The stored-App wiring (key-bearing)
22
+ * is createStoredAppRefreshDiscovery in github-installation-wiring.ts.
23
+ */
24
+
25
+ import type { Clock } from "./clock.ts";
26
+ import type { AccessProbe, BackfillUser } from "./github-access-backfill.ts";
27
+ import {
28
+ type AgentInstallationClient,
29
+ crawlAgentInstallation,
30
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
31
+ } from "./github-agent-installation-crawler.ts";
32
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
33
+ import type { GithubLookupClient } from "./github-lookup-client.ts";
34
+ import type { SnapshotKey } from "./github-repo-cache.ts";
35
+ import {
36
+ type CrawlStore,
37
+ crawlRepos,
38
+ lookupRepoPageSource,
39
+ type PageSource,
40
+ type RepoPage,
41
+ } from "./github-repo-crawler.ts";
42
+ import {
43
+ type RefreshDiscovery,
44
+ type RefreshTarget,
45
+ snapshotKeyString,
46
+ } from "./github-repo-refresher.ts";
47
+ import type { InstallationAgentRecord } from "./installation-ports.ts";
48
+
49
+ /** The lookup-client surface discovery and its targets use. */
50
+ export type LookupAppClient = AccessProbe &
51
+ Pick<
52
+ GithubLookupClient,
53
+ "listInstallations" | "listInstallationRepositoriesPage"
54
+ >;
55
+
56
+ export interface ResolvedLookupApp {
57
+ /** The scope that owns the App row (null: deployment-wide). */
58
+ accountId: string | null;
59
+ appId: string;
60
+ client: LookupAppClient;
61
+ }
62
+
63
+ export interface DiscoveryPorts {
64
+ /** Accounts with GitHub Apps of their own (the deployment-wide scope is implied). */
65
+ listAppScopes(): Promise<(string | null)[]>;
66
+ listAgents(): Promise<InstallationAgentRecord[]>;
67
+ /** The lookup App this scope resolves to; null when none is usable. */
68
+ lookupApp(scope: string | null): Promise<ResolvedLookupApp | null>;
69
+ /** Orgs the scope's installer App can reach; null when there is no installer with an enterprise slug. */
70
+ installerOrgs(scope: string | null): Promise<string[] | null>;
71
+ installer: AgentInstallationClient;
72
+ store: CrawlStore;
73
+ clock: Clock;
74
+ log?: (line: string) => void;
75
+ }
76
+
77
+ /**
78
+ * A lookup page source where not_found (the lookup App is not installed on
79
+ * the org) is an empty, last page, so the org records as an empty complete
80
+ * snapshot instead of failing with backoff forever.
81
+ */
82
+ export function notFoundAsEmpty(source: PageSource): PageSource {
83
+ return {
84
+ async fetchPage(page: number): Promise<RepoPage> {
85
+ try {
86
+ return await source.fetchPage(page);
87
+ } catch (err) {
88
+ if (err instanceof GithubEnterpriseError && err.kind === "not_found") {
89
+ return { repos: [], totalCount: 0, hasNext: false };
90
+ }
91
+ throw err;
92
+ }
93
+ },
94
+ };
95
+ }
96
+
97
+ const scopeKeyOf = (accountId: string | null | undefined): string =>
98
+ accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY;
99
+
100
+ /** Repo names (without org) in `org` from an agent's owner/repo list. */
101
+ function reposInOrg(repos: readonly string[], org: string): string[] {
102
+ const prefix = `${org.toLowerCase()}/`;
103
+ return repos
104
+ .filter((r) => r.toLowerCase().startsWith(prefix))
105
+ .map((r) => r.slice(prefix.length));
106
+ }
107
+
108
+ export function createRefreshDiscovery(
109
+ ports: DiscoveryPorts,
110
+ ): RefreshDiscovery {
111
+ const log = ports.log ?? ((line: string) => console.error(line));
112
+ return {
113
+ async listTargets(): Promise<RefreshTarget[]> {
114
+ const { store, clock, installer } = ports;
115
+ const lookupMemo = new Map<
116
+ string | null,
117
+ Promise<ResolvedLookupApp | null>
118
+ >();
119
+ const orgsMemo = new Map<string | null, Promise<string[] | null>>();
120
+ const lookupFor = (scope: string | null) => {
121
+ let p = lookupMemo.get(scope);
122
+ if (!p) {
123
+ p = ports.lookupApp(scope);
124
+ lookupMemo.set(scope, p);
125
+ }
126
+ return p;
127
+ };
128
+ const installerOrgsFor = (scope: string | null) => {
129
+ let p = orgsMemo.get(scope);
130
+ if (!p) {
131
+ p = ports.installerOrgs(scope);
132
+ orgsMemo.set(scope, p);
133
+ }
134
+ return p;
135
+ };
136
+
137
+ const scopes = [...new Set([null, ...(await ports.listAppScopes())])];
138
+ const agents = await ports.listAgents();
139
+ const targets = new Map<string, RefreshTarget>();
140
+ const add = (t: RefreshTarget) => {
141
+ const k = snapshotKeyString(t.key);
142
+ if (!targets.has(k)) targets.set(k, t);
143
+ };
144
+
145
+ // Access users per lookup scope key: agents with an App and a user.
146
+ const usersByScope = new Map<string, InstallationAgentRecord[]>();
147
+ for (const a of agents) {
148
+ if (a.appId === undefined || !a.githubUsername?.trim()) continue;
149
+ try {
150
+ const lookup = await lookupFor(a.accountId ?? null);
151
+ if (!lookup) continue;
152
+ const k = scopeKeyOf(lookup.accountId);
153
+ usersByScope.set(k, [...(usersByScope.get(k) ?? []), a]);
154
+ } catch {
155
+ // The scope loop below logs the same failure once.
156
+ }
157
+ }
158
+
159
+ for (const scope of scopes) {
160
+ try {
161
+ const lookup = await lookupFor(scope);
162
+ if (!lookup) continue;
163
+ const orgs =
164
+ (await installerOrgsFor(scope)) ??
165
+ (await lookup.client.listInstallations()).map((i) => i.login);
166
+ const accountId = scopeKeyOf(lookup.accountId);
167
+ const bound = usersByScope.get(accountId) ?? [];
168
+ for (const org of orgs) {
169
+ const key: SnapshotKey = {
170
+ accountId,
171
+ appKind: "lookup",
172
+ appRef: lookup.appId,
173
+ org,
174
+ };
175
+ const users: BackfillUser[] = bound.map((a) => ({
176
+ username: (a.githubUsername as string).trim(),
177
+ configuredRepos: reposInOrg(a.repos, org),
178
+ }));
179
+ const source = notFoundAsEmpty(
180
+ lookupRepoPageSource(lookup.client, org),
181
+ );
182
+ add({
183
+ key,
184
+ crawl: (ctx) =>
185
+ crawlRepos({
186
+ key,
187
+ source,
188
+ store,
189
+ clock,
190
+ shouldStop: ctx.shouldStop,
191
+ }),
192
+ ...(users.length > 0
193
+ ? { access: { probe: lookup.client, users } }
194
+ : {}),
195
+ });
196
+ }
197
+ } catch (err) {
198
+ log(
199
+ `[github-repo-refresher] discovery for scope ${scopeKeyOf(scope)} failed: ${messageOf(err)}`,
200
+ );
201
+ }
202
+ }
203
+
204
+ for (const a of agents) {
205
+ if (a.appId === undefined) continue;
206
+ try {
207
+ const orgs = await installerOrgsFor(a.accountId ?? null);
208
+ if (!orgs) continue;
209
+ for (const org of orgs) {
210
+ add({
211
+ key: {
212
+ accountId: scopeKeyOf(a.accountId),
213
+ appKind: "agent",
214
+ appRef: String(a.appId),
215
+ org,
216
+ },
217
+ crawl: (ctx) =>
218
+ crawlAgentInstallation({
219
+ agent: a,
220
+ org,
221
+ client: installer,
222
+ store,
223
+ clock,
224
+ shouldStop: ctx.shouldStop,
225
+ }),
226
+ });
227
+ }
228
+ } catch (err) {
229
+ log(
230
+ `[github-repo-refresher] discovery for agent ${a.id} failed: ${messageOf(err)}`,
231
+ );
232
+ }
233
+ }
234
+ return [...targets.values()];
235
+ },
236
+ };
237
+ }
238
+
239
+ function messageOf(err: unknown): string {
240
+ return err instanceof Error ? err.message : String(err);
241
+ }