@app-vitals/agent-admin 1.82.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.
@@ -3551,6 +3551,22 @@
3551
3551
  "type": "string",
3552
3552
  "description": "When the GitHub rate limit resets (ISO 8601)."
3553
3553
  },
3554
+ "attempts": {
3555
+ "type": "integer",
3556
+ "description": "Failed refresh attempts; absent when zero."
3557
+ },
3558
+ "nextAttemptAt": {
3559
+ "type": "string",
3560
+ "description": "Next refresh attempt while backing off (ISO 8601)."
3561
+ },
3562
+ "leaseHolder": {
3563
+ "type": "string",
3564
+ "description": "Holder of a live refresh lease, if any."
3565
+ },
3566
+ "lastTickAt": {
3567
+ "type": "string",
3568
+ "description": "Last refresh tick on the snapshot (ISO 8601)."
3569
+ },
3554
3570
  "orgs": {
3555
3571
  "type": "array",
3556
3572
  "items": {
@@ -3582,6 +3598,22 @@
3582
3598
  "type": "string",
3583
3599
  "description": "When the GitHub rate limit resets (ISO 8601)."
3584
3600
  },
3601
+ "attempts": {
3602
+ "type": "integer",
3603
+ "description": "Failed refresh attempts; absent when zero."
3604
+ },
3605
+ "nextAttemptAt": {
3606
+ "type": "string",
3607
+ "description": "Next refresh attempt while backing off (ISO 8601)."
3608
+ },
3609
+ "leaseHolder": {
3610
+ "type": "string",
3611
+ "description": "Holder of a live refresh lease, if any."
3612
+ },
3613
+ "lastTickAt": {
3614
+ "type": "string",
3615
+ "description": "Last refresh tick on the snapshot (ISO 8601)."
3616
+ },
3585
3617
  "repos": {
3586
3618
  "type": "array",
3587
3619
  "items": {
@@ -8454,6 +8486,76 @@
8454
8486
  }
8455
8487
  }
8456
8488
  },
