@app-vitals/agent-admin 1.80.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.80.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.80.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,9 +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
-
118
119
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
120
+ import {
121
+ GithubRepoRefresher,
122
+ resolveRefreshConfig,
123
+ } from "./github-repo-refresher.ts";
119
124
  import { PrincipalLookupService } from "./principal-lookup.ts";
120
125
  import { createPrincipalsApp } from "./principals-api.ts";
121
126
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
@@ -194,6 +199,9 @@ export async function startAdmin(
194
199
  prisma,
195
200
  makeStrictTokenCrypto(),
196
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);
197
205
 
198
206
  // Construct TokenCrypto — reads SHIPWRIGHT_ENCRYPTION_KEY at call time
199
207
  const crypto = makeTokenCrypto();
@@ -423,7 +431,7 @@ export async function startAdmin(
423
431
  provisioner,
424
432
  githubLookup: createGithubLookupService({
425
433
  appService: githubEnterpriseAppService,
426
- cache: new GitHubRepoCacheService(prisma),
434
+ cache: githubRepoCache,
427
435
  }),
428
436
  },
429
437
  };
@@ -844,6 +852,38 @@ export async function startAdmin(
844
852
  );
845
853
  }
846
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
+
847
887
  // Extension background passes (AEP-2.1) — after every platform sweeper,
848
888
  // same "registered here, never inside an app factory" rule.
849
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: [] });
@@ -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
+ }
@@ -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(
@@ -194,6 +194,17 @@ export class GitHubRepoCacheService {
194
194
  });
195
195
  }
196
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
+
197
208
  /**
198
209
  * Delete repos last seen before the snapshot's crawlStartedAt. Returns the
199
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
+ });