@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.79.0",
3
+ "version": "1.81.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.79.0",
46
+ "@app-vitals/agent-lib": "1.81.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
@@ -43,6 +43,7 @@ describe("admin-boot.ts boot sequence", () => {
43
43
  "new TrialExpirySweeper(",
44
44
  "new AccountTrialWarningSweeper(",
45
45
  "new AccountTrialExpirySweeper(",
46
+ "new GithubRepoRefresher(",
46
47
  "startBackgroundPasses(resolvedExtensions.backgroundPasses)",
47
48
  "const server = Bun.serve(",
48
49
  "const shutdown = registerGracefulShutdown(",
@@ -51,6 +52,16 @@ describe("admin-boot.ts boot sequence", () => {
51
52
  ]);
52
53
  });
53
54
 
55
+ it("registers the GitHub repo refresher on its own interval, with env-driven config (GLC-1.4)", () => {
56
+ assertOrdered([
57
+ "resolveRefreshConfig(process.env)",
58
+ "new GithubRepoRefresher(",
59
+ "createStoredAppRefreshDiscovery(",
60
+ "[github-repo-refresher] tick error:",
61
+ "githubRefreshConfig.intervalMs",
62
+ ]);
63
+ });
64
+
54
65
  it("applies the template seed after migrations, through the template service, without blocking serving (TMK-3.2)", () => {
55
66
  assertOrdered([
56
67
  "await runMigrations();",
package/src/admin-boot.ts CHANGED
@@ -99,6 +99,7 @@ import {
99
99
  } from "./caller-scope.ts";
100
100
  import { parseChatCredentialConfig } from "./chat-credential-config.ts";
101
101
  import { HttpChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
102
+ import { SystemClock } from "./clock.ts";
102
103
  import { CronRunNowService } from "./cron-run-now.ts";
103
104
  import { parseCronRunNowConfig } from "./cron-run-now-config.ts";
104
105
  import { CronRunTranscriptService } from "./cron-run-transcripts.ts";
@@ -113,8 +114,13 @@ import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
113
114
  import {
114
115
  createGithubInstallationRepos,
115
116
  createGithubSync,
117
+ createStoredAppRefreshDiscovery,
116
118
  } from "./github-installation-wiring.ts";
117
-
119
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
120
+ import {
121
+ GithubRepoRefresher,
122
+ resolveRefreshConfig,
123
+ } from "./github-repo-refresher.ts";
118
124
  import { PrincipalLookupService } from "./principal-lookup.ts";
119
125
  import { createPrincipalsApp } from "./principals-api.ts";
120
126
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
@@ -193,6 +199,9 @@ export async function startAdmin(
193
199
  prisma,
194
200
  makeStrictTokenCrypto(),
195
201
  );
202
+ // One repo-snapshot cache shared by githubLookup (reads) and the background
203
+ // GithubRepoRefresher (writes) so both see the same store.
204
+ const githubRepoCache = new GitHubRepoCacheService(prisma);
196
205
 
197
206
  // Construct TokenCrypto — reads SHIPWRIGHT_ENCRYPTION_KEY at call time
198
207
  const crypto = makeTokenCrypto();
@@ -422,6 +431,7 @@ export async function startAdmin(
422
431
  provisioner,
423
432
  githubLookup: createGithubLookupService({
424
433
  appService: githubEnterpriseAppService,
434
+ cache: githubRepoCache,
425
435
  }),
426
436
  },
427
437
  };
@@ -842,6 +852,38 @@ export async function startAdmin(
842
852
  );
843
853
  }
844
854
 
855
+ // GitHub repo/access cache refresher (GLC-1.4) — keeps the repo cache and
856
+ // per-user access rows current in the background so no request path calls
857
+ // GitHub. Registered HERE, never inside an app factory, like the sweepers
858
+ // above. Each tick is bounded by its time budget, a tick still running makes
859
+ // the next a no-op, and the per-org snapshot lease lets only one admin
860
+ // replica work an org at a time. Without stored GitHub Apps discovery finds
861
+ // nothing and every tick is idle.
862
+ {
863
+ const githubRefreshConfig = resolveRefreshConfig(process.env);
864
+ const githubRepoRefresher = new GithubRepoRefresher({
865
+ discovery: createStoredAppRefreshDiscovery({
866
+ prisma,
867
+ appService: githubEnterpriseAppService,
868
+ agentEnv: agentEnvService,
869
+ store: githubRepoCache,
870
+ clock: SystemClock(),
871
+ }),
872
+ store: githubRepoCache,
873
+ config: githubRefreshConfig,
874
+ });
875
+ setInterval(() => {
876
+ githubRepoRefresher
877
+ .tick()
878
+ .catch((err) =>
879
+ console.error("[github-repo-refresher] tick error:", err),
880
+ );
881
+ }, githubRefreshConfig.intervalMs);
882
+ console.log(
883
+ `[admin] github repo refresher started (interval: ${githubRefreshConfig.intervalMs}ms, ttl: ${githubRefreshConfig.ttlMs}ms, staleness cap: ${githubRefreshConfig.stalenessCapMs}ms, budget: ${githubRefreshConfig.timeBudgetMs}ms)`,
884
+ );
885
+ }
886
+
845
887
  // Extension background passes (AEP-2.1) — after every platform sweeper,
846
888
  // same "registered here, never inside an app factory" rule.
847
889
  startBackgroundPasses(resolvedExtensions.backgroundPasses);
@@ -98,6 +98,11 @@ export interface BackfillOptions {
98
98
  lowRemaining?: number;
99
99
  /** Most probes in this run. Default 500. */
100
100
  maxProbes?: number;
101
+ /**
102
+ * Checked before every probe after the first; true ends the run as
103
+ * in_progress. Lets a caller bound a run by time.
104
+ */
105
+ shouldStop?: () => boolean;
101
106
  }
102
107
 
103
108
  export type BackfillOutcome = "complete" | "in_progress" | "rate_limited";
@@ -240,7 +245,10 @@ export async function backfillAccess(
240
245
  );
241
246
 
242
247
  for (const item of queue) {
243
- if (result.probed >= maxProbes) {
248
+ if (
249
+ result.probed >= maxProbes ||
250
+ (result.probed > 0 && opts.shouldStop?.())
251
+ ) {
244
252
  result.outcome = "in_progress";
245
253
  return result;
246
254
  }
@@ -349,3 +349,19 @@ describe("backfillAccess", () => {
349
349
  });
350
350
  });
351
351
  });
352
+
353
+ describe("backfillAccess: shouldStop (GLC-1.4 time budget)", () => {
354
+ it("makes at least one probe, then stops in_progress when asked", async () => {
355
+ const h = makeStore();
356
+ const calls: string[] = [];
357
+ let n = 0;
358
+ const out = await run(
359
+ h,
360
+ probeOf(() => "write", calls),
361
+ { shouldStop: () => ++n > 1 },
362
+ );
363
+ expect(out.outcome).toBe("in_progress");
364
+ expect(calls).toEqual(["octocat/a", "octocat/b"]);
365
+ expect(out.missing).toBe(1);
366
+ });
367
+ });
@@ -5,7 +5,7 @@
5
5
  * A PageSource over the installer client's single-page installation listing,
6
6
  * fed through the same resumable engine (crawlRepos) and completeness check as
7
7
  * the lookup crawl, under appKind "agent" and appRef = the agent's GH_APP_ID.
8
- * Scheduling is not here (GLC-1.4).
8
+ * Scheduling lives in github-repo-refresher.ts (GLC-1.4).
9
9
  */
10
10
 
11
11
  import type { Clock } from "./clock.ts";
@@ -121,6 +121,8 @@ export interface CrawlAgentInstallationOptions {
121
121
  clock: Clock;
122
122
  maxPages?: number;
123
123
  backoffMs?: (attempts: number) => number;
124
+ /** Passed to the engine: checked before every page after the first. */
125
+ shouldStop?: () => boolean;
124
126
  }
125
127
 
126
128
  /** Crawl one agent App's installation repos on one org into the cache. */
@@ -174,6 +176,7 @@ export async function crawlAgentInstallation(
174
176
  clock,
175
177
  ...(opts.maxPages === undefined ? {} : { maxPages: opts.maxPages }),
176
178
  ...(opts.backoffMs === undefined ? {} : { backoffMs: opts.backoffMs }),
179
+ ...(opts.shouldStop === undefined ? {} : { shouldStop: opts.shouldStop }),
177
180
  };
178
181
  }
