@app-vitals/agent-admin 1.81.0 → 1.83.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.
@@ -430,6 +430,77 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
430
430
  );
431
431
  });
432
432
 
433
+ describe("cached snapshot states (GLC-2.2)", () => {
434
+ const seeded = (over: Record<string, unknown>) => ({
435
+ appId: 123,
436
+ orgs: [
437
+ {
438
+ org: "acme",
439
+ repos: [{ fullName: "acme/api" }, { fullName: "acme/web" }],
440
+ },
441
+ ],
442
+ ...over,
443
+ });
444
+ const page = async (view: unknown) => {
445
+ const { app, calls } = setup({
446
+ repos: ["acme/api", "other/gone"],
447
+ agentsApi: () => json(view),
448
+ });
449
+ const html = await (await get(app, "/configuration")).text();
450
+ return { html, calls };
451
+ };
452
+
453
+ it("complete: shows synced-at and N of M, and the coverage warning", async () => {
454
+ const { html, calls } = await page(
455
+ seeded({
456
+ complete: true,
457
+ syncedAt: "2026-11-20T10:00:00.000Z",
458
+ reposSeen: 2,
459
+ totalCount: 2,
460
+ }),
461
+ );
462
+ expect(html).toContain('data-installation-sync="complete"');
463
+ expect(html).toContain("2 of 2 repos");
464
+ expect(html).toContain("2026-11-20");
465
+ expect(html).toContain('id="repos-uncovered-warning"');
466
+ // The page reads the cached view only: no GitHub-backed route.
467
+ expect(
468
+ calls.every((c) => c.path.endsWith("/github-installation/repos")),
469
+ ).toBe(true);
470
+ });
471
+
472
+ it("partial: shows N of M and suppresses the coverage warning", async () => {
473
+ const { html } = await page(
474
+ seeded({ complete: false, reposSeen: 1, totalCount: 3 }),
475
+ );
476
+ expect(html).toContain('data-installation-sync="incomplete"');
477
+ expect(html).toContain("1 of 3 repos");
478
+ expect(html).not.toContain("repos-uncovered-warning");
479
+ expect(html).not.toContain('data-uncovered="1"');
480
+ });
481
+
482
+ it("errored: shows the last error and rate-limit reset, no warning", async () => {
483
+ const { html } = await page(
484
+ seeded({
485
+ complete: false,
486
+ reposSeen: 0,
487
+ lastError: "GitHub said <no>",
488
+ rateLimitResetAt: "2026-11-20T11:00:00.000Z",
489
+ }),
490
+ );
491
+ expect(html).toContain("GitHub said &lt;no&gt;");
492
+ expect(html).toContain("rate limit resets");
493
+ expect(html).toContain("2026-11-20");
494
+ expect(html).not.toContain("repos-uncovered-warning");
495
+ });
496
+
497
+ it("a view with no sync fields (older API) still warns", async () => {
498
+ const { html } = await page(seeded({}));
499
+ expect(html).toContain('id="repos-uncovered-warning"');
500
+ expect(html).not.toContain("data-installation-sync");
501
+ });
502
+ });
503
+
433
504
  it("confirm step lists the affected open work", async () => {
434
505
  const { app, calls } = setup({ repos: ["acme/web"], agentsApi: api });
435
506
  const res = await get(app, "/repos/removal-confirm?repo=acme/web");
@@ -18,7 +18,10 @@ import {
18
18
  renderGithubUsernameRow,
19
19
  } from "./admin-ui-github-identity-pages.ts";
20
20
  import {
21
+ type InstallationSyncView,
22
+ installationSnapshotComplete,
21
23
  renderGithubSyncCard,
24
+ renderInstallationSyncStatus,
22
25
  renderUncoveredBadge,
23
26
  uncoveredRepos,
24
27
  } from "./admin-ui-installation-repos-pages.ts";
@@ -1037,6 +1040,7 @@ export function agentSectionPath(
1037
1040
  export const AGENT_POST_SECTIONS: Readonly<Record<string, AgentSection>> = {
1038
1041
  "/github-username": "access",
1039
1042
  "/github-sync/apply-confirmed": "access",
1043
+ "/github-cache/refresh": "access",
1040
1044
  "/github-orgs/:org/install": "access",
1041
1045
  "/repos/remove-confirmed": "configuration",
1042
1046
  "/envs": "configuration",
@@ -1156,6 +1160,12 @@ export function renderAgentDetailPage(
1156
1160
  * could be listed. Absent means unknown: no coverage warning is shown.
1157
1161
  */
1158
1162
  installationRepos?: readonly string[];
1163
+ /**
1164
+ * GLC-2.2: sync detail of the cached installation view (synced-at, N of M,
1165
+ * last error, rate-limit reset). When `complete` is false the coverage
1166
+ * warning is suppressed.
1167
+ */
1168
+ installationSync?: InstallationSyncView;
1159
1169
  /**
1160
1170
  * ATP-2.4: present when agent templates are available. Turns on the
1161
1171
  * inherited/custom badges, the detach/reattach toggle and the per-item
@@ -1723,7 +1733,9 @@ export function renderAgentDetailPage(
1723
1733
  })();
1724
1734
  </script>`;
1725
1735
  const uncovered = new Set(
1726
- opts?.installationRepos
1736
+ opts?.installationRepos &&
1737
+ (!opts.installationSync ||
1738
+ installationSnapshotComplete(opts.installationSync))
1727
1739
  ? uncoveredRepos(agent.repos, opts.installationRepos)
1728
1740
  : [],
1729
1741
  );
@@ -1737,6 +1749,7 @@ export function renderAgentDetailPage(
1737
1749
  <button type="submit" class="btn btn-primary">Add</button>
1738
1750
  </div>
1739
1751
  </form>
1752
+ ${opts?.installationSync ? renderInstallationSyncStatus(opts.installationSync) : ""}
1740
1753
  <div class="data-table-wrapper">
1741
1754
  <table class="data-table">
1742
1755
  <thead>
package/src/admin-ui.ts CHANGED
@@ -62,6 +62,7 @@ import {
62
62
  type GithubSyncApplyView,
63
63
  type GithubSyncPreviewView,
64
64
  type InstallationReposView,
65
+ type InstallationSyncView,
65
66
  type OpenWorkView,
66
67
  type RepoRemovalPreviewView,
67
68
  renderInstallationReposBody,
@@ -2138,6 +2139,35 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2138
2139
  );
2139
2140
  });
2140
2141
 
2142
+ // GLC-2.4: fire-and-forget Refresh. Proxies the 202 API route and redirects
2143
+ // at once; a reload of the page shows progress.
2144
+ app.post("/admin/agents/:id/github-cache/refresh", requireAuth, async (c) => {
2145
+ const agentId = c.req.param("id");
2146
+ if (!c.var.isAdmin || !githubEnterpriseApi) {
2147
+ return new Response("Forbidden", { status: 403 });
2148
+ }
2149
+ const res = await callApi(
2150
+ c,
2151
+ githubEnterpriseApi,
2152
+ "/github-enterprise/refresh",
2153
+ {
2154
+ method: "POST",
2155
+ },
2156
+ );
2157
+ if (!res?.ok) {
2158
+ return c.redirect(
2159
+ agentSectionPath(agentId, "access", {
2160
+ error: await gheError(res, "Could not request a refresh."),
2161
+ }),
2162
+ 302,
2163
+ );
2164
+ }
2165
+ return c.redirect(
2166
+ `${agentSectionPath(agentId, "access")}?success=github_refresh_requested`,
2167
+ 302,
2168
+ );
2169
+ });
2170
+
2141
2171
  app.post(
2142
2172
  "/admin/agents/:id/github-orgs/:org/install",
2143
2173
  requireAuth,
@@ -2223,7 +2253,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2223
2253
  // No installation matched the numeric GH_APP_ID. If the agent still has an
2224
2254
  // installation by slug (the Installations card), the id is probably wrong.
2225
2255
  let appIdMismatch = false;
2226
- if (view.orgs.length === 0) {
2256
+ if (view.orgs.every((o) => o.repos.length === 0)) {
2227
2257
  const snap = await callApi(
2228
2258
  c,
2229
2259
  agentsApi,
@@ -2466,11 +2496,13 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2466
2496
  ? "GitHub username saved."
2467
2497
  : successParam === "github_username_cleared"
2468
2498
  ? "GitHub username cleared."
2469
- : successParam === "github_app_installed"
2470
- ? "Agent app installed."
2471
- : successParam === "github_app_already_installed"
2472
- ? "The agent app was already installed on that organization."
2473
- : undefined;
2499
+ : successParam === "github_refresh_requested"
2500
+ ? "Refresh requested. Reload the page to see progress."
2501
+ : successParam === "github_app_installed"
2502
+ ? "Agent app installed."
2503
+ : successParam === "github_app_already_installed"
2504
+ ? "The agent app was already installed on that organization."
2505
+ : undefined;
2474
2506
  const warningParam = c.req.query("warning");
2475
2507
  const warning =
2476
2508
  warningParam === "restrict_slack_no_members"
@@ -2512,6 +2544,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2512
2544
  // list's coverage warning. Best effort: unknown means no warning.
2513
2545
  const enterpriseConfigured = await githubEnterpriseConfigured(c);
2514
2546
  let installationRepos: string[] | undefined;
2547
+ let installationSync: InstallationSyncView | undefined;
2515
2548
  if (
2516
2549
  enterpriseConfigured &&
2517
2550
  agentsApi &&
@@ -2524,9 +2557,22 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2524
2557
  );
2525
2558
  if (res?.ok) {
2526
2559
  try {
2527
- installationRepos = (
2528
- (await res.json()) as InstallationReposView
2529
- ).orgs.flatMap((o) => o.repos.map((r) => r.fullName));
2560
+ const view = (await res.json()) as InstallationReposView;
2561
+ installationRepos = view.orgs.flatMap((o) =>
2562
+ o.repos.map((r) => r.fullName),
2563
+ );
2564
+ installationSync = {
2565
+ complete: view.complete,
2566
+ syncedAt: view.syncedAt,
2567
+ reposSeen: view.reposSeen,
2568
+ totalCount: view.totalCount,
2569
+ lastError: view.lastError,
2570
+ rateLimitResetAt: view.rateLimitResetAt,
2571
+ attempts: view.attempts,
2572
+ nextAttemptAt: view.nextAttemptAt,
2573
+ leaseHolder: view.leaseHolder,
2574
+ lastTickAt: view.lastTickAt,
2575
+ };
2530
2576
  } catch {
2531
2577
  // unknown: no coverage warning
2532
2578
  }
@@ -2562,6 +2608,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2562
2608
  agent.accountId ?? null,
2563
2609
  ),
2564
2610
  ...(installationRepos ? { installationRepos } : {}),
2611
+ ...(installationSync ? { installationSync } : {}),
2565
2612
  ...(agentsApi
2566
2613
  ? { template: { detached: agent.templateDetached === true } }
2567
2614
  : {}),
@@ -7303,6 +7303,9 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7303
7303
  agentRepos?: string[];
7304
7304
  pushable?: string[];
7305
7305
  openWork?: Partial<OpenWorkPort> | null;
7306
+ /** Seeded GLC cache rows read by the list route. */
7307
+ snapshots?: Array<Record<string, unknown>>;
7308
+ accessRows?: Array<Record<string, unknown>>;
7306
7309
  } = {},
7307
7310
  ) {
7308
7311
  const audits: Array<Record<string, unknown>> = [];
@@ -7376,6 +7379,12 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7376
7379
  state.repos = args.data.repos;
7377
7380
  },
7378
7381
  },
7382
+ gitHubRepoSnapshot: {
7383
+ findMany: async () => opts.snapshots ?? [],
7384
+ },
7385
+ gitHubRepoAccess: {
7386
+ findMany: async () => opts.accessRows ?? [],
7387
+ },
7379
7388
  gitHubReconcileAudit: {
7380
7389
  create: async (args: { data: Record<string, unknown> }) => {
7381
7390
  events.push(["audit"]);
@@ -7459,26 +7468,96 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7459
7468
  body: JSON.stringify(body),
7460
7469
  });
7461
7470
 
7462
- it("GET lists repos per org with push hints from the access lookup", async () => {
7463
- const { app } = setup();
7471
+ const T0 = new Date("2026-11-20T10:00:00.000Z");
7472
+ const seededSnapshot = (over: Record<string, unknown> = {}) => ({
7473
+ org: "acme-eng",
7474
+ completedAt: T0,
7475
+ totalCount: 2,
7476
+ lastError: null,
7477
+ rateLimitResetAt: null,
7478
+ repos: [{ fullName: "acme-eng/repo-1" }, { fullName: "acme-eng/repo-2" }],
7479
+ ...over,
7480
+ });
7481
+ const accessRow = (repo: string, status: string, canPush = false) => ({
7482
+ repo,
7483
+ status,
7484
+ canPush,
7485
+ });
7486
+
7487
+ it("GET reads the cache: repos with push hints from cached access rows, no GitHub call", async () => {
7488
+ const { app, gh } = setup({
7489
+ snapshots: [seededSnapshot()],
7490
+ accessRows: [
7491
+ accessRow("repo-1", "ok", true),
7492
+ accessRow("repo-2", "ok", false),
7493
+ ],
7494
+ });
7464
7495
  const res = await app.request(url(), { headers: asAdmin });
7465
7496
  expect(res.status).toBe(200);
7466
7497
  expect(await res.json()).toEqual({
7467
7498
  appId: 777,
7499
+ complete: true,
7500
+ reposSeen: 2,
7501
+ totalCount: 2,
7502
+ syncedAt: T0.toISOString(),
7468
7503
  orgs: [
7469
7504
  {
7470
7505
  org: "acme-eng",
7506
+ complete: true,
7507
+ reposSeen: 2,
7508
+ totalCount: 2,
7509
+ syncedAt: T0.toISOString(),
7471
7510
  repos: [
7472
7511
  { fullName: "acme-eng/repo-1", userCanPush: true },
7473
- { fullName: "acme-eng/repo-2" },
7512
+ { fullName: "acme-eng/repo-2", userCanPush: false },
7474
7513
  ],
7475
7514
  },
7476
7515
  ],
7477
7516
  });
7517
+ expect(gh).toEqual([]);
7518
+ });
7519
+
7520
+ it("GET omits hints for a partial or errored cache, never reporting false", async () => {
7521
+ for (const snapshots of [
7522
+ [seededSnapshot({ completedAt: null, totalCount: 5 })],
7523
+ [seededSnapshot({ completedAt: null, lastError: "boom" })],
7524
+ ]) {
7525
+ const { app, gh } = setup({
7526
+ snapshots,
7527
+ accessRows: [accessRow("repo-1", "ok", true)],
7528
+ });
7529
+ const body = (await (
7530
+ await app.request(url(), { headers: asAdmin })
7531
+ ).json()) as {
7532
+ complete: boolean;
7533
+ orgs: { repos: Record<string, unknown>[] }[];
7534
+ };
7535
+ expect(body.complete).toBe(false);
7536
+ expect(body.orgs[0]?.repos.map((r) => "userCanPush" in r)).toEqual([
7537
+ false,
7538
+ false,
7539
+ ]);
7540
+ expect(gh).toEqual([]);
7541
+ }
7542
+ const errored = setup({
7543
+ snapshots: [seededSnapshot()],
7544
+ accessRows: [
7545
+ accessRow("repo-1", "ok", true),
7546
+ accessRow("repo-2", "error"),
7547
+ ],
7548
+ });
7549
+ const eb = (await (
7550
+ await errored.app.request(url(), { headers: asAdmin })
7551
+ ).json()) as { orgs: { repos: Record<string, unknown>[] }[] };
7552
+ expect(eb.orgs[0]?.repos.some((r) => r.userCanPush === false)).toBe(false);
7478
7553
  });
7479
7554
 
7480
- it("GET omits the hint entirely for an agent with no bound username", async () => {
7481
- const { app } = setup({ username: null });
7555
+ it("GET with no bound username omits hints and makes no GitHub call", async () => {
7556
+ const { app, gh } = setup({
7557
+ username: null,
7558
+ snapshots: [seededSnapshot()],
7559
+ accessRows: [accessRow("repo-1", "ok", true)],
7560
+ });
7482
7561
  const body = (await (
7483
7562
  await app.request(url(), { headers: asAdmin })
7484
7563
  ).json()) as {
@@ -7488,6 +7567,7 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7488
7567
  false,
7489
7568
  false,
7490
7569
  ]);
7570
+ expect(gh).toEqual([]);
7491
7571
  });
7492
7572
 
7493
7573
  it("the direct add and remove routes are gone", async () => {
package/src/agents-api.ts CHANGED
@@ -641,18 +641,65 @@ const RepoFullNameSchema = z
641
641
  .string()
642
642
  .regex(/^[^/\s]+\/[^/\s]+$/, "must be owner/repo");
643
643
 
644
+ const InstallationSyncDetailShape = {
645
+ complete: z.boolean().optional().openapi({
646
+ description:
647
+ "Whether the cached crawl is complete. While false the list may be partial.",
648
+ }),
649
+ syncedAt: z
650
+ .string()
651
+ .optional()
652
+ .openapi({ description: "When the completed crawl finished (ISO 8601)." }),
653
+ reposSeen: z
654
+ .number()
655
+ .int()
656
+ .optional()
657
+ .openapi({ description: "Repos in the cache (the N of 'N of M')." }),
658
+ totalCount: z
659
+ .number()
660
+ .int()
661
+ .optional()
662
+ .openapi({ description: "GitHub's repo count, when known (the M)." }),
663
+ lastError: z.string().optional(),
664
+ rateLimitResetAt: z
665
+ .string()
666
+ .optional()
667
+ .openapi({ description: "When the GitHub rate limit resets (ISO 8601)." }),
668
+ attempts: z
669
+ .number()
670
+ .int()
671
+ .optional()
672
+ .openapi({ description: "Failed refresh attempts; absent when zero." }),
673
+ nextAttemptAt: z
674
+ .string()
675
+ .optional()
676
+ .openapi({
677
+ description: "Next refresh attempt while backing off (ISO 8601).",
678
+ }),
679
+ leaseHolder: z
680
+ .string()
681
+ .optional()
682
+ .openapi({ description: "Holder of a live refresh lease, if any." }),
683
+ lastTickAt: z
684
+ .string()
685
+ .optional()
686
+ .openapi({ description: "Last refresh tick on the snapshot (ISO 8601)." }),
687
+ };
688
+
644
689
  const GithubInstallationReposListSchema = z
645
690
  .object({
646
691
  appId: z.number().int(),
692
+ ...InstallationSyncDetailShape,
647
693
  orgs: z.array(
648
694
  z.object({
649
695
  org: z.string(),
696
+ ...InstallationSyncDetailShape,
650
697
  repos: z.array(
651
698
  z.object({
652
699
  fullName: z.string(),
653
700
  userCanPush: z.boolean().optional().openapi({
654
701
  description:
655
- "Whether the agent's bound GitHub user can push. Omitted when no username is bound or the org's access lookup is incomplete; never reported as false for unknown.",
702
+ "Whether the agent's bound GitHub user can push, from cached access rows. Omitted when no username is bound or the org's access data is incomplete (a missing or errored pair is never reported as false).",
656
703
  }),
657
704
  }),
658
705
  ),
@@ -1793,7 +1840,7 @@ const listInstallationReposRoute = createRoute({
1793
1840
  path: "/agents/{id}/github-installation/repos",
1794
1841
  summary: "List the repos on the agent App's installation",
1795
1842
  description:
1796
- "Platform-admin only (session members, ops keys and agent keys get 403). Per org the agent's own GitHub App (its GH_APP_ID) is installed on, lists the installation's repos. When the agent has a bound githubUsername, each repo carries `userCanPush` from the access lookup only when that org's lookup result is complete; otherwise the field is omitted (never false). 404 for an unknown agent; 422 when the agent has no GH_APP_ID.",
1843
+ "Platform-admin only (session members, ops keys and agent keys get 403). Per org the agent's own GitHub App (its GH_APP_ID) is installed on, lists the installation's repos from the background-synced cache; it makes no GitHub call. Sync detail (`complete`, `syncedAt`, `reposSeen`, `totalCount`, `lastError`, `rateLimitResetAt`) is reported per org and overall. When the agent has a bound githubUsername, each repo carries `userCanPush` from cached access rows only when that org's snapshot is complete and every repo has an answer; otherwise the field is omitted (never false). 404 for an unknown agent; 422 when the agent has no GH_APP_ID.",
1797
1844
  request: { params: AgentIdParamSchema },
1798
1845
  responses: {
1799
1846
  200: {
@@ -3453,7 +3500,8 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3453
3500
  return c.json({ appId: result.appId, orgs: [] }, 200);
3454
3501
  }
3455
3502
  if (result.status !== "ok") return installationFailure(agentId, result);
3456
- return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3503
+ const { status: _status, ...body } = result;
3504
+ return c.json(body, 200);
3457
3505
  });
3458
3506
 
3459
3507
  // /agents/:id/github-sync/{preview,apply} — IRM-3.1. Platform admin only;
@@ -15,6 +15,7 @@ import type {
15
15
  GitHubEnterpriseAppRole,
16
16
  SaveGitHubEnterpriseAppInput,
17
17
  } from "./github-enterprise-apps.ts";
18
+ import type { GithubRefreshAction } from "./github-refresh-action.ts";
18
19
 
19
20
  interface CassetteEntry {
20
21
  status: number;
@@ -117,6 +118,7 @@ function build(
117
118
  opts: {
118
119
  routes?: Record<string, string>;
119
120
  agents?: Record<string, Record<string, string> | null>;
121
+ refreshAction?: GithubRefreshAction;
120
122
  } = {},
121
123
  ) {
122
124
  const appService = fakeAppService();
@@ -151,6 +153,7 @@ function build(
151
153
  "root:tok-admin:*,ro:tok-read:platform.read,bot:tok-agent:agent-1",
152
154
  ),
153
155
  agentTokenService: { validate: async () => null },
156
+ ...(opts.refreshAction ? { refreshAction: opts.refreshAction } : {}),
154
157
  fetchFn,
155
158
  apiBase: "https://ghe.test",
156
159
  });
@@ -175,6 +178,7 @@ describe("auth", () => {
175
178
  ["DELETE", "/github-enterprise/apps/installer", ""],
176
179
  ["POST", "/github-enterprise/apps/installer/validate", ""],
177
180
  ["GET", "/github-enterprise/orgs", ""],
181
+ ["POST", "/github-enterprise/refresh", ""],
178
182
  [
179
183
  "POST",
180
184
  "/github-enterprise/orgs/org-1/install",
@@ -916,3 +920,72 @@ describe("account-scoped routes", () => {
916
920
  expect(res.status).toBe(403);
917
921
  });
918
922
  });
923
+
924
+ describe("refresh action (GLC-2.4)", () => {
925
+ const stub = () => {
926
+ const calls: string[] = [];
927
+ const action: GithubRefreshAction = {
928
+ requestRefresh: async () => {
929
+ calls.push("refresh");
930
+ return { snapshots: 2, accessPairs: 1 };
931
+ },
932
+ };
933
+ return { calls, action };
934
+ };
935
+
936
+ it("returns 202 for an admin and makes no GitHub call", async () => {
937
+ const { calls: marks, action } = stub();
938
+ const h = build({ refreshAction: action });
939
+ const res = await h.app.request("/github-enterprise/refresh", {
940
+ method: "POST",
941
+ headers: ADMIN,
942
+ });
943
+ expect(res.status).toBe(202);
944
+ expect(await res.json()).toEqual({
945
+ status: "accepted",
946
+ snapshots: 2,
947
+ accessPairs: 1,
948
+ });
949
+ expect(marks).toEqual(["refresh"]);
950
+ expect(h.calls).toEqual([]);
951
+ });
952
+
953
+ it("is 503 when refresh is not wired", async () => {
954
+ const h = build();
955
+ const res = await h.app.request("/github-enterprise/refresh", {
956
+ method: "POST",
957
+ headers: ADMIN,
958
+ });
959
+ expect(res.status).toBe(503);
960
+ expect(h.calls).toEqual([]);
961
+ });
962
+
963
+ it("marks stale after an App is saved, and a failed mark does not fail the save", async () => {
964
+ const { calls: marks, action } = stub();
965
+ const h = build({ refreshAction: action });
966
+ const res = await h.app.request("/github-enterprise/apps/installer", {
967
+ method: "PUT",
968
+ headers: JSON_ADMIN,
969
+ body: JSON.stringify(installerBody),
970
+ });
971
+ expect(res.status).toBe(200);
972
+ expect(marks).toEqual(["refresh"]);
973
+
974
+ const failing = build({
975
+ refreshAction: {
976
+ requestRefresh: async () => {
977
+ throw new Error("db down");
978
+ },
979
+ },
980
+ });
981
+ const res2 = await failing.app.request(
982
+ "/github-enterprise/apps/installer",
983
+ {
984
+ method: "PUT",
985
+ headers: JSON_ADMIN,
986
+ body: JSON.stringify(installerBody),
987
+ },
988
+ );
989
+ expect(res2.status).toBe(200);
990
+ });
991
+ });
@@ -55,6 +55,7 @@ import {
55
55
  type GithubLookupService,
56
56
  summarizeLookupSnapshots,
57
57
  } from "./github-lookup-repositories.ts";
58
+ import type { GithubRefreshAction } from "./github-refresh-action.ts";
58
59
  import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
59
60
  import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
60
61
  import { ErrorSchema } from "./openapi-schemas.ts";
@@ -72,6 +73,11 @@ export interface GithubEnterpriseApiDeps {
72
73
  sessionSecret: string;
73
74
  adminApiKeys?: Map<string, AdminApiKey>;
74
75
  agentTokenService: Pick<AgentTokenService, "validate">;
76
+ /**
77
+ * GLC-2.4: marks the GitHub cache stale. Backs POST /github-enterprise/refresh
78
+ * and runs (best effort) after an App is saved or an agent App is installed.
79
+ */
80
+ refreshAction?: GithubRefreshAction;
75
81
  /** Test seams; default to the real GitHub API. */
76
82
  fetchFn?: typeof fetch;
77
83
  apiBase?: string;
@@ -352,6 +358,31 @@ const orgsRoute = createRoute({
352
358
  },
353
359
  });
354
360
 
361
+ const refreshRoute = createRoute({
362
+ method: "post",
363
+ path: "/github-enterprise/refresh",
364
+ tags,
365
+ summary: "Request a refresh of the GitHub cache",
366
+ description:
367
+ "Admin-only. Marks the cached GitHub repo lists stale and clears retry waits so the background refresher works them next, then returns at once. It makes no GitHub call and does not wait for the refresher; reload the page to see progress. The refresher still honours its per-org lease and rate-limit window.",
368
+ responses: {
369
+ 202: {
370
+ description: "Refresh requested",
371
+ content: {
372
+ "application/json": {
373
+ schema: z.object({
374
+ status: z.literal("accepted"),
375
+ snapshots: z.number().int(),
376
+ accessPairs: z.number().int(),
377
+ }),
378
+ },
379
+ },
380
+ },
381
+ 503: { description: "Refresh is not available", ...jsonError },
382
+ ...errorResponses,
383
+ },
384
+ });
385
+
355
386
  const installRoute = createRoute({
356
387
  method: "post",
357
388
  path: "/github-enterprise/orgs/{org}/install",
@@ -721,9 +752,28 @@ export function createGithubEnterpriseApp(
721
752
  enterpriseSlug: body.enterpriseSlug ?? null,
722
753
  privateKey: body.privateKey,
723
754
  });
755
+ await markStaleQuietly();
724
756
  return c.json(serializeApp(saved), 200);
725
757
  });
726
758
 
759
+ /** Best effort: a failed mark never fails the App change that caused it. */
760
+ const markStaleQuietly = async () => {
761
+ try {
762
+ await deps.refreshAction?.requestRefresh();
763
+ } catch (err) {
764
+ console.error("[github-enterprise] cache refresh mark failed:", err);
765
+ }
766
+ };
767
+
768
+ app.openapi(refreshRoute, async (c) => {
769
+ requireAdmin(c);
770
+ if (!deps.refreshAction) {
771
+ return c.json({ error: "GitHub cache refresh is not available" }, 503);
772
+ }
773
+ const res = await deps.refreshAction.requestRefresh();
774
+ return c.json({ status: "accepted" as const, ...res }, 202);
775
+ });
776
+
727
777
  app.openapi(deleteRoute, async (c) => {
728
778
  requireAdmin(c);
729
779
  await appService.delete(
@@ -919,6 +969,7 @@ export function createGithubEnterpriseApp(
919
969
  repositorySelection: body.repositorySelection,
920
970
  ...(body.repositories ? { repositories: body.repositories } : {}),
921
971
  });
972
+ await markStaleQuietly();
922
973
  return c.json(
923
974
  {
924
975
  org,
@@ -14,9 +14,11 @@ import type { Clock } from "./clock.ts";
14
14
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
15
15
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
16
16
  import { GithubLookupClient } from "./github-lookup-client.ts";
17
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
17
18
  import type { CrawlStore } from "./github-repo-crawler.ts";
18
19
  import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
19
20
  import type { RefreshDiscovery } from "./github-repo-refresher.ts";
21
+ import { GithubSyncService } from "./github-sync.ts";
20
22
  import {
21
23
  createInstallationPort,
22
24
  type InstallationAgentRecord,
@@ -26,11 +28,10 @@ import {
26
28
  } from "./installation-ports.ts";
27
29
  import {
28
30
  createInstallationReposPort,
29
- type InstalledOrgsClient,
30
- InstallationReposService,
31
31
  type InstallationReposPort,
32
+ InstallationReposService,
33
+ type InstalledOrgsClient,
32
34
  } from "./installation-repos-service.ts";
33
- import { GithubSyncService } from "./github-sync.ts";
34
35
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
35
36
 
36
37
  export interface GithubInstallationWiringDeps {
@@ -110,6 +111,7 @@ export function createGithubInstallationRepos(
110
111
  installation:
111
112
  deps.installationRepos ??
112
113
  createInstallationReposPort(createInstallationPort(client), client),
114
+ cache: new GitHubRepoCacheService(deps.prisma),
113
115
  });
114
116
  }
115
117