@app-vitals/agent-admin 1.86.1 → 1.87.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,405 @@
1
+ /**
2
+ * admin/src/github-cache-roundtrip.integration.test.ts
3
+ * Real-database round trip for the GitHub repo cache (GFU-1.1). The real
4
+ * refresher, discovery and crawlers write snapshots and access rows through
5
+ * GitHubRepoCacheService into PostgreSQL, and every reader reads them back:
6
+ * githubLookup.listRepositories, GitHub Sync preview (lookupRepos plus
7
+ * cachedAccess) and the installation repos list.
8
+ *
9
+ * Earlier tests stubbed lookupRepos or the cache, which hid readers that
10
+ * looked under the wrong account key (GSF-1.1, GSF-4.1). Only the GitHub
11
+ * ports are faked here (lookup client, installer client); time is an injected
12
+ * Clock. Two scopes: a deployment-wide (null-account) lookup App, filed under
13
+ * DEPLOYMENT_WIDE_ACCOUNT_KEY, and an account-scoped App, read through its own
14
+ * account key plus the deployment key (lookupAccountKeys).
15
+ *
16
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
17
+ */
18
+
19
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
20
+ import type { PrismaClient } from "../prisma/client/client.ts";
21
+ import type { AgentEnvService } from "./agent-envs.ts";
22
+ import type { Clock } from "./clock.ts";
23
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
24
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
25
+ import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
26
+ import {
27
+ createGithubInstallationRepos,
28
+ createGithubSync,
29
+ } from "./github-installation-wiring.ts";
30
+ import {
31
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
32
+ lookupAccountKeys,
33
+ } from "./github-agent-installation-crawler.ts";
34
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
35
+ import {
36
+ createRefreshDiscovery,
37
+ type LookupAppClient,
38
+ } from "./github-repo-refresh-discovery.ts";
39
+ import { GithubRepoRefresher } from "./github-repo-refresher.ts";
40
+ import {
41
+ createInstallationPort,
42
+ type InstallationRepoClient,
43
+ PrismaInstallationAgents,
44
+ } from "./installation-ports.ts";
45
+ import { createInstallationReposPort } from "./installation-repos-service.ts";
46
+ import { createAdminPrismaClient } from "./prisma-client.ts";
47
+
48
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
49
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
50
+
51
+ const T0 = new Date("2026-11-20T12:00:00Z");
52
+ const MINUTE = 60_000;
53
+ const HOUR = 3_600_000;
54
+ const LOOKUP_APP_ID = "555";
55
+ const AGENT_APP_ID = 42;
56
+ const USERNAME = "octocat";
57
+
58
+ /** Repos per org: three, listed over two pages (two per page). */
59
+ const reposOf = (org: string) => ["a", "b", "c"].map((n) => `${org}/${n}`);
60
+
61
+ /** Fake lookup App client: the GitHub port the crawl and access backfill use. */
62
+ function fakeLookupClient(orgs: string[]): LookupAppClient {
63
+ return {
64
+ async listInstallations() {
65
+ return orgs.map((login, i) => ({
66
+ id: i + 1,
67
+ login,
68
+ })) as unknown as Awaited<
69
+ ReturnType<LookupAppClient["listInstallations"]>
70
+ >;
71
+ },
72
+ async listInstallationRepositoriesPage(org, page) {
73
+ const all = reposOf(org);
74
+ const slice = all.slice((page - 1) * 2, page * 2);
75
+ return {
76
+ repositories: slice.map((fullName) => ({
77
+ id: org.length * 1000 + all.indexOf(fullName) + 1,
78
+ fullName,
79
+ archived: false,
80
+ })),
81
+ totalCount: all.length,
82
+ hasNext: page * 2 < all.length,
83
+ rateLimit: { remaining: 4000, resetAt: null, retryAfterSeconds: null },
84
+ } as unknown as Awaited<
85
+ ReturnType<LookupAppClient["listInstallationRepositoriesPage"]>
86
+ >;
87
+ },
88
+ async getCollaboratorPermissionWithRateLimit(_org, repo) {
89
+ return {
90
+ role: repo === "a" ? "write" : "read",
91
+ rateLimit: { remaining: 4000, resetAt: null, retryAfterSeconds: null },
92
+ };
93
+ },
94
+ };
95
+ }
96
+
97
+ type InstallerClient = InstallationRepoClient &
98
+ Required<Pick<InstallationRepoClient, "listInstallationRepositoriesPage">> & {
99
+ listInstallableOrganizations(): Promise<{ login: string }[]>;
100
+ };
101
+
102
+ /** Fake installer client: the agent App has installation 900 on org `acme`. */
103
+ function fakeInstaller(): InstallerClient {
104
+ const repos = (org: string) =>
105
+ reposOf(org).map((fullName, i) => ({
106
+ id: 9000 + i,
107
+ fullName,
108
+ archived: false,
109
+ }));
110
+ return {
111
+ async listInstallableOrganizations() {
112
+ return [{ login: "acme" }];
113
+ },
114
+ async listOrgInstallations() {
115
+ return [{ id: 900, appId: AGENT_APP_ID }];
116
+ },
117
+ async listInstallationRepositories(org: string) {
118
+ return repos(org);
119
+ },
120
+ async listInstallationRepositoriesPage(
121
+ org: string,
122
+ _id: number,
123
+ page: number,
124
+ ) {
125
+ const all = repos(org);
126
+ const slice = all.slice((page - 1) * 2, page * 2);
127
+ return {
128
+ repos: slice,
129
+ perPage: 2,
130
+ hasNext: page * 2 < all.length,
131
+ };
132
+ },
133
+ async addRepositories() {},
134
+ async removeRepositories() {},
135
+ } as unknown as InstallerClient;
136
+ }
137
+
138
+ describeOrSkip("GitHub repo cache round trip (integration)", () => {
139
+ let prisma: PrismaClient;
140
+ let now: Date;
141
+ let cache: GitHubRepoCacheService;
142
+ const accountIds: string[] = [];
143
+ const agentIds: string[] = [];
144
+
145
+ const clock: Clock = { now: () => new Date(now) };
146
+
147
+ const agentEnv = {
148
+ getConfigBundle: async () => ({ env: { GH_APP_ID: String(AGENT_APP_ID) } }),
149
+ } as unknown as Pick<AgentEnvService, "getConfigBundle">;
150
+
151
+ /** Resolves a lookup App per scope, as the stored-App wiring would. */
152
+ interface Apps {
153
+ /** scope (null = deployment-wide) -> the App row that scope resolves to. */
154
+ byScope: Map<
155
+ string | null,
156
+ { ownerAccountId: string | null; orgs: string[] }
157
+ >;
158
+ }
159
+
160
+ const appService = (apps: Apps) =>
161
+ ({
162
+ get: async (role: string, scope?: string | null) => {
163
+ if (role !== "lookup") return null;
164
+ const found = apps.byScope.get(scope ?? null);
165
+ if (!found) return null;
166
+ return {
167
+ appId: LOOKUP_APP_ID,
168
+ accountId: found.ownerAccountId,
169
+ enterpriseSlug: null,
170
+ updatedAt: T0,
171
+ };
172
+ },
173
+ getPrivateKey: async (role: string, scope?: string | null) =>
174
+ role === "lookup" && apps.byScope.has(scope ?? null) ? "pem" : null,
175
+ }) as unknown as GitHubEnterpriseAppService;
176
+
177
+ /** Run the real refresher until every target is crawled and backfilled. */
178
+ async function refresh(apps: Apps, agentScope: string | null) {
179
+ const installer = fakeInstaller();
180
+ const agentsPort = new PrismaInstallationAgents(prisma, agentEnv);
181
+ const discovery = createRefreshDiscovery({
182
+ listAppScopes: async () =>
183
+ [...apps.byScope.keys()].filter((s): s is string => s !== null),
184
+ async listAgents() {
185
+ const out = [];
186
+ for (const id of agentIds) {
187
+ const rec = await agentsPort.get(id);
188
+ if (rec) out.push(rec);
189
+ }
190
+ return out;
191
+ },
192
+ async lookupApp(scope) {
193
+ const found = apps.byScope.get(scope);
194
+ if (!found) return null;
195
+ return {
196
+ accountId: found.ownerAccountId,
197
+ appId: LOOKUP_APP_ID,
198
+ client: fakeLookupClient(found.orgs),
199
+ };
200
+ },
201
+ // Only the agent's own scope has an installer; the others fall back to
202
+ // the lookup App's own installations for their orgs.
203
+ installerOrgs: async (scope) => (scope === agentScope ? ["acme"] : null),
204
+ installer,
205
+ store: cache,
206
+ clock,
207
+ log: () => {},
208
+ });
209
+ const refresher = new GithubRepoRefresher({
210
+ discovery,
211
+ store: cache,
212
+ clock,
213
+ holder: "roundtrip",
214
+ config: {
215
+ intervalMs: MINUTE,
216
+ ttlMs: HOUR,
217
+ stalenessCapMs: 6 * HOUR,
218
+ timeBudgetMs: 45_000,
219
+ },
220
+ log: () => {},
221
+ });
222
+ const result = await refresher.tick();
223
+ expect(result.targets.every((t) => t.state === "worked")).toBe(true);
224
+ // Readers run a little later, still inside the freshness window.
225
+ now = new Date(T0.getTime() + MINUTE);
226
+ return installer;
227
+ }
228
+
229
+ async function makeAgent(accountId: string | null) {
230
+ const agent = await prisma.agent.create({
231
+ data: {
232
+ name: `roundtrip-${agentIds.length}`,
233
+ githubUsername: USERNAME,
234
+ repos: ["acme/a"],
235
+ ...(accountId ? { accountId } : {}),
236
+ },
237
+ });
238
+ agentIds.push(agent.id);
239
+ return agent.id;
240
+ }
241
+
242
+ async function makeAccount(name: string) {
243
+ const acct = await prisma.account.create({ data: { name } });
244
+ accountIds.push(acct.id);
245
+ return acct.id;
246
+ }
247
+
248
+ const lister = (apps: Apps) =>
249
+ createGithubLookupService({
250
+ appService: appService(apps),
251
+ cache,
252
+ now: () => clock.now(),
253
+ });
254
+
255
+ const noLiveAccess: GithubAccessPreviewFn = async () => {
256
+ throw new Error("the live access resolver must not be consulted");
257
+ };
258
+
259
+ const wiring = (apps: Apps, installer: InstallerClient) => {
260
+ const installationRepos = createInstallationReposPort(
261
+ createInstallationPort(installer),
262
+ installer,
263
+ );
264
+ return {
265
+ prisma,
266
+ appService: appService(apps),
267
+ access: noLiveAccess,
268
+ agentEnv,
269
+ installationRepos,
270
+ now: () => clock.now(),
271
+ };
272
+ };
273
+
274
+ beforeEach(async () => {
275
+ prisma = createAdminPrismaClient(TEST_DB as string);
276
+ await prisma.gitHubRepoAccess.deleteMany();
277
+ await prisma.gitHubCachedRepo.deleteMany();
278
+ await prisma.gitHubRepoSnapshot.deleteMany();
279
+ now = T0;
280
+ cache = new GitHubRepoCacheService(prisma, clock);
281
+ accountIds.length = 0;
282
+ agentIds.length = 0;
283
+ });
284
+
285
+ afterEach(async () => {
286
+ await prisma.gitHubRepoAccess.deleteMany();
287
+ await prisma.gitHubCachedRepo.deleteMany();
288
+ await prisma.gitHubRepoSnapshot.deleteMany();
289
+ if (agentIds.length > 0) {
290
+ await prisma.agent.deleteMany({ where: { id: { in: agentIds } } });
291
+ }
292
+ if (accountIds.length > 0) {
293
+ await prisma.account.deleteMany({ where: { id: { in: accountIds } } });
294
+ }
295
+ await prisma.$disconnect();
296
+ });
297
+
298
+ it("null-account lookup App: every reader reads the deployment-keyed snapshots", async () => {
299
+ const agentId = await makeAgent(null);
300
+ const apps: Apps = {
301
+ byScope: new Map([[null, { ownerAccountId: null, orgs: ["acme"] }]]),
302
+ };
303
+ const installer = await refresh(apps, null);
304
+
305
+ // The writers filed everything under the deployment key.
306
+ const snaps = await prisma.gitHubRepoSnapshot.findMany();
307
+ expect(snaps.map((s) => [s.appKind, s.accountId, s.org]).sort()).toEqual([
308
+ ["agent", DEPLOYMENT_WIDE_ACCOUNT_KEY, "acme"],
309
+ ["lookup", DEPLOYMENT_WIDE_ACCOUNT_KEY, "acme"],
310
+ ]);
311
+
312
+ // 1. githubLookup.listRepositories
313
+ const listed = await lister(apps).listRepositories(null);
314
+ expect(listed.configured).toBe(true);
315
+ expect(listed.syncState).toBe("ready");
316
+ expect(listed.repos.map((r) => r.fullName).sort()).toEqual(reposOf("acme"));
317
+
318
+ // 2. Sync preview: lookupRepos + cachedAccess over the real cache.
319
+ const sync = createGithubSync(wiring(apps, installer));
320
+ const preview = await sync.preview(agentId);
321
+ if (preview.status !== "previewed") throw new Error(preview.status);
322
+ expect(preview.plan.skippedOrgs).toEqual([]);
323
+ expect(preview.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
324
+
325
+ // 3. Installation list: the agent App snapshot.
326
+ const list = await createGithubInstallationRepos(
327
+ wiring(apps, installer),
328
+ ).list(agentId);
329
+ if (list.status !== "ok") throw new Error(list.status);
330
+ expect(list.appId).toBe(AGENT_APP_ID);
331
+ expect(list.orgs).toHaveLength(1);
332
+ expect(list.orgs[0]?.org).toBe("acme");
333
+ expect(list.orgs[0]?.complete).toBe(true);
334
+ expect(list.orgs[0]?.repos.map((r) => r.fullName).sort()).toEqual(
335
+ reposOf("acme"),
336
+ );
337
+ });
338
+
339
+ it("account-scoped App: readers use the own account key plus the deployment key, never another account's", async () => {
340
+ const acct = await makeAccount("roundtrip-own");
341
+ const other = await makeAccount("roundtrip-other");
342
+ const agentId = await makeAgent(acct);
343
+ const apps: Apps = {
344
+ byScope: new Map([
345
+ // The account's own App covers `acme`; the deployment-wide App `beta`.
346
+ [acct, { ownerAccountId: acct, orgs: ["acme"] }],
347
+ [null, { ownerAccountId: null, orgs: ["beta"] }],
348
+ // Another account's App, same App id, must never be read.
349
+ [other, { ownerAccountId: other, orgs: ["evil"] }],
350
+ ]),
351
+ };
352
+ const installer = await refresh(apps, acct);
353
+
354
+ expect(lookupAccountKeys(acct)).toEqual([
355
+ acct,
356
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
357
+ ]);
358
+ const lookupSnaps = await prisma.gitHubRepoSnapshot.findMany({
359
+ where: { appKind: "lookup" },
360
+ });
361
+ expect(lookupSnaps.map((s) => [s.accountId, s.org]).sort()).toEqual(
362
+ [
363
+ [acct, "acme"],
364
+ [DEPLOYMENT_WIDE_ACCOUNT_KEY, "beta"],
365
+ [other, "evil"],
366
+ ].sort(),
367
+ );
368
+
369
+ // 1. Lister: own account's acme plus the deployment-wide beta, no evil.
370
+ const listed = await lister(apps).listRepositories(acct);
371
+ expect(listed.configured).toBe(true);
372
+ expect(listed.syncState).toBe("ready");
373
+ expect(listed.repos.map((r) => r.fullName).sort()).toEqual(
374
+ [...reposOf("acme"), ...reposOf("beta")].sort(),
375
+ );
376
+ expect(listed.repos.some((r) => r.fullName.startsWith("evil/"))).toBe(
377
+ false,
378
+ );
379
+
380
+ // The other account's lister sees its own org plus the deployment key only.
381
+ const otherListed = await lister(apps).listRepositories(other);
382
+ expect(otherListed.repos.map((r) => r.fullName).sort()).toEqual(
383
+ [...reposOf("evil"), ...reposOf("beta")].sort(),
384
+ );
385
+
386
+ // 2. Sync preview over the account's own access rows.
387
+ const sync = createGithubSync(wiring(apps, installer));
388
+ const preview = await sync.preview(agentId);
389
+ if (preview.status !== "previewed") throw new Error(preview.status);
390
+ expect(preview.plan.skippedOrgs).toEqual([]);
391
+ expect(preview.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
392
+
393
+ // 3. Installation list: the agent App snapshot under the account key.
394
+ const list = await createGithubInstallationRepos(
395
+ wiring(apps, installer),
396
+ ).list(agentId);
397
+ if (list.status !== "ok") throw new Error(list.status);
398
+ expect(list.orgs).toHaveLength(1);
399
+ expect(list.orgs[0]?.org).toBe("acme");
400
+ expect(list.orgs[0]?.complete).toBe(true);
401
+ expect(list.orgs[0]?.repos.map((r) => r.fullName).sort()).toEqual(
402
+ reposOf("acme"),
403
+ );
404
+ });
405
+ });
@@ -483,8 +483,8 @@ function serializeApp(m: GitHubEnterpriseAppMetadata) {
483
483
  // ─── Access preview (GHE-2.4) ─────────────────────────────────────────────────
484
484
 
485
485
  /**
486
- * Backs GET /agents/:id/github-access. Unconfigured (either App missing, or a
487
- * stored App without its key / enterprise slug) returns before any GitHub
486
+ * Backs GET /agents/:id/github-access. Unconfigured (the lookup App, or its
487
+ * key, missing) returns before any GitHub
488
488
  * call. A GitHub failure while listing orgs is rethrown as a 502 carrying only
489
489
  * the mapped, non-leaky message.
490
490
  */
@@ -499,32 +499,38 @@ export function createGithubAccessPreview(
499
499
  deps.appService.get("installer", accountId),
500
500
  deps.appService.get("lookup", accountId),
501
501
  ]);
502
- if (!installer || !lookup || !installer.enterpriseSlug) {
503
- return { status: "unconfigured" };
504
- }
502
+ if (!lookup) return { status: "unconfigured" };
505
503
  const [installerKey, lookupKey] = await Promise.all([
506
- deps.appService.getPrivateKey("installer", accountId),
504
+ installer ? deps.appService.getPrivateKey("installer", accountId) : null,
507
505
  deps.appService.getPrivateKey("lookup", accountId),
508
506
  ]);
509
- if (!installerKey || !lookupKey) return { status: "unconfigured" };
507
+ if (!lookupKey) return { status: "unconfigured" };
510
508
 
511
509
  const common = {
512
510
  apiBase: deps.apiBase,
513
511
  fetchFn: deps.fetchFn,
514
512
  now: deps.now,
515
513
  };
514
+ const lookupClient = new GithubLookupClient({
515
+ appId: lookup.appId,
516
+ privateKey: lookupKey,
517
+ ...common,
518
+ });
519
+ // The installer only widens the org list; without a usable one (no key or
520
+ // enterprise slug) the lookup App's own installations are the org source.
521
+ const installerClient =
522
+ installer?.enterpriseSlug && installerKey
523
+ ? new GithubEnterpriseClient({
524
+ appId: installer.appId,
525
+ enterprise: installer.enterpriseSlug,
526
+ privateKey: installerKey,
527
+ ...common,
528
+ })
529
+ : undefined;
516
530
  const resolver = new UserRepoAccessResolver({
517
- installer: new GithubEnterpriseClient({
518
- appId: installer.appId,
519
- enterprise: installer.enterpriseSlug,
520
- privateKey: installerKey,
521
- ...common,
522
- }),
523
- lookup: new GithubLookupClient({
524
- appId: lookup.appId,
525
- privateKey: lookupKey,
526
- ...common,
527
- }),
531
+ installer: installerClient,
532
+ lookupInstallations: lookupClient,
533
+ lookup: lookupClient,
528
534
  now: deps.now,
529
535
  });
530
536
  try {
@@ -9,6 +9,10 @@
9
9
 
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import type { AgentEnvService } from "./agent-envs.ts";
12
+ import type {
13
+ GithubAppsState,
14
+ GithubAppsStateFn,
15
+ } from "./github-apps-state.ts";
12
16
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
13
17
  import type { Clock } from "./clock.ts";
14
18
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
@@ -93,6 +97,35 @@ export function lazyInstallerClient(
93
97
  };
94
98
  }
95
99
 
100
+ /**
101
+ * Which Apps are usable for an account: the lookup App needs metadata and its
102
+ * key; the installer App also needs its enterprise slug (same test as
103
+ * lazyInstallerClient). Probed per call so config changes are picked up.
104
+ */
105
+ export function githubAppsStateProbe(
106
+ deps: Pick<GithubInstallationWiringDeps, "appService">,
107
+ ): GithubAppsStateFn {
108
+ return async (accountId): Promise<GithubAppsState> => {
109
+ const [lookup, lookupKey, installer, installerKey] = await Promise.all([
110
+ deps.appService.get("lookup", accountId),
111
+ deps.appService.getPrivateKey("lookup", accountId),
112
+ deps.appService.get("installer", accountId),
113
+ deps.appService.getPrivateKey("installer", accountId),
114
+ ]);
115
+ if (!lookup || !lookupKey) return "lookup_missing";
116
+ return installer?.enterpriseSlug && installerKey ? "both" : "lookup_only";
117
+ };
118
+ }
119
+
120
+ /** The probe only guards the real installer-backed port; a replaced port has no installer to probe. */
121
+ function appsStateDep(
122
+ deps: Pick<InstallationReposWiringDeps, "appService" | "installationRepos">,
123
+ ): { appsState?: GithubAppsStateFn } {
124
+ return deps.installationRepos
125
+ ? {}
126
+ : { appsState: githubAppsStateProbe(deps) };
127
+ }
128
+
96
129
  export interface InstallationReposWiringDeps
97
130
  extends GithubInstallationWiringDeps {
98
131
  /** Test seam: replaces the installer-App-backed port. */
@@ -116,6 +149,7 @@ export function createGithubInstallationRepos(
116
149
  deps.installationRepos ??
117
150
  createInstallationReposPort(createInstallationPort(client), client),
118
151
  cache: new GitHubRepoCacheService(deps.prisma),
152
+ ...appsStateDep(deps),
119
153
  });
120
154
  }
121
155
 
@@ -194,6 +228,7 @@ export function createGithubSync(
194
228
  deps.installationRepos ??
195
229
  createInstallationReposPort(createInstallationPort(client), client),
196
230
  audit: new PrismaInstallationAudit(deps.prisma),
231
+ ...appsStateDep(deps),
197
232
  ...(deps.openWork ? { openWork: deps.openWork } : {}),
198
233
  });
