@app-vitals/agent-admin 1.83.0 → 1.84.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.
@@ -3625,6 +3625,18 @@
3625
3625
  "userCanPush": {
3626
3626
  "type": "boolean",
3627
3627
  "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)."
3628
+ },
3629
+ "accessCheckedAt": {
3630
+ "type": "string",
3631
+ "description": "When the bound user's access to this repo was last checked (ISO 8601), when a cached row exists."
3632
+ },
3633
+ "accessAttempts": {
3634
+ "type": "integer",
3635
+ "description": "Failed access checks for this repo since the last success, when any."
3636
+ },
3637
+ "accessError": {
3638
+ "type": "string",
3639
+ "description": "Last access-check error for this repo, when any."
3628
3640
  }
3629
3641
  },
3630
3642
  "required": [
@@ -3697,7 +3709,7 @@
3697
3709
  "reason"
3698
3710
  ]
3699
3711
  },
3700
- "description": "Orgs whose access listing is missing, partial or failed, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed."
3712
+ "description": "Orgs whose access listing is missing, partial or failed, whose cached access data is incomplete or stale, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed. `reason` says why (for stale data, when it was checked)."
3701
3713
  },
3702
3714
  "openWork": {
3703
3715
  "type": "array",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.83.0",
3
+ "version": "1.84.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.83.0",
46
+ "@app-vitals/agent-lib": "1.84.0",
47
47
  "@hono/zod-openapi": "^1.0.0",
48
48
  "@prisma/adapter-pg": "^7.10.0",
49
49
  "@prisma/client": "^7.10.0",
@@ -42,7 +42,13 @@ export interface InstallationReposView extends InstallationSyncView {
42
42
  appId?: number;
43
43
  orgs: ({
44
44
  org: string;
45
- repos: { fullName: string; userCanPush?: boolean }[];
45
+ repos: {
46
+ fullName: string;
47
+ userCanPush?: boolean;
48
+ accessCheckedAt?: string;
49
+ accessAttempts?: number;
50
+ accessError?: string;
51
+ }[];
46
52
  } & InstallationSyncView)[];
47
53
  }
48
54
 
@@ -310,7 +316,19 @@ export function renderInstallationReposBody(
310
316
  : r.userCanPush
311
317
  ? '<span class="badge badge-green" title="The bound user can push">user can push</span>'
312
318
  : '<span class="badge badge-warning" title="The bound user cannot push">user cannot push</span>';
313
- return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}</td></tr>`;
319
+ const detail = [
320
+ r.accessCheckedAt
321
+ ? `checked ${escapeHtml(r.accessCheckedAt)}`
322
+ : "",
323
+ r.accessAttempts
324
+ ? `${r.accessAttempts} failed attempts`
325
+ : "",
326
+ r.accessError ? `error: ${escapeHtml(r.accessError)}` : "",
327
+ ].filter(Boolean);
328
+ const meta = detail.length
329
+ ? ` <span style="color:#6b7280;font-size:12px">${detail.join("; ")}</span>`
330
+ : "";
331
+ return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}${meta}</td></tr>`;
314
332
  })
315
333
  .join("");
