@app-vitals/agent-admin 1.109.0 → 1.111.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 (53) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  6. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  7. package/src/admin-ui-github-enterprise.ts +16 -1
  8. package/src/admin-ui-github-identity-pages.ts +35 -139
  9. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  10. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  11. package/src/admin-ui-installation-repos-pages.ts +2 -23
  12. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  13. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  14. package/src/admin-ui-pages.ts +4 -5
  15. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  16. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  17. package/src/admin-ui-slack-config-token.ts +51 -9
  18. package/src/admin-ui-templates-pages.ts +7 -1
  19. package/src/admin-ui-templates.smoke.test.ts +31 -5
  20. package/src/admin-ui-templates.ts +43 -8
  21. package/src/admin-ui.ts +51 -36
  22. package/src/agent-templates-api.integration.test.ts +29 -7
  23. package/src/agent-templates.ts +7 -1
  24. package/src/agents-api.smoke.test.ts +26 -315
  25. package/src/agents-api.ts +1 -107
  26. package/src/deployment-wide-settings.integration.test.ts +309 -0
  27. package/src/deployment-wide-settings.ts +42 -0
  28. package/src/github-access-preview.ts +2 -2
  29. package/src/github-agent-installation-crawler.ts +18 -1
  30. package/src/github-enterprise-api.integration.test.ts +7 -0
  31. package/src/github-enterprise-api.smoke.test.ts +26 -0
  32. package/src/github-enterprise-api.ts +24 -4
  33. package/src/github-enterprise-apps.integration.test.ts +33 -8
  34. package/src/github-enterprise-apps.ts +4 -0
  35. package/src/github-enterprise-client.integration.test.ts +0 -41
  36. package/src/github-enterprise-client.ts +0 -25
  37. package/src/github-enterprise-client.unit.test.ts +0 -18
  38. package/src/github-installation-wiring.ts +48 -13
  39. package/src/github-installation-wiring.unit.test.ts +38 -1
  40. package/src/github-sync-all-repos.unit.test.ts +116 -0
  41. package/src/github-sync-cache.integration.test.ts +9 -2
  42. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  43. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  44. package/src/github-sync.ts +103 -137
  45. package/src/github-sync.unit.test.ts +82 -1
  46. package/src/installation-ports.ts +1 -40
  47. package/src/installation-repos-service.ts +7 -4
  48. package/src/reconcile-open-work.integration.test.ts +0 -1
  49. package/src/slack-config-token.integration.test.ts +19 -2
  50. package/src/slack-config-token.ts +6 -1
  51. package/src/github-access-preview.integration.test.ts +0 -399
  52. package/src/github-sync-switch.integration.test.ts +0 -297
  53. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -0,0 +1,144 @@
