@app-vitals/agent-admin 1.86.1 → 1.88.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.
Files changed (33) hide show
  1. package/openapi.json +2 -2
  2. package/openapi.platform.json +30 -2
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -0
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
  7. package/prisma/client/models/GitHubRepoSnapshot.ts +33 -1
  8. package/prisma/migrations/20261125000000_add_github_snapshot_repository_selection/migration.sql +2 -0
  9. package/prisma/schema/schema.prisma +2 -0
  10. package/src/admin-ui-github-identity-pages.ts +22 -4
  11. package/src/admin-ui-github-identity-pages.unit.test.ts +87 -0
  12. package/src/admin-ui-installation-repos-pages.ts +29 -7
  13. package/src/admin-ui-installation-repos-pages.unit.test.ts +83 -0
  14. package/src/admin-ui-installation-repos.smoke.test.ts +77 -9
  15. package/src/admin-ui-pages.ts +15 -2
  16. package/src/admin-ui.ts +23 -17
  17. package/src/agents-api.smoke.test.ts +237 -2
  18. package/src/agents-api.ts +27 -4
  19. package/src/github-access-preview.integration.test.ts +38 -3
  20. package/src/github-access-preview.ts +1 -1
  21. package/src/github-agent-installation-crawler.ts +27 -8
  22. package/src/github-agent-installation-crawler.unit.test.ts +76 -1
  23. package/src/github-apps-state.ts +31 -0
  24. package/src/github-cache-roundtrip.integration.test.ts +405 -0
  25. package/src/github-enterprise-api.ts +24 -18
  26. package/src/github-installation-selection.integration.test.ts +91 -0
  27. package/src/github-installation-wiring.ts +35 -0
  28. package/src/github-repo-cache.ts +8 -0
  29. package/src/github-sync.ts +38 -4
  30. package/src/installation-ports.ts +2 -0
  31. package/src/installation-repos-service.ts +24 -1
  32. package/src/user-repo-access-resolver.ts +26 -5
  33. package/src/user-repo-access-resolver.unit.test.ts +80 -0
@@ -126,28 +126,65 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
126
126
  expect(cardHtml).not.toContain("<input");
127
127
  });
128
128
 