316
334
  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>`;
@@ -7363,6 +7363,36 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7363
7363
  headers: { "Content-Type": "application/json" },
7364
7364
  });
7365
7365
  }) as typeof fetch;
7366
+ // Sync reads the cache (GLC-2.3): unless a test seeds its own rows, serve a
7367
+ // complete, fresh cache that mirrors `pushable` over the installed, agent
7368
+ // and pushable repos.
7369
+ const checkedAt = new Date();
7370
+ const pushableRepos = opts.pushable ?? [
7371
+ "acme-eng/repo-1",
7372
+ "acme-eng/repo-3",
7373
+ ];
7374
+ const universe = [
7375
+ ...new Set([...state.installed, ...state.repos, ...pushableRepos]),
7376
+ ];
7377
+ const defaultSnapshots = [
7378
+ {
7379
+ org: "acme-eng",
7380
+ completedAt: checkedAt,
7381
+ totalCount: state.installed.length,
7382
+ lastError: null,
7383
+ rateLimitResetAt: null,
7384
+ repos: state.installed.map((fullName) => ({ fullName })),
7385
+ },
7386
+ ];
7387
+ const defaultAccess = universe.map((f) => ({
7388
+ repo: f.split("/")[1],
7389
+ status: "ok",
7390
+ canPush: pushableRepos.includes(f),
7391
+ level: pushableRepos.includes(f) ? "write" : "none",
7392
+ checkedAt,
7393
+ attempts: 0,
7394
+ lastError: null,
7395
+ }));
7366
7396
  const prisma = {
7367
7397
  agent: {
7368
7398
  findUnique: async () =>
@@ -7380,10 +7410,10 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7380
7410
  },
7381
7411
  },
7382
7412
  gitHubRepoSnapshot: {
7383
- findMany: async () => opts.snapshots ?? [],
7413
+ findMany: async () => opts.snapshots ?? defaultSnapshots,
7384
7414
  },
7385
7415
  gitHubRepoAccess: {
7386
- findMany: async () => opts.accessRows ?? [],
7416
+ findMany: async () => opts.accessRows ?? defaultAccess,
7387
7417
  },
7388
7418
  gitHubReconcileAudit: {
7389
7419
  create: async (args: { data: Record<string, unknown> }) => {
@@ -7435,6 +7465,13 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7435
7465
  const githubSync = createGithubSync({
7436
7466
  ...wiring,
7437
7467
  ...(openWork ? { openWork } : {}),
7468
+ syncOverrides: {
7469
+ lookupRepos: async () => [
7470
+ { org: "acme-eng", completedAt: checkedAt, repos: universe },
7471
+ ],
7472
+ // The live permission call agrees with `pushable`.
7473
+ verifyPush: async (_user, repo) => pushableRepos.includes(repo),
7474
+ },
7438
7475
  });
7439
7476
  const base = makeMockDeps();
7440
7477
  const app = createAdminApp({
package/src/agents-api.ts CHANGED
@@ -670,12 +670,9 @@ const InstallationSyncDetailShape = {
670
670
  .int()
671
671
  .optional()
672
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
- }),
673
+ nextAttemptAt: z.string().optional().openapi({
674
+ description: "Next refresh attempt while backing off (ISO 8601).",
675
+ }),
679
676
  leaseHolder: z
680
677
  .string()
681
678
  .optional()
@@ -701,6 +698,17 @@ const GithubInstallationReposListSchema = z
701
698
  description:
702
699
  "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).",
703
700
  }),
701
+ accessCheckedAt: z.string().optional().openapi({
702
+ description:
703
+ "When the bound user's access to this repo was last checked (ISO 8601), when a cached row exists.",
704
+ }),
705
+ accessAttempts: z.number().int().optional().openapi({
706
+ description:
707
+ "Failed access checks for this repo since the last success, when any.",
708
+ }),
709
+ accessError: z.string().optional().openapi({
710
+ description: "Last access-check error for this repo, when any.",
711
+ }),
704
712
  }),
705
713
  ),
706
714
  }),
@@ -738,7 +746,7 @@ const GithubSyncPreviewSchema = z
738
746
  }),
739
747
  skippedOrgs: SkippedOrgsSchema.optional().openapi({
740
748
  description:
741
- "Orgs whose access listing is missing, partial or failed, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed.",
749
+ "Orgs whose access listing is missing, partial or failed, whose cached access data is incomplete or stale, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed. `reason` says why (for stale data, when it was checked).",
742
750
  }),
743
751
  openWork: z.array(OpenWorkItemSchema).optional().openapi({
744
752
  description:
@@ -18,7 +18,8 @@ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
18
18
  import type { CrawlStore } from "./github-repo-crawler.ts";
19
19
  import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
20
20
  import type { RefreshDiscovery } from "./github-repo-refresher.ts";
21
- import { GithubSyncService } from "./github-sync.ts";
21
+ import { canPushForRole } from "./user-repo-access-resolver.ts";
22
+ import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
22
23
  import {
23
24
  createInstallationPort,
24
25
  type InstallationAgentRecord,
@@ -95,6 +96,8 @@ export interface InstallationReposWiringDeps
95
96
  extends GithubInstallationWiringDeps {
96
97
  /** Test seam: replaces the installer-App-backed port. */
97
98
  installationRepos?: InstallationReposPort;
99
+ /** Test seam: replaces the lookup-App-backed sync cache source and re-check. */
100
+ syncOverrides?: Pick<GithubSyncDeps, "lookupRepos" | "verifyPush">;
98
101
  }
99
102
 
100
103
  /**
@@ -125,9 +128,66 @@ export function createGithubSync(
125
128
  deps: InstallationReposWiringDeps,
126
129
  ): GithubSyncService {
127
130
  const client = lazyInstallerClient(deps);
131
+ const cache = new GitHubRepoCacheService(deps.prisma);
132
+ const lookupClients = new Map<string, GithubLookupClient>();
133
+ // The lookup client per App (and key version), reused with its installation tokens.
134
+ const lookupClient = async (accountId?: string | null) => {
135
+ const meta = await deps.appService.get("lookup", accountId);
136
+ if (!meta) return null;
137
+ const privateKey = await deps.appService.getPrivateKey("lookup", accountId);
138
+ if (!privateKey) return null;
139
+ const cacheKey = `${meta.accountId ?? ""}|${meta.appId}|${meta.updatedAt.getTime()}`;
140
+ let c = lookupClients.get(cacheKey);
141
+ if (!c) {
142
+ c = new GithubLookupClient({
143
+ appId: meta.appId,
144
+ privateKey,
145
+ apiBase: deps.apiBase,
146
+ fetchFn: deps.fetchFn,
147
+ now: deps.now,
148
+ });
149
+ lookupClients.set(cacheKey, c);
150
+ }
151
+ return { client: c, appId: meta.appId };
152
+ };
128
153
  return new GithubSyncService({
129
154
  agents: new PrismaInstallationAgents(deps.prisma, deps.agentEnv),
130
155
  access: deps.access,
156
+ cache,
157
+ ...(deps.now ? { now: deps.now } : {}),
158
+ lookupRepos: async (accountId) => {
159
+ const lookup = await lookupClient(accountId);
160
+ if (!lookup) return [];
161
+ // The crawler files a deployment-wide App's snapshots under accountId "".
162
+ const snapshots = await cache.listLookupOrgSnapshots(
163
+ accountId ? [accountId, ""] : [""],
164
+ lookup.appId,
165
+ );
166
+ return snapshots.map((s) => ({
167
+ org: s.org,
168
+ completedAt: s.completedAt,
169
+ repos: s.repos.map((r) => r.fullName),
170
+ }));
171
+ },
172
+ // One permission call per removal candidate; undefined on any failure.
173
+ verifyPush: async (username, repo, accountId) => {
174
+ try {
175
+ const lookup = await lookupClient(accountId);
176
+ if (!lookup) return undefined;
177
+ const [owner, name] = repo.split("/");
178
+ if (!owner || !name) return undefined;
179
+ const { role } =
180
+ await lookup.client.getCollaboratorPermissionWithRateLimit(
181
+ owner,
182
+ name,
183
+ username,
184
+ );
185
+ return canPushForRole(role);
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ },
190
+ ...deps.syncOverrides,
131
191
  installation:
132
192
  deps.installationRepos ??
133
193
  createInstallationReposPort(createInstallationPort(client), client),
@@ -4,6 +4,7 @@ import {
4
4
  envWith,
5
5
  fakeOpenWork,
6
6
  fakePrisma,
7
+ freshCache,
7
8
  } from "./github-installation.fixtures.ts";
8
9
  import {
9
10
  createGithubInstallationRepos,
@@ -72,17 +73,35 @@ describe("createGithubInstallationRepos", () => {
72
73
  });
73
74
 
74
75
  describe("createGithubSync", () => {
75
- const build = (openWork?: ReturnType<typeof fakeOpenWork>["port"]) => {
76
- const { prisma, state } = fakePrisma(["acme/old", "acme/api"]);
76
+ const ALL = ["acme/old", "acme/api"];
77
+ const build = (
78
+ openWork?: ReturnType<typeof fakeOpenWork>["port"],
79
+ opts: { checkedAt?: Date; verify?: boolean | undefined } = {},
80
+ ) => {
81
+ const checkedAt = opts.checkedAt ?? new Date();
82
+ const { prisma, state } = fakePrisma(
83
+ ALL,
84
+ freshCache("acme", ALL, ["acme/api"], checkedAt),
85
+ );
86
+ const verified: string[] = [];
77
87
  const svc = createGithubSync({
78
88
  prisma,
79
89
  appService: noApp,
80
90
  access: accessFor(["acme/api"]),
81
91
  agentEnv: envWith({ GH_APP_ID: "42" }),
82
92
  installationRepos: portWith([]),
93
+ syncOverrides: {
94
+ lookupRepos: async () => [
95
+ { org: "acme", completedAt: checkedAt, repos: ALL },
96
+ ],
97
+ verifyPush: async (_u, repo) => {
98
+ verified.push(repo);
99
+ return "verify" in opts ? opts.verify : false;
100
+ },
101
+ },
83
102
  openWork,
84
103
  });
85
- return { svc, state };
104
+ return { svc, state, verified };
86
105
  };
87
106
 
88
107
  it("with a port: preview lists affected open work and apply blocks it", async () => {
@@ -116,4 +135,37 @@ describe("createGithubSync", () => {
116
135
  expect(res.status).toBe("applied");
117
136
  expect(state.repos).toEqual(["acme/api"]);
118
137
  });
138
+
139
+ it("reads the cache: a stale org is skipped with the reason and nothing is removed", async () => {
140
+ const old = new Date(Date.now() - 24 * 3_600_000);
141
+ const { svc, state, verified } = build(undefined, { checkedAt: old });
142
+ const preview = await svc.preview("a1");
143
+ if (preview.status !== "previewed") throw new Error(preview.status);
144
+ expect(preview.plan.removedRepos).toEqual([]);
145
+ expect(preview.plan.skippedOrgs[0]?.reason).toContain("stale (checked");
146
+ const res = await svc.apply({
147
+ agentId: "a1",
148
+ caller: "root",
149
+ appAdds: [],
150
+ appRemoves: ["acme/old"],
151
+ agentRemoves: ["acme/old"],
152
+ });
153
+ expect(res.status).toBe("noop");
154
+ expect(verified).toEqual([]);
155
+ expect(state.repos).toEqual(ALL);
156
+ });
157
+
158
+ it("apply drops a candidate the live re-check still sees as pushable", async () => {
159
+ const { svc, state, verified } = build(undefined, { verify: true });
160
+ const res = await svc.apply({
161
+ agentId: "a1",
162
+ caller: "root",
163
+ appAdds: [],
164
+ appRemoves: [],
165
+ agentRemoves: ["acme/old"],
166
+ });
167
+ expect(res.status).toBe("noop");
168
+ expect(verified).toEqual(["acme/old"]);
169
+ expect(state.repos).toEqual(ALL);
170
+ });
119
171
  });
@@ -33,7 +33,48 @@ export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
33
33
  });
34
34
  };
35
35
 
36
- export function fakePrisma(repos: string[]) {
36
+ /** Cached rows the fake prisma serves (GLC-2.3 sync reads them). */
37
+ export interface FakeCache {
38
+ snapshots?: unknown[];
39
+ access?: unknown[];
40
+ }
41
+
42
+ /** A completed agent-App snapshot plus ok access rows for `repos` in `org`, all checked at `checkedAt`. */
43
+ export function freshCache(
44
+ org: string,
45
+ repos: string[],
46
+ pushable: string[],
47
+ checkedAt: Date,
48
+ ): FakeCache {
49
+ return {
50
+ snapshots: [
51
+ {
52
+ org,
53
+ completedAt: checkedAt,
54
+ totalCount: repos.length,
55
+ lastError: null,
56
+ rateLimitResetAt: null,
57
+ attempts: 0,
58
+ nextAttemptAt: null,
59
+ leaseHolder: null,
60
+ leasedUntil: null,
61
+ lastTickAt: null,
62
+ repos: repos.map((fullName) => ({ fullName })),
63
+ },
64
+ ],
65
+ access: repos.map((f) => ({
66
+ repo: f.slice(f.indexOf("/") + 1),
67
+ status: "ok",
68
+ canPush: pushable.includes(f),
69
+ level: pushable.includes(f) ? "write" : "none",
70
+ checkedAt,
71
+ attempts: 0,
72
+ lastError: null,
73
+ })),
74
+ };
75
+ }
76
+
77
+ export function fakePrisma(repos: string[], cache: FakeCache = {}) {
37
78
  const state = {
38
79
  repos: [...repos],
39
80
  audits: 0,
@@ -53,10 +94,10 @@ export function fakePrisma(repos: string[]) {
53
94
  gitHubRepoSnapshot: {
54
95
  findMany: async (args: unknown) => {
55
96
  state.snapshotQueries.push(args);
56
- return [];
97
+ return cache.snapshots ?? [];
57
98
  },
58
99
  },
59
- gitHubRepoAccess: { findMany: async () => [] },
100
+ gitHubRepoAccess: { findMany: async () => cache.access ?? [] },
60
101
  gitHubReconcileAudit: {
61
102
  create: async () => {
62
103
  state.audits += 1;
@@ -146,6 +146,21 @@ export class GitHubRepoCacheService {
146
146
  }));
147
147
  }
148
148
 
149
+ /** Lookup-App snapshots with their org and repos (GitHub Sync, GLC-2.3). Reads only the cache. */
150
+ async listLookupOrgSnapshots(accountIds: string[], appRef: string) {
151
+ requireNonEmpty("appRef", appRef);
152
+ const rows = await this.prisma.gitHubRepoSnapshot.findMany({
153
+ where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
154
+ include: { repos: { select: { fullName: true } } },
155
+ orderBy: { org: "asc" },
156
+ });
157
+ return rows.map((r) => ({
158
+ org: r.org,
159
+ completedAt: r.completedAt,
160
+ repos: r.repos,
161
+ }));
162
+ }
163
+
149
164
  /** Agent-App installation snapshots (with their repos) for one account scope and App id. Reads only the cache. */
150
165
  async listAgentSnapshots(accountId: string, appRef: string) {
151
166
  requireNonEmpty("accountId", accountId);
@@ -0,0 +1,134 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ accessFor,
4
+ envWith,
5
+ fakePrisma,
6
+ freshCache,
7
+ } from "./github-installation.fixtures.ts";
8
+ import {
9
+ createGithubInstallationRepos,
10
+ createGithubSync,
11
+ } from "./github-installation-wiring.ts";
12
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
13
+
14
+ // Sync preview over the real cache service (fake prisma): complete, partial, stale.
15
+
16
+ const REPOS = ["acme/a", "acme/b", "acme/c"];
17
+ const PUSHABLE = ["acme/a"];
18
+ const HOUR = 3_600_000;
19
+
20
+ const port: InstallationReposPort = {
21
+ listRepos: async () => ({ acme: REPOS }),
22
+ listInstalled: async () => ({
23
+ status: "found",
24
+ orgs: [{ org: "acme", repos: REPOS }],
25
+ }),
26
+ addRepos: async () => {},
27
+ removeRepos: async () => {},
28
+ };
29
+
30
+ function preview(cache: ReturnType<typeof freshCache>, now = new Date()) {
31
+ const { prisma } = fakePrisma(REPOS, cache);
32
+ const svc = createGithubSync({
33
+ prisma,
34
+ appService: { get: async () => null, getPrivateKey: async () => null },
35
+ access: accessFor([]), // the live resolver must not be consulted
36
+ agentEnv: envWith({ GH_APP_ID: "42" }),
37
+ installationRepos: port,
38
+ now: () => now,
39
+ syncOverrides: {
40
+ lookupRepos: async () => [
41
+ {
42
+ org: "acme",
43
+ completedAt: new Date(now.getTime() - 1000),
44
+ repos: REPOS,
45
+ },
46
+ ],
47
+ },
48
+ });
49
+ return svc.preview("a1");
50
+ }
51
+
52
+ describe("sync preview over the cache", () => {
53
+ it("proposes removals from a complete, fresh org", async () => {
54
+ const now = new Date();
55
+ const r = await preview(freshCache("acme", REPOS, PUSHABLE, now), now);
56
+ if (r.status !== "previewed") throw new Error(r.status);
57
+ expect(r.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
58
+ expect(r.plan.skippedOrgs).toEqual([]);
59
+ });
60
+
61
+ it("skips a partial org (a repo has no ok row) and says it is incomplete", async () => {
62
+ const now = new Date();
63
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
64
+ cache.access = (cache.access as { repo: string }[]).filter(
65
+ (r) => r.repo !== "c",
66
+ );
67
+ const r = await preview(cache, now);
68
+ if (r.status !== "previewed") throw new Error(r.status);
69
+ expect(r.plan.removedRepos).toEqual([]);
70
+ expect(r.plan.skippedOrgs).toEqual([
71
+ { org: "acme", reason: "access data is incomplete" },
72
+ ]);
73
+ });
74
+
75
+ it("skips an org whose crawl has not completed", async () => {
76
+ const now = new Date();
77
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
78
+ (cache.snapshots as { completedAt: Date | null }[])[0]!.completedAt = null;
79
+ const r = await preview(cache, now);
80
+ if (r.status !== "previewed") throw new Error(r.status);
81
+ expect(r.plan.removedRepos).toEqual([]);
82
+ expect(r.plan.skippedOrgs[0]?.reason).toBe("access data is incomplete");
83
+ });
84
+
85
+ it("skips a stale org and reports when it was checked", async () => {
86
+ const now = new Date();
87
+ const checked = new Date(now.getTime() - 7 * HOUR);
88
+ const r = await preview(freshCache("acme", REPOS, PUSHABLE, checked), now);
89
+ if (r.status !== "previewed") throw new Error(r.status);
90
+ expect(r.plan.removedRepos).toEqual([]);
91
+ expect(r.plan.skippedOrgs[0]?.reason).toBe(
92
+ `access data is stale (checked ${checked.toISOString()})`,
93
+ );
94
+ expect(r.warnings.join()).toContain("stale");
95
+ });
96
+
97
+ it("an errored access row makes the org incomplete, never 'no access'", async () => {
98
+ const now = new Date();
99
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
100
+ (cache.access as { repo: string; status: string }[])[1]!.status = "error";
101
+ const r = await preview(cache, now);
102
+ if (r.status !== "previewed") throw new Error(r.status);
103
+ expect(r.plan.removedRepos).toEqual([]);
104
+ });
105
+ });
106
+
107
+ describe("installation list access detail", () => {
108
+ it("adds checkedAt, attempts and last error per repo", async () => {
109
+ const now = new Date("2026-11-21T00:00:00.000Z");
110
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
111
+ Object.assign((cache.access as Record<string, unknown>[])[1] as object, {
112
+ status: "error",
113
+ attempts: 2,
114
+ lastError: "boom",
115
+ });
116
+ const { prisma } = fakePrisma(REPOS, cache);
117
+ const svc = createGithubInstallationRepos({
118
+ prisma,
119
+ appService: { get: async () => null, getPrivateKey: async () => null },
120
+ access: accessFor([]),
121
+ agentEnv: envWith({ GH_APP_ID: "42" }),
122
+ installationRepos: port,
123
+ });
124
+ const r = await svc.list("a1");
125
+ if (r.status !== "ok") throw new Error(r.status);
126
+ const repos = r.orgs[0]?.repos ?? [];
127
+ expect(repos[0]?.accessCheckedAt).toBe(now.toISOString());
128
+ expect(repos[1]).toMatchObject({
129
+ accessAttempts: 2,
130
+ accessError: "boom",
131
+ });
132
+ expect(repos[1]?.userCanPush).toBeUndefined();
133
+ });
134
+ });
@@ -0,0 +1,125 @@
1
+ /**
2
+ * admin/src/github-sync-cached-access.ts
3
+ * Builds the bound user's access result for GitHub Sync from the repo/access
4
+ * cache (GLC-2.3). No GitHub call, no I/O: callers pass the cached rows.
5
+ *
6
+ * An org is usable (status ok) only when its data is complete and fresh:
7
+ * - every required crawl snapshot has completed;
8
+ * - every repo in the org has an ok access row;
9
+ * - every one of those rows (and each completed crawl) was checked within
10
+ * maxAgeMs of now.
11
+ * Otherwise the org is reported partial with a reason and no repos, so the
12
+ * shared access rules skip it (unknown is never none): incomplete data wins
13
+ * over stale data when both apply.
14
+ */
15
+
16
+ import type { CachedAccessRow } from "./installation-repos-service.ts";
17
+ import {
18
+ INCOMPLETE_ACCESS_REASON,
19
+ staleAccessReason,
20
+ } from "./repo-access-rules.ts";
21
+ import {
22
+ canPushForRole,
23
+ type OrgAccessResult,
24
+ type ResolvedRepoAccess,
25
+ type UserRepoAccessResult,
26
+ } from "./user-repo-access-resolver.ts";
27
+ import type { RepoRole } from "./github-lookup-client.ts";
28
+
29
+ export interface CachedOrgInput {
30
+ org: string;
31
+ /** completedAt of each crawl snapshot this org depends on; null = not completed. Empty = none needed. */
32
+ crawls: { completedAt: Date | null }[];
33
+ /** True when a crawl snapshot that must exist does not. */
34
+ crawlMissing?: boolean;
35
+ /** Every repo (full name) that needs an answer. */
36
+ repos: string[];
37
+ /** Cached access rows for the user over those repos. */
38
+ rows: readonly CachedAccessRow[];
39
+ }
40
+
41
+ const ROLES = new Set<string>([
42
+ "admin",
43
+ "maintain",
44
+ "write",
45
+ "triage",
46
+ "read",
47
+ "none",
48
+ ]);
49
+
50
+ const nameOf = (fullName: string): string =>
51
+ fullName.slice(fullName.indexOf("/") + 1).toLowerCase();
52
+
53
+ export function buildCachedAccess(opts: {
54
+ username: string;
55
+ now: Date;
56
+ maxAgeMs: number;
57
+ orgs: readonly CachedOrgInput[];
58
+ }): UserRepoAccessResult {
59
+ const staleBefore = opts.now.getTime() - opts.maxAgeMs;
60
+ const orgs: OrgAccessResult[] = [];
61
+ for (const o of opts.orgs) {
62
+ const byRepo = new Map(o.rows.map((r) => [r.repo.toLowerCase(), r]));
63
+ const answers = o.repos.map((f) => ({
64
+ fullName: f,
65
+ row: byRepo.get(nameOf(f)),
66
+ }));
67
+ const missing = answers.filter((a) => a.row?.status !== "ok");
68
+ const incomplete =
69
+ o.crawlMissing === true ||
70
+ o.crawls.some((c) => c.completedAt === null) ||
71
+ missing.length > 0;
72
+ if (incomplete) {
73
+ orgs.push({
74
+ org: o.org,
75
+ status: "partial",
76
+ repos: [],
77
+ unresolved: missing.length,
78
+ reason: INCOMPLETE_ACCESS_REASON,
79
+ });
80
+ continue;
81
+ }
82
+ const times = [
83
+ ...o.crawls.map((c) => c.completedAt as Date),
84
+ ...answers.map((a) => a.row?.checkedAt),
85
+ ];
86
+ const unknownTime = times.some((t) => t === undefined);
87
+ const known = times.filter((t): t is Date => t !== undefined);
88
+ const oldest = known.sort((a, b) => a.getTime() - b.getTime())[0];
89
+ if (unknownTime || (oldest && oldest.getTime() < staleBefore)) {
90
+ orgs.push({
91
+ org: o.org,
92
+ status: "partial",
93
+ repos: [],
94
+ unresolved: 0,
95
+ reason: staleAccessReason(unknownTime ? undefined : oldest),
96
+ });
97
+ continue;
98
+ }
99
+ const repos: ResolvedRepoAccess[] = answers.map(({ fullName, row }) => {
100
+ const level: RepoRole = ROLES.has(row?.level ?? "")
101
+ ? (row?.level as RepoRole)
102
+ : row?.canPush
103
+ ? "write"
104
+ : "read";
105
+ return {
106
+ fullName,
107
+ level,
108
+ canPush: row?.canPush ?? canPushForRole(level),
109
+ };
110
+ });
111
+ orgs.push({ org: o.org, status: "ok", repos, unresolved: 0 });
112
+ }
113
+ const unresolved = orgs.reduce((a, o) => a + o.unresolved, 0);
114
+ return {
115
+ username: opts.username,
116
+ outcome: "ok",
117
+ // Per-org gating decides what is usable; a nonexistent user is also
118
+ // caught by the live re-check before any removal is applied.
119
+ userVerified: true,
120
+ orgs,
121
+ unresolved,
122
+ complete: orgs.length > 0 && orgs.every((o) => o.status === "ok"),
123
+ checkedAt: opts.now.toISOString(),
124
+ };
125
+ }
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ GithubSyncService,
4
+ REVERIFY_FAILED_REASON,
5
+ STILL_PUSHABLE_REASON,
6
+ } from "./github-sync.ts";
7
+ import type { InstallationCachePort } from "./installation-repos-service.ts";
8
+ import { MAX_UNCONFIRMED_REMOVALS } from "./installation-ports.ts";
9
+
10
+ const NOW = new Date("2026-11-21T00:00:00.000Z");
11
+ const names = (n: number) => Array.from({ length: n }, (_, i) => `acme/r${i}`);
12
+
13
+ function build(
14
+ repos: string[],
15
+ verify: (repo: string) => Promise<boolean | undefined>,
16
+ ) {
17
+ const removed: string[][] = [];
18
+ const cache: InstallationCachePort = {
19
+ listAgentSnapshots: async () => [
20
+ {
21
+ org: "acme",
22
+ completedAt: NOW,
23
+ totalCount: repos.length,
24
+ lastError: null,
25
+ rateLimitResetAt: null,
26
+ repos: repos.map((fullName) => ({ fullName })),
27
+ },
28
+ ],
29
+ getAccessRows: async () =>
30
+ repos.map((f) => ({
31
+ repo: f.slice(5),
32
+ status: "ok",
33
+ canPush: false,
34
+ level: "none",
35
+ checkedAt: NOW,
36
+ })),
37
+ };
38
+ const svc = new GithubSyncService({
39
+ agents: {
40
+ get: async () => ({
41
+ id: "ag",
42
+ githubUsername: "octo",
43
+ appId: 7,
44
+ repos: [],
45
+ }),
46
+ setRepos: async () => {},
47
+ },
48
+ access: async () => {
49
+ throw new Error("live resolver must not be called");
50
+ },
51
+ cache,
52
+ now: () => NOW,
53
+ verifyPush: (_u, repo) => verify(repo),
54
+ installation: {
55
+ listInstalled: async () => ({
56
+ status: "found",
57
+ orgs: [{ org: "acme", repos }],
58
+ }),
59
+ addRepos: async () => {},
60
+ removeRepos: async (_a, _o, r) => {
61
+ removed.push([...r]);
62
+ },
63
+ },
64
+ audit: { write: async () => "audit-1" },
65
+ });
66
+ return { svc, removed };
67
+ }
68
+
69
+ const input = (appRemoves: string[], extra = {}) => ({
70
+ agentId: "ag",
71
+ caller: "root",
72
+ appAdds: [],
73
+ appRemoves,
74
+ agentRemoves: [],
75
+ ...extra,
76
+ });
77
+
78
+ describe("GithubSyncService live re-verify of removals", () => {
79
+ it("removes only candidates the live call says cannot push, one call each", async () => {
80
+ const calls: string[] = [];
81
+ const { svc, removed } = build(["acme/a", "acme/b"], async (r) => {
82
+ calls.push(r);
83
+ return false;
84
+ });
85
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
86
+ expect(res.status).toBe("applied");
87
+ expect(calls).toEqual(["acme/a", "acme/b"]);
88
+ expect(removed).toEqual([["acme/a", "acme/b"]]);
89
+ });
90
+
91
+ it("drops a candidate that is still pushable and reports it", async () => {
92
+ const { svc, removed } = build(
93
+ ["acme/a", "acme/b"],
94
+ async (r) => r === "acme/a",
95
+ );
96
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
97
+ if (res.status !== "applied") throw new Error(res.status);
98
+ expect(removed).toEqual([["acme/b"]]);
99
+ expect(res.plan.notApplied).toEqual([
100
+ { repo: "acme/a", reason: STILL_PUSHABLE_REASON },
101
+ ]);
102
+ });
103
+
104
+ it("drops a candidate when the call returns undefined or throws (unknown is never none)", async () => {
105
+ const { svc, removed } = build(["acme/a", "acme/b"], async (r) => {
106
+ if (r === "acme/b") throw new Error("boom");
107
+ return undefined;
108
+ });
109
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
110
+ if (res.status !== "noop") throw new Error(res.status);
111
+ expect(removed).toEqual([]);
112
+ expect(res.plan.notApplied.map((n) => n.reason)).toEqual([
113
+ REVERIFY_FAILED_REASON,
114
+ REVERIFY_FAILED_REASON,
115
+ ]);
116
+ });
117
+
118
+ it("preview makes no live calls", async () => {
119
+ let calls = 0;
120
+ const { svc } = build(["acme/a"], async () => {
121
+ calls += 1;
122
+ return false;
123
+ });
124
+ const r = await svc.preview("ag");
125
+ if (r.status !== "previewed") throw new Error(r.status);
126
+ expect(r.plan.appRemoves).toEqual(["acme/a"]);
127
+ expect(calls).toBe(0);
128
+ });
129
+
130
+ it("the removal cap counts what survives the re-check", async () => {
131
+ const repos = names(MAX_UNCONFIRMED_REMOVALS + 1);
132
+ const { svc } = build(repos, async (r) => r === repos[0]);
133
+ const res = await svc.apply(input(repos));
134
+ expect(res.status).toBe("applied");
135
+ const { svc: svc2 } = build(repos, async () => false);
136
+ expect((await svc2.apply(input(repos))).status).toBe("removal_cap");
137
+ });
138
+ });
@@ -25,8 +25,15 @@
25
25
  */
26
26
 
27
27
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
28
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
29
+ import { DEFAULT_REFRESH_STALENESS_CAP_MS } from "./github-repo-refresher.ts";
30
+ import {
31
+ buildCachedAccess,
32
+ type CachedOrgInput,
33
+ } from "./github-sync-cached-access.ts";
28
34
  import {
29
35
  identityOf,
36
+ type InstallationCachePort,
30
37
  type InstallationReposPort,
31
38
  NO_INSTALLATION_REASON,
32
39
  } from "./installation-repos-service.ts";
@@ -60,6 +67,8 @@ export const NOT_ADDABLE_REASON = "the bound user cannot push to this repo";
60
67
  export const ALREADY_INSTALLED_REASON = "already on the agent installation";
61
68
  export const NOT_INSTALLED_ORG_REASON =
62
69
  "the agent App is not installed on this org";
70
+ export const REVERIFY_FAILED_REASON =
71
+ "the live permission re-check failed, so the removal was dropped";
63
72
  export const NOT_PRESENT_REASON =
64
73
  "not on the agent installation or in the agent's repos";
65
74
 
@@ -230,9 +239,42 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
230
239
  };
231
240
  }
232
241
 
242
+ /** One org's lookup-App crawl from the cache (adds are drawn from it). */
243
+ export interface CachedLookupOrg {
244
+ org: string;
245
+ completedAt: Date | null;
246
+ repos: readonly string[];
247
+ }
248
+
249
+ /** Default freshness bound: the refresher's staleness cap (the longest data is left unrefreshed). */
250
+ export const DEFAULT_SYNC_MAX_AGE_MS = DEFAULT_REFRESH_STALENESS_CAP_MS;
251
+
233
252
  export interface GithubSyncDeps {
234
253
  agents: InstallationAgentsPort;
254
+ /** Live resolver; used only when no `cache` is given. */
235
255
  access: GithubAccessPreviewFn;
256
+ /**
257
+ * The repo/access cache (GLC-2.3). When set, access is built from cached
258
+ * rows and an org is used only while its data is complete and fresh.
259
+ */
260
+ cache?: InstallationCachePort;
261
+ /** Cached lookup-App crawl per org, the source of installation adds. */
262
+ lookupRepos?: (
263
+ accountId: string | null | undefined,
264
+ ) => Promise<CachedLookupOrg[]>;
265
+ /** Freshness bound for cached data, ms. Default DEFAULT_SYNC_MAX_AGE_MS. */
266
+ maxAgeMs?: number;
267
+ now?: () => Date;
268
+ /**
269
+ * One live permission call for a removal candidate: true = the user can
270
+ * still push, false = definitively cannot, undefined = could not tell.
271
+ * Apply drops every candidate that is not definitively false.
272
+ */
273
+ verifyPush?: (
274
+ username: string,
275
+ repo: string,
276
+ accountId?: string | null,
277
+ ) => Promise<boolean | undefined>;
236
278
  installation: Pick<
237
279
  InstallationReposPort,
238
280
  "listInstalled" | "addRepos" | "removeRepos"
@@ -308,10 +350,11 @@ export class GithubSyncService {
308
350
  async apply(input: GithubSyncApplyInput): Promise<GithubSyncApplyResult> {
309
351
  const agent = await this.deps.agents.get(input.agentId);
310
352
  if (!agent) return { status: "agent_not_found" };
311
- const plan = await this.planFor(agent, input);
353
+ let plan = await this.planFor(agent, input);
312
354
  if (plan.skipped) {
313
355
  return { status: "skipped", reason: plan.skipReason ?? "skipped" };
314
356
  }
357
+ plan = await this.reverifyRemovals(plan, agent);
315
358
  if (plan.appAdds.length + plan.removedRepos.length === 0) {
316
359
  return { status: "noop", plan };
317
360
  }
@@ -374,6 +417,123 @@ export class GithubSyncService {
374
417
  return { status: "applied", plan, auditId, warnings };
375
418
  }
376
419
 
420
+ /** Drops every removal the live permission call does not confirm (unknown is never none). */
421
+ private async reverifyRemovals(
422
+ plan: GithubSyncPlan,
423
+ agent: InstallationAgentRecord,
424
+ ): Promise<GithubSyncPlan> {
425
+ const verify = this.deps.verifyPush;
426
+ const username = agent.githubUsername?.trim();
427
+ if (!verify || !username || plan.removedRepos.length === 0) return plan;
428
+ const dropped = new Map<string, string>();
429
+ for (const repo of plan.removedRepos) {
430
+ let pushable: boolean | undefined;
431
+ try {
432
+ pushable = await verify(username, repo, agent.accountId);
433
+ } catch {
434
+ pushable = undefined;
435
+ }
436
+ if (pushable === false) continue;
437
+ dropped.set(
438
+ repo,
439
+ pushable === true ? STILL_PUSHABLE_REASON : REVERIFY_FAILED_REASON,
440
+ );
441
+ }
442
+ if (dropped.size === 0) return plan;
443
+ const keep = (repos: string[]) => repos.filter((r) => !dropped.has(r));
444
+ const appRemoves = keep(plan.appRemoves);
445
+ const agentRemoves = keep(plan.agentRemoves);
446
+ return {
447
+ ...plan,
448
+ appRemoves,
449
+ agentRemoves,
450
+ removedRepos: sorted(new Set([...appRemoves, ...agentRemoves])),
451
+ notApplied: [
452
+ ...plan.notApplied,
453
+ ...[...dropped].map(([repo, reason]) => ({ repo, reason })),
454
+ ].sort((a, b) => a.repo.localeCompare(b.repo)),
455
+ };
456
+ }
457
+
458
+ /** Access from the cache (complete and fresh orgs only), with the installed orgs. */
459
+ private async cachedAccess(
460
+ agent: InstallationAgentRecord,
461
+ username: string,
462
+ installed: { org: string; repos: string[] }[],
463
+ ): Promise<UserRepoAccessResult> {
464
+ const cache = this.deps.cache as InstallationCachePort;
465
+ const accountId = agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY;
466
+ const now = (this.deps.now ?? (() => new Date()))();
467
+ const maxAgeMs = this.deps.maxAgeMs ?? DEFAULT_SYNC_MAX_AGE_MS;
468
+ let agentSnaps: Awaited<
469
+ ReturnType<InstallationCachePort["listAgentSnapshots"]>
470
+ > = [];
471
+ let lookup: CachedLookupOrg[] = [];
472
+ let readFailed = false;
473
+ try {
474
+ agentSnaps = await cache.listAgentSnapshots(
475
+ accountId,
476
+ String(agent.appId),
477
+ );
478
+ if (this.deps.lookupRepos)
479
+ lookup = await this.deps.lookupRepos(agent.accountId);
480
+ } catch {
481
+ readFailed = true;
482
+ }
483
+ const key = (s: string) => s.toLowerCase();
484
+ const orgNames = new Map<string, string>();
485
+ for (const i of installed) orgNames.set(key(i.org), i.org);
486
+ for (const r of agent.repos) {
487
+ const o = repoOrg(r);
488
+ if (o && !orgNames.has(key(o))) orgNames.set(key(o), o);
489
+ }
490
+ const inputs: CachedOrgInput[] = [];
491
+ for (const [k, org] of orgNames) {
492
+ const inst = installed.find((i) => key(i.org) === k);
493
+ const snap = agentSnaps.find((s) => key(s.org) === k);
494
+ const lk = lookup.filter((l) => key(l.org) === k);
495
+ const repos = new Map<string, string>();
496
+ for (const r of [
497
+ ...(inst?.repos ?? []),
498
+ ...agent.repos.filter((r) => key(repoOrg(r)) === k),
499
+ ...lk.flatMap((l) => l.repos),
500
+ ]) {
501
+ repos.set(key(r), r);
502
+ }
503
+ const crawls = [
504
+ ...(inst && snap ? [{ completedAt: snap.completedAt }] : []),
505
+ ...lk.map((l) => ({ completedAt: l.completedAt })),
506
+ ];
507
+ let rows: Awaited<ReturnType<InstallationCachePort["getAccessRows"]>> =
508
+ [];
509
+ let failed = readFailed;
510
+ if (!failed && repos.size > 0) {
511
+ try {
512
+ rows = await cache.getAccessRows({
513
+ accountId,
514
+ org,
515
+ username,
516
+ repos: [...repos.values()].map((f) => f.slice(f.indexOf("/") + 1)),
517
+ });
518
+ } catch {
519
+ failed = true;
520
+ }
521
+ }
522
+ inputs.push({
523
+ org,
524
+ crawls,
525
+ // A read failure, an installed org with no crawl, or a lookup source with no crawl of this org.
526
+ crawlMissing:
527
+ failed ||
528
+ (inst !== undefined && !snap) ||
529
+ (this.deps.lookupRepos !== undefined && lk.length === 0),
530
+ repos: [...repos.values()],
531
+ rows,
532
+ });
533
+ }
534
+ return buildCachedAccess({ username, now, maxAgeMs, orgs: inputs });
535
+ }
536
+
377
537
  private async planFor(
378
538
  agent: InstallationAgentRecord,
379
539
  requested?: SyncLists,
@@ -382,22 +542,28 @@ export class GithubSyncService {
382
542
  if (!username) {
383
543
  return skippedPlan(accessSkipReason(username, null) as string);
384
544
  }
385
- const preview = await this.deps.access(username, agent.accountId);
386
- if (preview.status === "unconfigured") {
387
- return skippedPlan("GitHub Apps are not configured");
545
+ let liveAccess: UserRepoAccessResult | null = null;
546
+ if (!this.deps.cache) {
547
+ const preview = await this.deps.access(username, agent.accountId);
548
+ if (preview.status === "unconfigured") {
549
+ return skippedPlan("GitHub Apps are not configured");
550
+ }
551
+ // Whole-call skips need no installation calls.
552
+ const skip = accessSkipReason(username, preview.access);
553
+ if (skip) return skippedPlan(skip);
554
+ liveAccess = preview.access;
388
555
  }
389
- // Whole-call skips need no installation calls.
390
- const skip = accessSkipReason(username, preview.access);
391
- if (skip) return skippedPlan(skip);
392
556
  if (agent.appId === undefined) return skippedPlan(MISSING_APP_ID_REASON);
393
557
  const installed = await this.deps.installation.listInstalled(
394
558
  agent.appId,
395
559
  identityOf(agent),
396
560
  );
397
561
  if (installed.status === "none") return skippedPlan(NO_INSTALLATION_REASON);
562
+ const resolved =
563
+ liveAccess ?? (await this.cachedAccess(agent, username, installed.orgs));
398
564
  return planGithubSync({
399
565
  username,
400
- access: preview.access,
566
+ access: resolved,
401
567
  agentRepos: agent.repos,
402
568
  installationRepos: Object.fromEntries(
403
569
  installed.orgs.map(({ org, repos }) => [org, repos]),
@@ -44,6 +44,12 @@ export interface InstallationRepoView {
44
44
  fullName: string;
45
45
  /** Present only when the bound user's access to this repo is known. */
46
46
  userCanPush?: boolean;
47
+ /** ISO time the bound user's access to this repo was last checked, when a row exists. */
48
+ accessCheckedAt?: string;
49
+ /** Failed access checks for this repo since the last success, when any. */
50
+ accessAttempts?: number;
51
+ /** Last access-check error for this repo, when any. */
52
+ accessError?: string;
47
53
  }
48
54
 
49
55
  /** Sync detail for one org's cached snapshot (all optional, additive). */
@@ -94,6 +100,10 @@ export interface CachedAccessRow {
94
100
  repo: string;
95
101
  status: string;
96
102
  canPush: boolean;
103
+ level?: string | null;
104
+ checkedAt?: Date;
105
+ attempts?: number;
106
+ lastError?: string | null;
97
107
  }
98
108
 
99
109
  /** The slice of GitHubRepoCacheService the list reads; never calls GitHub. */
@@ -198,6 +208,28 @@ export function userPushHints(
198
208
  });
199
209
  }
200
210
 
211
+ /** Adds per-repo checkedAt / attempts / last error from the cached rows (additive). */
212
+ function withAccessDetail(
213
+ views: InstallationRepoView[],
214
+ rows: readonly CachedAccessRow[],
215
+ ): InstallationRepoView[] {
216
+ const byRepo = new Map(rows.map((r) => [r.repo.toLowerCase(), r]));
217
+ return views.map((v) => {
218
+ const row = byRepo.get(
219
+ v.fullName.slice(v.fullName.indexOf("/") + 1).toLowerCase(),
220
+ );
221
+ if (!row) return v;
222
+ return {
223
+ ...v,
224
+ ...(row.checkedAt
225
+ ? { accessCheckedAt: row.checkedAt.toISOString() }
226
+ : {}),
227
+ ...(row.attempts ? { accessAttempts: row.attempts } : {}),
228
+ ...(row.lastError ? { accessError: row.lastError } : {}),
229
+ };
230
+ });
231
+ }
232
+
201
233
  const iso = (d: Date | null): string | undefined =>
202
234
  d ? d.toISOString() : undefined;
203
235
 
@@ -279,7 +311,10 @@ export class InstallationReposService {
279
311
  username,
280
312
  repos: names.map((f) => f.slice(f.indexOf("/") + 1)),
281
313
  });
282
- repos = userPushHints({ cachedRows: rows }, s.org, names);
314
+ repos = withAccessDetail(
315
+ userPushHints({ cachedRows: rows }, s.org, names),
316
+ rows,
317
+ );
283
318
  } catch {
284
319
  // The hint is advisory: a failed cache read omits it.
285
320
  }
@@ -37,7 +37,9 @@ export function orgSkipReason(
37
37
  if (result.reason === SELECTED_REPOS_REASON) {
38
38
  return "lookup app is installed on selected repositories only";
39
39
  }
40
- if (result.status === "partial") return "access listing is incomplete";
40
+ if (result.status === "partial") {
41
+ return result.reason ?? "access listing is incomplete";
42
+ }
41
43
  if (result.status !== "ok") return `access lookup failed: ${result.status}`;
42
44
  return undefined;
43
45
  }
@@ -56,3 +58,13 @@ export function accessSkipReason(
56
58
  if (!access.userVerified) return "GitHub user could not be verified";
57
59
  return undefined;
58
60
  }
61
+
62
+ /** Why cached access data cannot justify removals: a crawl or a repo answer is missing. */
63
+ export const INCOMPLETE_ACCESS_REASON = "access data is incomplete";
64
+
65
+ /** Why cached access data cannot justify removals: it is older than the freshness bound. */
66
+ export function staleAccessReason(oldestChecked: Date | undefined): string {
67
+ return oldestChecked
68
+ ? `access data is stale (checked ${oldestChecked.toISOString()})`
69
+ : "access data is stale (check time unknown)";
70
+ }