1
+ /**
2
+ * admin/src/github-sync-snapshot-refresh.unit.test.ts
3
+ * After a Sync apply the cached agent-App snapshot (what the admin UI lists)
4
+ * is refreshed for each org apply changed. Root cause of the "second Sync says
5
+ * up to date" report: the plan reads the LIVE installation (listInstalled), so
6
+ * once apply lands it is already in sync, while the UI list reads the cached
7
+ * snapshot, which stayed stale until the background tick.
8
+ */
9
+
10
+ import { describe, expect, it } from "bun:test";
11
+ import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
12
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
13
+
14
+ const NOW = new Date("2026-11-25T12:00:00.000Z");
15
+
16
+ function setup(opts: { refreshFails?: boolean; noRefresh?: boolean } = {}) {
17
+ let live = ["acme/a", "acme/b", "acme/c"];
18
+ let snapshot = [...live];
19
+ const refreshed: [number | undefined, string, string | null | undefined][] =
20
+ [];
21
+ const port: InstallationReposPort = {
22
+ listRepos: async () => ({ acme: live }),
23
+ listInstalled: async () => ({
24
+ status: "found",
25
+ orgs: [{ org: "acme", repos: live }],
26
+ }),
27
+ addRepos: async (_a, _o, repos) => {
28
+ live = [...live, ...repos];
29
+ },
30
+ removeRepos: async (_a, _o, repos) => {
31
+ live = live.filter((r) => !repos.includes(r));
32
+ },
33
+ };
34
+ const deps = {
35
+ agents: {
36
+ get: async () => ({
37
+ id: "ag",
38
+ githubUsername: "octo",
39
+ appId: 7,
40
+ repos: [] as string[],
41
+ }),
42
+ setRepos: async () => {},
43
+ },
44
+ access: async () => {
45
+ throw new Error("live resolver must not be used");
46
+ },
47
+ cache: {
48
+ listAgentSnapshots: async () => [
49
+ {
50
+ org: "acme",
51
+ completedAt: new Date(NOW.getTime() - 1000),
52
+ totalCount: snapshot.length,
53
+ lastError: null,
54
+ rateLimitResetAt: null,
55
+ repositorySelection: "selected" as const,
56
+ repos: snapshot.map((fullName) => ({ fullName })),
57
+ },
58
+ ],
59
+ getAccessRows: async () =>
60
+ ["a", "b", "c"].map((repo) => ({
61
+ repo,
62
+ status: "ok",
63
+ canPush: repo === "a",
64
+ checkedAt: new Date(NOW.getTime() - 1000),
65
+ })),
66
+ },
67
+ lookupRepos: async () => [
68
+ {
69
+ org: "acme",
70
+ completedAt: new Date(NOW.getTime() - 1000),
71
+ repos: ["acme/a", "acme/b", "acme/c"],
72
+ },
73
+ ],
74
+ now: () => NOW,
75
+ verifyPush: async (_u: string, repo: string) => repo === "acme/a",
76
+ installation: port,
77
+ audit: { write: async () => "audit-1" },
78
+ ...(opts.noRefresh
79
+ ? {}
80
+ : {
81
+ refreshAgentSnapshot: async (
82
+ agent: { appId?: number; accountId?: string | null },
83
+ org: string,
84
+ ) => {
85
+ refreshed.push([agent.appId, org, agent.accountId]);
86
+ if (opts.refreshFails) throw new Error("github down");
87
+ snapshot = [...live];
88
+ },
89
+ }),
90
+ };
91
+ const svc = new GithubSyncService(deps as unknown as GithubSyncDeps);
92
+ const snap = async () =>
93
+ (await deps.cache.listAgentSnapshots()).flatMap((s) =>
94
+ s.repos.map((r) => r.fullName),
95
+ );
96
+ return { svc, snap, refreshed, live: () => live };
97
+ }
98
+
99
+ const lists = {
100
+ agentId: "ag",
101
+ caller: "root",
102
+ appAdds: [] as string[],
103
+ appRemoves: ["acme/b", "acme/c"],
104
+ agentRemoves: [] as string[],
105
+ };
106
+
107
+ describe("Sync apply refreshes the agent snapshot", () => {
108
+ it("snapshot reflects the removes right after apply, and a second Sync is a noop", async () => {
109
+ const { svc, snap, live } = setup();
110
+ const r = await svc.apply(lists);
111
+ expect(r.status).toBe("applied");
112
+ expect(live()).toEqual(["acme/a"]);
113
+ // The UI list (snapshot) must match the live installation, not lag it.
114
+ expect(await snap()).toEqual(["acme/a"]);
115
+ const second = await svc.apply(lists);
116
+ expect(second.status).toBe("noop");
117
+ });
118
+
119
+ it("refreshes only the changed org, once", async () => {
120
+ const { svc, refreshed } = setup();
121
+ await svc.apply(lists);
122
+ expect(refreshed).toEqual([[7, "acme", undefined]]);
123
+ });
124
+
125
+ it("does not refresh on a noop", async () => {
126
+ const { svc, refreshed } = setup();
127
+ await svc.apply(lists);
128
+ refreshed.length = 0;
129
+ await svc.apply(lists);
130
+ expect(refreshed).toEqual([]);
131
+ });
132
+
133
+ it("a failed refresh does not fail the apply result", async () => {
134
+ const { svc, refreshed } = setup({ refreshFails: true });
135
+ const r = await svc.apply(lists);
136
+ expect(refreshed).toHaveLength(1);
137
+ expect(r.status).toBe("applied");
138
+ });
139
+
140
+ it("works without the optional dep", async () => {
141
+ const { svc } = setup({ noRefresh: true });
142
+ expect((await svc.apply(lists)).status).toBe("applied");
143
+ });
144
+ });
@@ -20,14 +20,11 @@
20
20
  * MAX_UNCONFIRMED_REMOVALS removals need confirmRemovals.