199
234
  }
@@ -25,6 +25,11 @@
25
25
  */
26
26
 
27
27
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
28
+ import {
29
+ GITHUB_APPS_STATE_REASONS,
30
+ type GithubAppsState,
31
+ type GithubAppsStateFn,
32
+ } from "./github-apps-state.ts";
28
33
  import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
29
34
  import { DEFAULT_REFRESH_STALENESS_CAP_MS } from "./github-repo-refresher.ts";
30
35
  import {
@@ -104,6 +109,8 @@ export interface NotAppliedRepo {
104
109
  export interface GithubSyncPlan {
105
110
  skipped: boolean;
106
111
  skipReason?: string;
112
+ /** Set when the skip is because an App role is missing (additive). */
113
+ appsState?: Exclude<GithubAppsState, "both">;
107
114
  appAdds: string[];
108
115
  appRemoves: string[];
109
116
  agentRemoves: string[];
@@ -291,11 +298,17 @@ export interface GithubSyncDeps {
291
298
  audit: InstallationAuditPort;
292
299
  /** Optional: with none, nothing is listed or blocked. */
293
300
  openWork?: OpenWorkPort;
301
+ /** Optional: which Apps are usable; without both, Sync is skipped with a specific reason. */
302
+ appsState?: GithubAppsStateFn;
294
303
  }
295
304
 
296
305
  export type GithubSyncPreviewResult =
297
306
  | { status: "agent_not_found" }
298
- | { status: "skipped"; reason: string }
307
+ | {
308
+ status: "skipped";
309
+ reason: string;
310
+ appsState?: Exclude<GithubAppsState, "both">;
311
+ }
299
312
  | {
300
313
  status: "previewed";
301
314
  plan: GithubSyncPlan;
@@ -312,7 +325,11 @@ export interface GithubSyncApplyInput extends SyncLists {
312
325
 
313
326
  export type GithubSyncApplyResult =
314
327
  | { status: "agent_not_found" }
315
- | { status: "skipped"; reason: string }
328
+ | {
329
+ status: "skipped";
330
+ reason: string;
331
+ appsState?: Exclude<GithubAppsState, "both">;
332
+ }
316
333
  | { status: "noop"; plan: GithubSyncPlan }
317
334
  | { status: "removal_cap"; plan: GithubSyncPlan; removals: number }
318
335
  | {
@@ -341,7 +358,11 @@ export class GithubSyncService {
341
358
  if (!agent) return { status: "agent_not_found" };
342
359
  const plan = await this.planFor(agent);
343
360
  if (plan.skipped) {
344
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
361
+ return {
362
+ status: "skipped",
363
+ reason: plan.skipReason ?? "skipped",
364
+ ...(plan.appsState ? { appsState: plan.appsState } : {}),
365
+ };
345
366
  }
346
367
  const work = await previewRepoRemovalWork(
347
368
  this.deps.openWork,
@@ -361,7 +382,11 @@ export class GithubSyncService {
361
382
  if (!agent) return { status: "agent_not_found" };
362
383
  let plan = await this.planFor(agent, input);
363
384
  if (plan.skipped) {
364
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
385
+ return {
386
+ status: "skipped",
387
+ reason: plan.skipReason ?? "skipped",
388
+ ...(plan.appsState ? { appsState: plan.appsState } : {}),
389
+ };
365
390
  }
366
391
  plan = await this.reverifyRemovals(plan, agent);
367
392
  if (plan.appAdds.length + plan.removedRepos.length === 0) {
@@ -568,6 +593,15 @@ export class GithubSyncService {
568
593
  if (!username) {
569
594
  return skippedPlan(accessSkipReason(username, null) as string);
570
595
  }
596
+ if (this.deps.appsState) {
597
+ const state = await this.deps.appsState(agent.accountId);
598
+ if (state !== "both") {
599
+ return {
600
+ ...skippedPlan(GITHUB_APPS_STATE_REASONS[state]),
601
+ appsState: state,
602
+ };
603
+ }
604
+ }
571
605
  let liveAccess: UserRepoAccessResult | null = null;
572
606
  if (!this.deps.cache) {
573
607
  const preview = await this.deps.access(username, agent.accountId);
@@ -7,6 +7,11 @@
7
7
  * through the installation port.
8
8
  */
9
9
 
10
+ import {
11
+ GITHUB_APPS_STATE_REASONS,
12
+ type GithubAppsState,
13
+ type GithubAppsStateFn,
14
+ } from "./github-apps-state.ts";
10
15
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
11
16
  import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
12
17
  import {
@@ -128,6 +133,9 @@ export type InstallationListResult =
128
133
  status: "ok";
129
134
  appId: number;
130
135
  orgs: InstallationOrgView[];
136
+ /** Set when an App role is missing; the listing is the cached crawl only (additive). */
137
+ appsState?: Exclude<GithubAppsState, "both">;
138
+ reason?: string;
131
139
  } & InstallationSyncDetail);
132
140
 
133
141
  export interface InstallationReposDeps {
@@ -137,6 +145,8 @@ export interface InstallationReposDeps {
137
145
  installation: InstallationReposPort;
138
146
  /** The repo/access cache list() reads. Without it list() reports nothing synced. */
139
147
  cache?: InstallationCachePort;
148
+ /** Optional: which Apps are usable; without both, list() says why (additive fields). */
149
+ appsState?: GithubAppsStateFn;
140
150
  }
141
151
 
142
152
  /** The agent's App identity keys (client id, slug), when stored. */
@@ -338,7 +348,18 @@ export class InstallationReposService {
338
348
  ...(s.lastTickAt ? { lastTickAt: iso(s.lastTickAt) } : {}),
339
349
  });
340
350
  }
341
- return { status: "ok", appId: agent.appId, orgs, ...summarize(orgs) };
351
+ const state = this.deps.appsState
352
+ ? await this.deps.appsState(agent.accountId)
353
+ : "both";
354
+ return {
355
+ status: "ok",
356
+ appId: agent.appId,
357
+ orgs,
358
+ ...summarize(orgs),
359
+ ...(state !== "both"
360
+ ? { appsState: state, reason: GITHUB_APPS_STATE_REASONS[state] }
361
+ : {}),
362
+ };
342
363
  }
343
364
  }
344
365