@app-vitals/agent-admin 1.35.1 → 1.36.1

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.
@@ -7,7 +7,7 @@ import {
7
7
  } from "./github-installation.fixtures.ts";
8
8
  import {
9
9
  createGithubInstallationRepos,
10
- createGithubLostAccessRemoval,
10
+ createGithubSync,
11
11
  } from "./github-installation-wiring.ts";
12
12
  import type { InstallationReposPort } from "./installation-repos-service.ts";
13
13
 
@@ -67,10 +67,10 @@ describe("createGithubInstallationRepos", () => {
67
67
  });
68
68
  });
69
69
 
70
- describe("createGithubLostAccessRemoval", () => {
70
+ describe("createGithubSync", () => {
71
71
  const build = (openWork?: ReturnType<typeof fakeOpenWork>["port"]) => {
72
72
  const { prisma, state } = fakePrisma(["acme/old", "acme/api"]);
73
- const svc = createGithubLostAccessRemoval({
73
+ const svc = createGithubSync({
74
74
  prisma,
75
75
  appService: noApp,
76
76
  access: accessFor(["acme/api"]),
@@ -81,15 +81,17 @@ describe("createGithubLostAccessRemoval", () => {
81
81
  return { svc, state };
82
82
  };
83
83
 
84
- it("with a port: preview lists affected open work and remove blocks it", async () => {
84
+ it("with a port: preview lists affected open work and apply blocks it", async () => {
85
85
  const { port, calls } = fakeOpenWork();
86
86
  const { svc, state } = build(port);
87
87
  const preview = await svc.preview("a1");
88
88
  expect(preview.status).toBe("previewed");
89
- const res = await svc.remove({
89
+ const res = await svc.apply({
90
90
  agentId: "a1",
91
91
  caller: "root",
92
- repos: ["acme/old"],
92
+ appAdds: [],
93
+ appRemoves: ["acme/old"],
94
+ agentRemoves: ["acme/old"],
93
95
  });
94
96
  expect(res.status).toBe("applied");
95
97
  expect(state.repos).toEqual(["acme/api"]);
@@ -98,12 +100,14 @@ describe("createGithubLostAccessRemoval", () => {
98
100
  expect(block?.args[1]).toEqual(["acme/old"]);
99
101
  });
100
102
 
101
- it("without a port: nothing is blocked, remove still works", async () => {
103
+ it("without a port: nothing is blocked, apply still works", async () => {
102
104
  const { svc, state } = build();
103
- const res = await svc.remove({
105
+ const res = await svc.apply({
104
106
  agentId: "a1",
105
107
  caller: "root",
106
- repos: ["acme/old"],
108
+ appAdds: [],
109
+ appRemoves: [],
110
+ agentRemoves: ["acme/old"],
107
111
  });
108
112
  expect(res.status).toBe("applied");
109
113
  expect(state.repos).toEqual(["acme/api"]);
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * admin/src/github-installation.fixtures.ts
3
- * Shared fakes for the installation repos / lost-access removal wiring tests.
3
+ * Shared fakes for the installation repos / GitHub Sync wiring tests.
4
4
  */
5
5
 
6
6
  import type { PrismaClient } from "../prisma/client/client.ts";
@@ -0,0 +1,414 @@
1
+ /**
2
+ * admin/src/github-sync.ts
3
+ * GitHub Sync (IRM-3.1): one preview and one apply, per agent with a bound
4
+ * GitHub username, that bring the agent App's installation and the agent's
5
+ * own repos in line with what the bound user can push to.
6
+ *
7
+ * Preview computes three lists plus the open work the removals would block:
8
+ * 1. APP adds: repos the user can push to, in orgs the agent App is
9
+ * installed on, that are not on the installation (no cap);
10
+ * 2. APP removes: installation repos the user can no longer push to;
11
+ * 3. AGENT removes: configured agent repos the user can no longer push to.
12
+ * The agent's repos are only ever removed from, never added to.
13
+ *
14
+ * Apply takes the exact lists the admin confirmed and re-checks each against
15
+ * the user's current access. The safety rules are the shared access rules
16
+ * (accessSkipReason / orgSkipReason): unknown is never none, so an org whose
17
+ * listing is missing, partial or failed, or whose lookup App is not installed
18
+ * or selected-only, is skipped and reported (adds included); an unbound,
19
+ * not-found or unverified user skips the whole call. More than
20
+ * MAX_UNCONFIRMED_REMOVALS removals need confirmRemovals.
21
+ *
22
+ * Order: installation adds, installation removals, agent-repo removals, one
23
+ * audit entry, then the agent's open work on the removed repos is blocked
24
+ * through the optional OpenWorkPort (a port failure is a warning).
25
+ */
26
+
27
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
28
+ import {
29
+ identityOf,
30
+ type InstallationReposPort,
31
+ } from "./installation-repos-service.ts";
32
+ import {
33
+ MAX_UNCONFIRMED_REMOVALS,
34
+ MISSING_APP_ID_REASON,
35
+ type InstallationAgentRecord,
36
+ type InstallationAgentsPort,
37
+ type InstallationAuditPort,
38
+ } from "./installation-ports.ts";
39
+ import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
40
+ import {
41
+ accessSkipReason,
42
+ type OrgSkip,
43
+ orgSkipReason,
44
+ repoOrg,
45
+ } from "./repo-access-rules.ts";
46
+ import {
47
+ blockRepoRemovalWork,
48
+ previewRepoRemovalWork,
49
+ repoLostAccessBlockReason,
50
+ } from "./repo-removal-open-work.ts";
51
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
52
+
53
+ /** `planHash` of the audit row a sync apply writes. */
54
+ export const GITHUB_SYNC_AUDIT_PLAN_HASH = "sync:apply";
55
+
56
+ export const STILL_PUSHABLE_REASON =
57
+ "the bound user can still push to this repo";
58
+ export const NOT_ADDABLE_REASON = "the bound user cannot push to this repo";
59
+ export const ALREADY_INSTALLED_REASON = "already on the agent installation";
60
+ export const NOT_INSTALLED_ORG_REASON =
61
+ "the agent App is not installed on this org";
62
+ export const NOT_PRESENT_REASON =
63
+ "not on the agent installation or in the agent's repos";
64
+
65
+ export interface SyncLists {
66
+ appAdds: readonly string[];
67
+ appRemoves: readonly string[];
68
+ agentRemoves: readonly string[];
69
+ }
70
+
71
+ export interface GithubSyncPlanInput {
72
+ username: string | null | undefined;
73
+ /** Null when the resolver was not run. */
74
+ access: UserRepoAccessResult | null;
75
+ agentRepos: readonly string[];
76
+ /** Repos the agent App's installation covers, per org login it is installed on. */
77
+ installationRepos: Readonly<Record<string, readonly string[]>>;
78
+ /**
79
+ * The lists the admin confirmed. When set, only these are candidates and
80
+ * every one left alone is reported in `notApplied`; when unset (preview),
81
+ * every eligible repo is a candidate.
82
+ */
83
+ requested?: SyncLists;
84
+ }
85
+
86
+ export interface NotAppliedRepo {
87
+ repo: string;
88
+ reason: string;
89
+ }
90
+
91
+ export interface GithubSyncPlan {
92
+ skipped: boolean;
93
+ skipReason?: string;
94
+ appAdds: string[];
95
+ appRemoves: string[];
96
+ agentRemoves: string[];
97
+ /** Every repo removed from either place, sorted. */
98
+ removedRepos: string[];
99
+ skippedOrgs: OrgSkip[];
100
+ notApplied: NotAppliedRepo[];
101
+ warnings: string[];
102
+ }
103
+
104
+ const lower = (s: string): string => s.toLowerCase();
105
+ const sorted = (xs: Iterable<string>): string[] => [...xs].sort();
106
+
107
+ function skippedPlan(reason: string): GithubSyncPlan {
108
+ return {
109
+ skipped: true,
110
+ skipReason: reason,
111
+ appAdds: [],
112
+ appRemoves: [],
113
+ agentRemoves: [],
114
+ removedRepos: [],
115
+ skippedOrgs: [],
116
+ notApplied: [],
117
+ warnings: [],
118
+ };
119
+ }
120
+
121
+ /** Pure: the installation adds and removes and agent-repo removes to sync. */
122
+ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
123
+ const skip = accessSkipReason(input.username, input.access);
124
+ if (skip) return skippedPlan(skip);
125
+ const access = input.access as UserRepoAccessResult;
126
+
127
+ const orgResults = new Map(access.orgs.map((o) => [lower(o.org), o]));
128
+ const pushable = new Map<string, string>();
129
+ for (const o of access.orgs) {
130
+ for (const r of o.repos)
131
+ if (r.canPush) pushable.set(lower(r.fullName), r.fullName);
132
+ }
133
+ // Keyed by lower-case name; values keep the stored spelling.
134
+ const installed = new Map<string, string>();
135
+ const installedOrgs = new Set<string>();
136
+ for (const [org, repos] of Object.entries(input.installationRepos)) {
137
+ installedOrgs.add(lower(org));
138
+ for (const r of repos) installed.set(lower(r), r);
139
+ }
140
+ const configured = new Map(input.agentRepos.map((r) => [lower(r), r]));
141
+
142
+ const requested = input.requested;
143
+ const addCandidates = requested
144
+ ? requested.appAdds
145
+ : [...pushable.values()].filter((r) =>
146
+ installedOrgs.has(lower(repoOrg(r))),
147
+ );
148
+ const appRemoveCandidates = requested
149
+ ? requested.appRemoves
150
+ : [...installed.values()];
151
+ const agentRemoveCandidates = requested
152
+ ? requested.agentRemoves
153
+ : [...configured.values()];
154
+
155
+ const skipReasons = new Map<string, string>();
156
+ const notApplied = new Map<string, NotAppliedRepo>();
157
+ const leave = (repo: string, reason: string) => {
158
+ if (requested)
159
+ notApplied.set(`${lower(repo)}\0${reason}`, { repo, reason });
160
+ };
161
+ // Unknown is never none: false (with the reason recorded) for a skipped org.
162
+ const orgUsable = (repo: string): boolean => {
163
+ const org = repoOrg(repo);
164
+ const reason = orgSkipReason(orgResults.get(lower(org)));
165
+ if (!reason) return true;
166
+ skipReasons.set(org, reason);
167
+ leave(repo, `skipped for org: ${reason}`);
168
+ return false;
169
+ };
170
+
171
+ const appAdds = new Set<string>();
172
+ for (const repo of new Set(addCandidates)) {
173
+ if (!orgUsable(repo)) continue;
174
+ if (!installedOrgs.has(lower(repoOrg(repo)))) {
175
+ leave(repo, NOT_INSTALLED_ORG_REASON);
176
+ continue;
177
+ }
178
+ const name = pushable.get(lower(repo));
179
+ if (!name) {
180
+ leave(repo, NOT_ADDABLE_REASON);
181
+ continue;
182
+ }
183
+ if (installed.has(lower(repo))) {
184
+ leave(repo, ALREADY_INSTALLED_REASON);
185
+ continue;
186
+ }
187
+ appAdds.add(name);
188
+ }
189
+ // Removal candidates must be present in the place they come out of and
190
+ // not pushable by the user.
191
+ const removable = (
192
+ repos: Iterable<string>,
193
+ present: Map<string, string>,
194
+ ): Set<string> => {
195
+ const out = new Set<string>();
196
+ for (const repo of new Set(repos)) {
197
+ if (!orgUsable(repo)) continue;
198
+ if (pushable.has(lower(repo))) {
199
+ leave(repo, STILL_PUSHABLE_REASON);
200
+ continue;
201
+ }
202
+ const stored = present.get(lower(repo));
203
+ if (!stored) {
204
+ leave(repo, NOT_PRESENT_REASON);
205
+ continue;
206
+ }
207
+ out.add(stored);
208
+ }
209
+ return out;
210
+ };
211
+ const appRemoves = removable(appRemoveCandidates, installed);
212
+ const agentRemoves = removable(agentRemoveCandidates, configured);
213
+
214
+ const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
215
+ org,
216
+ reason: skipReasons.get(org) as string,
217
+ }));
218
+ return {
219
+ skipped: false,
220
+ appAdds: sorted(appAdds),
221
+ appRemoves: sorted(appRemoves),
222
+ agentRemoves: sorted(agentRemoves),
223
+ removedRepos: sorted(new Set([...appRemoves, ...agentRemoves])),
224
+ skippedOrgs,
225
+ notApplied: [...notApplied.values()].sort((a, b) =>
226
+ a.repo.localeCompare(b.repo),
227
+ ),
228
+ warnings: skippedOrgs.map((s) => `${s.org}: skipped (${s.reason})`),
229
+ };
230
+ }
231
+
232
+ export interface GithubSyncDeps {
233
+ agents: InstallationAgentsPort;
234
+ access: GithubAccessPreviewFn;
235
+ installation: Pick<
236
+ InstallationReposPort,
237
+ "listInstalled" | "addRepos" | "removeRepos"
238
+ >;
239
+ audit: InstallationAuditPort;
240
+ /** Optional: with none, nothing is listed or blocked. */
241
+ openWork?: OpenWorkPort;
242
+ }
243
+
244
+ export type GithubSyncPreviewResult =
245
+ | { status: "agent_not_found" }
246
+ | { status: "skipped"; reason: string }
247
+ | {
248
+ status: "previewed";
249
+ plan: GithubSyncPlan;
250
+ openWork: OpenWorkItem[];
251
+ warnings: string[];
252
+ };
253
+
254
+ export interface GithubSyncApplyInput extends SyncLists {
255
+ agentId: string;
256
+ /** Who asked (audit trail). */
257
+ caller: string;
258
+ confirmRemovals?: boolean;
259
+ }
260
+
261
+ export type GithubSyncApplyResult =
262
+ | { status: "agent_not_found" }
263
+ | { status: "skipped"; reason: string }
264
+ | { status: "noop"; plan: GithubSyncPlan }
265
+ | { status: "removal_cap"; plan: GithubSyncPlan; removals: number }
266
+ | {
267
+ status: "applied";
268
+ plan: GithubSyncPlan;
269
+ auditId: string;
270
+ warnings: string[];
271
+ }
272
+ | { status: "failed"; plan: GithubSyncPlan; auditId: string; error: string };
273
+
274
+ function groupByOrg(repos: readonly string[]): Map<string, string[]> {
275
+ const byOrg = new Map<string, string[]>();
276
+ for (const r of repos) {
277
+ const org = repoOrg(r);
278
+ byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
279
+ }
280
+ return byOrg;
281
+ }
282
+
283
+ export class GithubSyncService {
284
+ constructor(private readonly deps: GithubSyncDeps) {}
285
+
286
+ /** Read-only: what would change and the open work the removals would block. */
287
+ async preview(agentId: string): Promise<GithubSyncPreviewResult> {
288
+ const agent = await this.deps.agents.get(agentId);
289
+ if (!agent) return { status: "agent_not_found" };
290
+ const plan = await this.planFor(agent);
291
+ if (plan.skipped) {
292
+ return { status: "skipped", reason: plan.skipReason ?? "skipped" };
293
+ }
294
+ const work = await previewRepoRemovalWork(
295
+ this.deps.openWork,
296
+ agentId,
297
+ plan.removedRepos,
298
+ );
299
+ return {
300
+ status: "previewed",
301
+ plan,
302
+ openWork: work.openWork,
303
+ warnings: [...plan.warnings, ...work.warnings],
304
+ };
305
+ }
306
+
307
+ async apply(input: GithubSyncApplyInput): Promise<GithubSyncApplyResult> {
308
+ const agent = await this.deps.agents.get(input.agentId);
309
+ if (!agent) return { status: "agent_not_found" };
310
+ const plan = await this.planFor(agent, input);
311
+ if (plan.skipped) {
312
+ return { status: "skipped", reason: plan.skipReason ?? "skipped" };
313
+ }
314
+ if (plan.appAdds.length + plan.removedRepos.length === 0) {
315
+ return { status: "noop", plan };
316
+ }
317
+ const removals = plan.removedRepos.length;
318
+ if (removals > MAX_UNCONFIRMED_REMOVALS && !input.confirmRemovals) {
319
+ return { status: "removal_cap", plan, removals };
320
+ }
321
+
322
+ const appId = agent.appId as number;
323
+ const identity = identityOf(agent);
324
+ const added: string[] = [];
325
+ const removed: string[] = [];
326
+ let configDone = false;
327
+ let error: string | undefined;
328
+ try {
329
+ for (const [org, repos] of groupByOrg(plan.appAdds)) {
330
+ await this.deps.installation.addRepos(appId, org, repos, identity);
331
+ added.push(...repos);
332
+ }
333
+ for (const [org, repos] of groupByOrg(plan.appRemoves)) {
334
+ await this.deps.installation.removeRepos(appId, org, repos, identity);
335
+ removed.push(...repos);
336
+ }
337
+ if (plan.agentRemoves.length > 0) {
338
+ const drop = new Set(plan.agentRemoves);
339
+ await this.deps.agents.setRepos(
340
+ agent.id,
341
+ agent.repos.filter((r) => !drop.has(r)),
342
+ );
343
+ }
344
+ configDone = true;
345
+ } catch (err) {
346
+ error = err instanceof Error ? err.message : String(err);
347
+ }
348
+ // Record what actually changed; on failure, only what landed.
349
+ const auditId = await this.deps.audit.write({
350
+ agentId: input.agentId,
351
+ caller: input.caller,
352
+ planHash: GITHUB_SYNC_AUDIT_PLAN_HASH,
353
+ diff: {
354
+ installationAdds: added,
355
+ installationRemoves: removed,
356
+ configAdds: [],
357
+ configRemoves: configDone ? plan.agentRemoves : [],
358
+ },
359
+ result:
360
+ error === undefined
361
+ ? { status: "applied" }
362
+ : { status: "failed", error },
363
+ });
364
+ if (error !== undefined) {
365
+ return { status: "failed", plan, auditId, error };
366
+ }
367
+ const warnings = await blockRepoRemovalWork(
368
+ this.deps.openWork,
369
+ input.agentId,
370
+ plan.removedRepos,
371
+ repoLostAccessBlockReason,
372
+ );
373
+ return { status: "applied", plan, auditId, warnings };
374
+ }
375
+
376
+ private async planFor(
377
+ agent: InstallationAgentRecord,
378
+ requested?: SyncLists,
379
+ ): Promise<GithubSyncPlan> {
380
+ const username = agent.githubUsername?.trim();
381
+ if (!username) {
382
+ return skippedPlan(accessSkipReason(username, null) as string);
383
+ }
384
+ const preview = await this.deps.access(username);
385
+ if (preview.status === "unconfigured") {
386
+ return skippedPlan("GitHub Apps are not configured");
387
+ }
388
+ // Whole-call skips need no installation calls.
389
+ const skip = accessSkipReason(username, preview.access);
390
+ if (skip) return skippedPlan(skip);
391
+ if (agent.appId === undefined) return skippedPlan(MISSING_APP_ID_REASON);
392
+ const installed = await this.deps.installation.listInstalled(
393
+ agent.appId,
394
+ identityOf(agent),
395
+ );
396
+ return planGithubSync({
397
+ username,
398
+ access: preview.access,
399
+ agentRepos: agent.repos,
400
+ installationRepos: Object.fromEntries(
401
+ installed.map(({ org, repos }) => [org, repos]),
402
+ ),
403
+ ...(requested
404
+ ? {
405
+ requested: {
406
+ appAdds: requested.appAdds,
407
+ appRemoves: requested.appRemoves,
408
+ agentRemoves: requested.agentRemoves,
409
+ },
410
+ }
411
+ : {}),
412
+ });
413
+ }
414
+ }