179
182
  }
@@ -268,6 +268,20 @@ describe("crawlAgentInstallation", () => {
268
268
  expect(calls.pages).toEqual([1, 1, 2, 3]);
269
269
  });
270
270
 
271
+ it("passes shouldStop through to the engine", async () => {
272
+ const { client, calls } = fakeClient({ total: 5 });
273
+ const res = await crawlAgentInstallation({
274
+ agent: agent(),
275
+ org: "acme",
276
+ client,
277
+ store,
278
+ clock,
279
+ shouldStop: () => true,
280
+ });
281
+ expect(res.outcome).toBe("in_progress");
282
+ expect(calls.pages).toEqual([1]);
283
+ });
284
+
271
285
  it("records not-installed as a completed empty snapshot, not an error", async () => {
272
286
  store.rows.set(1, { fullName: "acme/stale", seenAt: new Date(0) });
273
287
  const { client, calls } = fakeClient({ installs: [] });
@@ -53,10 +53,9 @@ import { resolveValidation } from "./github-enterprise-warnings.ts";
53
53
  import { GithubLookupClient } from "./github-lookup-client.ts";
54
54
  import {
55
55
  type GithubLookupService,
56
- type LookupInstallerPort,
57
- type LookupRepositoriesPort,
58
- listLookupRepositories,
56
+ summarizeLookupSnapshots,
59
57
  } from "./github-lookup-repositories.ts";
58
+ import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
60
59
  import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
61
60
  import { ErrorSchema } from "./openapi-schemas.ts";
62
61
  import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
@@ -509,67 +508,41 @@ export function createGithubAccessPreview(
509
508
  };
510
509
  }
511
510
 
512
- /** Backs AdminPlatformServices.githubLookup (SCR-1.7). */
511
+ /** Backs AdminPlatformServices.githubLookup: reads the repo cache, never GitHub. */
513
512
  export function createGithubLookupService(
514
- deps: Pick<
515
- GithubEnterpriseApiDeps,
516
- "appService" | "fetchFn" | "apiBase" | "now"
517
- > & {
518
- /** Test seam: replaces the clients built from the stored Apps. */
519
- clients?: {
520
- installer?: LookupInstallerPort;
521
- lookup: LookupRepositoriesPort;
522
- };
513
+ deps: Pick<GithubEnterpriseApiDeps, "appService" | "now"> & {
514
+ cache: Pick<GitHubRepoCacheService, "listLookupSnapshots">;
515
+ /** Age past which a completed crawl reads as stale. */
516
+ ttlMs?: number;
523
517
  },
524
518
  ): GithubLookupService {
525
519
  return {
526
520
  async listRepositories(accountId) {
527
- let clients = deps.clients;
528
- if (!clients) {
529
- const [installer, lookup] = await Promise.all([
530
- deps.appService.get("installer", accountId),
531
- deps.appService.get("lookup", accountId),
532
- ]);
533
- if (!lookup) return { configured: false, repos: [] };
534
- const lookupKey = await deps.appService.getPrivateKey(
535
- "lookup",
536
- accountId,
537
- );
538
- if (!lookupKey) return { configured: false, repos: [] };
539
- const common = {
540
- apiBase: deps.apiBase,
541
- fetchFn: deps.fetchFn,
542
- now: deps.now,
543
- };
544
- // An installer with an enterprise slug supplies the org list; without
545
- // one the lookup App lists the orgs it is installed on.
546
- const installerKey = installer?.enterpriseSlug
547
- ? await deps.appService.getPrivateKey("installer", accountId)
548
- : null;
549
- if (installer?.enterpriseSlug && !installerKey) {
550
- return { configured: false, repos: [] };
551
- }
552
- clients = {
553
- installer:
554
- installer?.enterpriseSlug && installerKey
555
- ? new GithubEnterpriseClient({
556
- appId: installer.appId,
557
- enterprise: installer.enterpriseSlug,
558
- privateKey: installerKey,
559
- ...common,
560
- })
561
- : undefined,
562
- lookup: new GithubLookupClient({
563
- appId: lookup.appId,
564
- privateKey: lookupKey,
565
- ...common,
566
- }),
567
- };
521
+ const [installer, lookup] = await Promise.all([
522
+ deps.appService.get("installer", accountId),
523
+ deps.appService.get("lookup", accountId),
524
+ ]);
525
+ if (!lookup) return { configured: false, repos: [] };
526
+ const [lookupKey, installerKey] = await Promise.all([
527
+ deps.appService.getPrivateKey("lookup", accountId),
528
+ installer?.enterpriseSlug
529
+ ? deps.appService.getPrivateKey("installer", accountId)
530
+ : null,
531
+ ]);
532
+ if (!lookupKey || (installer?.enterpriseSlug && !installerKey)) {
533
+ return { configured: false, repos: [] };
568
534
  }
569
- return {
570
- configured: true,
571
- repos: await listLookupRepositories(clients.installer, clients.lookup),
572
- };
535
+ // The crawler files a deployment-wide App's snapshots under accountId "".
536
+ const accountIds = accountId ? [accountId, ""] : [""];
537
+ const snapshots = await deps.cache.listLookupSnapshots(
538
+ accountIds,
539
+ lookup.appId,
540
+ );
541
+ return summarizeLookupSnapshots(
542
+ snapshots,
543
+ (deps.now ?? (() => new Date()))(),
544
+ deps.ttlMs,
545
+ );
573
546
  },
574
547
  };
575
548
  }
@@ -181,6 +181,17 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
181
181
  expect((await service.get("lookup"))?.appId).toBe("900");
182
182
  });
183
183
 
184
+ it("listAccountIds returns each account with Apps of its own once, never the deployment scope", async () => {
185
+ await service.save(lookup);
186
+ expect(await service.listAccountIds()).toEqual([]);
187
+ await service.save({ ...lookup, accountId: acctA });
188
+ await service.save({ ...installer, accountId: acctA });
189
+ await service.save({ ...installer, accountId: acctB });
190
+ expect((await service.listAccountIds()).sort()).toEqual(
191
+ [acctA, acctB].sort(),
192
+ );
193
+ });
194
+
184
195
  it("get(role) without accountId never sees an account row", async () => {
185
196
  await service.save({ ...lookup, accountId: acctA });
186
197
  expect(await service.get("lookup")).toBeNull();
@@ -197,6 +197,16 @@ export class GitHubEnterpriseAppService {
197
197
  return rows.map(toGitHubEnterpriseAppMetadata);
198
198
  }
199
199
 
200
+ /** Ids of the accounts with at least one App of their own (no key material). */
201
+ async listAccountIds(): Promise<string[]> {
202
+ const rows = await this.prisma.gitHubEnterpriseApp.findMany({
203
+ where: { accountId: { not: null } },
204
+ select: { accountId: true },
205
+ distinct: ["accountId"],
206
+ });
207
+ return rows.flatMap((r) => (r.accountId ? [r.accountId] : []));
208
+ }
209
+
200
210
  /** Delete the app at exactly this (accountId, role). No-ops if absent. */
201
211
  async delete(
202
212
  role: GitHubEnterpriseAppRole,
@@ -2,17 +2,24 @@
2
2
  * admin/src/github-installation-wiring.ts
3
3
  * Composition of the installation repos list and GitHub Sync services for
4
4
  * admin boot, from the stored installer App and an optional host-supplied
5
- * OpenWorkPort. The agent App id comes from each agent's own stored
5
+ * OpenWorkPort, plus the GitHub cache refresher's target discovery over the
6
+ * stored Apps (GLC-1.4). The agent App id comes from each agent's own stored
6
7
  * GH_APP_ID; without an open-work port nothing is listed or blocked.
7
8
  */
8
9
 
9
10
  import type { PrismaClient } from "../prisma/client/client.ts";
10
11
  import type { AgentEnvService } from "./agent-envs.ts";
11
12
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
13
+ import type { Clock } from "./clock.ts";
12
14
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
13
15
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
16
+ import { GithubLookupClient } from "./github-lookup-client.ts";
17
+ import type { CrawlStore } from "./github-repo-crawler.ts";
18
+ import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
19
+ import type { RefreshDiscovery } from "./github-repo-refresher.ts";
14
20
  import {
15
21
  createInstallationPort,
22
+ type InstallationAgentRecord,
16
23
  type InstallationRepoClient,
17
24
  PrismaInstallationAgents,
18
25
  PrismaInstallationAudit,
@@ -126,3 +133,76 @@ export function createGithubSync(
126
133
  ...(deps.openWork ? { openWork: deps.openWork } : {}),
127
134
  });
128
135
  }
136
+
137
+ export interface StoredAppDiscoveryDeps {
138
+ prisma: PrismaClient;
139
+ appService: Pick<
140
+ GitHubEnterpriseAppService,
141
+ "get" | "getPrivateKey" | "listAccountIds"
142
+ >;
143
+ /** Reads each agent's stored GH_APP_ID (its own GitHub App). */
144
+ agentEnv: Pick<AgentEnvService, "getConfigBundle">;
145
+ store: CrawlStore;
146
+ clock: Clock;
147
+ /** Test seams; default to the real GitHub API. */
148
+ fetchFn?: typeof fetch;
149
+ apiBase?: string;
150
+ }
151
+
152
+ /**
153
+ * The refresher's target discovery (GLC-1.4) over the stored Apps, the
154
+ * agents table and real GitHub clients. Lives here, beside the other
155
+ * key-bearing installation wiring, so the private key stays in the
156
+ * allowlisted modules.
157
+ */
158
+ export function createStoredAppRefreshDiscovery(
159
+ deps: StoredAppDiscoveryDeps,
160
+ ): RefreshDiscovery {
161
+ const { prisma, appService, fetchFn, apiBase, clock } = deps;
162
+ const now = () => clock.now();
163
+ const installer = lazyInstallerClient({ appService, fetchFn, apiBase, now });
164
+ const agentsPort = new PrismaInstallationAgents(prisma, deps.agentEnv);
165
+ // Reuse a client (and its cached installation tokens) until the App changes.
166
+ const lookupClients = new Map<string, GithubLookupClient>();
167
+ return createRefreshDiscovery({
168
+ listAppScopes: () => appService.listAccountIds(),
169
+ async listAgents() {
170
+ const rows = await prisma.agent.findMany({ select: { id: true } });
171
+ const out: InstallationAgentRecord[] = [];
172
+ for (const { id } of rows) {
173
+ const rec = await agentsPort.get(id);
174
+ if (rec) out.push(rec);
175
+ }
176
+ return out;
177
+ },
178
+ async lookupApp(scope) {
179
+ const meta = await appService.get("lookup", scope);
180
+ if (!meta) return null;
181
+ const privateKey = await appService.getPrivateKey("lookup", scope);
182
+ if (!privateKey) return null;
183
+ const cacheKey = `${meta.accountId ?? ""}|${meta.appId}|${meta.updatedAt.getTime()}`;
184
+ let client = lookupClients.get(cacheKey);
185
+ if (!client) {
186
+ client = new GithubLookupClient({
187
+ appId: meta.appId,
188
+ privateKey,
189
+ apiBase,
190
+ fetchFn,
191
+ now,
192
+ });
193
+ lookupClients.set(cacheKey, client);
194
+ }
195
+ return { accountId: meta.accountId ?? null, appId: meta.appId, client };
196
+ },
197
+ async installerOrgs(scope) {
198
+ const meta = await appService.get("installer", scope);
199
+ if (!meta?.enterpriseSlug) return null;
200
+ return (await installer.listInstallableOrganizations(scope)).map(
201
+ (o) => o.login,
202
+ );
203
+ },
204
+ installer,
205
+ store: deps.store,
206
+ clock,
207
+ });
208
+ }