@app-vitals/agent-admin 1.82.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.
@@ -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]),