@app-vitals/agent-admin 1.129.0 → 1.130.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 (30) hide show
  1. package/package.json +2 -2
  2. package/src/admin-boot.ts +2 -0
  3. package/src/admin-ui-pages.ts +20 -6
  4. package/src/admin-ui-pages.unit.test.ts +23 -0
  5. package/src/admin-ui.ts +36 -2
  6. package/src/agent-github-apps-api.smoke.test.ts +155 -0
  7. package/src/agent-github-apps.integration.test.ts +168 -0
  8. package/src/agent-github-apps.ts +157 -0
  9. package/src/agent-github-apps.unit.test.ts +34 -0
  10. package/src/agents-api.smoke.test.ts +103 -0
  11. package/src/agents-api.ts +76 -1
  12. package/src/github-agent-installation-crawler.integration.test.ts +182 -11
  13. package/src/github-agent-installation-crawler.ts +41 -1
  14. package/src/github-agent-installation-crawler.unit.test.ts +155 -0
  15. package/src/github-enterprise-api.ts +14 -1
  16. package/src/github-installation-wiring.ts +7 -5
  17. package/src/github-installation.fixtures.ts +2 -0
  18. package/src/github-provisioning-service.integration.test.ts +189 -0
  19. package/src/github-provisioning-service.ts +66 -29
  20. package/src/github-provisioning-service.unit.test.ts +114 -6
  21. package/src/github-repo-refresh-discovery.ts +41 -31
  22. package/src/github-repo-refresh-discovery.unit.test.ts +86 -0
  23. package/src/github-sync-multi-app.integration.test.ts +122 -0
  24. package/src/github-sync-multi-app.unit.test.ts +156 -0
  25. package/src/github-sync.ts +59 -14
  26. package/src/installation-ports.integration.test.ts +79 -3
  27. package/src/installation-ports.ts +87 -12
  28. package/src/installation-ports.unit.test.ts +23 -0
  29. package/src/installation-repos-service.ts +40 -5
  30. package/src/installation-repos-service.unit.test.ts +100 -0
@@ -12,23 +12,56 @@ import { GithubProvisioningService } from "./github-provisioning-service.ts";
12
12
  const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
13
13
  const AGENT_ID = "agent-test-123";
14
14
 
