@app-vitals/agent-admin 1.81.0 → 1.82.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.
@@ -3528,6 +3528,29 @@
3528
3528
  "appId": {
3529
3529
  "type": "integer"
3530
3530
  },
3531
+ "complete": {
3532
+ "type": "boolean",
3533
+ "description": "Whether the cached crawl is complete. While false the list may be partial."
3534
+ },
3535
+ "syncedAt": {
3536
+ "type": "string",
3537
+ "description": "When the completed crawl finished (ISO 8601)."
3538
+ },
3539
+ "reposSeen": {
3540
+ "type": "integer",
3541
+ "description": "Repos in the cache (the N of 'N of M')."
3542
+ },
3543
+ "totalCount": {
3544
+ "type": "integer",
3545
+ "description": "GitHub's repo count, when known (the M)."
3546
+ },
3547
+ "lastError": {
3548
+ "type": "string"
3549
+ },
3550
+ "rateLimitResetAt": {
3551
+ "type": "string",
3552
+ "description": "When the GitHub rate limit resets (ISO 8601)."
3553
+ },
3531
3554
  "orgs": {
3532
3555
  "type": "array",
3533
3556
  "items": {
@@ -3536,6 +3559,29 @@
3536
3559
  "org": {
3537
3560
  "type": "string"
3538
3561
  },
3562
+ "complete": {
3563
+ "type": "boolean",
3564
+ "description": "Whether the cached crawl is complete. While false the list may be partial."
3565
+ },
3566
+ "syncedAt": {
3567
+ "type": "string",
3568
+ "description": "When the completed crawl finished (ISO 8601)."
3569
+ },
3570
+ "reposSeen": {
3571
+ "type": "integer",
3572
+ "description": "Repos in the cache (the N of 'N of M')."
3573
+ },
3574
+ "totalCount": {
3575
+ "type": "integer",
3576
+ "description": "GitHub's repo count, when known (the M)."
3577
+ },
3578
+ "lastError": {
3579
+ "type": "string"
3580
+ },
3581
+ "rateLimitResetAt": {
3582
+ "type": "string",
3583
+ "description": "When the GitHub rate limit resets (ISO 8601)."
3584
+ },
3539
3585
  "repos": {
3540
3586
  "type": "array",
3541
3587
  "items": {
@@ -3546,7 +3592,7 @@
3546
3592
  },
3547
3593
  "userCanPush": {
3548
3594
  "type": "boolean",
3549
- "description": "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."
3595
+ "description": "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)."
3550
3596
  }
3551
3597
  },
3552
3598
  "required": [
@@ -7879,7 +7925,7 @@
7879
7925
  "/agents/{id}/github-installation/repos": {
7880
7926
  "get": {
7881
7927
  "summary": "List the repos on the agent App's installation",
7882
- "description": "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.",
7928
+ "description": "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.",
7883
7929
  "parameters": [
7884
7930
  {
7885
7931
  "schema": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.81.0",
3
+ "version": "1.82.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.81.0",
46
+ "@app-vitals/agent-lib": "1.82.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
@@ -24,12 +24,67 @@ export interface OpenWorkView {
24
24
  }
25
25
 
26
26
  /** JSON body of GET /agents/:id/github-installation/repos. */
27
- export interface InstallationReposView {
27
+ export interface InstallationSyncView {
28
+ /** False while the cached crawl is incomplete. Absent (older API): treated as complete. */
29
+ complete?: boolean;
30
+ syncedAt?: string;
31
+ reposSeen?: number;
32
+ totalCount?: number;
33
+ lastError?: string;
34
+ rateLimitResetAt?: string;
35
+ }
36
+
37
+ export interface InstallationReposView extends InstallationSyncView {
28
38
  appId?: number;
29
- orgs: {
39
+ orgs: ({
30
40
  org: string;
31
41
  repos: { fullName: string; userCanPush?: boolean }[];
32
- }[];
42
+ } & InstallationSyncView)[];
43
+ }
44
+
45
+ /** True unless the view says its snapshot is incomplete. */
46
+ export const installationSnapshotComplete = (
47
+ view: InstallationSyncView,
48
+ ): boolean => view.complete !== false;
49
+
50
+ /** True when the view carries any sync detail worth showing. */
51
+ const hasSyncDetail = (v: InstallationSyncView): boolean =>
52
+ v.complete !== undefined ||
53
+ v.syncedAt !== undefined ||
54
+ v.reposSeen !== undefined ||
55
+ v.lastError !== undefined ||
56
+ v.rateLimitResetAt !== undefined;
57
+
58
+ /**
59
+ * One-line sync status: synced-at, "N of M repos", last error and the rate-limit
60
+ * reset. Empty when the view has no sync detail (older API).
61
+ */
62
+ export function renderInstallationSyncStatus(v: InstallationSyncView): string {
63
+ if (!hasSyncDetail(v)) return "";
64
+ const complete = installationSnapshotComplete(v);
65
+ const parts: string[] = [];
66
+ parts.push(
67
+ v.syncedAt
68
+ ? `Synced ${escapeHtml(v.syncedAt.slice(0, 16).replace("T", " "))} UTC`
69
+ : complete
70
+ ? "Synced"
71
+ : "Sync in progress",
72
+ );
73
+ if (v.reposSeen !== undefined) {
74
+ parts.push(
75
+ v.totalCount !== undefined
76
+ ? `${v.reposSeen} of ${v.totalCount} repos`
77
+ : `${v.reposSeen} repos`,
78
+ );
79
+ }
80
+ if (v.lastError) parts.push(`Last error: ${escapeHtml(v.lastError)}`);
81
+ if (v.rateLimitResetAt) {
82
+ parts.push(
83
+ `GitHub rate limit resets ${escapeHtml(v.rateLimitResetAt.slice(0, 16).replace("T", " "))} UTC`,
84
+ );
85
+ }
86
+ const cls = v.lastError || v.rateLimitResetAt ? "alert alert-warning" : "";
87
+ return `<div class="${cls}" data-installation-sync="${complete ? "complete" : "incomplete"}" style="color:#6b7280;font-size:12px;margin:8px 0">${parts.join(" &middot; ")}</div>`;
33
88
  }
34
89
 
35
90
  /** JSON body of GET /agents/:id/repos/:owner/:name/removal-preview. */
@@ -198,31 +253,40 @@ export function renderInstallationReposBody(
198
253
  view: InstallationReposView,
199
254
  opts: { appIdMismatch?: boolean } = {},
200
255
  ): string {
201
- if (view.orgs.length === 0) {
256
+ const sync = renderInstallationSyncStatus(view);
257
+ if (view.orgs.length === 0 || view.orgs.every((o) => o.repos.length === 0)) {
202
258
  if (opts.appIdMismatch) {
203
- return `<div class="alert alert-warning" data-reason="app-id-mismatch">${escapeHtml(APP_ID_MISMATCH_MESSAGE)}</div>`;
259
+ return `${sync}<div class="alert alert-warning" data-reason="app-id-mismatch">${escapeHtml(APP_ID_MISMATCH_MESSAGE)}</div>`;
260
+ }
261
+ if (!installationSnapshotComplete(view)) {
262
+ return `${sync}<p class="empty-state">The installation repos have not finished syncing yet.</p>`;
263
+ }
264
+ if (view.orgs.length === 0) {
265
+ return `${sync}<p class="empty-state">The agent App is not installed on any organization the installer can reach.</p>`;
204
266
  }
205
- return `<p class="empty-state">The agent App is not installed on any organization the installer can reach.</p>`;
206
267
  }
207
- return view.orgs
208
- .map((o) => {
209
- const rows =
210
- o.repos.length === 0
211
- ? `<tr><td colspan="2" class="empty-state">No repos.</td></tr>`
212
- : o.repos
213
- .map((r) => {
214
- const hint =
215
- r.userCanPush === undefined
216
- ? ""
217
- : r.userCanPush
218
- ? '<span class="badge badge-green" title="The bound user can push">user can push</span>'
219
- : '<span class="badge badge-warning" title="The bound user cannot push">user cannot push</span>';
220
- return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}</td></tr>`;
221
- })
222
- .join("");
223
- return `<div class="github-installation-org" data-org="${escapeHtml(o.org)}" style="margin-bottom:16px"><div style="font-weight:600;margin-bottom:6px">${escapeHtml(o.org)}</div><table class="detail-table"><thead><tr><th>Repo</th><th>Bound user</th></tr></thead><tbody>${rows}</tbody></table></div>`;
224
- })
225
- .join("");
268
+ return (
269
+ sync +
270
+ view.orgs
271
+ .map((o) => {
272
+ const rows =
273
+ o.repos.length === 0
274
+ ? `<tr><td colspan="2" class="empty-state">No repos.</td></tr>`
275
+ : o.repos
276
+ .map((r) => {
277
+ const hint =
278
+ r.userCanPush === undefined
279
+ ? ""
280
+ : r.userCanPush
281
+ ? '<span class="badge badge-green" title="The bound user can push">user can push</span>'
282
+ : '<span class="badge badge-warning" title="The bound user cannot push">user cannot push</span>';
283
+ return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}</td></tr>`;
284
+ })
285
+ .join("");
286
+ return `<div class="github-installation-org" data-org="${escapeHtml(o.org)}" style="margin-bottom:16px"><div style="font-weight:600;margin-bottom:6px">${escapeHtml(o.org)}</div>${renderInstallationSyncStatus(o)}<table class="detail-table"><thead><tr><th>Repo</th><th>Bound user</th></tr></thead><tbody>${rows}</tbody></table></div>`;
287
+ })
288
+ .join("")
289
+ );
226
290
  }
227
291
 
228
292
  /** Why the card body could not be shown, distinct per cause. */
@@ -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";
@@ -1156,6 +1159,12 @@ export function renderAgentDetailPage(
1156
1159
  * could be listed. Absent means unknown: no coverage warning is shown.
1157
1160
  */
1158
1161
  installationRepos?: readonly string[];
1162
+ /**
1163
+ * GLC-2.2: sync detail of the cached installation view (synced-at, N of M,
1164
+ * last error, rate-limit reset). When `complete` is false the coverage
1165
+ * warning is suppressed.
1166
+ */
1167
+ installationSync?: InstallationSyncView;
1159
1168
  /**
1160
1169
  * ATP-2.4: present when agent templates are available. Turns on the
1161
1170
  * inherited/custom badges, the detach/reattach toggle and the per-item
@@ -1723,7 +1732,9 @@ export function renderAgentDetailPage(
1723
1732
  })();
1724
1733
  </script>`;
1725
1734
  const uncovered = new Set(
1726
- opts?.installationRepos
1735
+ opts?.installationRepos &&
1736
+ (!opts.installationSync ||
1737
+ installationSnapshotComplete(opts.installationSync))
1727
1738
  ? uncoveredRepos(agent.repos, opts.installationRepos)
1728
1739
  : [],
1729
1740
  );
@@ -1737,6 +1748,7 @@ export function renderAgentDetailPage(
1737
1748
  <button type="submit" class="btn btn-primary">Add</button>
1738
1749
  </div>
1739
1750
  </form>
1751
+ ${opts?.installationSync ? renderInstallationSyncStatus(opts.installationSync) : ""}
1740
1752
  <div class="data-table-wrapper">
1741
1753
  <table class="data-table">
1742
1754
  <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,
@@ -2223,7 +2224,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2223
2224
  // No installation matched the numeric GH_APP_ID. If the agent still has an
2224
2225
  // installation by slug (the Installations card), the id is probably wrong.
2225
2226
  let appIdMismatch = false;
2226
- if (view.orgs.length === 0) {
2227
+ if (view.orgs.every((o) => o.repos.length === 0)) {
2227
2228
  const snap = await callApi(
2228
2229
  c,
2229
2230
  agentsApi,
@@ -2512,6 +2513,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2512
2513
  // list's coverage warning. Best effort: unknown means no warning.
2513
2514
  const enterpriseConfigured = await githubEnterpriseConfigured(c);
2514
2515
  let installationRepos: string[] | undefined;
2516
+ let installationSync: InstallationSyncView | undefined;
2515
2517
  if (
2516
2518
  enterpriseConfigured &&
2517
2519
  agentsApi &&
@@ -2524,9 +2526,18 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2524
2526
  );
2525
2527
  if (res?.ok) {
2526
2528
  try {
2527
- installationRepos = (
2528
- (await res.json()) as InstallationReposView
2529
- ).orgs.flatMap((o) => o.repos.map((r) => r.fullName));
2529
+ const view = (await res.json()) as InstallationReposView;
2530
+ installationRepos = view.orgs.flatMap((o) =>
2531
+ o.repos.map((r) => r.fullName),
2532
+ );
2533
+ installationSync = {
2534
+ complete: view.complete,
2535
+ syncedAt: view.syncedAt,
2536
+ reposSeen: view.reposSeen,
2537
+ totalCount: view.totalCount,
2538
+ lastError: view.lastError,
2539
+ rateLimitResetAt: view.rateLimitResetAt,
2540
+ };
2530
2541
  } catch {
2531
2542
  // unknown: no coverage warning
2532
2543
  }
@@ -2562,6 +2573,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2562
2573
  agent.accountId ?? null,
2563
2574
  ),
2564
2575
  ...(installationRepos ? { installationRepos } : {}),
2576
+ ...(installationSync ? { installationSync } : {}),
2565
2577
  ...(agentsApi
2566
2578
  ? { template: { detached: agent.templateDetached === true } }
2567
2579
  : {}),
@@ -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,46 @@ 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
+ };
669
+
644
670
  const GithubInstallationReposListSchema = z
645
671
  .object({
646
672
  appId: z.number().int(),
673
+ ...InstallationSyncDetailShape,
647
674
  orgs: z.array(
648
675
  z.object({
649
676
  org: z.string(),
677
+ ...InstallationSyncDetailShape,
650
678
  repos: z.array(
651
679
  z.object({
652
680
  fullName: z.string(),
653
681
  userCanPush: z.boolean().optional().openapi({
654
682
  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.",
683
+ "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
684
  }),
657
685
  }),
658
686
  ),
@@ -1793,7 +1821,7 @@ const listInstallationReposRoute = createRoute({
1793
1821
  path: "/agents/{id}/github-installation/repos",
1794
1822
  summary: "List the repos on the agent App's installation",
1795
1823
  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.",
1824
+ "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
1825
  request: { params: AgentIdParamSchema },
1798
1826
  responses: {
1799
1827
  200: {
@@ -3453,7 +3481,8 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3453
3481
  return c.json({ appId: result.appId, orgs: [] }, 200);
3454
3482
  }
3455
3483
  if (result.status !== "ok") return installationFailure(agentId, result);
3456
- return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3484
+ const { status: _status, ...body } = result;
3485
+ return c.json(body, 200);
3457
3486
  });
3458
3487
 
3459
3488
  // /agents/:id/github-sync/{preview,apply} — IRM-3.1. Platform admin only;
@@ -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
 
@@ -30,9 +30,9 @@ const portWith = (
30
30
  });
31
31
 
32
32
  describe("createGithubInstallationRepos", () => {
33
- it("lists from the agent's own stored GH_APP_ID", async () => {
33
+ it("lists from the cache under the agent's own stored GH_APP_ID, without GitHub", async () => {
34
34
  const seen: number[] = [];
35
- const { prisma } = fakePrisma(["acme/old"]);
35
+ const { prisma, state } = fakePrisma(["acme/old"]);
36
36
  const svc = createGithubInstallationRepos({
37
37
  prisma,
38
38
  appService: noApp,
@@ -41,8 +41,12 @@ describe("createGithubInstallationRepos", () => {
41
41
  installationRepos: portWith(seen),
42
42
  });
43
43
  const res = await svc.list("a1");
44
- expect(seen).toEqual([77]);
45
- expect(res.status).toBe("ok");
44
+ // The port (live GitHub) is never used; the cache is read for App 77.
45
+ expect(seen).toEqual([]);
46
+ expect(state.snapshotQueries).toMatchObject([
47
+ { where: { appKind: "agent", appRef: "77" } },
48
+ ]);
49
+ expect(res).toMatchObject({ status: "ok", appId: 77, complete: false });
46
50
  });
47
51
 
48
52
  it("reports an agent with no GH_APP_ID, naming the missing var", async () => {
@@ -34,7 +34,11 @@ export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
34
34
  };
35
35
 
36
36
  export function fakePrisma(repos: string[]) {
37
- const state = { repos: [...repos], audits: 0 };
37
+ const state = {
38
+ repos: [...repos],
39
+ audits: 0,
40
+ snapshotQueries: [] as unknown[],
41
+ };
38
42
  const prisma = {
39
43
  agent: {
40
44
  findUnique: async () => ({
@@ -46,6 +50,13 @@ export function fakePrisma(repos: string[]) {
46
50
  state.repos = args.data.repos;
47
51
  },
48
52
  },
53
+ gitHubRepoSnapshot: {
54
+ findMany: async (args: unknown) => {
55
+ state.snapshotQueries.push(args);
56
+ return [];
57
+ },
58
+ },
59
+ gitHubRepoAccess: { findMany: async () => [] },
49
60
  gitHubReconcileAudit: {
50
61
  create: async () => {
51
62
  state.audits += 1;
@@ -146,6 +146,25 @@ export class GitHubRepoCacheService {
146
146
  }));
147
147
  }
148
148
 
149
+ /** Agent-App installation snapshots (with their repos) for one account scope and App id. Reads only the cache. */
150
+ async listAgentSnapshots(accountId: string, appRef: string) {
151
+ requireNonEmpty("accountId", accountId);
152
+ requireNonEmpty("appRef", appRef);
153
+ const rows = await this.prisma.gitHubRepoSnapshot.findMany({
154
+ where: { accountId, appKind: "agent", appRef },
155
+ include: { repos: { select: { fullName: true } } },
156
+ orderBy: { org: "asc" },
157
+ });
158
+ return rows.map((r) => ({
159
+ org: r.org,
160
+ completedAt: r.completedAt,
161
+ totalCount: r.totalCount,
162
+ lastError: r.lastError,
163
+ rateLimitResetAt: r.rateLimitResetAt,
164
+ repos: r.repos,
165
+ }));
166
+ }
167
+
149
168
  /** Upsert repos for a snapshot in batches, stamping each with `seenAt`. */
150
169
  async upsertRepos(
151
170
  snapshotId: string,
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * admin/src/installation-repos-service.ts
3
3
  * Read-only listing of the repos on an agent's own GitHub App installation
4
- * (IRM-1.2), with the bound user's push hint. Changes go through the Sync flow
5
- * (github-sync.ts, IRM-3.1). Uses the installer App through the installation port.
4
+ * (IRM-1.2), with the bound user's push hint. list() reads only the repo/access
5
+ * cache (GLC-2.2): no GitHub call, sync detail alongside. Changes go through
6
+ * the Sync flow (github-sync.ts, IRM-3.1), which still uses the installer App
7
+ * through the installation port.
6
8
  */
7
9
 
8
10
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
11
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
9
12
  import {
10
- AppNotInstalledError,
11
- MISSING_APP_ID_REASON,
12
13
  type AppIdentity,
13
- type InstallationAgentsPort,
14
14
  type AppInstallationPort,
15
+ AppNotInstalledError,
16
+ type InstallationAgentsPort,
17
+ MISSING_APP_ID_REASON,
15
18
  } from "./installation-ports.ts";
16
19
  import type {
17
20
  OrgAccessResult,
@@ -43,21 +46,74 @@ export interface InstallationRepoView {
43
46
  userCanPush?: boolean;
44
47
  }
45
48
 
46
- export interface InstallationOrgView {
49
+ /** Sync detail for one org's cached snapshot (all optional, additive). */
50
+ export interface InstallationSyncDetail {
51
+ /** True once the org's crawl completed. */
52
+ complete?: boolean;
53
+ /** ISO time of the completed crawl; absent until one completed. */
54
+ syncedAt?: string;
55
+ /** Repos in the cache for the org. */
56
+ reposSeen?: number;
57
+ /** GitHub's repo count for the org, when known ("N of M"). */
58
+ totalCount?: number;
59
+ lastError?: string;
60
+ /** ISO time the GitHub rate limit resets, while limited. */
61
+ rateLimitResetAt?: string;
62
+ }
63
+
64
+ export interface InstallationOrgView extends InstallationSyncDetail {
47
65
  org: string;
48
66
  repos: InstallationRepoView[];
49
67
  }
50
68
 
69
+ /** One cached agent-App snapshot with its repos (GitHubRepoCacheService.listAgentSnapshots). */
70
+ export interface InstallationSnapshotRow {
71
+ org: string;
72
+ completedAt: Date | null;
73
+ totalCount: number | null;
74
+ lastError: string | null;
75
+ rateLimitResetAt: Date | null;
76
+ repos: { fullName: string }[];
77
+ }
78
+
79
+ /** A cached per-user access row (repo is the name without the org). */
80
+ export interface CachedAccessRow {
81
+ repo: string;
82
+ status: string;
83
+ canPush: boolean;
84
+ }
85
+
86
+ /** The slice of GitHubRepoCacheService the list reads; never calls GitHub. */
87
+ export interface InstallationCachePort {
88
+ listAgentSnapshots(
89
+ accountId: string,
90
+ appRef: string,
91
+ ): Promise<InstallationSnapshotRow[]>;
92
+ getAccessRows(query: {
93
+ accountId: string;
94
+ org: string;
95
+ username: string;
96
+ repos: string[];
97
+ }): Promise<CachedAccessRow[]>;
98
+ }
99
+
51
100
  export type InstallationListResult =
52
101
  | { status: "agent_not_found" }
53
102
  | { status: "no_app_id"; reason: string }
54
103
  | { status: "skipped"; appId: number; reason: string }
55
- | { status: "ok"; appId: number; orgs: InstallationOrgView[] };
104
+ | ({
105
+ status: "ok";
106
+ appId: number;
107
+ orgs: InstallationOrgView[];
108
+ } & InstallationSyncDetail);
56
109
 
57
110
  export interface InstallationReposDeps {
58
111
  agents: Pick<InstallationAgentsPort, "get">;
112
+ /** Used by GitHub Sync, not by list(), which reads only the cache. */
59
113
  access: GithubAccessPreviewFn;
60
114
  installation: InstallationReposPort;
115
+ /** The repo/access cache list() reads. Without it list() reports nothing synced. */
116
+ cache?: InstallationCachePort;
61
117
  }
62
118
 
63
119
  /** The agent's App identity keys (client id, slug), when stored. */
@@ -75,31 +131,52 @@ export function identityOf(agent: {
75
131
 
76
132
  const orgKey = (org: string): string => org.toLowerCase();
77
133
 
134
+ /** Cached access rows for one org and user, as read from the access cache. */
135
+ export interface CachedAccessRows {
136
+ cachedRows: readonly CachedAccessRow[];
137
+ }
138
+
78
139
  /**
79
140
  * The user-can-push hint for one org: true/false per repo only when the bound
80
- * user is verified and this org's lookup result is complete ("ok", nothing
81
- * unresolved). A repo the lookup did not list is unknown, so it gets no hint
82
- * (never false).
141
+ * user is verified and this org's access data is complete (a live "ok" lookup
142
+ * with nothing unresolved, or cached rows with an "ok" row for every listed
143
+ * repo). Anything else is unknown, so it gets no hint (never false).
83
144
  */
84
145
  export function userPushHints(
85
- access: UserRepoAccessResult | undefined,
146
+ access: UserRepoAccessResult | CachedAccessRows | undefined,
86
147
  org: string,
87
148
  repos: readonly string[],
88
149
  ): InstallationRepoView[] {
89
- const orgResult: OrgAccessResult | undefined = access?.orgs.find(
90
- (o) => orgKey(o.org) === orgKey(org),
91
- );
92
- const complete =
93
- access !== undefined &&
94
- access.outcome === "ok" &&
95
- access.userVerified &&
96
- orgResult !== undefined &&
97
- orgResult.status === "ok" &&
98
- orgResult.unresolved === 0;
99
150
  const pushByName = new Map<string, boolean>();
100
- if (complete) {
101
- for (const r of orgResult.repos) {
102
- pushByName.set(r.fullName.toLowerCase(), r.canPush);
151
+ if (access && "cachedRows" in access) {
152
+ const byRepo = new Map<string, CachedAccessRow>();
153
+ for (const r of access.cachedRows) byRepo.set(r.repo.toLowerCase(), r);
154
+ const nameOf = (fullName: string) =>
155
+ fullName.slice(fullName.indexOf("/") + 1).toLowerCase();
156
+ const complete = repos.every((f) => byRepo.get(nameOf(f))?.status === "ok");
157
+ if (complete) {
158
+ for (const f of repos) {
159
+ pushByName.set(
160
+ f.toLowerCase(),
161
+ byRepo.get(nameOf(f))?.canPush ?? false,
162
+ );
163
+ }
164
+ }
165
+ } else {
166
+ const orgResult: OrgAccessResult | undefined = access?.orgs.find(
167
+ (o) => orgKey(o.org) === orgKey(org),
168
+ );
169
+ const complete =
170
+ access !== undefined &&
171
+ access.outcome === "ok" &&
172
+ access.userVerified &&
173
+ orgResult !== undefined &&
174
+ orgResult.status === "ok" &&
175
+ orgResult.unresolved === 0;
176
+ if (complete) {
177
+ for (const r of orgResult.repos) {
178
+ pushByName.set(r.fullName.toLowerCase(), r.canPush);
179
+ }
103
180
  }
104
181
  }
105
182
  return repos.map((fullName) => {
@@ -108,44 +185,91 @@ export function userPushHints(
108
185
  });
109
186
  }
110
187
 
188
+ const iso = (d: Date | null): string | undefined =>
189
+ d ? d.toISOString() : undefined;
190
+
191
+ /** Folds per-org sync detail into the page-level detail. */
192
+ function summarize(
193
+ orgs: readonly InstallationOrgView[],
194
+ ): InstallationSyncDetail {
195
+ const complete = orgs.length > 0 && orgs.every((o) => o.complete === true);
196
+ const synced = orgs
197
+ .map((o) => o.syncedAt)
198
+ .filter((d): d is string => d !== undefined)
199
+ .sort();
200
+ const totals = orgs.map((o) => o.totalCount);
201
+ const totalCount = totals.every((t) => t !== undefined)
202
+ ? totals.reduce<number>((a, t) => a + (t ?? 0), 0)
203
+ : undefined;
204
+ const lastError = orgs.find((o) => o.lastError)?.lastError;
205
+ const reset = orgs
206
+ .map((o) => o.rateLimitResetAt)
207
+ .filter((d): d is string => d !== undefined)
208
+ .sort()
209
+ .at(-1);
210
+ return {
211
+ complete,
212
+ reposSeen: orgs.reduce((a, o) => a + (o.reposSeen ?? 0), 0),
213
+ ...(complete && synced[0] ? { syncedAt: synced[0] } : {}),
214
+ ...(orgs.length > 0 && totalCount !== undefined ? { totalCount } : {}),
215
+ ...(lastError ? { lastError } : {}),
216
+ ...(reset ? { rateLimitResetAt: reset } : {}),
217
+ };
218
+ }
219
+
111
220
  export class InstallationReposService {
112
221
  constructor(private readonly deps: InstallationReposDeps) {}
113
222
 
223
+ /**
224
+ * Reads the agent-installation cache (crawled in the background) and the
225
+ * cached access rows; it never calls GitHub. A hint appears only when the
226
+ * org's snapshot is complete and every repo has an ok access row.
227
+ */
114
228
  async list(agentId: string): Promise<InstallationListResult> {
115
229
  const agent = await this.deps.agents.get(agentId);
116
230
  if (!agent) return { status: "agent_not_found" };
117
231
  if (agent.appId === undefined) {
118
232
  return { status: "no_app_id", reason: MISSING_APP_ID_REASON };
119
233
  }
120
- const installed = await this.deps.installation.listInstalled(
121
- agent.appId,
122
- identityOf(agent),
123
- );
124
- if (installed.status === "none") {
125
- return {
126
- status: "skipped",
127
- appId: agent.appId,
128
- reason: NO_INSTALLATION_REASON,
129
- };
130
- }
234
+ const cache = this.deps.cache;
235
+ const accountId = agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY;
236
+ const snapshots = cache
237
+ ? await cache.listAgentSnapshots(accountId, String(agent.appId))
238
+ : [];
131
239
  const username = agent.githubUsername?.trim();
132
- let access: UserRepoAccessResult | undefined;
133
- if (username) {
134
- try {
135
- const preview = await this.deps.access(username, agent.accountId);
136
- if (preview.status === "ok") access = preview.access;
137
- } catch {
138
- // The hint is advisory: a failed lookup omits it.
240
+ const orgs: InstallationOrgView[] = [];
241
+ for (const s of snapshots) {
242
+ const names = s.repos.map((r) => r.fullName);
243
+ let repos: InstallationRepoView[] = names.map((fullName) => ({
244
+ fullName,
245
+ }));
246
+ if (cache && username && s.completedAt && names.length > 0) {
247
+ try {
248
+ const rows = await cache.getAccessRows({
249
+ accountId,
250
+ org: s.org,
251
+ username,
252
+ repos: names.map((f) => f.slice(f.indexOf("/") + 1)),
253
+ });
254
+ repos = userPushHints({ cachedRows: rows }, s.org, names);
255
+ } catch {
256
+ // The hint is advisory: a failed cache read omits it.
257
+ }
139
258
  }
259
+ orgs.push({
260
+ org: s.org,
261
+ repos,
262
+ complete: s.completedAt !== null,
263
+ reposSeen: names.length,
264
+ ...(s.completedAt ? { syncedAt: iso(s.completedAt) } : {}),
265
+ ...(s.totalCount !== null ? { totalCount: s.totalCount } : {}),
266
+ ...(s.lastError ? { lastError: s.lastError } : {}),
267
+ ...(s.rateLimitResetAt
268
+ ? { rateLimitResetAt: iso(s.rateLimitResetAt) }
269
+ : {}),
270
+ });
140
271
  }
141
- return {
142
- status: "ok",
143
- appId: agent.appId,
144
- orgs: installed.orgs.map(({ org, repos }) => ({
145
- org,
146
- repos: userPushHints(access, org, repos),
147
- })),
148
- };
272
+ return { status: "ok", appId: agent.appId, orgs, ...summarize(orgs) };
149
273
  }
150
274
  }
151
275
 
@@ -6,9 +6,10 @@
6
6
 
7
7
  import { describe, expect, it } from "bun:test";
8
8
  import {
9
+ type CachedAccessRow,
10
+ type InstallationCachePort,
9
11
  InstallationReposService,
10
- NO_INSTALLATION_REASON,
11
- type InstallationReposPort,
12
+ type InstallationSnapshotRow,
12
13
  userPushHints,
13
14
  } from "./installation-repos-service.ts";
14
15
  import type {
@@ -101,93 +102,197 @@ function noHint(r: { userCanPush?: boolean }): boolean {
101
102
  return r.userCanPush === undefined;
102
103
  }
103
104
 
105
+ const row = (
106
+ repo: string,
107
+ status: string,
108
+ canPush = false,
109
+ ): CachedAccessRow => ({ repo, status, canPush });
110
+
111
+ describe("userPushHints from cached access rows", () => {
112
+ const repos = ["acme/push", "acme/readonly"];
113
+
114
+ it("reports true/false per repo when every repo has an ok row", () => {
115
+ const out = userPushHints(
116
+ { cachedRows: [row("push", "ok", true), row("ReadOnly", "ok", false)] },
117
+ "acme",
118
+ repos,
119
+ );
120
+ expect(out).toEqual([
121
+ { fullName: "acme/push", userCanPush: true },
122
+ { fullName: "acme/readonly", userCanPush: false },
123
+ ]);
124
+ });
125
+
126
+ it("omits every hint when any pair is missing, errored or terminal (never false)", () => {
127
+ for (const second of [
128
+ undefined,
129
+ row("readonly", "error", false),
130
+ row("readonly", "terminal", false),
131
+ ]) {
132
+ const rows = [row("push", "ok", true), ...(second ? [second] : [])];
133
+ expect(
134
+ userPushHints({ cachedRows: rows }, "acme", repos).every(noHint),
135
+ ).toBe(true);
136
+ }
137
+ });
138
+
139
+ it("omits hints with no rows at all", () => {
140
+ expect(userPushHints({ cachedRows: [] }, "acme", repos).every(noHint)).toBe(
141
+ true,
142
+ );
143
+ });
144
+ });
145
+
146
+ const T0 = new Date("2026-11-20T10:00:00Z");
147
+ const snap = (
148
+ over: Partial<InstallationSnapshotRow> = {},
149
+ ): InstallationSnapshotRow => ({
150
+ org: "acme",
151
+ completedAt: T0,
152
+ totalCount: 2,
153
+ lastError: null,
154
+ rateLimitResetAt: null,
155
+ repos: [{ fullName: "acme/push" }, { fullName: "acme/readonly" }],
156
+ ...over,
157
+ });
158
+
104
159
  function build(
105
160
  opts: {
106
161
  agent?: { githubUsername: string | null; appId?: number } | null;
107
- noInstallation?: boolean;
108
- access?: () => Promise<
109
- | { status: "unconfigured" }
110
- | { status: "ok"; access: UserRepoAccessResult }
111
- >;
162
+ snapshots?: InstallationSnapshotRow[];
163
+ rows?: CachedAccessRow[];
112
164
  } = {},
113
165
  ) {
114
- const installation: InstallationReposPort = {
115
- listInstalled: async () =>
116
- opts.noInstallation
117
- ? { status: "none" }
118
- : {
119
- status: "found",
120
- orgs: [{ org: "acme", repos: ["acme/push", "acme/unlisted"] }],
121
- },
122
- listRepos: async () => ({}),
123
- addRepos: async () => {},
124
- removeRepos: async () => {},
166
+ const calls: string[] = [];
167
+ const cache: InstallationCachePort = {
168
+ listAgentSnapshots: async (accountId, appRef) => {
169
+ calls.push(`snapshots:${accountId}:${appRef}`);
170
+ return opts.snapshots ?? [snap()];
171
+ },
172
+ getAccessRows: async (q) => {
173
+ calls.push(`rows:${q.accountId}:${q.org}:${q.username}`);
174
+ return opts.rows ?? [row("push", "ok", true), row("readonly", "ok")];
175
+ },
125
176
  };
126
177
  const agent =
127
178
  opts.agent === undefined
128
179
  ? { id: "a1", repos: [], githubUsername: "dev", appId: 42 }
129
180
  : opts.agent && { id: "a1", repos: [], ...opts.agent };
181
+ const boom = () => {
182
+ throw new Error("GitHub must not be called");
183
+ };
130
184
  const svc = new InstallationReposService({
131
185
  agents: { get: async () => agent },
132
- access:
133
- opts.access ??
134
- (async () => ({ status: "ok", access: accessOf([orgResult()]) })),
135
- installation,
186
+ access: boom,
187
+ installation: {
188
+ listInstalled: boom,
189
+ listRepos: boom,
190
+ addRepos: boom,
191
+ removeRepos: boom,
192
+ },
193
+ cache,
136
194
  });
137
- return { svc };
195
+ return { svc, calls };
138
196
  }
139
197
 
140
- describe("InstallationReposService.list", () => {
141
- it("returns repos per org with hints for a bound user", async () => {
142
- const { svc } = build();
143
- expect(await svc.list("a1")).toEqual({
198
+ describe("InstallationReposService.list (cache read)", () => {
199
+ it("returns cached repos with hints and sync detail for a complete snapshot", async () => {
200
+ const { svc, calls } = build();
201
+ const r = await svc.list("a1");
202
+ expect(r).toMatchObject({
144
203
  status: "ok",
145
204
  appId: 42,
205
+ complete: true,
206
+ syncedAt: T0.toISOString(),
207
+ reposSeen: 2,
208
+ totalCount: 2,
146
209
  orgs: [
147
210
  {
148
211
  org: "acme",
212
+ complete: true,
213
+ syncedAt: T0.toISOString(),
214
+ reposSeen: 2,
215
+ totalCount: 2,
149
216
  repos: [
150
217
  { fullName: "acme/push", userCanPush: true },
151
- { fullName: "acme/unlisted" },
218
+ { fullName: "acme/readonly", userCanPush: false },
152
219
  ],
153
220
  },
154
221
  ],
155
222
  });
223
+ expect(calls[0]).toBe("snapshots:deployment:42");
156
224
  });
157
225
 
158
- it("omits hints for an unbound agent without calling access", async () => {
159
- let called = false;
160
- const { svc } = build({
226
+ it("omits hints when an access pair is errored or missing", async () => {
227
+ const r = await build({
228
+ rows: [row("push", "ok", true), row("readonly", "error")],
229
+ }).svc.list("a1");
230
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
231
+ });
232
+
233
+ it("omits hints and skips the access read for an unbound agent", async () => {
234
+ const { svc, calls } = build({
161
235
  agent: { githubUsername: null, appId: 42 },
162
- access: async () => {
163
- called = true;
164
- return { status: "unconfigured" };
165
- },
166
236
  });
167
237
  const r = await svc.list("a1");
168
- expect(called).toBe(false);
238
+ expect(calls.some((c) => c.startsWith("rows:"))).toBe(false);
169
239
  expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
170
240
  });
171
241
 
172
- it("omits hints when access is unconfigured or the lookup throws", async () => {
173
- for (const access of [
174
- async () => ({ status: "unconfigured" as const }),
175
- async () => {
176
- throw new Error("502");
177
- },
178
- ]) {
179
- const r = await build({ access }).svc.list("a1");
180
- expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
181
- }
242
+ it("an incomplete snapshot is not complete and carries error and rate-limit detail", async () => {
243
+ const reset = new Date("2026-11-20T11:00:00Z");
244
+ const r = await build({
245
+ snapshots: [
246
+ snap({
247
+ completedAt: null,
248
+ totalCount: 5,
249
+ lastError: "boom",
250
+ rateLimitResetAt: reset,
251
+ repos: [{ fullName: "acme/push" }],
252
+ }),
253
+ ],
254
+ }).svc.list("a1");
255
+ expect(r).toMatchObject({
256
+ status: "ok",
257
+ complete: false,
258
+ reposSeen: 1,
259
+ totalCount: 5,
260
+ lastError: "boom",
261
+ rateLimitResetAt: reset.toISOString(),
262
+ });
263
+ expect(r.status === "ok" && r.syncedAt).toBeUndefined();
264
+ expect(r.status === "ok" && r.orgs[0]?.repos.every(noHint)).toBe(true);
182
265
  });
183
266
 
184
- it("is skipped with a reason when the App matches no installation", async () => {
185
- const r = await build({ noInstallation: true }).svc.list("a1");
186
- expect(r).toEqual({
187
- status: "skipped",
188
- appId: 42,
189
- reason: NO_INSTALLATION_REASON,
267
+ it("no snapshots yet: ok, empty, not complete", async () => {
268
+ const r = await build({ snapshots: [] }).svc.list("a1");
269
+ expect(r).toMatchObject({ status: "ok", orgs: [], complete: false });
270
+ });
271
+
272
+ it("uses the agent's account for the cache scope", async () => {
273
+ const calls: string[] = [];
274
+ const svc = new InstallationReposService({
275
+ agents: {
276
+ get: async () => ({
277
+ id: "a1",
278
+ repos: [],
279
+ githubUsername: null,
280
+ appId: 7,
281
+ accountId: "acct-1",
282
+ }),
283
+ },
284
+ access: async () => ({ status: "unconfigured" }),
285
+ installation: {} as never,
286
+ cache: {
287
+ listAgentSnapshots: async (a, r) => {
288
+ calls.push(`${a}:${r}`);
289
+ return [];
290
+ },
291
+ getAccessRows: async () => [],
292
+ },
190
293
  });
294
+ await svc.list("a1");
295
+ expect(calls).toEqual(["acct-1:7"]);
191
296
  });
192
297
 
193
298
  it("reports unknown agent and a missing GH_APP_ID distinctly", async () => {