21
21
  *
22
22
  * An org whose agent installation is on "All repositories" (read from the
23
- * crawl cache; unknown is never "all") cannot take add/remove calls, so Sync
24
- * switches it to "selected" first (GIS-1.2): target = installed repos minus the
25
- * confirmed app removes for that org. The first MAX_SELECTION_PATCH_REPOS go in
26
- * the PATCH, the rest through the batched add. The org's removes fold into the
27
- * switch but still count in removedRepos. An empty target skips the org with a
28
- * warning and leaves it on "all".
23
+ * crawl cache; unknown is never "all") cannot take add/remove calls, and
24
+ * switching it in-app fails on large orgs (GitHub HTTP 400, 100 implicit
25
+ * removals max). Sync skips it with ALL_REPOS_INSTALLATION_REASON.
29
26
  *
30
- * Order: selection switches, installation adds, installation removals,
27
+ * Order: installation adds, installation removals,
31
28
  * agent-repo removals, one audit entry, then the agent's open work on the
32
29
  * removed repos is blocked through the optional OpenWorkPort (a port failure is
33
30
  * a warning).
@@ -94,21 +91,9 @@ export const NOT_PRESENT_REASON =
94
91
  export const ARCHIVED_REASON =
95
92
  "the repo is archived (read-only), so it is not added to the installation";
96
93
 
97
- /** GitHub caps the repositories in a selection-switch PATCH at 50. */
98
- export const MAX_SELECTION_PATCH_REPOS = 50;
99
-
100
- export const EMPTY_SWITCH_TARGET_REASON =
101
- "the bound user can push to none of this org's repos, so it cannot be switched to selected repositories and stays on All repositories; use Uninstall to remove the agent App from this org";
102
-
103
- /** The installer App's permission a selection switch needs. */
104
- export const SWITCH_PERMISSION_MESSAGE = (org: string): string =>
105
- `GitHub refused to switch the agent App on ${org} to selected repositories (403): the installer App needs the enterprise_organization_installation_repositories permission with write access`;
106
-
107
- /** An "all" installation Sync switches to "selected" with this repo list. */
108
- export interface SelectionSwitch {
109
- org: string;
110
- repos: string[];
111
- }
94
+ /** Shown for an org whose agent installation is on All repositories. */
95
+ export const ALL_REPOS_INSTALLATION_REASON =
96
+ "Sync does not work when the app has access to all repositories; uninstall the app and install again with selected repositories.";
112
97
 