15
- function makeService(storedInstallationId?: string) {
15
+ /**
16
+ * Table-based fixture (multi-github-apps 1.5): the stored installation id
17
+ * lives on the agent's primary AgentGitHubApp row, and App writes go to the
18
+ * table as well as the env mirror. `envOnly` keeps one env-fallback fixture
19
+ * for an agent the backfill has not reached.
20
+ */
21
+ function makeService(
22
+ storedInstallationId?: string,
23
+ opts: { envOnly?: boolean; slug?: string } = {},
24
+ ) {
16
25
  const patchCalls: Array<Record<string, string>> = [];
26
+ const tableCalls: Array<Record<string, string>> = [];
17
27
  const reconcileCalls: string[] = [];
28
+ const primary =
29
+ storedInstallationId || opts.slug
30
+ ? {
31
+ id: "row-1",
32
+ agentId: AGENT_ID,
33
+ appId: "42",
34
+ slug: opts.slug ?? null,
35
+ clientId: null,
36
+ installationId: storedInstallationId ?? null,
37
+ priority: 0,
38
+ }
39
+ : null;
18
40
  const service = new GithubProvisioningService({
19
41
  githubAppClient: {} as never,
20
42
  agentService: {} as never,
21
43
  agentEnvService: {
22
44
  getByAgentId: async () => ({
23
- env: storedInstallationId
24
- ? { GH_APP_INSTALLATION_ID: storedInstallationId }
25
- : {},
45
+ env:
46
+ opts.envOnly && storedInstallationId
47
+ ? { GH_APP_INSTALLATION_ID: storedInstallationId }
48
+ : {},
26
49
  secretKeys: [],
27
50
  }),
28
51
  patch: async (_id: string, env: Record<string, string>) => {
29
52
  patchCalls.push(env);
30
53
  },
31
54
  } as never,
55
+ agentGitHubAppService: {
56
+ getPrimary: async () => (opts.envOnly ? null : primary),
57
+ applyLegacyEnvPatch: async (
58
+ _id: string,
59
+ patch: Record<string, string>,
60
+ ) => {
61
+ tableCalls.push(patch);
62
+ return null;
63
+ },
64
+ } as never,
32
65
  agentCronJobService: {
33
66
  reconcileSystemCrons: async (id: string) => {
34
67
  reconcileCalls.push(id);
@@ -39,7 +72,7 @@ function makeService(storedInstallationId?: string) {
39
72
  appBaseUrl: "https://example.com",
40
73
  secretEnvVars: new Set(),
41
74
  });
42
- return { service, patchCalls, reconcileCalls };
75
+ return { service, patchCalls, tableCalls, reconcileCalls };
43
76
  }
44
77
 
45
78
  async function stateCookie(agentId = AGENT_ID): Promise<string> {
@@ -96,7 +129,7 @@ describe("GithubProvisioningService.completeInstalled", () => {
96
129
  });
97
130
 
98
131
  it("no stored ID + valid cookie → stores the installation ID and reconciles crons", async () => {
99
- const { service, patchCalls, reconcileCalls } = makeService();
132
+ const { service, patchCalls, tableCalls, reconcileCalls } = makeService();
100
133
  const result = await service.completeInstalled(
101
134
  await stateCookie(),
102
135
  "778899",
@@ -108,9 +141,28 @@ describe("GithubProvisioningService.completeInstalled", () => {
108
141
  alreadyStored: false,
109
142
  });
110
143
  expect(patchCalls).toEqual([{ GH_APP_INSTALLATION_ID: "778899" }]);
144
+ expect(tableCalls).toEqual([{ GH_APP_INSTALLATION_ID: "778899" }]);
111
145
  expect(reconcileCalls).toEqual([AGENT_ID]);
112
146
  });
113
147
 
148
+ it("env-only agent (no table row): the stored env installation ID is still honoured", async () => {
149
+ const { service, patchCalls, tableCalls } = makeService("111", {
150
+ envOnly: true,
151
+ });
152
+ const result = await service.completeInstalled(
153
+ undefined,
154
+ "778899",
155
+ AGENT_ID,
156
+ );
157
+ expect(result).toEqual({
158
+ outcome: "success",
159
+ agentId: AGENT_ID,
160
+ alreadyStored: true,
161
+ });
162
+ expect(patchCalls).toHaveLength(0);
163
+ expect(tableCalls).toHaveLength(0);
164
+ });
165
+
114
166
  it("no stored ID + cookie for a different agent → agent_mismatch", async () => {
115
167
  const { service } = makeService();
116
168
  const result = await service.completeInstalled(
@@ -124,6 +176,7 @@ describe("GithubProvisioningService.completeInstalled", () => {
124
176
 
125
177
  describe("GithubProvisioningService.completeConnect (SWI-16.1)", () => {
126
178
  it("success result exposes githubOrg from the state cookie", async () => {
179
+ const tableWrites: unknown[] = [];
127
180
  const service = new GithubProvisioningService({
128
181
  githubAppClient: {
129
182
  exchangeManifestCode: async () => ({
@@ -136,6 +189,13 @@ describe("GithubProvisioningService.completeConnect (SWI-16.1)", () => {
136
189
  } as never,
137
190
  agentService: {} as never,
138
191
  agentEnvService: { patch: async () => {} } as never,
192
+ agentGitHubAppService: {
193
+ getPrimary: async () => null,
194
+ applyLegacyEnvPatch: async (_id: string, patch: unknown) => {
195
+ tableWrites.push(patch);
196
+ return null;
197
+ },
198
+ } as never,
139
199
  agentCronJobService: {} as never,
140
200
  sessionSecret: SESSION_SECRET,
141
201
  appBaseUrl: "https://example.com",
@@ -152,5 +212,53 @@ describe("GithubProvisioningService.completeConnect (SWI-16.1)", () => {
152
212
  installUrl: "https://github.com/apps/my-app/installations/new",
153
213
  githubOrg: "my-org",
154
214
  });
215
+ expect(tableWrites).toEqual([
216
+ {
217
+ GH_APP_ID: "1",
218
+ GH_APP_PRIVATE_KEY: "pem",
219
+ GH_APP_CLIENT_ID: "cid",
220
+ GH_APP_CLIENT_SECRET: "secret",
221
+ GH_APP_SLUG: "my-app",
222
+ },
223
+ ]);
224
+ });
225
+ });
226
+
227
+ describe("GithubProvisioningService App writes (multi-github-apps 1.5)", () => {
228
+ it("manual paste writes the table and mirrors env with the same fields", async () => {
229
+ const { service, patchCalls, tableCalls } = makeService();
230
+ const svc = service as unknown as {
231
+ deps: { agentService: { getDetail: () => Promise<unknown> } };
232
+ };
233
+ svc.deps.agentService.getDetail = async () => ({ id: AGENT_ID });
234
+ const pem =
235
+ "-----BEGIN RSA PRIVATE KEY-----\nabc\n-----END RSA PRIVATE KEY-----";
236
+ const result = await service.startAppManualConnect(AGENT_ID, {
237
+ ghAppId: "42",
238
+ ghAppInstallationId: "7",
239
+ ghAppPrivateKey: pem,
240
+ });
241
+ expect(result.ok).toBe(true);
242
+ const expected = {
243
+ GH_APP_ID: "42",
244
+ GH_APP_INSTALLATION_ID: "7",
245
+ GH_APP_PRIVATE_KEY: pem,
246
+ };
247
+ expect(tableCalls).toEqual([expected]);
248
+ expect(patchCalls).toEqual([expected]);
249
+ });
250
+
251
+ it("getAddOrgUrl reads the slug from the table primary", async () => {
252
+ const { service } = makeService(undefined, { slug: "my-app" });
253
+ expect(await service.getAddOrgUrl(AGENT_ID)).toEqual({
254
+ ok: true,
255
+ url: "https://github.com/apps/my-app/installations/new",
256
+ });
257
+ });
258
+
259
+ it("getAddOrgUrl without a slug reports the missing slug", async () => {
260
+ const { service } = makeService();
261
+ const result = await service.getAddOrgUrl(AGENT_ID);
262
+ expect(result.ok).toBe(false);
155
263
  });
156
264
  });
@@ -10,12 +10,14 @@
10
10
  * per org, keyed by the scope that owns the lookup App (accountId, or
11
11
  * DEPLOYMENT_WIDE_ACCOUNT_KEY). Orgs come from the resolved installer App when
12
12
  * it has an enterprise slug, else from the lookup App's own installations.
13
- * Agents with a GH_APP_ID and a GitHub username whose account resolves to that
14
- * lookup App supply the access-backfill users.
13
+ * Agents with at least one App and a GitHub username whose account resolves
14
+ * to that lookup App supply the access-backfill users; every App of theirs
15
+ * contributes an installation key.
15
16
  *
16
- * Each agent with a GH_APP_ID also gets one agent target per org its account's
17
- * installer can reach (keyed as GLC-1.5 keys it). No installer, no agent
18
- * targets.
17
+ * Each agent App (agentApps: the AgentGitHubApp rows, else the legacy
18
+ * GH_APP_ID) also gets one agent target per org its account's installer can
19
+ * reach (keyed as GLC-1.5 keys it, appRef = that App's id). An agent with one
20
+ * App gets exactly the targets it always did. No installer, no agent targets.
19
21
  *
20
22
  * Keys are deduplicated, and a scope or agent whose discovery fails is logged
21
23
  * and skipped without affecting the rest. The stored-App wiring (key-bearing)
@@ -44,7 +46,10 @@ import {
44
46
  type RefreshTarget,
45
47
  snapshotKeyString,
46
48
  } from "./github-repo-refresher.ts";
47
- import type { InstallationAgentRecord } from "./installation-ports.ts";
49
+ import {
50
+ agentApps,
51
+ type InstallationAgentRecord,
52
+ } from "./installation-ports.ts";
48
53
 
49
54
  /** The lookup-client surface discovery and its targets use. */
50
55
  export type LookupAppClient = AccessProbe &
@@ -145,7 +150,7 @@ export function createRefreshDiscovery(
145
150
  // Access users per lookup scope key: agents with an App and a user.
146
151
  const usersByScope = new Map<string, InstallationAgentRecord[]>();
147
152
  for (const a of agents) {
148
- if (a.appId === undefined || !a.githubUsername?.trim()) continue;
153
+ if (agentApps(a).length === 0 || !a.githubUsername?.trim()) continue;
149
154
  try {
150
155
  const lookup = await lookupFor(a.accountId ?? null);
151
156
  if (!lookup) continue;
@@ -194,13 +199,15 @@ export function createRefreshDiscovery(
194
199
  access: {
195
200
  probe: lookup.client,
196
201
  users,
197
- installationKeys: bound.map(
198
- (a): SnapshotKey => ({
199
- accountId: scopeKeyOf(a.accountId),
200
- appKind: "agent",
201
- appRef: String(a.appId),
202
- org,
203
- }),
202
+ installationKeys: bound.flatMap((a) =>
203
+ agentApps(a).map(
204
+ (app): SnapshotKey => ({
205
+ accountId: scopeKeyOf(a.accountId),
206
+ appKind: "agent",
207
+ appRef: String(app.appId),
208
+ org,
209
+ }),
210
+ ),
204
211
  ),
205
212
  },
206
213
  }
@@ -215,28 +222,31 @@ export function createRefreshDiscovery(
215
222
  }
216
223
 
217
224
  for (const a of agents) {
218
- if (a.appId === undefined) continue;
225
+ const apps = agentApps(a);
226
+ if (apps.length === 0) continue;
219
227
  try {
220
228
  const orgs = await installerOrgsFor(a.accountId ?? null);
221
229
  if (!orgs) continue;
222
230
  for (const org of orgs) {
223
- add({
224
- key: {
225
- accountId: scopeKeyOf(a.accountId),
226
- appKind: "agent",
227
- appRef: String(a.appId),
228
- org,
229
- },
230
- crawl: (ctx) =>
231
- crawlAgentInstallation({
232
- agent: a,
231
+ for (const app of apps) {
232
+ add({
233
+ key: {
234
+ accountId: scopeKeyOf(a.accountId),
235
+ appKind: "agent",
236
+ appRef: String(app.appId),
233
237
  org,
234
- client: installer,
235
- store,
236
- clock,
237
- shouldStop: ctx.shouldStop,
238
- }),
239
- });
238
+ },
239
+ crawl: (ctx) =>
240
+ crawlAgentInstallation({
241
+ agent: { accountId: a.accountId, ...app },
242
+ org,
243
+ client: installer,
244
+ store,
245
+ clock,
246
+ shouldStop: ctx.shouldStop,
247
+ }),
248
+ });
249
+ }
240
250
  }
241
251
  } catch (err) {
242
252
  log(
@@ -107,6 +107,92 @@ describe("createRefreshDiscovery", () => {
107
107
  expect(targets[2]?.access).toBeUndefined();
108
108
  });
109
109
 
110
+ it("emits one agent target per app per org, and every app's installation keys for access", async () => {
111
+ const d = createRefreshDiscovery(
112
+ ports({
113
+ listAgents: async () => [
114
+ agent({
115
+ id: "a1",
116
+ appId: 777,
117
+ apps: [{ appId: 777 }, { appId: 888, slug: "second-app" }],
118
+ githubUsername: "octocat",
119
+ }),
120
+ ],
121
+ }),
122
+ );
123
+ const targets = await d.listTargets();
124
+ expect(keys(targets)).toEqual([
125
+ "deployment|lookup|555|acme",
126
+ "deployment|lookup|555|beta",
127
+ "deployment|agent|777|acme",
128
+ "deployment|agent|888|acme",
129
+ "deployment|agent|777|beta",
130
+ "deployment|agent|888|beta",
131
+ ]);
132
+ expect(targets[0]?.access?.users).toEqual([
133
+ { username: "octocat", configuredRepos: [] },
134
+ ]);
135
+ expect(
136
+ targets[0]?.access?.installationKeys?.map((k) => `${k.appRef}|${k.org}`),
137
+ ).toEqual(["777|acme", "888|acme"]);
138
+ });
139
+
140
+ it("a single-app agent yields the same targets with or without the apps list", async () => {
141
+ const run = async (a: InstallationAgentRecord) =>
142
+ (
143
+ await createRefreshDiscovery(
144
+ ports({ listAgents: async () => [a] }),
145
+ ).listTargets()
146
+ ).map((t) => ({
147
+ key: t.key,
148
+ installationKeys: t.access?.installationKeys,
149
+ }));
150
+ const legacy = agent({ appId: 777, githubUsername: "octocat" });
151
+ expect(await run({ ...legacy, apps: [{ appId: 777 }] })).toEqual(
152
+ await run(legacy),
153
+ );
154
+ });
155
+
156
+ it("crawls each app's own installation for its target", async () => {
157
+ const seen: string[] = [];
158
+ const d = createRefreshDiscovery(
159
+ ports({
160
+ installerOrgs: async () => ["acme"],
161
+ installer: {
162
+ async listOrgInstallations() {
163
+ return [{ id: 601, appSlug: "second-app" }];
164
+ },
165
+ async listInstallationRepositoriesPage(_org, id) {
166
+ seen.push(`page:${id}`);
167
+ throw new Error("stop");
168
+ },
169
+ },
170
+ store: {
171
+ getSnapshot: async () => null,
172
+ upsertSnapshot: async (k: { appRef: string }) => {
173
+ seen.push(`snap:${k.appRef}`);
174
+ return { id: k.appRef } as never;
175
+ },
176
+ upsertRepos: async () => 0,
177
+ countReposSeenSince: async () => 0,
178
+ sweepGeneration: async () => 0,
179
+ } as unknown as DiscoveryPorts["store"],
180
+ listAgents: async () => [
181
+ agent({
182
+ appId: 777,
183
+ apps: [{ appId: 777 }, { appId: 888, slug: "second-app" }],
184
+ }),
185
+ ],
186
+ }),
187
+ );
188
+ const target = (await d.listTargets()).find(
189
+ (t) => t.key.appKind === "agent" && t.key.appRef === "888",
190
+ );
191
+ await target?.crawl({ shouldStop: () => false });
192
+ expect(seen).toContain("page:601");
193
+ expect(seen.every((s) => s === "page:601" || s === "snap:888")).toBe(true);
194
+ });
195
+
110
196
  it("uses the lookup App's own installations when no installer is configured, with no agent targets", async () => {
111
197
  const d = createRefreshDiscovery(
112
198
  ports({
@@ -0,0 +1,122 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { GithubSyncService } from "./github-sync.ts";
3
+ import type { InstallationAgentRecord } from "./installation-ports.ts";
4
+ import type { InstallationCachePort } from "./installation-repos-service.ts";
5
+
6
+ // Sync over the cached path with two Apps: each org's snapshot comes from the
7
+ // App routed to it, and apply goes through that App's installation.
8
+
9
+ const NOW = new Date("2026-12-01T00:00:00.000Z");
10
+ const ORGS: Record<
11
+ string,
12
+ { repos: string[]; pushable: string[]; app: number }
13
+ > = {
14
+ alpha: { repos: ["a", "b"], pushable: ["a"], app: 1 },
15
+ beta: { repos: ["x", "y"], pushable: ["x"], app: 2 },
16
+ };
17
+
18
+ const snapshot = (org: string, selection: "all" | "selected") => ({
19
+ org,
20
+ completedAt: NOW,
21
+ totalCount: ORGS[org]?.repos.length ?? 0,
22
+ lastError: null,
23
+ rateLimitResetAt: null,
24
+ repositorySelection: selection,
25
+ repos: (ORGS[org]?.repos ?? []).map((r) => ({ fullName: `${org}/${r}` })),
26
+ });
27
+
28
+ function setup(selections: Record<number, "all" | "selected"> = {}) {
29
+ const calls: unknown[][] = [];
30
+ const cache: InstallationCachePort = {
31
+ // Every App records a snapshot for every org it was crawled on; only the
32
+ // installed one carries repos.
33
+ listAgentSnapshots: async (_acct, appRef) =>
34
+ Object.entries(ORGS).map(([org, o]) =>
35
+ o.app === Number(appRef)
36
+ ? snapshot(org, selections[o.app] ?? "selected")
37
+ : {
38
+ ...snapshot(org, "selected"),
39
+ repositorySelection: null,
40
+ repos: [],
41
+ totalCount: 0,
42
+ },
43
+ ),
44
+ getAccessRows: async ({ org, repos }) =>
45
+ repos.map((repo) => ({
46
+ repo,
47
+ status: "ok",
48
+ canPush: ORGS[org]?.pushable.includes(repo) ?? false,
49
+ checkedAt: NOW,
50
+ })),
51
+ };
52
+ const agent: InstallationAgentRecord = {
53
+ id: "ag",
54
+ githubUsername: "octo",
55
+ appId: 1,
56
+ apps: [{ appId: 1 }, { appId: 2 }],
57
+ repos: [],
58
+ };
59
+ const svc = new GithubSyncService({
60
+ agents: { get: async () => agent, setRepos: async () => {} },
61
+ access: async () => ({ status: "unconfigured" }),
62
+ cache,
63
+ lookupRepos: async () =>
64
+ Object.entries(ORGS).map(([org, o]) => ({
65
+ org,
66
+ completedAt: NOW,
67
+ repos: o.repos.map((r) => `${org}/${r}`).concat(`${org}/new`),
68
+ })),
69
+ now: () => NOW,
70
+ installation: {
71
+ listInstalled: async (appId) => {
72
+ const orgs = Object.entries(ORGS)
73
+ .filter(([, o]) => o.app === appId)
74
+ .map(([org, o]) => ({
75
+ org,
76
+ repos: o.repos.map((r) => `${org}/${r}`),
77
+ }));
78
+ return orgs.length ? { status: "found", orgs } : { status: "none" };
79
+ },
80
+ addRepos: async (appId, org, repos) => {
81
+ calls.push(["add", appId, org, [...repos]]);
82
+ },
83
+ removeRepos: async (appId, org, repos) => {
84
+ calls.push(["remove", appId, org, [...repos]]);
85
+ },
86
+ },
87
+ audit: { write: async () => "audit-1" },
88
+ });
89
+ return { svc, calls };
90
+ }
91
+
92
+ describe("sync over the cache with two Apps", () => {
93
+ it("plans removals per org from each org's own App snapshot", async () => {
94
+ const r = await setup().svc.preview("ag");
95
+ if (r.status !== "previewed") throw new Error(r.status);
96
+ expect(r.plan.appRemoves).toEqual(["alpha/b", "beta/y"]);
97
+ expect(r.plan.skippedOrgs).toEqual([]);
98
+ });
99
+
100
+ it("applies each org's removals through its own App", async () => {
101
+ const { svc, calls } = setup();
102
+ const r = await svc.apply({
103
+ agentId: "ag",
104
+ caller: "root",
105
+ appAdds: [],
106
+ appRemoves: ["alpha/b", "beta/y"],
107
+ agentRemoves: [],
108
+ });
109
+ expect(r.status).toBe("applied");
110
+ expect(calls).toEqual([
111
+ ["remove", 1, "alpha", ["alpha/b"]],
112
+ ["remove", 2, "beta", ["beta/y"]],
113
+ ]);
114
+ });
115
+
116
+ it("skips only the org whose App is on All repositories", async () => {
117
+ const r = await setup({ 2: "all" }).svc.preview("ag");
118
+ if (r.status !== "previewed") throw new Error(r.status);
119
+ expect(r.plan.appRemoves).toEqual(["alpha/b"]);
120
+ expect(r.plan.skippedOrgs.map((s) => s.org)).toEqual(["beta"]);
121
+ });
122
+ });
@@ -0,0 +1,156 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { GithubSyncService } from "./github-sync.ts";
3
+ import type { InstallationAgentRecord } from "./installation-ports.ts";
4
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
5
+
6
+ const orgAccess = (org: string, repos: Record<string, boolean>) => ({
7
+ org,
8
+ status: "ok" as const,
9
+ unresolved: 0,
10
+ repos: Object.entries(repos).map(([n, canPush]) => ({
11
+ fullName: `${org}/${n}`,
12
+ level: canPush ? ("write" as const) : ("read" as const),
13
+ canPush,
14
+ })),
15
+ });
16
+
17
+ const ACCESS: UserRepoAccessResult = {
18
+ username: "octo",
19
+ outcome: "ok",
20
+ userVerified: true,
21
+ orgs: [
22
+ orgAccess("alpha", { a: true, b: false, c: true }),
23
+ orgAccess("beta", { x: true, y: false, z: true }),
24
+ orgAccess("gamma", { q: true }),
25
+ ],
26
+ unresolved: 0,
27
+ complete: true,
28
+ checkedAt: "2026-11-11T00:00:00.000Z",
29
+ };
30
+
31
+ type Install = Record<number, { org: string; repos: string[] }[]>;
32
+
33
+ function harness(installs: Install, apps = [{ appId: 1 }, { appId: 2 }]) {
34
+ const calls: unknown[][] = [];
35
+ const agent: InstallationAgentRecord = {
36
+ id: "ag",
37
+ githubUsername: "octo",
38
+ appId: 1,
39
+ apps,
40
+ repos: [],
41
+ };
42
+ const svc = new GithubSyncService({
43
+ agents: { get: async () => agent, setRepos: async () => {} },
44
+ access: async () => ({ status: "ok", access: ACCESS }),
45
+ installation: {
46
+ listInstalled: async (appId) => {
47
+ const orgs = installs[appId];
48
+ return orgs ? { status: "found", orgs } : { status: "none" };
49
+ },
50
+ addRepos: async (appId, org, repos) => {
51
+ calls.push(["add", appId, org, [...repos]]);
52
+ },
53
+ removeRepos: async (appId, org, repos) => {
54
+ calls.push(["remove", appId, org, [...repos]]);
55
+ },
56
+ },
57
+ audit: { write: async () => "audit-1" },
58
+ });
59
+ return { svc, calls };
60
+ }
61
+
62
+ const lists = (over: object) => ({
63
+ agentId: "ag",
64
+ caller: "root",
65
+ appAdds: [],
66
+ appRemoves: [],
67
+ agentRemoves: [],
68
+ ...over,
69
+ });
70
+
71
+ const MIXED: Install = {
72
+ 1: [{ org: "alpha", repos: ["alpha/a", "alpha/b"] }],
73
+ 2: [{ org: "beta", repos: ["beta/x", "beta/y"] }],
74
+ };
75
+
76
+ describe("GithubSyncService with several Apps", () => {
77
+ it("previews adds and removes for orgs on different Apps", async () => {
78
+ const r = await harness(MIXED).svc.preview("ag");
79
+ if (r.status !== "previewed") throw new Error(r.status);
80
+ expect(r.plan.appAdds).toEqual(["alpha/c", "beta/z"]);
81
+ expect(r.plan.appRemoves).toEqual(["alpha/b", "beta/y"]);
82
+ });
83
+
84
+ it("routes each org's changes through the App installed on it", async () => {
85
+ const { svc, calls } = harness(MIXED);
86
+ const r = await svc.apply(
87
+ lists({
88
+ appAdds: ["alpha/c", "beta/z"],
89
+ appRemoves: ["alpha/b", "beta/y"],
90
+ }),
91
+ );
92
+ expect(r.status).toBe("applied");
93
+ expect(calls).toEqual([
94
+ ["add", 1, "alpha", ["alpha/c"]],
95
+ ["add", 2, "beta", ["beta/z"]],
96
+ ["remove", 1, "alpha", ["alpha/b"]],
97
+ ["remove", 2, "beta", ["beta/y"]],
98
+ ]);
99
+ });
100
+
101
+ it("uses the lowest-priority App when two are installed on one org", async () => {
102
+ const { svc, calls } = harness({
103
+ 1: [{ org: "alpha", repos: ["alpha/a"] }],
104
+ 2: [{ org: "alpha", repos: ["alpha/a", "alpha/b"] }],
105
+ });
106
+ await svc.apply(lists({ appAdds: ["alpha/c"] }));
107
+ expect(calls).toEqual([["add", 1, "alpha", ["alpha/c"]]]);
108
+ });
109
+
110
+ it("reports an org with no installation instead of routing it", async () => {
111
+ const { svc, calls } = harness(MIXED);
112
+ const r = await svc.apply(lists({ appAdds: ["gamma/q"] }));
113
+ expect(r.status).toBe("noop");
114
+ if (r.status !== "noop") return;
115
+ expect(r.plan.notApplied).toEqual([
116
+ expect.objectContaining({ repo: "gamma/q" }),
117
+ ]);
118
+ expect(calls).toEqual([]);
119
+ });
120
+
121
+ it("still caps unconfirmed removals across Apps", async () => {
122
+ const many = (org: string) =>
123
+ Array.from({ length: 6 }, (_, i) => `${org}/r${i}`);
124
+ const access: UserRepoAccessResult = {
125
+ ...ACCESS,
126
+ orgs: [
127
+ orgAccess(
128
+ "alpha",
129
+ Object.fromEntries(many("alpha").map((r) => [r.slice(6), false])),
130
+ ),
131
+ orgAccess(
132
+ "beta",
133
+ Object.fromEntries(many("beta").map((r) => [r.slice(5), false])),
134
+ ),
135
+ ],
136
+ };
137
+ const { svc } = harness({
138
+ 1: [{ org: "alpha", repos: many("alpha") }],
139
+ 2: [{ org: "beta", repos: many("beta") }],
140
+ });
141
+ // Reuse the harness service with a different access answer.
142
+ const capped = new GithubSyncService({
143
+ ...(
144
+ svc as unknown as {
145
+ deps: ConstructorParameters<typeof GithubSyncService>[0];
146
+ }
147
+ ).deps,
148
+ access: async () => ({ status: "ok", access }),
149
+ });
150
+ const input = lists({ appRemoves: [...many("alpha"), ...many("beta")] });
151
+ expect((await capped.apply(input)).status).toBe("removal_cap");
152
+ expect(
153
+ (await capped.apply({ ...input, confirmRemovals: true })).status,
154
+ ).toBe("applied");
155
+ });
156
+ });