@app-vitals/agent-admin 1.76.0 → 1.78.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.76.0",
3
+ "version": "1.78.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.76.0",
46
+ "@app-vitals/agent-lib": "1.78.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,29 @@
1
+ {
2
+ "_comment": "Hand-authored from GitHub's enterprise organization-installations OpenAPI description (nothing recorded live). Repo list pages are generated in the test: only the routes, headers and status codes live here.",
3
+ "enterprise_installation": {
4
+ "status": 200,
5
+ "body": { "id": 4242, "app_id": 12345, "app_slug": "shipwright-installer", "repository_selection": "all", "target_type": "Enterprise" }
6
+ },
7
+ "installer_token": {
8
+ "status": 201,
9
+ "body": { "token": "ghs_cassetteInstallationToken0000000000", "expires_at": "2026-11-20T13:00:00Z" }
10
+ },
11
+ "org_installations_agent": {
12
+ "status": 200,
13
+ "body": [
14
+ { "id": 900, "client_id": "Iv1.other", "app_id": 111, "app_slug": "other-app", "account": { "login": "acme-eng" }, "repository_selection": "all" },
15
+ { "id": 501, "client_id": "Iv1.agentapp0001", "app_id": 777, "app_slug": "doc-agent", "account": { "login": "acme-eng" }, "repository_selection": "selected" }
16
+ ]
17
+ },
18
+ "org_installations_no_agent": {
19
+ "status": 200,
20
+ "body": [
21
+ { "id": 900, "client_id": "Iv1.other", "app_id": 111, "app_slug": "other-app", "account": { "login": "beta-eng" }, "repository_selection": "all" }
22
+ ]
23
+ },
24
+ "repos_rate_limited": {
25
+ "status": 429,
26
+ "headers": { "retry-after": "30" },
27
+ "body": { "message": "API rate limit exceeded" }
28
+ }
29
+ }
@@ -513,5 +513,70 @@
513
513
  "message": "Service Unavailable",
514
514
  "documentation_url": "https://docs.github.com/rest"
515
515
  }
516
+ },
517
+ "repos_page_1_rate_limit_exhausted": {
518
+ "status": 200,
519
+ "headers": {
520
+ "link": "<https://ghe.test/installation/repositories?per_page=100&page=2>; rel=\"next\"",
521
+ "x-ratelimit-limit": "5000",
522
+ "x-ratelimit-remaining": "0",
523
+ "x-ratelimit-reset": "1794226500"
524
+ },
525
+ "body": {
526
+ "total_count": 3,
527
+ "repositories": [
528
+ {
529
+ "id": 1,
530
+ "name": "api",
531
+ "full_name": "acme-eng/api",
532
+ "private": false,
533
+ "archived": false
534
+ },
535
+ {
536
+ "id": 2,
537
+ "name": "web",
538
+ "full_name": "acme-eng/web",
539
+ "private": true,
540
+ "archived": false
541
+ }
542
+ ]
543
+ }
544
+ },
545
+ "repos_page_2_total_mismatch": {
546
+ "status": 200,
547
+ "body": {
548
+ "total_count": 4,
549
+ "repositories": [
550
+ {
551
+ "id": 3,
552
+ "name": "infra",
553
+ "full_name": "acme-eng/infra",
554
+ "private": false,
555
+ "archived": false
556
+ }
557
+ ]
558
+ }
559
+ },
560
+ "repos_403_rate_limited": {
561
+ "status": 403,
562
+ "headers": {
563
+ "x-ratelimit-limit": "5000",
564
+ "x-ratelimit-remaining": "0",
565
+ "x-ratelimit-reset": "1794226500"
566
+ },
567
+ "body": {
568
+ "message": "API rate limit exceeded for installation ID 7001.",
569
+ "documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"
570
+ }
571
+ },
572
+ "repos_403_secondary_retry_after": {
573
+ "status": 403,
574
+ "headers": {
575
+ "retry-after": "120"
576
+ },
577
+ "body": {
578
+ "message": "You have exceeded a secondary rate limit. Please wait a few minutes before you try again.",
579
+ "documentation_url": "https://docs.github.com/rest/overview/rate-limits-for-the-rest-api#about-secondary-rate-limits"
580
+ }
516
581
  }
