@app-vitals/agent-admin 1.35.0 → 1.36.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 (36) hide show
  1. package/openapi.platform.json +136 -766
  2. package/package.json +2 -2
  3. package/src/admin-boot.ts +4 -15
  4. package/src/admin-extension.ts +3 -3
  5. package/src/admin-ui-github-identity.smoke.test.ts +24 -116
  6. package/src/admin-ui-installation-repos-pages.ts +198 -231
  7. package/src/admin-ui-installation-repos-pages.unit.test.ts +199 -0
  8. package/src/admin-ui-installation-repos.smoke.test.ts +166 -173
  9. package/src/admin-ui-pages.ts +2 -2
  10. package/src/admin-ui.ts +103 -171
  11. package/src/agents-api.smoke.test.ts +195 -642
  12. package/src/agents-api.ts +86 -477
  13. package/src/github-enterprise-isolation.unit.test.ts +4 -4
  14. package/src/{github-reconcile-wiring.ts → github-installation-wiring.ts} +24 -46
  15. package/src/github-installation-wiring.unit.test.ts +115 -0
  16. package/src/github-installation.fixtures.ts +76 -0
  17. package/src/github-sync.ts +407 -0
  18. package/src/{lost-access-removal.unit.test.ts → github-sync.unit.test.ts} +220 -115
  19. package/src/installation-ports.integration.test.ts +89 -0
  20. package/src/installation-ports.ts +207 -0
  21. package/src/installation-ports.unit.test.ts +51 -0
  22. package/src/installation-repos-service.ts +10 -105
  23. package/src/installation-repos-service.unit.test.ts +5 -90
  24. package/src/reconcile-open-work.ts +5 -7
  25. package/src/repo-access-rules.ts +58 -0
  26. package/src/repo-access-rules.unit.test.ts +98 -0
  27. package/src/admin-ui-github-reconcile-pages.ts +0 -208
  28. package/src/admin-ui-github-reconcile-pages.unit.test.ts +0 -226
  29. package/src/github-reconcile-routes.integration.test.ts +0 -206
  30. package/src/github-reconcile-wiring.unit.test.ts +0 -170
  31. package/src/lost-access-removal.ts +0 -333
  32. package/src/reconcile-apply-service.integration.test.ts +0 -271
  33. package/src/reconcile-apply-service.ts +0 -439
  34. package/src/reconcile-apply-service.unit.test.ts +0 -279
  35. package/src/reconcile-planner.ts +0 -264
  36. package/src/reconcile-planner.unit.test.ts +0 -274