113
98
  export interface SyncLists {
114
99
  appAdds: readonly string[];
@@ -158,8 +143,6 @@ export interface GithubSyncPlan {
158
143
  agentRemoves: string[];
159
144
  /** Every repo removed from either place, sorted. */
160
145
  removedRepos: string[];
161
- /** "All" installations to switch to "selected" first (additive). */
162
- selectionSwitches?: SelectionSwitch[];
163
146
  skippedOrgs: OrgSkip[];
164
147
  notApplied: NotAppliedRepo[];
165
148
  warnings: string[];
@@ -176,43 +159,12 @@ function skippedPlan(reason: string): GithubSyncPlan {
176
159
  appRemoves: [],
177
160
  agentRemoves: [],
178
161
  removedRepos: [],
179
- selectionSwitches: [],
180
162
  skippedOrgs: [],
181
163
  notApplied: [],
182
164
  warnings: [],
183
165
  };
184
166
  }
185
167
 
186
- /**
187
- * Pure: the orgs on "all" and the "selected" list each switches to (installed
188
- * repos minus `appRemoves`). An org with an empty target is returned in
189
- * `emptyOrgs` instead. Only orgs `eligible` returns true for are considered.
190
- */
191
- export function planSelectionSwitches(input: {
192
- installationRepos: Readonly<Record<string, readonly string[]>>;
193
- selections?: GithubSyncPlanInput["selections"];
194
- appRemoves: readonly string[];
195
- eligible?: (org: string) => boolean;
196
- }): { switches: SelectionSwitch[]; emptyOrgs: string[] } {
197
- const selections = new Map(
198
- Object.entries(input.selections ?? {}).map(([o, v]) => [lower(o), v]),
199
- );
200
- const removed = new Set(input.appRemoves.map(lower));
201
- const switches: SelectionSwitch[] = [];
202
- const emptyOrgs: string[] = [];
203
- for (const [org, repos] of Object.entries(input.installationRepos)) {
204
- if (selections.get(lower(org)) !== "all") continue;
205
- if (input.eligible && !input.eligible(org)) continue;
206
- const target = sorted(repos.filter((r) => !removed.has(lower(r))));
207
- if (target.length === 0) emptyOrgs.push(org);
208
- else switches.push({ org, repos: target });
209
- }
210
- return {
211
- switches: switches.sort((a, b) => a.org.localeCompare(b.org)),
212
- emptyOrgs: emptyOrgs.sort(),
213
- };
214
- }
215
-
216
168
  /** Pure: the installation adds and removes and agent-repo removes to sync. */
217
169
  export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
218
170
  const skip = accessSkipReason(input.username, input.access);
@@ -248,6 +200,16 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
248
200
  : [...configured.values()];
249
201
 
250
202
  const skipReasons = new Map<string, string>();
203
+ // Orgs whose installation is on "all" (unknown is never "all"): always reported.
204
+ const selections = new Map(
205
+ Object.entries(input.selections ?? {}).map(([o, v]) => [lower(o), v]),
206
+ );
207
+ const allOrgs = new Map<string, string>();
208
+ for (const org of Object.keys(input.installationRepos)) {
209
+ if (selections.get(lower(org)) !== "all") continue;
210
+ allOrgs.set(lower(org), org);
211
+ skipReasons.set(org, ALL_REPOS_INSTALLATION_REASON);
212
+ }
251
213
  const skipDetails = new Map<string, OrgSkipDetail>();
252
214
  const notApplied = new Map<string, NotAppliedRepo>();
253
215
  const leave = (repo: string, reason: string) => {
@@ -257,6 +219,11 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
257
219
  // Unknown is never none: false (with the reason recorded) for a skipped org.
258
220
  const orgUsable = (repo: string): boolean => {
259
221
  const org = repoOrg(repo);
222
+ const allOrg = allOrgs.get(lower(org));
223
+ if (allOrg !== undefined) {
224
+ leave(repo, `skipped for org: ${ALL_REPOS_INSTALLATION_REASON}`);
225
+ return false;
226
+ }
260
227
  const result = orgResults.get(lower(org));
261
228
  const reason = orgSkipReason(result);
262
229
  if (!reason) return true;
@@ -321,20 +288,7 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
321
288
  const confirmedAppRemoves = removable(appRemoveCandidates, installed);
322
289
  const agentRemoves = removable(agentRemoveCandidates, configured);
323
290
 
324
- const { switches, emptyOrgs } = planSelectionSwitches({
325
- installationRepos: input.installationRepos,
326
- ...(input.selections ? { selections: input.selections } : {}),
327
- appRemoves: [...confirmedAppRemoves],
328
- eligible: (o) => !orgSkipReason(orgResults.get(lower(o))),
329
- });
330
- // An empty target leaves the org on "all", where removes cannot be applied.
331
- const emptySet = new Set(emptyOrgs.map(lower));
332
- const appRemoves = new Set<string>();
333
- for (const r of confirmedAppRemoves) {
334
- if (emptySet.has(lower(repoOrg(r)))) leave(r, EMPTY_SWITCH_TARGET_REASON);
335
- else appRemoves.add(r);
336
- }
337
- for (const o of emptyOrgs) skipReasons.set(o, EMPTY_SWITCH_TARGET_REASON);
291
+ const appRemoves = confirmedAppRemoves;
338
292
 
339
293
  const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
340
294
  org,
@@ -347,7 +301,6 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
347
301
  appRemoves: sorted(appRemoves),
348
302
  agentRemoves: sorted(agentRemoves),
349
303
  removedRepos: sorted(new Set([...appRemoves, ...agentRemoves])),
350
- selectionSwitches: switches,
351
304
  skippedOrgs,
352
305
  notApplied: [...notApplied.values()].sort((a, b) =>
353
306
  a.repo.localeCompare(b.repo),
@@ -403,13 +356,22 @@ export interface GithubSyncDeps {
403
356
  ) => Promise<boolean | undefined>;
404
357
  installation: Pick<
405
358
  InstallationReposPort,
406
- "listInstalled" | "addRepos" | "removeRepos" | "setRepositorySelection"
359
+ "listInstalled" | "addRepos" | "removeRepos"
407
360
  >;
408
361
  audit: InstallationAuditPort;
409
362
  /** Optional: with none, nothing is listed or blocked. */
410
363
  openWork?: OpenWorkPort;
411
364
  /** Optional: which Apps are usable; without both, Sync is skipped with a specific reason. */
412
365
  appsState?: GithubAppsStateFn;
366
+ /**
367
+ * Optional: re-crawl one org's agent-App snapshot (the cache the admin UI
368
+ * lists). Called after apply for each org it changed; errors are logged and
369
+ * never fail the apply.
370
+ */
371
+ refreshAgentSnapshot?: (
372
+ agent: InstallationAgentRecord,
373
+ org: string,
374
+ ) => Promise<void>;
413
375
  }
414
376
 
415
377
  export type GithubSyncPreviewResult =
@@ -450,22 +412,13 @@ export type GithubSyncApplyResult =
450
412
  }
451
413
  | { status: "failed"; plan: GithubSyncPlan; auditId: string; error: string };
452
414
 
453
- /** A plan plus the installation context a re-verified plan recomputes switches from. */
415
+ /** A plan plus the installation context it was computed from. */
454
416
  interface PlannedSync {
455
417
  plan: GithubSyncPlan;
456
418
  installationRepos: Record<string, string[]>;
457
419
  selections?: Record<string, "all" | "selected" | null>;
458
420
  }
459
421
 
460
- /** A 403 on a selection switch becomes a message naming the missing permission. */
461
- function switchError(org: string, err: unknown): Error {
462
- const e = err as { kind?: string; status?: number } | undefined;
463
- if (e?.kind === "permission" || (e?.status === 403 && e.kind === undefined)) {
464
- return new Error(SWITCH_PERMISSION_MESSAGE(org));
465
- }
466
- return err instanceof Error ? err : new Error(String(err));
467
- }
468
-
469
422
  function groupByOrg(repos: readonly string[]): Map<string, string[]> {
470
423
  const byOrg = new Map<string, string[]>();
471
424
  for (const r of repos) {
@@ -478,6 +431,50 @@ function groupByOrg(repos: readonly string[]): Map<string, string[]> {
478
431
  export class GithubSyncService {
479
432
  constructor(private readonly deps: GithubSyncDeps) {}
480
433
 
434
+ /**
435
+ * Repo names (not owner/name) the bound user can push to, per org, for the
436
+ * org Install picker. Cache only: it never calls GitHub. An org with no
437
+ * completed cached crawl, or no ok push row, is absent (unknown is never
438
+ * none). Returns {} when there is no cache, lookup source or bound user.
439
+ */
440
+ async installRepoChoices(
441
+ agentId: string,
442
+ orgs: readonly string[],
443
+ ): Promise<Record<string, string[]>> {
444
+ const { cache, lookupRepos } = this.deps;
445
+ if (!cache || !lookupRepos) return {};
446
+ const agent = await this.deps.agents.get(agentId);
447
+ const username = agent?.githubUsername?.trim();
448
+ if (!agent || !username) return {};
449
+ const lookup = await lookupRepos(agent.accountId);
450
+ const out: Record<string, string[]> = {};
451
+ for (const org of orgs) {
452
+ const lk = lookup.filter(
453
+ (l) => l.org.toLowerCase() === org.toLowerCase() && l.completedAt,
454
+ );
455
+ const names = [
456
+ ...new Set(
457
+ lk.flatMap((l) => l.repos).map((r) => r.slice(r.indexOf("/") + 1)),
458
+ ),
459
+ ];
460
+ if (names.length === 0) continue;
461
+ const rows = await getAccessRowsAcrossKeys(cache, {
462
+ accountId: agent.accountId,
463
+ org,
464
+ username,
465
+ repos: names,
466
+ });
467
+ const pushable = new Set(
468
+ rows
469
+ .filter((r) => r.status === "ok" && r.canPush)
470
+ .map((r) => r.repo.toLowerCase()),
471
+ );
472
+ const picked = names.filter((n) => pushable.has(n.toLowerCase()));
473
+ if (picked.length > 0) out[org] = picked.sort();
474
+ }
475
+ return out;
476
+ }
477
+
481
478
  /** Read-only: what would change and the open work the removals would block. */
482
479
  async preview(agentId: string): Promise<GithubSyncPreviewResult> {
483
480
  const agent = await this.deps.agents.get(agentId);
@@ -515,12 +512,8 @@ export class GithubSyncService {
515
512
  ...(plan.appsState ? { appsState: plan.appsState } : {}),
516
513
  };
517
514
  }
518
- plan = await this.reverifyRemovals(plan, agent, planned);
519
- const switches = plan.selectionSwitches ?? [];
520
- if (
521
- plan.appAdds.length + plan.removedRepos.length + switches.length ===
522
- 0
523
- ) {
515
+ plan = await this.reverifyRemovals(plan, agent);
516
+ if (plan.appAdds.length + plan.removedRepos.length === 0) {
524
517
  return { status: "noop", plan };
525
518
  }
526
519
  const removals = plan.removedRepos.length;
@@ -532,49 +525,14 @@ export class GithubSyncService {
532
525
  const identity = identityOf(agent);
533
526
  const added: string[] = [];
534
527
  const removed: string[] = [];
535
- const switchRecords: SelectionSwitch[] = [];
536
- const switchedOrgs = new Set(switches.map((s) => lower(s.org)));
537
528
  let configDone = false;
538
529
  let error: string | undefined;
539
530
  try {
540
- for (const sw of switches) {
541
- const record: SelectionSwitch = { org: sw.org, repos: [] };
542
- const head = sw.repos.slice(0, MAX_SELECTION_PATCH_REPOS);
543
- const rest = sw.repos.slice(MAX_SELECTION_PATCH_REPOS);
544
- const setSelection = this.deps.installation.setRepositorySelection;
545
- if (!setSelection) {
546
- throw new Error(
547
- `cannot switch ${sw.org} to selected repositories: the installation port does not support it`,
548
- );
549
- }
550
- try {
551
- await setSelection.call(
552
- this.deps.installation,
553
- appId,
554
- sw.org,
555
- head,
556
- identity,
557
- );
558
- } catch (err) {
559
- throw switchError(sw.org, err);
560
- }
561
- // The switch landed: the org's confirmed removes are now off the installation.
562
- record.repos = head;
563
- switchRecords.push(record);
564
- removed.push(
565
- ...plan.appRemoves.filter((r) => lower(repoOrg(r)) === lower(sw.org)),
566
- );
567
- if (rest.length > 0) {
568
- await this.deps.installation.addRepos(appId, sw.org, rest, identity);
569
- record.repos = sw.repos;
570
- }
571
- }
572
531
  for (const [org, repos] of groupByOrg(plan.appAdds)) {
573
532
  await this.deps.installation.addRepos(appId, org, repos, identity);
574
533
  added.push(...repos);
575
534
  }
576
535
  for (const [org, repos] of groupByOrg(plan.appRemoves)) {
577
- if (switchedOrgs.has(lower(org))) continue;
578
536
  await this.deps.installation.removeRepos(appId, org, repos, identity);
579
537
  removed.push(...repos);
580
538
  }
@@ -599,15 +557,15 @@ export class GithubSyncService {
599
557
  installationRemoves: removed,
600
558
  configAdds: [],
601
559
  configRemoves: configDone ? plan.agentRemoves : [],
602
- ...(switchRecords.length > 0
603
- ? { selectionSwitches: switchRecords }
604
- : {}),
605
560
  },
606
561
  result:
607
562
  error === undefined
608
563
  ? { status: "applied" }
609
564
  : { status: "failed", error },
610
565
  });
566
+ // Refresh the cached snapshot for every org that changed, even after a
567
+ // partial failure (some changes may have landed).
568
+ await this.refreshChangedOrgs(agent, [...added, ...removed]);
611
569
  if (error !== undefined) {
612
570
  return { status: "failed", plan, auditId, error };
613
571
  }
@@ -620,11 +578,30 @@ export class GithubSyncService {
620
578
  return { status: "applied", plan, auditId, warnings };
621
579
  }
622
580
 
581
+ /** Targeted per-org snapshot refresh; a failure is logged, never thrown. */
582
+ private async refreshChangedOrgs(
583
+ agent: InstallationAgentRecord,
584
+ repos: readonly string[],
585
+ ): Promise<void> {
586
+ const refresh = this.deps.refreshAgentSnapshot;
587
+ if (!refresh) return;
588
+ const orgs = new Map<string, string>();
589
+ for (const r of repos) orgs.set(lower(repoOrg(r)), repoOrg(r));
590
+ for (const org of orgs.values()) {
591
+ try {
592
+ await refresh(agent, org);
593
+ } catch (err) {
594
+ console.error(
595
+ `[github-sync] snapshot refresh for ${org} failed: ${err instanceof Error ? err.message : String(err)}`,
596
+ );
597
+ }
598
+ }
599
+ }
600
+
623
601
  /** Drops every removal the live permission call does not confirm (unknown is never none). */
624
602
  private async reverifyRemovals(
625
603
  plan: GithubSyncPlan,
626
604
  agent: InstallationAgentRecord,
627
- planned: PlannedSync,
628
605
  ): Promise<GithubSyncPlan> {
629
606
  const verify = this.deps.verifyPush;
630
607
  const username = agent.githubUsername?.trim();
@@ -647,21 +624,10 @@ export class GithubSyncService {
647
624
  const keep = (repos: string[]) => repos.filter((r) => !dropped.has(r));
648
625
  const appRemoves = keep(plan.appRemoves);
649
626
  const agentRemoves = keep(plan.agentRemoves);
650
- // A removal the user can still push to goes back on the switch target.
651
- const switchOrgs = new Set(
652
- (plan.selectionSwitches ?? []).map((s) => lower(s.org)),
653
- );
654
- const { switches } = planSelectionSwitches({
655
- installationRepos: planned.installationRepos,
656
- ...(planned.selections ? { selections: planned.selections } : {}),
657
- appRemoves,
658
- eligible: (o) => switchOrgs.has(lower(o)),
659
- });
660
627
  return {
661
628
  ...plan,
662
629
  appRemoves,
663
630
  agentRemoves,
664
- selectionSwitches: switches,
665
631
  removedRepos: sorted(new Set([...appRemoves, ...agentRemoves])),
666
632
  notApplied: [
667
633
  ...plan.notApplied,
@@ -279,7 +279,9 @@ describe("planGithubSync (archived repos)", () => {
279
279
  }),
280
280
  );
281
281
  expect(p.skippedOrgs).toEqual([]);
282
- expect(p.notApplied).toEqual([{ repo: "other/old", reason: ARCHIVED_REASON }]);
282
+ expect(p.notApplied).toEqual([
283
+ { repo: "other/old", reason: ARCHIVED_REASON },
284
+ ]);
283
285
  });
284
286
 
285
287
  test("an installed archived repo in an unchecked org is kept, not removed", () => {
@@ -863,3 +865,82 @@ describe("skippedOrgs detail", () => {
863
865
  });
864
866
  });
865
867
  });
868
+
869
+ describe("GithubSyncService.installRepoChoices", () => {
870
+ const svc = (username: string | undefined, calls: string[]) =>
871
+ new GithubSyncService({
872
+ agents: {
873
+ get: async () => ({
874
+ id: "ag",
875
+ githubUsername: username ?? null,
876
+ appId: 7,
877
+ repos: [],
878
+ }),
879
+ setRepos: async () => {},
880
+ },
881
+ access: async () => {
882
+ throw new Error("live resolver must not be used");
883
+ },
884
+ installation: {} as never,
885
+ audit: {} as never,
886
+ cache: {
887
+ listAgentSnapshots: async () => [],
888
+ getAccessRows: async (q: { repos: string[] }) => {
889
+ calls.push(q.repos.join(","));
890
+ return q.repos.map((r) => ({
891
+ repo: r,
892
+ status: "ok",
893
+ canPush: r !== "ro",
894
+ }));
895
+ },
896
+ } as never,
897
+ lookupRepos: async () => [
898
+ {
899
+ org: "acme",
900
+ completedAt: new Date(),
901
+ repos: ["acme/web", "acme/ro", "acme/api"],
902
+ },
903
+ { org: "beta", completedAt: null, repos: ["beta/x"] },
904
+ ],
905
+ });
906
+
907
+ it("returns sorted pushable repo names; skips incomplete orgs", async () => {
908
+ const calls: string[] = [];
909
+ expect(
910
+ await svc("octo", calls).installRepoChoices("ag", ["acme", "beta"]),
911
+ ).toEqual({
912
+ acme: ["api", "web"],
913
+ });
914
+ });
915
+
916
+ it("returns nothing without a bound user", async () => {
917
+ expect(await svc(undefined, []).installRepoChoices("ag", ["acme"])).toEqual(
918
+ {},
919
+ );
920
+ });
921
+ });
922
+
923
+ describe("GithubSyncService.preview with an incomplete apps state", () => {
924
+ it("skips with the apps-state reason and plans nothing", async () => {
925
+ const svc = new GithubSyncService({
926
+ agents: {
927
+ get: async () => ({
928
+ id: "ag",
929
+ accountId: "acct",
930
+ githubUsername: "octo",
931
+ appId: 7,
932
+ repos: [],
933
+ }),
934
+ setRepos: async () => {},
935
+ },
936
+ access: async () => {
937
+ throw new Error("live resolver must not be used");
938
+ },
939
+ installation: {} as never,
940
+ audit: {} as never,
941
+ appsState: async () => "lookup_only",
942
+ } as never);
943
+ const r = await svc.preview("ag");
944
+ expect(r).toMatchObject({ status: "skipped", appsState: "lookup_only" });
945
+ });
946
+ });