517
582
  }
@@ -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
+ });
@@ -0,0 +1,179 @@
1
+ /**
2
+ * admin/src/github-agent-installation-crawler.ts
3
+ * Crawl each agent App's own installation repos into the repo cache (GLC-1.5).
4
+ *
5
+ * A PageSource over the installer client's single-page installation listing,
6
+ * fed through the same resumable engine (crawlRepos) and completeness check as
7
+ * the lookup crawl, under appKind "agent" and appRef = the agent's GH_APP_ID.
8
+ * Scheduling is not here (GLC-1.4).
9
+ */
10
+
11
+ import type { Clock } from "./clock.ts";
12
+ import type { SnapshotKey } from "./github-repo-cache.ts";
13
+ import {
14
+ type CrawlResult,
15
+ type CrawlStore,
16
+ crawlRepos,
17
+ type PageSource,
18
+ type RepoPage,
19
+ } from "./github-repo-crawler.ts";
20
+ import { identityOf } from "./installation-repos-service.ts";
21
+ import {
22
+ AppNotInstalledError,
23
+ type AppIdentity,
24
+ type InstallationAgentRecord,
25
+ type InstallationRepoClient,
26
+ matchInstallation,
27
+ } from "./installation-ports.ts";
28
+
29
+ /**
30
+ * SnapshotKey.accountId for an agent with no account (the deployment-wide
31
+ * installer/App pair). The cache requires a non-empty accountId.
32
+ */
33
+ export const DEPLOYMENT_WIDE_ACCOUNT_KEY = "deployment";
34
+
35
+ /** The slice of the installer client the crawl needs. */
36
+ export type AgentInstallationClient = Pick<
37
+ InstallationRepoClient,
38
+ "listOrgInstallations"
39
+ > &
40
+ Required<Pick<InstallationRepoClient, "listInstallationRepositoriesPage">>;
41
+
42
+ export interface AgentInstallationPageSource extends PageSource {
43
+ /** The agent App's installation id on the org; throws AppNotInstalledError. Cached. */
44
+ resolveInstallationId(): Promise<number>;
45
+ }
46
+
47
+ export interface AgentInstallationSourceOptions {
48
+ client: AgentInstallationClient;
49
+ org: string;
50
+ appId: number;
51
+ identity?: AppIdentity;
52
+ }
53
+
54
+ /**
55
+ * PageSource over the agent App's installation repositories on `org`. The
56
+ * installation id is resolved lazily, once per source.
57
+ *
58
+ * The enterprise endpoint returns a bare array without total_count, so
59
+ * totalCount is (page - 1) * perPage + repos.length: exact on the last page
60
+ * because every earlier page is full. If rows duplicated or shifted between
61
+ * pages, the engine sees fewer distinct rows than this total and marks the
62
+ * crawl incomplete.
63
+ */
64
+ export function agentInstallationPageSource(
65
+ opts: AgentInstallationSourceOptions,
66
+ ): AgentInstallationPageSource {
67
+ const { client, org, appId, identity } = opts;
68
+ let installationId: Promise<number> | undefined;
69
+ const resolveInstallationId = (): Promise<number> => {
70
+ installationId ??= client
71
+ .listOrgInstallations(org, identity?.accountId)
72
+ .then((installs) => {
73
+ const found = matchInstallation(installs, appId, identity);
74
+ if (!found) throw new AppNotInstalledError(appId, org);
75
+ return found.id;
76
+ });
77
+ // Do not cache a failure: a later page or run may succeed.
78
+ installationId.catch(() => {
79
+ installationId = undefined;
80
+ });
81
+ return installationId;
82
+ };
83
+ return {
84
+ resolveInstallationId,
85
+ async fetchPage(page: number): Promise<RepoPage> {
86
+ const id = await resolveInstallationId();
87
+ const res = await client.listInstallationRepositoriesPage(
88
+ org,
89
+ id,
90
+ page,
91
+ identity?.accountId,
92
+ );
93
+ return {
94
+ repos: res.repos.map((r) => ({
95
+ githubId: r.id,
96
+ fullName: r.fullName,
97
+ archived: r.archived,
98
+ })),
99
+ totalCount: (page - 1) * res.perPage + res.repos.length,
100
+ hasNext: res.hasNext,
101
+ };
102
+ },
103
+ };
104
+ }
105
+
106
+ export type AgentInstallationCrawlResult =
107
+ | CrawlResult
108
+ /** The agent App has no installation on the org; recorded as an empty, complete snapshot. */
109
+ | { outcome: "not_installed"; pagesFetched: 0; swept: number }
110
+ /** The agent has no GH_APP_ID; nothing was read or written. */
111
+ | { outcome: "skipped_no_app_id"; pagesFetched: 0 };
112
+
113
+ export interface CrawlAgentInstallationOptions {
114
+ agent: Pick<
115
+ InstallationAgentRecord,
116
+ "accountId" | "appId" | "clientId" | "slug"
117
+ >;
118
+ org: string;
119
+ client: AgentInstallationClient;
120
+ store: CrawlStore;
121
+ clock: Clock;
122
+ maxPages?: number;
123
+ backoffMs?: (attempts: number) => number;
124
+ }
125
+
126
+ /** Crawl one agent App's installation repos on one org into the cache. */
127
+ export async function crawlAgentInstallation(
128
+ opts: CrawlAgentInstallationOptions,
129
+ ): Promise<AgentInstallationCrawlResult> {
130
+ const { agent, org, client, store, clock } = opts;
131
+ if (agent.appId === undefined) {
132
+ return { outcome: "skipped_no_app_id", pagesFetched: 0 };
133
+ }
134
+ const key: SnapshotKey = {
135
+ accountId: agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY,
136
+ appKind: "agent",
137
+ appRef: String(agent.appId),
138
+ org,
139
+ };
140
+ const source = agentInstallationPageSource({
141
+ client,
142
+ org,
143
+ appId: agent.appId,
144
+ identity: identityOf(agent),
145
+ });
146
+ try {
147
+ await source.resolveInstallationId();
148
+ } catch (err) {
149
+ if (!(err instanceof AppNotInstalledError)) {
150
+ // Let the engine record GitHub failures and rate limits on the snapshot.
151
+ return crawlRepos({ ...engineOpts(), key, source });
152
+ }
153
+ // Not installed: an empty, complete snapshot (stale rows swept), no error.
154
+ const now = clock.now();
155
+ const snap = await store.upsertSnapshot(key, {
156
+ crawlStartedAt: now,
157
+ crawlPage: 0,
158
+ completedAt: now,
159
+ totalCount: 0,
160
+ lastError: null,
161
+ attempts: 0,
162
+ nextAttemptAt: null,
163
+ rateLimitResetAt: null,
164
+ lastTickAt: now,
165
+ });
166
+ const swept = await store.sweepGeneration(snap.id);
167
+ return { outcome: "not_installed", pagesFetched: 0, swept };
168
+ }
169
+ return crawlRepos({ ...engineOpts(), key, source });
170
+
171
+ function engineOpts() {
172
+ return {
173
+ store,
174
+ clock,
175
+ ...(opts.maxPages === undefined ? {} : { maxPages: opts.maxPages }),
176
+ ...(opts.backoffMs === undefined ? {} : { backoffMs: opts.backoffMs }),
177
+ };
178
+ }
179
+ }