129
- it("is absent when only the installer App is configured", async () => {
130
- const { app } = setup({
129
+ it("lookup-only: shows the access preview and the plain installer explanation, no Sync button or installer-backed body", async () => {
130
+ const { app, calls } = setup({
131
131
  enterprise: {
132
132
  configured: true,
133
- installer: { role: "installer" },
134
- lookup: null,
133
+ installer: null,
134
+ lookup: { role: "lookup" },
135
135
  },
136
136
  });
137
137
  const html = await (await get(app, "/access")).text();
138
- expect(html).not.toContain("github-installation-card");
138
+ expect(html).toContain('id="github-access-btn"');
139
+ const card = html.slice(html.indexOf('id="github-installation-card"'));
140
+ const cardHtml = card.slice(0, card.indexOf("</script>"));
141
+ expect(cardHtml).toContain('data-reason="lookup-only"');
142
+ expect(cardHtml).toContain(
143
+ "Sync and the agent App&#39;s installation repos need an enterprise installer App",
144
+ );
145
+ expect(cardHtml).not.toContain('id="github-sync-btn"');
146
+ expect(cardHtml).not.toContain('id="github-installation-body"');
147
+ expect(html).toContain('id="github-install-card"');
148
+ expect(html).toContain('data-reason="lookup-only"');
149
+ expect(html).not.toContain(
150
+ "is not configured, so repo access cannot be checked",
151
+ );
152
+ // No installer-backed list was requested for the page render.
153
+ expect(
154
+ calls.some((c) => c.path.includes("/github-installation/repos")),
155
+ ).toBe(false);
156
+ });
157
+
158
+ it("both Apps: renders as before, with no lookup-only or lookup-missing text", async () => {
159
+ const { app } = setup({ agentsApi: () => json(INSTALLED) });
160
+ const html = await (await get(app, "/access")).text();
161
+ expect(html).toContain('id="github-access-btn"');
162
+ expect(html).toContain('id="github-sync-btn"');
163
+ expect(html).toContain('id="github-installation-body"');
164
+ expect(html).toContain(
165
+ 'data-url="/admin/agents/' + AGENT_ID + '/github-orgs"',
166
+ );
167
+ expect(html).not.toContain('data-reason="lookup-only"');
168
+ expect(html).not.toContain('data-reason="lookup-missing"');
139
169
  });
140
170
 
141
- it("is absent when only the lookup App is configured", async () => {
171
+ it("lookup App missing (installer only): the Sync card says the lookup App is missing", async () => {
142
172
  const { app } = setup({
143
173
  enterprise: {
144
174
  configured: true,
145
- installer: null,
146
- lookup: { role: "lookup" },
175
+ installer: { role: "installer" },
176
+ lookup: null,
147
177
  },
148
178
  });
149
179
  const html = await (await get(app, "/access")).text();
150
- expect(html).not.toContain("github-installation-card");
180
+ const card = html.slice(html.indexOf('id="github-installation-card"'));
181
+ const cardHtml = card.slice(0, card.indexOf("</script>"));
182
+ expect(cardHtml).toContain('data-reason="lookup-missing"');
183
+ expect(cardHtml).toContain("The lookup GitHub App is not configured");
184
+ expect(cardHtml).not.toContain("installer");
185
+ expect(cardHtml).not.toContain('id="github-sync-btn"');
186
+ expect(html).not.toContain('id="github-access-btn"');
187
+ expect(html).not.toContain('data-reason="lookup-only"');
151
188
  });
152
189
 
153
190
  it("is absent when no App is configured", async () => {
@@ -227,6 +264,37 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
227
264
  expect(html).not.toContain('data-reason="no-username"');
228
265
  });
229
266
 
267
+ it("renders the lookup-only skip reason from the agents API in the sync confirm fragment", async () => {
268
+ const { app } = setup({
269
+ agentsApi: () =>
270
+ json({
271
+ status: "skipped",
272
+ appsState: "lookup_only",
273
+ reason:
274
+ "Only the lookup GitHub App is configured, so repo access is visible",
275
+ }),
276
+ });
277
+ const html = await (await get(app, "/github-sync/confirm")).text();
278
+ expect(html).toContain('data-apps-state="lookup_only"');
279
+ expect(html).toContain("Only the lookup GitHub App is configured");
280
+ });
281
+
282
+ it("renders the lookup-missing skip reason distinctly", async () => {
283
+ const { app } = setup({
284
+ agentsApi: () =>
285
+ json({
286
+ status: "skipped",
287
+ appsState: "lookup_missing",
288
+ reason:
289
+ "The lookup GitHub App is not configured, so repo access cannot be checked.",
290
+ }),
291
+ });
292
+ const html = await (await get(app, "/github-sync/confirm")).text();
293
+ expect(html).toContain('data-apps-state="lookup_missing"');
294
+ expect(html).toContain("The lookup GitHub App is not configured");
295
+ expect(html).not.toContain("Only the lookup");
296
+ });
297
+
230
298
  it("is forbidden for a non-admin and makes no call", async () => {
231
299
  const { app, calls } = setup({});
232
300
  const res = await get(app, "/github-installation", member);
@@ -10,6 +10,7 @@
10
10
  * coding/ (AEP-3.2) and are mounted by the coding AdminExtension.
11
11
  */
12
12
 
13
+ import type { GithubAppsState } from "./github-apps-state.ts";
13
14
  import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
14
15
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
15
16
  import {
@@ -1149,6 +1150,12 @@ export function renderAgentDetailPage(
1149
1150
  * false renders the card without them.
1150
1151
  */
1151
1152
  githubEnterpriseConfigured?: boolean;
1153
+ /**
1154
+ * Which enterprise GitHub Apps are configured (GFU-2.2). Supersedes
1155
+ * githubEnterpriseConfigured (true = "both") when set; absent = neither
1156
+ * App configured, so no GitHub identity cards.
1157
+ */
1158
+ githubAppsState?: GithubAppsState;
1152
1159
  /**
1153
1160
  * SCT-4.1: a stored Slack config token resolves for this agent's account
1154
1161
  * (its own row, else the deployment default). The xoxpToken fields become
@@ -1704,8 +1711,14 @@ export function renderAgentDetailPage(
1704
1711
  </div>`
1705
1712
  : "";
1706
1713
 
1714
+ const appsState: GithubAppsState | undefined =
1715
+ opts?.githubAppsState ??
1716
+ (opts?.githubEnterpriseConfigured === true ? "both" : undefined);
1717
+ // Username, access preview and the repo-removal flow need the lookup App;
1718
+ // the Sync/Install cards also show for a missing lookup App, to say so.
1707
1719
  const showGithubIdentity =
1708
- isAdmin && opts?.githubEnterpriseConfigured === true;
1720
+ isAdmin && (appsState === "both" || appsState === "lookup_only");
1721
+ const showGithubCards = isAdmin && appsState !== undefined;
1709
1722
  // IRM-1.7: removing a repo first shows the open work it would block.
1710
1723
  const repoRemovalScript = `<div id="repo-removal-confirm" style="margin-top:12px"></div>
1711
1724
  <script>
@@ -2113,7 +2126,7 @@ export function renderAgentDetailPage(
2113
2126
 
2114
2127
  // One GitHub card: connect actions plus (admin + enterprise GitHub) the
2115
2128
  // Preview access and GitHub sync fragments.
2116
- const githubCardBody = `${githubConnectActionsHtml}${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubIdentity ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername }) : ""}${showGithubIdentity ? renderGithubInstallCard(agent.id) : ""}`;
2129
+ const githubCardBody = `${githubConnectActionsHtml}${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubCards ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername, ...(appsState === "both" ? {} : { appsState }) }) : ""}${showGithubIdentity ? renderGithubInstallCard(agent.id, appsState) : ""}`;
2117
2130
  const githubSection =
2118
2131
  canManage && githubCardBody.trim() !== ""
2119
2132
  ? `<div class="card">
package/src/admin-ui.ts CHANGED
@@ -137,6 +137,7 @@ import {
137
137
  GITHUB_PROVISION_STATE_TTL_SECONDS,
138
138
  GithubProvisioningService,
139
139
  } from "./github-provisioning-service.ts";
140
+ import type { GithubAppsState } from "./github-apps-state.ts";
140
141
  import type { GoogleAuthClient } from "./google-auth-client.ts";
141
142
  import {
142
143
  type ChatClient,
@@ -2003,33 +2004,35 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2003
2004
  }
2004
2005
  };
2005
2006
 
2006
- // True only for a platform admin when BOTH the installer and the lookup
2007
- // enterprise GitHub Apps are configured (GHE-1.3 status) and the agents API
2008
- // seam is wired. One role alone is not enough: the access preview and Sync
2009
- // both need the pair.
2010
- const githubEnterpriseConfigured = async (
2007
+ // Which enterprise GitHub Apps are configured (GHE-1.3 status), for a
2008
+ // platform admin with the agents API seam wired. undefined = nothing to show
2009
+ // (not an admin, seam unwired, status unavailable, or neither App set).
2010
+ // "both": today's behavior. "lookup_only": access preview works, Sync and
2011
+ // installation repos need an installer App. "lookup_missing": the lookup App
2012
+ // is missing (the installer alone cannot preview access or sync).
2013
+ const githubAppsState = async (
2011
2014
  c: Context<AdminUIEnv>,
2012
- ): Promise<boolean> => {
2013
- if (!c.var.isAdmin || !githubEnterpriseApi || !agentsApi) return false;
2015
+ ): Promise<GithubAppsState | undefined> => {
2016
+ if (!c.var.isAdmin || !githubEnterpriseApi || !agentsApi) return undefined;
2014
2017
  const res = await callApi(
2015
2018
  c,
2016
2019
  githubEnterpriseApi,
2017
2020
  "/github-enterprise/apps",
2018
2021
  );
2019
- if (!res?.ok) return false;
2022
+ if (!res?.ok) return undefined;
2020
2023
  try {
2021
2024
  const status = (await res.json()) as {
2022
2025
  configured?: unknown;
2023
2026
  installer?: unknown;
2024
2027
  lookup?: unknown;
2025
2028
  };
2026
- return (
2027
- status.configured === true &&
2028
- status.installer != null &&
2029
- status.lookup != null
2030
- );
2029
+ if (status.configured !== true) return undefined;
2030
+ if (status.lookup == null) {
2031
+ return status.installer != null ? "lookup_missing" : undefined;
2032
+ }
2033
+ return status.installer != null ? "both" : "lookup_only";
2031
2034
  } catch {
2032
- return false;
2035
+ return undefined;
2033
2036
  }
2034
2037
  };
2035
2038
 
@@ -2544,7 +2547,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2544
2547
 
2545
2548
  // IRM-1.4: the repos the agent App's installation covers, for the repos
2546
2549
  // list's coverage warning. Best effort: unknown means no warning.
2547
- const enterpriseConfigured = await githubEnterpriseConfigured(c);
2550
+ const appsState = await githubAppsState(c);
2551
+ const enterpriseConfigured = appsState === "both";
2548
2552
  let installationRepos: string[] | undefined;
2549
2553
  let installationSync: InstallationSyncView | undefined;
2550
2554
  if (
@@ -2604,7 +2608,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2604
2608
  configurationCardsHtml: cards.configuration,
2605
2609
  queueActivityLinks: deps.queueActivityLinks,
2606
2610
  marketplaces,
2607
- githubEnterpriseConfigured: enterpriseConfigured,
2611
+ ...(appsState ? { githubAppsState: appsState } : {}),
2608
2612
  slackConfigTokenStored: await hasStoredSlackConfigToken(
2609
2613
  deps.slackConfigTokens,
2610
2614
  agent.accountId ?? null,
@@ -3521,7 +3525,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3521
3525
  configurationCardsHtml: cards.configuration,
3522
3526
  queueActivityLinks: deps.queueActivityLinks,
3523
3527
  marketplaces,
3524
- githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
3528
+ ...(await githubAppsState(c).then((st) =>
3529
+ st ? { githubAppsState: st } : {},
3530
+ )),
3525
3531
  slackConfigTokenStored: await hasStoredSlackConfigToken(
3526
3532
  deps.slackConfigTokens,
3527
3533
  agent.accountId ?? null,
@@ -24,6 +24,7 @@ import type { AgentTokenService } from "./agent-tokens.ts";
24
24
  import type { AdminDeps } from "./agents-api.ts";
25
25
  import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
26
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
27
+ import { createGithubAccessPreview } from "./github-enterprise-api.ts";
27
28
  import { accessFor, envWith } from "./github-installation.fixtures.ts";
28
29
  import {
29
30
  createGithubInstallationRepos,
@@ -7246,6 +7247,134 @@ describe("admin API — GET /agents/:id/github-access (GHE-2.4)", () => {
7246
7247
  expect(await res.json()).toEqual({ status: "unconfigured" });
7247
7248
  });
7248
7249
 
7250
+ describe("real preview over a fake GitHub (lookup-only and both Apps)", () => {
7251
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
7252
+ modulusLength: 2048,
7253
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
7254
+ publicKeyEncoding: { type: "spki", format: "pem" },
7255
+ });
7256
+ type Role = "installer" | "lookup";
7257
+ const record = (role: Role) => ({
7258
+ role,
7259
+ appId: role === "lookup" ? "555" : "12345",
7260
+ slug: `example-${role}`,
7261
+ enterpriseSlug: role === "installer" ? "acme" : null,
7262
+ });
7263
+
7264
+ function preview(roles: Role[]) {
7265
+ const paths: string[] = [];
7266
+ const json = (body: unknown, status = 200) =>
7267
+ new Response(JSON.stringify(body), {
7268
+ status,
7269
+ headers: { "Content-Type": "application/json" },
7270
+ });
7271
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
7272
+ const path = new URL(input.toString()).pathname;
7273
+ paths.push(`${init?.method ?? "GET"} ${path}`);
7274
+ if (path === "/app/installations")
7275
+ return json([
7276
+ { id: 7001, account: { login: "acme-eng", type: "Organization" } },
7277
+ ]);
7278
+ if (path === "/enterprises/acme/installation")
7279
+ return json({
7280
+ id: 4242,
7281
+ access_tokens_url:
7282
+ "https://ghe.test/app/installations/4242/access_tokens",
7283
+ });
7284
+ if (path === "/app/installations/4242/access_tokens")
7285
+ return json({ token: "ghs_i", expires_at: "2099-01-01T00:00:00Z" });
7286
+ if (path === "/enterprises/acme/apps/installable_organizations")
7287
+ return json([{ id: 1, login: "acme-eng" }]);
7288
+ if (path === "/orgs/acme-eng/installation")
7289
+ return json({ id: 7001, repository_selection: "all" });
7290
+ if (path === "/app/installations/7001/access_tokens")
7291
+ return json({ token: "ghs_l", expires_at: "2099-01-01T00:00:00Z" });
7292
+ if (path === "/installation/repositories")
7293
+ return json({
7294
+ total_count: 1,
7295
+ repositories: [
7296
+ {
7297
+ id: 1,
7298
+ name: "api",
7299
+ full_name: "acme-eng/api",
7300
+ private: true,
7301
+ archived: false,
7302
+ },
7303
+ ],
7304
+ });
7305
+ if (path === "/users/octocat")
7306
+ return json({ id: 9, login: "octocat", type: "User" });
7307
+ if (path === "/repos/acme-eng/api/collaborators/octocat/permission")
7308
+ return json({ permission: "write", role_name: "write" });
7309
+ return json({ message: "Not Found" }, 404);
7310
+ }) as typeof fetch;
7311
+ const appService = {
7312
+ get: async (role: Role) => (roles.includes(role) ? record(role) : null),
7313
+ getPrivateKey: async (role: Role) =>
7314
+ roles.includes(role) ? PEM : null,
7315
+ } as unknown as Parameters<
7316
+ typeof createGithubAccessPreview
7317
+ >[0]["appService"];
7318
+ return {
7319
+ paths,
7320
+ fn: createGithubAccessPreview({
7321
+ appService,
7322
+ fetchFn,
7323
+ apiBase: "https://ghe.test",
7324
+ now: () => new Date("2026-11-09T12:00:00Z"),
7325
+ }),
7326
+ };
7327
+ }
7328
+
7329
+ const expectedOrgs = [
7330
+ {
7331
+ org: "acme-eng",
7332
+ status: "ok",
7333
+ repos: [{ fullName: "acme-eng/api", level: "write", canPush: true }],
7334
+ unresolved: 0,
7335
+ },
7336
+ ];
7337
+
7338
+ it("lookup-only: status ok with the repos the lookup App sees", async () => {
7339
+ const p = preview(["lookup"]);
7340
+ const { app } = setup({ githubUsername: "octocat", preview: p.fn });
7341
+ const res = await get(app, asAdmin);
7342
+ expect(res.status).toBe(200);
7343
+ const body = (await res.json()) as {
7344
+ status: string;
7345
+ access: { orgs: unknown[]; complete: boolean };
7346
+ };
7347
+ expect(body.status).toBe("ok");
7348
+ expect(body.access.orgs).toEqual(expectedOrgs);
7349
+ expect(body.access.complete).toBe(true);
7350
+ expect(p.paths).toContain("GET /app/installations");
7351
+ expect(p.paths.some((x) => x.includes("/enterprises/"))).toBe(false);
7352
+ });
7353
+
7354
+ it("both Apps: same result, orgs come from the installer", async () => {
7355
+ const p = preview(["installer", "lookup"]);
7356
+ const { app } = setup({ githubUsername: "octocat", preview: p.fn });
7357
+ const body = (await (await get(app, asAdmin)).json()) as {
7358
+ status: string;
7359
+ access: { orgs: unknown[] };
7360
+ };
7361
+ expect(body.status).toBe("ok");
7362
+ expect(body.access.orgs).toEqual(expectedOrgs);
7363
+ expect(p.paths).toContain(
7364
+ "GET /enterprises/acme/apps/installable_organizations",
7365
+ );
7366
+ expect(p.paths).not.toContain("GET /app/installations");
7367
+ });
7368
+
7369
+ it("installer-only is unconfigured with no GitHub call", async () => {
7370
+ const p = preview(["installer"]);
7371
+ const { app } = setup({ githubUsername: "octocat", preview: p.fn });
7372
+ const res = await get(app, asAdmin);
7373
+ expect(await res.json()).toEqual({ status: "unconfigured" });
7374
+ expect(p.paths).toEqual([]);
7375
+ });
7376
+ });
7377
+
7249
7378
  it("user_not_found is passed through", async () => {
7250
7379
  const access = { ...ACCESS, outcome: "user_not_found" as const, orgs: [] };
7251
7380
  const { app } = setup({
@@ -7306,6 +7435,8 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7306
7435
  /** Seeded GLC cache rows read by the list route. */
7307
7436
  snapshots?: Array<Record<string, unknown>>;
7308
7437
  accessRows?: Array<Record<string, unknown>>;
7438
+ /** Which Apps are stored (GFU-2.2); default both. */
7439
+ apps?: "both" | "lookup_only" | "lookup_missing";
7309
7440
  } = {},
7310
7441
  ) {
7311
7442
  const audits: Array<Record<string, unknown>> = [];
@@ -7441,8 +7572,16 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7441
7572
  const wiring = {
7442
7573
  prisma,
7443
7574
  appService: {
7444
- get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
7445
- getPrivateKey: async () => PEM,
7575
+ get: async (role: string) =>
7576
+ (opts.apps === "lookup_missing" ||
7577
+ (opts.apps === "lookup_only" && role === "installer")
7578
+ ? null
7579
+ : { appId: 12345, enterpriseSlug: "acme" }) as never,
7580
+ getPrivateKey: async (role: string) =>
7581
+ opts.apps === "lookup_missing" ||
7582
+ (opts.apps === "lookup_only" && role === "installer")
7583
+ ? null
7584
+ : PEM,
7446
7585
  },
7447
7586
  access: async (username: string) => {
7448
7587
  const base = await accessFor(
@@ -7689,6 +7828,102 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7689
7828
  expect(audits).toEqual([]);
7690
7829
  });
7691
7830
 
7831
+ describe("App roles (GFU-2.2)", () => {
7832
+ const LOOKUP_ONLY = "Only the lookup GitHub App is configured";
7833
+ const LOOKUP_MISSING = "The lookup GitHub App is not configured";
7834
+
7835
+ it("both Apps: no appsState or reason on any response", async () => {
7836
+ const { app } = setup();
7837
+ const list = await (
7838
+ await app.request(url(), { headers: asAdmin })
7839
+ ).json();
7840
+ expect(list).not.toHaveProperty("appsState");
7841
+ expect(list).not.toHaveProperty("reason");
7842
+ const pre = await (
7843
+ await app.request(previewUrl, { headers: asAdmin })
7844
+ ).json();
7845
+ expect(pre).toMatchObject({ status: "previewed" });
7846
+ expect(pre).not.toHaveProperty("appsState");
7847
+ });
7848
+
7849
+ it("lookup-only: list is the cached crawl with a lookup-only reason; no GitHub call", async () => {
7850
+ const { app, gh } = setup({ apps: "lookup_only" });
7851
+ const res = await app.request(url(), { headers: asAdmin });
7852
+ expect(res.status).toBe(200);
7853
+ const body = (await res.json()) as {
7854
+ appsState: string;
7855
+ reason: string;
7856
+ orgs: unknown[];
7857
+ };
7858
+ expect(body.appsState).toBe("lookup_only");
7859
+ expect(body.reason).toContain(LOOKUP_ONLY);
7860
+ expect(body.orgs.length).toBeGreaterThan(0);
7861
+ expect(gh).toEqual([]);
7862
+ });
7863
+
7864
+ it("lookup-missing: list carries a distinct lookup-missing reason", async () => {
7865
+ const { app } = setup({ apps: "lookup_missing" });
7866
+ const body = (await (
7867
+ await app.request(url(), { headers: asAdmin })
7868
+ ).json()) as { appsState: string; reason: string };
7869
+ expect(body.appsState).toBe("lookup_missing");
7870
+ expect(body.reason).toContain(LOOKUP_MISSING);
7871
+ expect(body.reason).not.toContain(LOOKUP_ONLY);
7872
+ });
7873
+
7874
+ it("lookup-only: sync preview and apply are skipped with the lookup-only reason; nothing changed", async () => {
7875
+ const { app, audits, gh } = setup({ apps: "lookup_only" });
7876
+ const pre = await (
7877
+ await app.request(previewUrl, { headers: asAdmin })
7878
+ ).json();
7879
+ expect(pre).toMatchObject({
7880
+ status: "skipped",
7881
+ appsState: "lookup_only",
7882
+ });
7883
+ expect((pre as { reason: string }).reason).toContain(LOOKUP_ONLY);
7884
+ const ap = await apply(app, { appAdds: ["acme-eng/repo-3"] });
7885
+ expect(await ap.json()).toMatchObject({
7886
+ status: "skipped",
7887
+ appsState: "lookup_only",
7888
+ });
7889
+ expect(audits).toEqual([]);
7890
+ expect(gh).toEqual([]);
7891
+ });
7892
+
7893
+ it("lookup-missing: sync preview and apply are skipped with a distinct reason", async () => {
7894
+ const { app, audits } = setup({ apps: "lookup_missing" });
7895
+ const pre = (await (
7896
+ await app.request(previewUrl, { headers: asAdmin })
7897
+ ).json()) as { status: string; appsState: string; reason: string };
7898
+ expect(pre.status).toBe("skipped");
7899
+ expect(pre.appsState).toBe("lookup_missing");
7900
+ expect(pre.reason).toContain(LOOKUP_MISSING);
7901
+ expect(pre.reason).not.toContain(LOOKUP_ONLY);
7902
+ const ap = (await (
7903
+ await apply(app, { appAdds: ["acme-eng/repo-3"] })
7904
+ ).json()) as { appsState: string };
7905
+ expect(ap.appsState).toBe("lookup_missing");
7906
+ expect(audits).toEqual([]);
7907
+ });
7908
+
7909
+ it("an unbound user still gets the existing no-username reason first", async () => {
7910
+ const { app } = setup({ apps: "lookup_only", username: null });
7911
+ const pre = (await (
7912
+ await app.request(previewUrl, { headers: asAdmin })
7913
+ ).json()) as { reason: string };
7914
+ expect(pre.reason).not.toContain(LOOKUP_ONLY);
7915
+ });
7916
+
7917
+ it("the 422 for a missing GH_APP_ID keeps its text in every state", async () => {
7918
+ for (const apps of ["both", "lookup_only", "lookup_missing"] as const) {
7919
+ const { app } = setup({ env: {}, apps });
7920
+ const res = await app.request(url(), { headers: asAdmin });
7921
+ expect(res.status).toBe(422);
7922
+ expect(JSON.stringify(await res.json())).toContain("GH_APP_ID");
7923
+ }
7924
+ });
7925
+ });
7926
+
7692
7927
  it("503 when the Apps are not wired", async () => {
7693
7928
  const app = createAdminApp({
7694
7929
  ...makeMockDeps(),
package/src/agents-api.ts CHANGED
@@ -618,7 +618,7 @@ const GithubAccessPreviewSchema = z
618
618
  .object({
619
619
  status: z.enum(["ok", "user_not_found", "unconfigured"]).openapi({
620
620
  description:
621
- "`unconfigured` when the installer or lookup App is not set (no GitHub call was made).",
621
+ "`unconfigured` when the lookup App or its key is not set (no GitHub call was made). The installer App is optional.",
622
622
  }),
623
623
  access: z
624
624
  .object({
@@ -683,9 +683,19 @@ const InstallationSyncDetailShape = {
683
683
  .openapi({ description: "Last refresh tick on the snapshot (ISO 8601)." }),
684
684
  };
685
685
 
686
+ const AppsStateSchema = z.enum(["lookup_only", "lookup_missing"]).openapi({
687
+ description:
688
+ "Present only when an App role is missing: `lookup_only` (the enterprise installer App is not configured: repo access is visible but Sync and the agent App's installation repos are unavailable) or `lookup_missing` (the lookup App is not configured). `reason` carries the matching text.",
689
+ });
690
+
686
691
  const GithubInstallationReposListSchema = z
687
692
  .object({
688
693
  appId: z.number().int(),
694
+ appsState: AppsStateSchema.optional(),
695
+ reason: z.string().optional().openapi({
696
+ description:
697
+ "Set with `appsState`: why the installation repos cannot be changed here. The listing is the cached lookup crawl.",
698
+ }),
689
699
  ...InstallationSyncDetailShape,
690
700
  orgs: z.array(
691
701
  z.object({
@@ -763,6 +773,7 @@ const GithubSyncPreviewSchema = z
763
773
  "`skipped` (not an error) when no GitHub username is bound, the user is not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured; `reason` says why.",
764
774
  }),
765
775
  reason: z.string().optional(),
776
+ appsState: AppsStateSchema.optional(),
766
777
  appAdds: z.array(z.string()).optional().openapi({
767
778
  description:
768
779
  "Repos the bound user can push to, in orgs the agent App is installed on with a complete access listing, that are not on the installation. No cap.",
@@ -811,6 +822,7 @@ const GithubSyncApplyResultSchema = z
811
822
  .object({
812
823
  status: z.enum(["applied", "noop", "skipped"]),
813
824
  reason: z.string().optional(),
825
+ appsState: AppsStateSchema.optional(),
814
826
  auditId: z.string().optional(),
815
827
  appAdds: z.array(z.string()).optional(),
816
828
  appRemoves: z.array(z.string()).optional(),
@@ -1847,7 +1859,7 @@ const getGithubAccessRoute = createRoute({
1847
1859
  path: "/agents/{id}/github-access",
1848
1860
  summary: "Preview the repos the agent's bound GitHub user can reach",
1849
1861
  description:
1850
- "Platform-admin only (session members, ops keys and agent keys get 403): the response lists repo names the bound user can reach. Read-only; nothing is stored. 404 for an unknown agent; 422 when no githubUsername is bound. Returns `status: unconfigured` (not an error, no GitHub call) when the enterprise Apps are not configured, and `status: user_not_found` when the user does not exist on GitHub; otherwise `access` is the resolver output (per-org status, repos with level and canPush, unresolved count, complete flag).",
1862
+ "Platform-admin only (session members, ops keys and agent keys get 403): the response lists repo names the bound user can reach. Read-only; nothing is stored. 404 for an unknown agent; 422 when no githubUsername is bound. Returns `status: unconfigured` (not an error, no GitHub call) when the lookup App is not configured (the installer App is optional), and `status: user_not_found` when the user does not exist on GitHub; otherwise `access` is the resolver output (per-org status, repos with level and canPush, unresolved count, complete flag).",
1851
1863
  request: { params: AgentIdParamSchema },
1852
1864
  responses: {
1853
1865
  200: {
@@ -3561,7 +3573,14 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3561
3573
  throw new NotFoundError(`agent ${agentId} not found`);
3562
3574
  }
3563
3575
  if (result.status === "skipped") {
3564
- return c.json({ status: "skipped" as const, reason: result.reason }, 200);
3576
+ return c.json(
3577
+ {
3578
+ status: "skipped" as const,
3579
+ reason: result.reason,
3580
+ ...(result.appsState ? { appsState: result.appsState } : {}),
3581
+ },
3582
+ 200,
3583
+ );
3565
3584
  }
3566
3585
  const { plan } = result;
3567
3586
  return c.json(
@@ -3596,7 +3615,11 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3596
3615
  throw new NotFoundError(`agent ${agentId} not found`);
3597
3616
  case "skipped":
3598
3617
  return c.json(
3599
- { status: "skipped" as const, reason: result.reason },
3618
+ {
3619
+ status: "skipped" as const,
3620
+ reason: result.reason,
3621
+ ...(result.appsState ? { appsState: result.appsState } : {}),
3622
+ },
3600
3623
  200,
3601
3624
  );
3602
3625
  case "removal_cap":
@@ -166,6 +166,15 @@ const ROUTES: Record<string, [Cassette, string]> = {
166
166
  enterprise,
167
167
  "installable_orgs_success",
168
168
  ],
169
+ "GET /app/installations": [
170
+ {
171
+ lookup_only_installations: {
172
+ status: 200,
173
+ body: [{ id: 7001, account: { login: "org-1", type: "Organization" } }],
174
+ },
175
+ },
176
+ "lookup_only_installations",
177
+ ],
169
178
  "GET /orgs/org-1/installation": [lookup, "org_installation_success"],
170
179
  "GET /orgs/org-2/installation": [lookup, "org_installation_404"],
171
180
  "POST /app/installations/7001/access_tokens": [
@@ -319,7 +328,24 @@ describeOrSkip("GET /agents/:id/github-access (integration)", () => {
319
328
  expect(calls).toEqual([]);
320
329
  });
321
330
 
322
- it("only one App configured is still unconfigured", async () => {
331
+ it("only the installer configured is still unconfigured", async () => {
332
+ const agent = await prisma.agent.create({
333
+ data: { name: "A", githubUsername: "octocat" },
334
+ });
335
+ const svc = svcNoApps();
336
+ await svc.save({
337
+ role: "installer",
338
+ appId: "12345",
339
+ slug: "example-installer",
340
+ enterpriseSlug: "acme",
341
+ privateKey: PEM,
342
+ });
343
+ const res = await get(build(svc), agent.id);
344
+ expect(await res.json()).toEqual({ status: "unconfigured" });
345
+ expect(calls).toEqual([]);
346
+ });
347
+
348
+ it("only the lookup App configured resolves through its own installations", async () => {
323
349
  const agent = await prisma.agent.create({
324
350
  data: { name: "A", githubUsername: "octocat" },
325
351
  });
@@ -332,8 +358,17 @@ describeOrSkip("GET /agents/:id/github-access (integration)", () => {
332
358
  privateKey: PEM,
333
359
  });
334
360
  const res = await get(build(svc), agent.id);
335
- expect(await res.json()).toEqual({ status: "unconfigured" });
336
- expect(calls).toEqual([]);
361
+ const json = (await res.json()) as {
362
+ status: string;
363
+ access: { orgs: { org: string; status: string }[] };
364
+ };
365
+ expect(json.status).toBe("ok");
366
+ expect(json.access.orgs.map((o) => [o.org, o.status])).toEqual([
367
+ ["org-1", "ok"],
368
+ ]);
369
+ expect(calls).not.toContain(
370
+ "GET /enterprises/acme/apps/installable_organizations",
371
+ );
337
372
  });
338
373
 
339
374
  it("user_not_found when the user does not exist on GitHub", async () => {