@@ -1,206 +0,0 @@
1
- /**
2
- * admin/src/github-reconcile-routes.integration.test.ts
3
- * POST /agents/:id/github-reconcile/{plan,apply} (GHE-3.4) against a real DB:
4
- * stale plan hash -> 409, removal cap -> 422, then a confirmed apply. GitHub is
5
- * faked.
6
- *
7
- * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
- */
9
-
10
- import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
- import type { PrismaClient } from "../prisma/client/client.ts";
12
- import { AgentChatTokenService } from "./agent-chat-tokens.ts";
13
- import { AgentCronJobService } from "./agent-cron-jobs.ts";
14
- import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
15
- import { AgentCronRunService } from "./agent-cron-runs.ts";
16
- import { AgentEnvService } from "./agent-envs.ts";
17
- import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
18
- import { AgentMemberService } from "./agent-members.ts";
19
- import { AgentPluginService } from "./agent-plugins.ts";
20
- import { NoopAgentProvisioner } from "./agent-provisioner.ts";
21
- import { AgentTokenService } from "./agent-tokens.ts";
22
- import { AgentToolService } from "./agent-tools.ts";
23
- import { AgentService } from "./agents.ts";
24
- import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
25
- import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
26
- import { createAdminPrismaClient } from "./prisma-client.ts";
27
- import {
28
- MAX_UNCONFIRMED_REMOVALS,
29
- PrismaReconcileAgents,
30
- PrismaReconcileAudit,
31
- ReconcileApplyService,
32
- } from "./reconcile-apply-service.ts";
33
- import { identityCrypto } from "./token-crypto.ts";
34
-
35
- const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
36
- const describeOrSkip = TEST_DB ? describe : describe.skip;
37
- const KEY = "reconcile-admin-key";
38
-
39
- describeOrSkip("github reconcile routes (integration)", () => {
40
- let prisma: PrismaClient;
41
- let pushable: string[];
42
- let installed: string[];
43
- let envService: AgentEnvService;
44
-
45
- const buildApp = () => {
46
- const reconcile = new ReconcileApplyService({
47
- agents: new PrismaReconcileAgents(prisma, envService),
48
- access: async () => ({
49
- status: "ok",
50
- access: {
51
- username: "dev",
52
- outcome: "ok",
53
- userVerified: true,
54
- complete: true,
55
- unresolved: 0,
56
- checkedAt: "2026-11-11T00:00:00.000Z",
57
- orgs: [
58
- {
59
- org: "acme",
60
- status: "ok",
61
- unresolved: 0,
62
- repos: pushable.map((fullName) => ({
63
- fullName,
64
- level: "write" as const,
65
- canPush: true,
66
- })),
67
- },
68
- ],
69
- },
70
- }),
71
- installation: {
72
- listRepos: async () => ({ acme: [...installed] }),
73
- addRepos: async () => {},
74
- removeRepos: async () => {},
75
- },
76
- audit: new PrismaReconcileAudit(prisma),
77
- });
78
- return createAdminApp({
79
- agentService: new AgentService(prisma),
80
- agentEnvService: envService,
81
- agentCronJobService: new AgentCronJobService(prisma),
82
- agentCronRunService: new AgentCronRunService(prisma),
83
- agentCronRunStatsService: new AgentCronRunStatsService(prisma),
84
- agentToolService: new AgentToolService(prisma),
85
- agentTokenService: new AgentTokenService(prisma),
86
- agentPluginService: new AgentPluginService(prisma),
87
- agentMemberService: new AgentMemberService(prisma),
88
- specialtyRegistry: {
89
- getType: () => {
90
- throw new Error("unused");
91
- },
92
- tryGetType: () => undefined,
93
- listTypes: () => [],
94
- },
95
- agentChatTokenService: new AgentChatTokenService(prisma),
96
- agentGitHubInstallationsService: new AgentGitHubInstallationsService(
97
- prisma,
98
- ),
99
- prisma,
100
- provisioner: new NoopAgentProvisioner(),
101
- serviceIntegrations: [],
102
- chatService: new NoopChatServiceProvisioningClient(),
103
- slack: { deleteApp: async () => {} },
104
- decrypt: (v: string) => v,
105
- sessionSecret: "test-admin-session-secret-32-bytes!",
106
- adminApiKeys: parseAdminApiKeys(`root:${KEY}:*`),
107
- githubReconcile: reconcile,
108
- });
109
- };
110
-
111
- const call = (
112
- app: ReturnType<typeof createAdminApp>,
113
- id: string,
114
- action: "plan" | "apply",
115
- body: unknown,
116
- ) =>
117
- app.request(`/agents/${id}/github-reconcile/${action}`, {
118
- method: "POST",
119
- headers: {
120
- Authorization: `Bearer ${KEY}`,
121
- "Content-Type": "application/json",
122
- },
123
- body: JSON.stringify(body),
124
- });
125
-
126
- beforeEach(async () => {
127
- prisma = createAdminPrismaClient(TEST_DB as string);
128
- envService = new AgentEnvService(prisma, identityCrypto);
129
- await prisma.gitHubReconcileAudit.deleteMany();
130
- await prisma.agentGitHubInstallationsSnapshot.deleteMany();
131
- await prisma.agentWorkQueueSnapshot.deleteMany();
132
- await prisma.agentChatTokenUsageDailyByModel.deleteMany();
133
- await prisma.agentCronRun.deleteMany();
134
- await prisma.agentToken.deleteMany();
135
- await prisma.agentCronJob.deleteMany();
136
- await prisma.agentTool.deleteMany();
137
- await prisma.agentEnv.deleteMany();
138
- await prisma.agentMember.deleteMany();
139
- await prisma.agent.deleteMany();
140
- pushable = [];
141
- installed = [];
142
- });
143
-
144
- afterEach(async () => {
145
- await prisma.$disconnect();
146
- });
147
-
148
- it("409 when the hash is stale, and nothing is written", async () => {
149
- const agent = await prisma.agent.create({
150
- data: { name: "A", repos: ["acme/a", "acme/b"], githubUsername: "dev" },
151
- });
152
- await envService.patch(agent.id, { GH_APP_ID: "42" });
153
- installed = ["acme/a", "acme/b"];
154
- pushable = ["acme/a"];
155
- const app = buildApp();
156
- const plan = (await (await call(app, agent.id, "plan", {})).json()) as {
157
- planHash: string;
158
- };
159
- pushable = []; // access changed after the plan was reviewed
160
- const res = await call(app, agent.id, "apply", {
161
- planHash: plan.planHash,
162
- });
163
- expect(res.status).toBe(409);
164
- expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
165
- const after = await prisma.agent.findUniqueOrThrow({
166
- where: { id: agent.id },
167
- });
168
- expect(after.repos).toEqual(["acme/a", "acme/b"]);
169
- });
170
-
171
- it("422 over the removal cap, then applies with confirmRemovals", async () => {
172
- const repos = Array.from(
173
- { length: MAX_UNCONFIRMED_REMOVALS + 1 },
174
- (_, i) => `acme/r${i}`,
175
- );
176
- const agent = await prisma.agent.create({
177
- data: { name: "A", repos, githubUsername: "dev" },
178
- });
179
- await envService.patch(agent.id, { GH_APP_ID: "42" });
180
- installed = [...repos];
181
- pushable = ["acme/keep"];
182
- const app = buildApp();
183
- const plan = (await (await call(app, agent.id, "plan", {})).json()) as {
184
- planHash: string;
185
- diff: { configRemoves: string[] };
186
- };
187
- expect(plan.diff.configRemoves).toHaveLength(repos.length);
188
- const capped = await call(app, agent.id, "apply", {
189
- planHash: plan.planHash,
190
- });
191
- expect(capped.status).toBe(422);
192
- expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
193
-
194
- const ok = await call(app, agent.id, "apply", {
195
- planHash: plan.planHash,
196
- confirmRemovals: true,
197
- });
198
- expect(ok.status).toBe(200);
199
- const body = (await ok.json()) as { status: string; auditId: string };
200
- expect(body.status).toBe("applied");
201
- const audit = await prisma.gitHubReconcileAudit.findUniqueOrThrow({
202
- where: { id: body.auditId },
203
- });
204
- expect(audit.agentId).toBe(agent.id);
205
- });
206
- });
@@ -1,170 +0,0 @@
1
- import { describe, expect, it } from "bun:test";
2
- import type { PrismaClient } from "../prisma/client/client.ts";
3
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
4
- import { createGithubReconcile } from "./github-reconcile-wiring.ts";
5
- import type { ReconcileInstallationPort } from "./reconcile-apply-service.ts";
6
- import type { OpenWorkPort } from "./reconcile-open-work.ts";
7
-
8
- export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
9
- return async () => ({
10
- status: "ok",
11
- access: {
12
- username: "dev",
13
- outcome: "ok",
14
- userVerified: true,
15
- complete: true,
16
- unresolved: 0,
17
- checkedAt: "2026-11-11T00:00:00.000Z",
18
- orgs: [
19
- {
20
- org: "acme",
21
- status: "ok",
22
- unresolved: 0,
23
- repos: pushable.map((fullName) => ({
24
- fullName,
25
- level: "write" as const,
26
- canPush: true,
27
- })),
28
- },
29
- ],
30
- },
31
- });
32
- };
33
-
34
- export function fakePrisma(repos: string[]) {
35
- const state = { repos: [...repos], audits: 0 };
36
- const prisma = {
37
- agent: {
38
- findUnique: async () => ({
39
- id: "a1",
40
- repos: state.repos,
41
- githubUsername: "dev",
42
- }),
43
- update: async (args: { data: { repos: string[] } }) => {
44
- state.repos = args.data.repos;
45
- },
46
- },
47
- gitHubReconcileAudit: {
48
- create: async () => {
49
- state.audits += 1;
50
- return { id: "audit-1" };
51
- },
52
- },
53
- } as unknown as PrismaClient;
54
- return { prisma, state };
55
- }
56
-
57
- export function fakeOpenWork() {
58
- const calls: { fn: string; args: unknown[] }[] = [];
59
- const port: OpenWorkPort = {
60
- listOpenWork: async (...args) => {
61
- calls.push({ fn: "list", args });
62
- return [{ id: "T-1", repo: "acme/old", title: "fix it" }];
63
- },
64
- blockOpenWork: async (...args) => {
65
- calls.push({ fn: "block", args });
66
- },
67
- };
68
- return { port, calls };
69
- }
70
-
71
- export const envWith = (env?: Record<string, string>) => ({
72
- getConfigBundle: async (agentId: string) =>
73
- env ? { env, agentId, allowedTools: [] } : null,
74
- });
75
-
76
- const installation: ReconcileInstallationPort = {
77
- listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
78
- addRepos: async () => {},
79
- removeRepos: async () => {},
80
- };
81
-
82
- const build = (openWork?: OpenWorkPort) => {
83
- const { prisma, state } = fakePrisma(["acme/old"]);
84
- const svc = createGithubReconcile({
85
- prisma,
86
- appService: { get: async () => null, getPrivateKey: async () => null },
87
- access: accessFor(["acme/api"]),
88
- agentEnv: envWith({ GH_APP_ID: "42" }),
89
- installation,
90
- openWork,
91
- });
92
- if (!svc) throw new Error("expected a reconcile service");
93
- return { svc, state };
94
- };
95
-
96
- describe("createGithubReconcile", () => {
97
- it("plans from the agent's own stored GH_APP_ID", async () => {
98
- const seen: number[] = [];
99
- const { prisma } = fakePrisma(["acme/old"]);
100
- const svc = createGithubReconcile({
101
- prisma,
102
- appService: { get: async () => null, getPrivateKey: async () => null },
103
- access: accessFor(["acme/api"]),
104
- agentEnv: envWith({ GH_APP_ID: " 77 " }),
105
- installation: {
106
- ...installation,
107
- listRepos: async (appId) => {
108
- seen.push(appId);
109
- return { acme: ["acme/old", "acme/api"] };
110
- },
111
- },
112
- });
113
- const plan = await svc.plan("a1");
114
- expect(seen).toEqual([77]);
115
- expect(plan.skipped).toBe(false);
116
- });
117
-
118
- it("skips an agent with no GH_APP_ID, naming the missing var", async () => {
119
- const { prisma } = fakePrisma(["acme/old"]);
120
- const envs: (Record<string, string> | undefined)[] = [
121
- undefined,
122
- { OTHER: "x" },
123
- { GH_APP_ID: "abc" },
124
- ];
125
- for (const env of envs) {
126
- const svc = createGithubReconcile({
127
- prisma,
128
- appService: { get: async () => null, getPrivateKey: async () => null },
129
- access: accessFor([]),
130
- agentEnv: envWith(env),
131
- installation,
132
- });
133
- const plan = await svc.plan("a1");
134
- expect(plan.skipped).toBe(true);
135
- expect(plan.skipReason).toContain("GH_APP_ID");
136
- }
137
- });
138
-
139
- it("with a port: plan lists affected open work and apply blocks it", async () => {
140
- const { port, calls } = fakeOpenWork();
141
- const { svc } = build(port);
142
- const { plan, openWork } = await svc.planWithOpenWork("a1");
143
- expect(plan.diff.configRemoves).toEqual(["acme/old"]);
144
- expect(openWork).toEqual([
145
- { id: "T-1", repo: "acme/old", title: "fix it" },
146
- ]);
147
- const res = await svc.apply({
148
- agentId: "a1",
149
- caller: "root",
150
- planHash: plan.planHash,
151
- });
152
- expect(res.status).toBe("applied");
153
- const block = calls.find((c) => c.fn === "block");
154
- expect(block?.args[0]).toBe("a1");
155
- expect(block?.args[1]).toEqual(["acme/old"]);
156
- });
157
-
158
- it("without a port: nothing is listed or blocked, apply still works", async () => {
159
- const { svc, state } = build();
160
- const { plan, openWork } = await svc.planWithOpenWork("a1");
161
- expect(openWork).toEqual([]);
162
- const res = await svc.apply({
163
- agentId: "a1",
164
- caller: "root",
165
- planHash: plan.planHash,
166
- });
167
- expect(res.status).toBe("applied");
168
- expect(state.repos).toEqual([]);
169
- });
170
- });
@@ -1,333 +0,0 @@
1
- /**
2
- * admin/src/lost-access-removal.ts
3
- * Lost-access removal (IRM-1.3): removes, from both the agent App's
4
- * installation and the agent's own repos, every repo the agent's bound GitHub
5
- * user can no longer push to. It never adds repos.
6
- *
7
- * The admin reviews a read-only preview, then sends the exact repos they
8
- * confirmed; the server re-checks each against the user's current access and
9
- * removes only those still without it (no plan hash). The safety rules are the
10
- * reconcile planner's (accessSkipReason / orgSkipReason): unknown is never
11
- * none, so orgs with a missing, partial or failed listing, or a selected-only
12
- * lookup install, are skipped and reported; an unbound, not-found or
13
- * unverified user skips the whole call. More than MAX_UNCONFIRMED_REMOVALS
14
- * removals need confirmRemovals.
15
- *
16
- * Order: installation removals, then the agent's repos, then one audit entry,
17
- * then the agent's open work on the removed repos is blocked through the
18
- * optional OpenWorkPort (a port failure is a warning, never a failed call).
19
- */
20
-
21
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
22
- import type { InstallationReposPort } from "./installation-repos-service.ts";
23
- import {
24
- MAX_UNCONFIRMED_REMOVALS,
25
- MISSING_APP_ID_REASON,
26
- type ReconcileAgentRecord,
27
- type ReconcileAgentsPort,
28
- type ReconcileAuditPort,
29
- } from "./reconcile-apply-service.ts";
30
- import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
31
- import {
32
- accessSkipReason,
33
- type OrgSkip,
34
- orgSkipReason,
35
- repoOrg,
36
- } from "./reconcile-planner.ts";
37
- import {
38
- blockRepoRemovalWork,
39
- previewRepoRemovalWork,
40
- repoLostAccessBlockReason,
41
- } from "./repo-removal-open-work.ts";
42
- import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
43
-
44
- /** `planHash` of the audit row a lost-access removal writes. */
45
- export const LOST_ACCESS_AUDIT_PLAN_HASH = "lost-access:remove";
46
-
47
- export const STILL_PUSHABLE_REASON =
48
- "the bound user can still push to this repo";
49
- export const NOT_PRESENT_REASON =
50
- "not on the agent installation or in the agent's repos";
51
-
52
- export interface LostAccessPlanInput {
53
- username: string | null | undefined;
54
- /** Null when the resolver was not run. */
55
- access: UserRepoAccessResult | null;
56
- agentRepos: readonly string[];
57
- /** Repos the agent App's installation covers, per org login. */
58
- installationRepos: Readonly<Record<string, readonly string[]>>;
59
- /**
60
- * The repos the admin confirmed. When set, only these are candidates and
61
- * every one left alone is reported in `notRemoved`; when unset (preview),
62
- * every installation and agent repo is a candidate.
63
- */
64
- requested?: readonly string[];
65
- }
66
-
67
- export interface NotRemovedRepo {
68
- repo: string;
69
- reason: string;
70
- }
71
-
72
- export interface LostAccessPlan {
73
- skipped: boolean;
74
- skipReason?: string;
75
- /** Every repo removed from either place, sorted. */
76
- repos: string[];
77
- installationRemoves: string[];
78
- configRemoves: string[];
79
- skippedOrgs: OrgSkip[];
80
- notRemoved: NotRemovedRepo[];
81
- warnings: string[];
82
- }
83
-
84
- const lower = (s: string): string => s.toLowerCase();
85
- const sorted = (xs: Iterable<string>): string[] => [...xs].sort();
86
-
87
- function skippedPlan(reason: string): LostAccessPlan {
88
- return {
89
- skipped: true,
90
- skipReason: reason,
91
- repos: [],
92
- installationRemoves: [],
93
- configRemoves: [],
94
- skippedOrgs: [],
95
- notRemoved: [],
96
- warnings: [],
97
- };
98
- }
99
-
100
- /** Pure: the repos to remove because the bound user lost push access. */
101
- export function planLostAccessRemoval(
102
- input: LostAccessPlanInput,
103
- ): LostAccessPlan {
104
- const skip = accessSkipReason(input.username, input.access);
105
- if (skip) return skippedPlan(skip);
106
- const access = input.access as UserRepoAccessResult;
107
-
108
- const orgResults = new Map(access.orgs.map((o) => [lower(o.org), o]));
109
- const pushable = new Set<string>();
110
- for (const o of access.orgs) {
111
- for (const r of o.repos) if (r.canPush) pushable.add(lower(r.fullName));
112
- }
113
- // Keyed by lower-case name; values keep the stored spelling.
114
- const installed = new Map<string, string>();
115
- for (const repos of Object.values(input.installationRepos)) {
116
- for (const r of repos) installed.set(lower(r), r);
117
- }
118
- const configured = new Map(input.agentRepos.map((r) => [lower(r), r]));
119
-
120
- const candidates = input.requested
121
- ? sorted(new Set(input.requested))
122
- : sorted(new Set([...configured.values(), ...installed.values()]));
123
-
124
- const skipReasons = new Map<string, string>();
125
- const notRemoved: NotRemovedRepo[] = [];
126
- const leave = (repo: string, reason: string) => {
127
- if (input.requested) notRemoved.push({ repo, reason });
128
- };
129
- const installationRemoves = new Set<string>();
130
- const configRemoves = new Set<string>();
131
- for (const repo of candidates) {
132
- const org = repoOrg(repo);
133
- const orgSkip = orgSkipReason(orgResults.get(lower(org)));
134
- if (orgSkip) {
135
- // Unknown is never none.
136
- skipReasons.set(org, orgSkip);
137
- leave(repo, `removals skipped for org: ${orgSkip}`);
138
- continue;
139
- }
140
- if (pushable.has(lower(repo))) {
141
- leave(repo, STILL_PUSHABLE_REASON);
142
- continue;
143
- }
144
- const inInstallation = installed.get(lower(repo));
145
- const inConfig = configured.get(lower(repo));
146
- if (!inInstallation && !inConfig) {
147
- leave(repo, NOT_PRESENT_REASON);
148
- continue;
149
- }
150
- if (inInstallation) installationRemoves.add(inInstallation);
151
- if (inConfig) configRemoves.add(inConfig);
152
- }
153
-
154
- const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
155
- org,
156
- reason: skipReasons.get(org) as string,
157
- }));
158
- return {
159
- skipped: false,
160
- repos: sorted(new Set([...installationRemoves, ...configRemoves])),
161
- installationRemoves: sorted(installationRemoves),
162
- configRemoves: sorted(configRemoves),
163
- skippedOrgs,
164
- notRemoved,
165
- warnings: skippedOrgs.map(
166
- (s) => `${s.org}: removals skipped (${s.reason})`,
167
- ),
168
- };
169
- }
170
-
171
- export interface LostAccessRemovalDeps {
172
- agents: ReconcileAgentsPort;
173
- access: GithubAccessPreviewFn;
174
- installation: Pick<InstallationReposPort, "listInstalled" | "removeRepos">;
175
- audit: ReconcileAuditPort;
176
- /** Optional: with none, nothing is listed or blocked. */
177
- openWork?: OpenWorkPort;
178
- }
179
-
180
- export type LostAccessPreviewResult =
181
- | { status: "agent_not_found" }
182
- | { status: "skipped"; reason: string }
183
- | {
184
- status: "previewed";
185
- plan: LostAccessPlan;
186
- openWork: OpenWorkItem[];
187
- warnings: string[];
188
- };
189
-
190
- export interface LostAccessRemoveInput {
191
- agentId: string;
192
- /** Who asked (audit trail). */
193
- caller: string;
194
- /** The repos the admin confirmed from the preview. */
195
- repos: readonly string[];
196
- confirmRemovals?: boolean;
197
- }
198
-
199
- export type LostAccessRemoveResult =
200
- | { status: "agent_not_found" }
201
- | { status: "skipped"; reason: string }
202
- | { status: "noop"; plan: LostAccessPlan }
203
- | { status: "removal_cap"; plan: LostAccessPlan; removals: number }
204
- | {
205
- status: "applied";
206
- plan: LostAccessPlan;
207
- auditId: string;
208
- warnings: string[];
209
- }
210
- | { status: "failed"; plan: LostAccessPlan; auditId: string; error: string };
211
-
212
- function groupByOrg(repos: readonly string[]): Map<string, string[]> {
213
- const byOrg = new Map<string, string[]>();
214
- for (const r of repos) {
215
- const org = repoOrg(r);
216
- byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
217
- }
218
- return byOrg;
219
- }
220
-
221
- export class LostAccessRemovalService {
222
- constructor(private readonly deps: LostAccessRemovalDeps) {}
223
-
224
- /** Read-only: what would be removed and the open work it would block. */
225
- async preview(agentId: string): Promise<LostAccessPreviewResult> {
226
- const agent = await this.deps.agents.get(agentId);
227
- if (!agent) return { status: "agent_not_found" };
228
- const plan = await this.planFor(agent);
229
- if (plan.skipped) {
230
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
231
- }
232
- const work = await previewRepoRemovalWork(
233
- this.deps.openWork,
234
- agentId,
235
- plan.repos,
236
- );
237
- return {
238
- status: "previewed",
239
- plan,
240
- openWork: work.openWork,
241
- warnings: [...plan.warnings, ...work.warnings],
242
- };
243
- }
244
-
245
- async remove(input: LostAccessRemoveInput): Promise<LostAccessRemoveResult> {
246
- const agent = await this.deps.agents.get(input.agentId);
247
- if (!agent) return { status: "agent_not_found" };
248
- const plan = await this.planFor(agent, input.repos);
249
- if (plan.skipped) {
250
- return { status: "skipped", reason: plan.skipReason ?? "skipped" };
251
- }
252
- if (plan.repos.length === 0) return { status: "noop", plan };
253
- const removals = plan.repos.length;
254
- if (removals > MAX_UNCONFIRMED_REMOVALS && !input.confirmRemovals) {
255
- return { status: "removal_cap", plan, removals };
256
- }
257
-
258
- const appId = agent.appId as number;
259
- const removedFromInstallation: string[] = [];
260
- let configDone = false;
261
- let error: string | undefined;
262
- try {
263
- for (const [org, repos] of groupByOrg(plan.installationRemoves)) {
264
- await this.deps.installation.removeRepos(appId, org, repos);
265
- removedFromInstallation.push(...repos);
266
- }
267
- if (plan.configRemoves.length > 0) {
268
- const drop = new Set(plan.configRemoves);
269
- await this.deps.agents.setRepos(
270
- agent.id,
271
- agent.repos.filter((r) => !drop.has(r)),
272
- );
273
- }
274
- configDone = true;
275
- } catch (err) {
276
- error = err instanceof Error ? err.message : String(err);
277
- }
278
- // Record what actually changed; on failure, only what landed.
279
- const auditId = await this.deps.audit.write({
280
- agentId: input.agentId,
281
- caller: input.caller,
282
- planHash: LOST_ACCESS_AUDIT_PLAN_HASH,
283
- diff: {
284
- installationAdds: [],
285
- installationRemoves: removedFromInstallation,
286
- configAdds: [],
287
- configRemoves: configDone ? plan.configRemoves : [],
288
- },
289
- result:
290
- error === undefined
291
- ? { status: "applied" }
292
- : { status: "failed", error },
293
- });
294
- if (error !== undefined) {
295
- return { status: "failed", plan, auditId, error };
296
- }
297
- const warnings = await blockRepoRemovalWork(
298
- this.deps.openWork,
299
- input.agentId,
300
- plan.repos,
301
- repoLostAccessBlockReason,
302
- );
303
- return { status: "applied", plan, auditId, warnings };
304
- }
305
-
306
- private async planFor(
307
- agent: ReconcileAgentRecord,
308
- requested?: readonly string[],
309
- ): Promise<LostAccessPlan> {
310
- const username = agent.githubUsername?.trim();
311
- if (!username) {
312
- return skippedPlan(accessSkipReason(username, null) as string);
313
- }
314
- const preview = await this.deps.access(username);
315
- if (preview.status === "unconfigured") {
316
- return skippedPlan("GitHub Apps are not configured");
317
- }
318
- // Whole-call skips need no installation calls.
319
- const skip = accessSkipReason(username, preview.access);
320
- if (skip) return skippedPlan(skip);
321
- if (agent.appId === undefined) return skippedPlan(MISSING_APP_ID_REASON);
322
- const installed = await this.deps.installation.listInstalled(agent.appId);
323
- return planLostAccessRemoval({
324
- username,
325
- access: preview.access,
326
- agentRepos: agent.repos,
327
- installationRepos: Object.fromEntries(
328
- installed.map(({ org, repos }) => [org, repos]),
329
- ),
330
- ...(requested ? { requested } : {}),
331
- });
332
- }
333
- }