8489
+ "/github-enterprise/refresh": {
8490
+ "post": {
8491
+ "tags": [
8492
+ "github-enterprise"
8493
+ ],
8494
+ "summary": "Request a refresh of the GitHub cache",
8495
+ "description": "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.",
8496
+ "responses": {
8497
+ "202": {
8498
+ "description": "Refresh requested",
8499
+ "content": {
8500
+ "application/json": {
8501
+ "schema": {
8502
+ "type": "object",
8503
+ "properties": {
8504
+ "status": {
8505
+ "type": "string",
8506
+ "enum": [
8507
+ "accepted"
8508
+ ]
8509
+ },
8510
+ "snapshots": {
8511
+ "type": "integer"
8512
+ },
8513
+ "accessPairs": {
8514
+ "type": "integer"
8515
+ }
8516
+ },
8517
+ "required": [
8518
+ "status",
8519
+ "snapshots",
8520
+ "accessPairs"
8521
+ ]
8522
+ }
8523
+ }
8524
+ }
8525
+ },
8526
+ "401": {
8527
+ "description": "Unauthorized",
8528
+ "content": {
8529
+ "application/json": {
8530
+ "schema": {
8531
+ "$ref": "#/components/schemas/Error"
8532
+ }
8533
+ }
8534
+ }
8535
+ },
8536
+ "403": {
8537
+ "description": "Forbidden (non-admin caller)",
8538
+ "content": {
8539
+ "application/json": {
8540
+ "schema": {
8541
+ "$ref": "#/components/schemas/Error"
8542
+ }
8543
+ }
8544
+ }
8545
+ },
8546
+ "503": {
8547
+ "description": "Refresh is not available",
8548
+ "content": {
8549
+ "application/json": {
8550
+ "schema": {
8551
+ "$ref": "#/components/schemas/Error"
8552
+ }
8553
+ }
8554
+ }
8555
+ }
8556
+ }
8557
+ }
8558
+ },
8457
8559
  "/github-enterprise/apps/{role}/validate": {
8458
8560
  "post": {
8459
8561
  "tags": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.82.0",
3
+ "version": "1.83.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.82.0",
46
+ "@app-vitals/agent-lib": "1.83.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -116,18 +116,19 @@ import {
116
116
  createGithubSync,
117
117
  createStoredAppRefreshDiscovery,
118
118
  } from "./github-installation-wiring.ts";
119
+ import { createGithubRefreshAction } from "./github-refresh-action.ts";
119
120
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
120
121
  import {
121
122
  GithubRepoRefresher,
122
123
  resolveRefreshConfig,
123
124
  } from "./github-repo-refresher.ts";
124
- import { PrincipalLookupService } from "./principal-lookup.ts";
125
- import { createPrincipalsApp } from "./principals-api.ts";
126
125
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
127
126
  import { HttpChatClient } from "./http-chat-client.ts";
128
127
  import { HttpOktaAuthClient } from "./okta-auth-client.ts";
129
128
  import { mountPlatformDoc } from "./platform-doc-route.ts";
130
129
  import { parsePodServiceAccountConfig } from "./pod-service-account-config.ts";
130
+ import { PrincipalLookupService } from "./principal-lookup.ts";
131
+ import { createPrincipalsApp } from "./principals-api.ts";
131
132
  import { createAdminPrismaClient } from "./prisma-client.ts";
132
133
  import { isPushEnabled } from "./push-sender.ts";
133
134
  import { PushService } from "./push-service.ts";
@@ -649,7 +650,17 @@ export async function startAdmin(
649
650
  // 3b'. GitHub Enterprise Apps API — /github-enterprise/* — admin-only,
650
651
  // optional (GHE-1.3). With no rows configured it reports unconfigured
651
652
  // and does nothing else. Strict crypto: no plain-text key storage.
653
+ // GLC-2.4: the Refresh action marks the cache stale (DB only). It asks the
654
+ // refresher (created further down) to re-discover through this hook.
655
+ const githubRefreshConfig = resolveRefreshConfig(process.env);
656
+ let invalidateGithubDiscovery: () => void = () => {};
657
+ const githubRefreshAction = createGithubRefreshAction({
658
+ cache: githubRepoCache,
659
+ stalenessCapMs: githubRefreshConfig.stalenessCapMs,
660
+ onMarked: () => invalidateGithubDiscovery(),
661
+ });
652
662
  const githubEnterpriseApp = createGithubEnterpriseApp({
663
+ refreshAction: githubRefreshAction,
653
664
  appService: githubEnterpriseAppService,
654
665
  agentService,
655
666
  agentEnvService,
@@ -860,7 +871,6 @@ export async function startAdmin(
860
871
  // replica work an org at a time. Without stored GitHub Apps discovery finds
861
872
  // nothing and every tick is idle.
862
873
  {
863
- const githubRefreshConfig = resolveRefreshConfig(process.env);
864
874
  const githubRepoRefresher = new GithubRepoRefresher({
865
875
  discovery: createStoredAppRefreshDiscovery({
866
876
  prisma,
@@ -872,6 +882,7 @@ export async function startAdmin(
872
882
  store: githubRepoCache,
873
883
  config: githubRefreshConfig,
874
884
  });
885
+ invalidateGithubDiscovery = () => githubRepoRefresher.invalidateDiscovery();
875
886
  setInterval(() => {
876
887
  githubRepoRefresher
877
888
  .tick()
@@ -0,0 +1,96 @@
1
+ /**
2
+ * admin/src/admin-ui-github-refresh.smoke.test.ts
3
+ * GLC-2.4: the Refresh button on the agent GitHub card and its POST route:
4
+ * admin only, redirects at once, and makes no GitHub call (the enterprise API
5
+ * is a stub that records paths). No DB, no network.
6
+ */
7
+
8
+ import { beforeAll, describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ makeMockDeps,
12
+ makeSessionCookie,
13
+ } from "./admin-ui.fixtures.ts";
14
+ import { createAdminUIApp } from "./admin-ui.ts";
15
+
16
+ const json = (b: unknown, status = 200) =>
17
+ new Response(JSON.stringify(b), {
18
+ status,
19
+ headers: { "Content-Type": "application/json" },
20
+ });
21
+
22
+ function setup(refreshStatus = 202) {
23
+ const paths: string[] = [];
24
+ const deps = makeMockDeps({
25
+ githubEnterpriseApi: (path: string, init?: RequestInit) => {
26
+ paths.push(`${init?.method ?? "GET"} ${path}`);
27
+ if (path === "/github-enterprise/refresh") {
28
+ return refreshStatus === 202
29
+ ? json({ status: "accepted", snapshots: 1, accessPairs: 0 }, 202)
30
+ : json({ error: "nope" }, refreshStatus);
31
+ }
32
+ return json({
33
+ configured: true,
34
+ installer: { role: "installer" },
35
+ lookup: { role: "lookup" },
36
+ });
37
+ },
38
+ agentsApi: () => json({ appId: 1, orgs: [] }),
39
+ } as never);
40
+ return { app: createAdminUIApp(deps), paths };
41
+ }
42
+
43
+ describe("admin UI — GitHub cache Refresh (GLC-2.4)", () => {
44
+ let admin: string;
45
+ let member: string;
46
+ beforeAll(async () => {
47
+ admin = await makeSessionCookie();
48
+ member = await makeSessionCookie(
49
+ undefined,
50
+ "sub-2",
51
+ "other@example.com",
52
+ false,
53
+ );
54
+ });
55
+ const h = (cookie: string) => ({ Cookie: `admin_session=${cookie}` });
56
+ const refresh = (app: ReturnType<typeof setup>["app"], c = admin) =>
57
+ app.request(`/admin/agents/${AGENT_ID}/github-cache/refresh`, {
58
+ method: "POST",
59
+ headers: h(c),
60
+ redirect: "manual",
61
+ });
62
+
63
+ it("shows the Refresh button on the agent GitHub card", async () => {
64
+ const { app } = setup();
65
+ const html = await (
66
+ await app.request(`/admin/agents/${AGENT_ID}/access`, {
67
+ headers: h(admin),
68
+ })
69
+ ).text();
70
+ expect(html).toContain('id="github-refresh-btn"');
71
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/github-cache/refresh`);
72
+ });
73
+
74
+ it("redirects an admin with 302 after one refresh call", async () => {
75
+ const { app, paths } = setup();
76
+ const res = await refresh(app);
77
+ expect(res.status).toBe(302);
78
+ expect(res.headers.get("location")).toContain(
79
+ "success=github_refresh_requested",
80
+ );
81
+ expect(paths).toEqual(["POST /github-enterprise/refresh"]);
82
+ });
83
+
84
+ it("redirects with an error when the API refuses", async () => {
85
+ const { app } = setup(503);
86
+ const res = await refresh(app);
87
+ expect(res.status).toBe(302);
88
+ expect(res.headers.get("location")).toContain("error=");
89
+ });
90
+
91
+ it("is forbidden for a non-admin and calls nothing", async () => {
92
+ const { app, paths } = setup();
93
+ expect((await refresh(app, member)).status).toBe(403);
94
+ expect(paths).toEqual([]);
95
+ });
96
+ });
@@ -32,6 +32,10 @@ export interface InstallationSyncView {
32
32
  totalCount?: number;
33
33
  lastError?: string;
34
34
  rateLimitResetAt?: string;
35
+ attempts?: number;
36
+ nextAttemptAt?: string;
37
+ leaseHolder?: string;
38
+ lastTickAt?: string;
35
39
  }
36
40
 
37
41
  export interface InstallationReposView extends InstallationSyncView {
@@ -53,7 +57,14 @@ const hasSyncDetail = (v: InstallationSyncView): boolean =>
53
57
  v.syncedAt !== undefined ||
54
58
  v.reposSeen !== undefined ||
55
59
  v.lastError !== undefined ||
56
- v.rateLimitResetAt !== undefined;
60
+ v.rateLimitResetAt !== undefined ||
61
+ v.attempts !== undefined ||
62
+ v.nextAttemptAt !== undefined ||
63
+ v.leaseHolder !== undefined ||
64
+ v.lastTickAt !== undefined;
65
+
66
+ const utc = (iso: string): string =>
67
+ `${escapeHtml(iso.slice(0, 16).replace("T", " "))} UTC`;
57
68
 
58
69
  /**
59
70
  * One-line sync status: synced-at, "N of M repos", last error and the rate-limit
@@ -83,6 +94,14 @@ export function renderInstallationSyncStatus(v: InstallationSyncView): string {
83
94
  `GitHub rate limit resets ${escapeHtml(v.rateLimitResetAt.slice(0, 16).replace("T", " "))} UTC`,
84
95
  );
85
96
  }
97
+ if (v.attempts) {
98
+ parts.push(
99
+ `${v.attempts} failed ${v.attempts === 1 ? "attempt" : "attempts"}`,
100
+ );
101
+ }
102
+ if (v.nextAttemptAt) parts.push(`Next attempt ${utc(v.nextAttemptAt)}`);
103
+ if (v.leaseHolder) parts.push(`Refreshing (${escapeHtml(v.leaseHolder)})`);
104
+ if (v.lastTickAt) parts.push(`Last tick ${utc(v.lastTickAt)}`);
86
105
  const cls = v.lastError || v.rateLimitResetAt ? "alert alert-warning" : "";
87
106
  return `<div class="${cls}" data-installation-sync="${complete ? "complete" : "incomplete"}" style="color:#6b7280;font-size:12px;margin:8px 0">${parts.join(" &middot; ")}</div>`;
88
107
  }
@@ -197,9 +216,11 @@ export function renderGithubSyncCard(
197
216
  const loader = state.hasAppId
198
217
  ? `<div id="github-installation-body">Loading...</div>`
199
218
  : "";
219
+ const refresh = `<div style="margin:0 0 12px"><button type="button" class="btn btn-secondary" id="github-refresh-btn" data-url="/admin/agents/${id}/github-cache/refresh">Refresh</button> <span style="color:#6b7280;font-size:12px">Re-reads the cached repo lists in the background. Reload the page to see progress.</span></div>`;
200
220
  return `<div id="github-installation-card" data-base-url="${base}" style="margin-top:20px">
201
221
  <div class="form-label" style="font-weight:600;margin-bottom:6px">GitHub sync</div>
202
222
  <p style="color:#6b7280;font-size:12px;margin:0 0 12px">Brings this agent's App installation and its repos in line with what the bound GitHub user can push to.</p>
223
+ ${refresh}
203
224
  ${action}
204
225
  ${loader}
205
226
  <script>
@@ -216,6 +237,15 @@ export function renderGithubSyncCard(
216
237
  .then(function(t) { body.innerHTML = t; })
217
238
  .catch(function() { body.textContent = 'The request failed.'; });
218
239
  }
240
+ var refreshBtn = document.getElementById('github-refresh-btn');
241
+ if (refreshBtn) {
242
+ refreshBtn.addEventListener('click', function() {
243
+ refreshBtn.disabled = true;
244
+ fetch(refreshBtn.getAttribute('data-url'), { method: 'POST', credentials: 'same-origin' })
245
+ .then(function(r) { window.location.href = r.url; })
246
+ .catch(function() { refreshBtn.disabled = false; });
247
+ });
248
+ }
219
249
  if (!out) return;
220
250
  card.addEventListener('click', function(e) {
221
251
  var t = e.target;
@@ -5,11 +5,12 @@
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
7
  import {
8
- actuallyBlockedWork,
9
8
  APP_ID_MISMATCH_MESSAGE,
9
+ actuallyBlockedWork,
10
10
  NO_USERNAME_REASON,
11
11
  renderGithubSyncCard,
12
12
  renderInstallationReposBody,
13
+ renderInstallationSyncStatus,
13
14
  renderOpenWorkByRepo,
14
15
  renderSyncConfirm,
15
16
  renderSyncResult,
@@ -254,3 +255,50 @@ describe("renderSyncResult", () => {
254
255
  ).toContain("no user");
255
256
  });
256
257
  });
258
+
259
+ describe("renderInstallationSyncStatus debug detail", () => {
260
+ it("shows attempts, next attempt, lease holder and last tick on a failed snapshot, as an error", () => {
261
+ const html = renderInstallationSyncStatus({
262
+ complete: false,
263
+ reposSeen: 3,
264
+ totalCount: 10,
265
+ lastError: "boom <b>",
266
+ attempts: 3,
267
+ nextAttemptAt: "2026-11-21T10:30:00.000Z",
268
+ leaseHolder: "worker-1",
269
+ lastTickAt: "2026-11-21T10:00:00.000Z",
270
+ });
271
+ expect(html).toContain("alert alert-warning");
272
+ expect(html).toContain("Last error: boom &lt;b&gt;");
273
+ expect(html).toContain("3 failed attempts");
274
+ expect(html).toContain("Next attempt 2026-11-21 10:30 UTC");
275
+ expect(html).toContain("Refreshing (worker-1)");
276
+ expect(html).toContain("Last tick 2026-11-21 10:00 UTC");
277
+ expect(html).not.toContain("no access");
278
+ });
279
+
280
+ it("shows nothing misleading on a complete snapshot with unset fields", () => {
281
+ const html = renderInstallationSyncStatus({
282
+ complete: true,
283
+ syncedAt: "2026-11-21T10:00:00.000Z",
284
+ reposSeen: 2,
285
+ totalCount: 2,
286
+ });
287
+ expect(html).toContain("Synced 2026-11-21 10:00 UTC");
288
+ expect(html).toContain("2 of 2 repos");
289
+ expect(html).not.toMatch(/attempt|Refreshing|Last tick|error/i);
290
+ });
291
+
292
+ it("singularizes one attempt and ignores zero attempts", () => {
293
+ expect(
294
+ renderInstallationSyncStatus({ complete: true, attempts: 1 }),
295
+ ).toContain("1 failed attempt<");
296
+ expect(
297
+ renderInstallationSyncStatus({ complete: true, attempts: 0 }),
298
+ ).not.toContain("attempt");
299
+ });
300
+
301
+ it("renders nothing for an older API with no detail", () => {
302
+ expect(renderInstallationSyncStatus({})).toBe("");
303
+ });
304
+ });
@@ -1040,6 +1040,7 @@ export function agentSectionPath(
1040
1040
  export const AGENT_POST_SECTIONS: Readonly<Record<string, AgentSection>> = {
1041
1041
  "/github-username": "access",
1042
1042
  "/github-sync/apply-confirmed": "access",
1043
+ "/github-cache/refresh": "access",
1043
1044
  "/github-orgs/:org/install": "access",
1044
1045
  "/repos/remove-confirmed": "configuration",
1045
1046
  "/envs": "configuration",
package/src/admin-ui.ts CHANGED
@@ -2139,6 +2139,35 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2139
2139
  );
2140
2140
  });
2141
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
+
2142
2171
  app.post(
2143
2172
  "/admin/agents/:id/github-orgs/:org/install",
2144
2173
  requireAuth,
@@ -2467,11 +2496,13 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2467
2496
  ? "GitHub username saved."
2468
2497
  : successParam === "github_username_cleared"
2469
2498
  ? "GitHub username cleared."
2470
- : successParam === "github_app_installed"
2471
- ? "Agent app installed."
2472
- : successParam === "github_app_already_installed"
2473
- ? "The agent app was already installed on that organization."
2474
- : 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;
2475
2506
  const warningParam = c.req.query("warning");
2476
2507
  const warning =
2477
2508
  warningParam === "restrict_slack_no_members"
@@ -2537,6 +2568,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2537
2568
  totalCount: view.totalCount,
2538
2569
  lastError: view.lastError,
2539
2570
  rateLimitResetAt: view.rateLimitResetAt,
2571
+ attempts: view.attempts,
2572
+ nextAttemptAt: view.nextAttemptAt,
2573
+ leaseHolder: view.leaseHolder,
2574
+ lastTickAt: view.lastTickAt,
2540
2575
  };
2541
2576
  } catch {
2542
2577
  // unknown: no coverage warning
package/src/agents-api.ts CHANGED
@@ -665,6 +665,25 @@ const InstallationSyncDetailShape = {
665
665
  .string()
666
666
  .optional()
667
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)." }),
668
687
  };
669
688
 
670
689
  const GithubInstallationReposListSchema = z
@@ -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,
@@ -0,0 +1,45 @@
1
+ /**
2
+ * admin/src/github-refresh-action.ts
3
+ * The fire-and-forget Refresh action (GLC-2.4). requestRefresh() only writes
4
+ * to the database (ages the cache snapshots past the staleness cap, clears
5
+ * crawl and access backoff) and asks discovery to run again; it never calls
6
+ * GitHub and never waits on the refresher. The next tick does the work, still
7
+ * behind the snapshot lease and the rate-limit window.
8
+ */
9
+
10
+ import { type Clock, SystemClock } from "./clock.ts";
11
+ import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
12
+
13
+ export interface RefreshRequestResult {
14
+ snapshots: number;
15
+ accessPairs: number;
16
+ }
17
+
18
+ export interface GithubRefreshAction {
19
+ requestRefresh(): Promise<RefreshRequestResult>;
20
+ }
21
+
22
+ export function createGithubRefreshAction(deps: {
23
+ cache: Pick<GitHubRepoCacheService, "markStale">;
24
+ /** Snapshots are aged past this so the planner treats them as capped work. */
25
+ stalenessCapMs: number;
26
+ /** Runs after the mark (e.g. refresher.invalidateDiscovery). Failures are ignored. */
27
+ onMarked?: () => void;
28
+ clock?: Clock;
29
+ }): GithubRefreshAction {
30
+ const clock = deps.clock ?? SystemClock();
31
+ return {
32
+ async requestRefresh() {
33
+ const staleBefore = new Date(
34
+ clock.now().getTime() - deps.stalenessCapMs - 1,
35
+ );
36
+ const res = await deps.cache.markStale(staleBefore);
37
+ try {
38
+ deps.onMarked?.();
39
+ } catch {
40
+ // discovery refresh is best effort
41
+ }
42
+ return res;
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * admin/src/github-refresh-action.unit.test.ts
3
+ * GLC-2.4: stale-marking resets the right rows (and only those), and the
4
+ * action never touches leases or rate-limit windows. Fake prisma; no DB.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
9
+ import { createGithubRefreshAction } from "./github-refresh-action.ts";
10
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
11
+
12
+ type Call = { model: string; args: { where: unknown; data: unknown } };
13
+
14
+ function fakePrisma(counts = { snap: 2, access: 3 }) {
15
+ const calls: Call[] = [];
16
+ const model = (name: string, count: number) => ({
17
+ updateMany: async (args: Call["args"]) => {
18
+ calls.push({ model: name, args });
19
+ return { count };
20
+ },
21
+ });
22
+ const prisma = {
23
+ gitHubRepoSnapshot: model("snapshot", counts.snap),
24
+ gitHubRepoAccess: model("access", counts.access),
25
+ } as unknown as PrismaClient;
26
+ return { prisma, calls };
27
+ }
28
+
29
+ describe("GitHubRepoCacheService.markStale", () => {
30
+ const staleBefore = new Date("2026-11-01T00:00:00Z");
31
+
32
+ it("ages completed snapshots, clears backoff on snapshots and pending access pairs", async () => {
33
+ const { prisma, calls } = fakePrisma();
34
+ const res = await new GitHubRepoCacheService(prisma).markStale(staleBefore);
35
+ expect(res).toEqual({ snapshots: 2, accessPairs: 3 });
36
+ expect(calls).toEqual([
37
+ {
38
+ model: "snapshot",
39
+ args: {
40
+ where: { completedAt: { gt: staleBefore } },
41
+ data: { completedAt: staleBefore },
42
+ },
43
+ },
44
+ {
45
+ model: "snapshot",
46
+ args: {
47
+ where: { nextAttemptAt: { not: null } },
48
+ data: { nextAttemptAt: null },
49
+ },
50
+ },
51
+ {
52
+ model: "access",
53
+ args: {
54
+ where: { status: "error", nextAttemptAt: { not: null } },
55
+ data: { nextAttemptAt: null },
56
+ },
57
+ },
58
+ ]);
59
+ });
60
+
61
+ it("never writes the lease, rate-limit or terminal/ok-row columns", async () => {
62
+ const { prisma, calls } = fakePrisma();
63
+ await new GitHubRepoCacheService(prisma).markStale(staleBefore);
64
+ for (const c of calls) {
65
+ const written = Object.keys(c.args.data as object);
66
+ for (const col of [
67
+ "leaseHolder",
68
+ "leasedUntil",
69
+ "rateLimitResetAt",
70
+ "status",
71
+ "checkedAt",
72
+ ]) {
73
+ expect(written).not.toContain(col);
74
+ }
75
+ }
76
+ const access = calls.find((c) => c.model === "access");
77
+ expect(JSON.stringify(access?.args.where)).toContain('"status":"error"');
78
+ });
79
+ });
80
+
81
+ describe("createGithubRefreshAction", () => {
82
+ const now = new Date("2026-11-20T12:00:00Z");
83
+
84
+ it("marks snapshots past the staleness cap and notifies", async () => {
85
+ const seen: Date[] = [];
86
+ let notified = 0;
87
+ const action = createGithubRefreshAction({
88
+ cache: {
89
+ markStale: async (d: Date) => {
90
+ seen.push(d);
91
+ return { snapshots: 1, accessPairs: 0 };
92
+ },
93
+ },
94
+ stalenessCapMs: 6 * 3_600_000,
95
+ onMarked: () => {
96
+ notified++;
97
+ },
98
+ clock: { now: () => now },
99
+ });
100
+ expect(await action.requestRefresh()).toEqual({
101
+ snapshots: 1,
102
+ accessPairs: 0,
103
+ });
104
+ expect(seen[0]?.getTime()).toBeLessThan(now.getTime() - 6 * 3_600_000);
105
+ expect(notified).toBe(1);
106
+ });
107
+
108
+ it("ignores a failing onMarked hook", async () => {
109
+ const action = createGithubRefreshAction({
110
+ cache: { markStale: async () => ({ snapshots: 0, accessPairs: 0 }) },
111
+ stalenessCapMs: 1000,
112
+ onMarked: () => {
113
+ throw new Error("boom");
114
+ },
115
+ });
116
+ await expect(action.requestRefresh()).resolves.toEqual({
117
+ snapshots: 0,
118
+ accessPairs: 0,
119
+ });
120
+ });
121
+ });
@@ -161,6 +161,11 @@ export class GitHubRepoCacheService {
161
161
  totalCount: r.totalCount,
162
162
  lastError: r.lastError,
163
163
  rateLimitResetAt: r.rateLimitResetAt,
164
+ attempts: r.attempts,
165
+ nextAttemptAt: r.nextAttemptAt,
166
+ leaseHolder: r.leaseHolder,
167
+ leasedUntil: r.leasedUntil,
168
+ lastTickAt: r.lastTickAt,
164
169
  repos: r.repos,
165
170
  }));
166
171
  }
@@ -241,6 +246,38 @@ export class GitHubRepoCacheService {
241
246
  return count;
242
247
  }
243
248
 
249
+ /**
250
+ * Refresh request (GLC-2.4): make every snapshot's work the next thing the
251
+ * refresher runs, without touching GitHub. A completed list is aged to
252
+ * `staleBefore` (callers pass a time past the staleness cap, so the planner
253
+ * ranks it ahead of expired-only work); any snapshot's crawl backoff
254
+ * (nextAttemptAt) is cleared, and so is the backoff on access pairs that
255
+ * are still pending (status error). Leases and rateLimitResetAt are left
256
+ * alone, so the lease and the rate-limit window still gate the work.
257
+ * Terminal and ok access rows are not touched.
258
+ */
259
+ async markStale(staleBefore: Date): Promise<{
260
+ snapshots: number;
261
+ accessPairs: number;
262
+ }> {
263
+ const aged = await this.prisma.gitHubRepoSnapshot.updateMany({
264
+ where: { completedAt: { gt: staleBefore } },
265
+ data: { completedAt: staleBefore },
266
+ });
267
+ const backoff = await this.prisma.gitHubRepoSnapshot.updateMany({
268
+ where: { nextAttemptAt: { not: null } },
269
+ data: { nextAttemptAt: null },
270
+ });
271
+ const access = await this.prisma.gitHubRepoAccess.updateMany({
272
+ where: { status: "error", nextAttemptAt: { not: null } },
273
+ data: { nextAttemptAt: null },
274
+ });
275
+ return {
276
+ snapshots: Math.max(aged.count, backoff.count),
277
+ accessPairs: access.count,
278
+ };
279
+ }
280
+
244
281
  /**
245
282
  * Take the org's lease for `ttlMs`. True when this holder now owns it; false
246
283
  * when another holder's lease is still live or the snapshot does not exist.
@@ -313,6 +313,11 @@ export class GithubRepoRefresher {
313
313
  deps.discoveryIntervalMs ?? DEFAULT_REFRESH_DISCOVERY_INTERVAL_MS;
314
314
  }
315
315
 
316
+ /** Make the next tick re-discover targets (new or changed GitHub Apps). */
317
+ invalidateDiscovery(): void {
318
+ this.discoveredAt = null;
319
+ }
320
+
316
321
  /** Debug snapshot of the last ticks (a copy). */
317
322
  status(): RefreshStatus {
318
323
  return {
@@ -59,6 +59,14 @@ export interface InstallationSyncDetail {
59
59
  lastError?: string;
60
60
  /** ISO time the GitHub rate limit resets, while limited. */
61
61
  rateLimitResetAt?: string;
62
+ /** Failed refresh attempts since the last success. */
63
+ attempts?: number;
64
+ /** ISO time of the next refresh attempt, while backing off. */
65
+ nextAttemptAt?: string;
66
+ /** Holder of a live refresh lease. */
67
+ leaseHolder?: string;
68
+ /** ISO time of the last refresh tick on this snapshot. */
69
+ lastTickAt?: string;
62
70
  }
63
71
 
64
72
  export interface InstallationOrgView extends InstallationSyncDetail {
@@ -73,6 +81,11 @@ export interface InstallationSnapshotRow {
73
81
  totalCount: number | null;
74
82
  lastError: string | null;
75
83
  rateLimitResetAt: Date | null;
84
+ attempts?: number;
85
+ nextAttemptAt?: Date | null;
86
+ leaseHolder?: string | null;
87
+ leasedUntil?: Date | null;
88
+ lastTickAt?: Date | null;
76
89
  repos: { fullName: string }[];
77
90
  }
78
91
 
@@ -207,8 +220,23 @@ function summarize(
207
220
  .filter((d): d is string => d !== undefined)
208
221
  .sort()
209
222
  .at(-1);
223
+ const attempts = Math.max(0, ...orgs.map((o) => o.attempts ?? 0));
224
+ const next = orgs
225
+ .map((o) => o.nextAttemptAt)
226
+ .filter((d): d is string => d !== undefined)
227
+ .sort()[0];
228
+ const tick = orgs
229
+ .map((o) => o.lastTickAt)
230
+ .filter((d): d is string => d !== undefined)
231
+ .sort()
232
+ .at(-1);
233
+ const holder = orgs.find((o) => o.leaseHolder)?.leaseHolder;
210
234
  return {
211
235
  complete,
236
+ ...(attempts > 0 ? { attempts } : {}),
237
+ ...(next ? { nextAttemptAt: next } : {}),
238
+ ...(holder ? { leaseHolder: holder } : {}),
239
+ ...(tick ? { lastTickAt: tick } : {}),
212
240
  reposSeen: orgs.reduce((a, o) => a + (o.reposSeen ?? 0), 0),
213
241
  ...(complete && synced[0] ? { syncedAt: synced[0] } : {}),
214
242
  ...(orgs.length > 0 && totalCount !== undefined ? { totalCount } : {}),
@@ -267,6 +295,12 @@ export class InstallationReposService {
267
295
  ...(s.rateLimitResetAt
268
296
  ? { rateLimitResetAt: iso(s.rateLimitResetAt) }
269
297
  : {}),
298
+ ...(s.attempts ? { attempts: s.attempts } : {}),
299
+ ...(s.nextAttemptAt ? { nextAttemptAt: iso(s.nextAttemptAt) } : {}),
300
+ ...(s.leaseHolder && s.leasedUntil && s.leasedUntil > new Date()
301
+ ? { leaseHolder: s.leaseHolder }
302
+ : {}),
303
+ ...(s.lastTickAt ? { lastTickAt: iso(s.lastTickAt) } : {}),
270
304
  });
271
305
  }
272
306
  return { status: "ok", appId: agent.appId, orgs, ...summarize(orgs) };
@@ -303,3 +303,37 @@ describe("InstallationReposService.list (cache read)", () => {
303
303
  expect(r.status).toBe("no_app_id");
304
304
  });
305
305
  });
306
+
307
+ describe("InstallationReposService.list debug detail", () => {
308
+ it("surfaces attempts, next attempt, live lease and last tick; drops an expired lease", async () => {
309
+ const future = new Date(Date.now() + 60_000);
310
+ const past = new Date(Date.now() - 60_000);
311
+ const live = build({
312
+ snapshots: [
313
+ snap({
314
+ attempts: 2,
315
+ nextAttemptAt: T0,
316
+ lastTickAt: T0,
317
+ leaseHolder: "w1",
318
+ leasedUntil: future,
319
+ lastError: "x",
320
+ }),
321
+ ],
322
+ });
323
+ const r = await live.svc.list("a1");
324
+ if (r.status !== "ok") throw new Error("expected ok");
325
+ expect(r.attempts).toBe(2);
326
+ expect(r.nextAttemptAt).toBe(T0.toISOString());
327
+ expect(r.lastTickAt).toBe(T0.toISOString());
328
+ expect(r.leaseHolder).toBe("w1");
329
+ expect(r.orgs[0]?.lastError).toBe("x");
330
+
331
+ const stale = build({
332
+ snapshots: [snap({ leaseHolder: "w1", leasedUntil: past })],
333
+ });
334
+ const r2 = await stale.svc.list("a1");
335
+ if (r2.status !== "ok") throw new Error("expected ok");
336
+ expect(r2.leaseHolder).toBeUndefined();
337
+ expect(r2.attempts).toBeUndefined();
338
+ });
339
+ });