@app-vitals/agent-admin 1.33.0 → 1.35.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.
package/src/agents-api.ts CHANGED
@@ -166,6 +166,7 @@ import {
166
166
  UpsertChatTokenDailyBodySchema,
167
167
  } from "./openapi-schemas.ts";
168
168
  import type { InstallationReposService } from "./installation-repos-service.ts";
169
+ import type { LostAccessRemovalService } from "./lost-access-removal.ts";
169
170
  import type { ReconcileApplyService } from "./reconcile-apply-service.ts";
170
171
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
171
172
  import {
@@ -291,6 +292,15 @@ export interface AdminDeps {
291
292
  InstallationReposService,
292
293
  "list" | "add" | "remove"
293
294
  >;
295
+ /**
296
+ * IRM-1.3: backs the admin-only /agents/:id/github-lost-access/{preview,remove}
297
+ * routes. Optional (additive); absent means the enterprise Apps are not
298
+ * wired and the routes answer 503.
299
+ */
300
+ githubLostAccessRemoval?: Pick<
301
+ LostAccessRemovalService,
302
+ "preview" | "remove"
303
+ >;
294
304
  /**
295
305
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
296
306
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -739,6 +749,73 @@ const GithubInstallationReposChangeSchema = z
739
749
  })
740
750
  .openapi("GithubInstallationReposChange");
741
751
 
752
+ const OpenWorkItemSchema = z.object({
753
+ id: z.string(),
754
+ repo: z.string(),
755
+ title: z.string().optional(),
756
+ });
757
+
758
+ const SkippedOrgsSchema = z.array(
759
+ z.object({ org: z.string(), reason: z.string() }),
760
+ );
761
+
762
+ const GithubLostAccessPreviewSchema = z
763
+ .object({
764
+ status: z.enum(["previewed", "skipped"]).openapi({
765
+ description:
766
+ "`skipped` (not an error) when no GitHub username is bound, the user is not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured; `reason` says why.",
767
+ }),
768
+ reason: z.string().optional(),
769
+ repos: z.array(z.string()).optional().openapi({
770
+ description:
771
+ "Every repo the bound user can no longer push to that would be removed from the installation or the agent's repos.",
772
+ }),
773
+ installationRemoves: z.array(z.string()).optional(),
774
+ configRemoves: z.array(z.string()).optional(),
775
+ skippedOrgs: SkippedOrgsSchema.optional().openapi({
776
+ description:
777
+ "Orgs whose access listing is missing, partial or failed, or whose lookup App is installed on selected repositories only; nothing there is removed.",
778
+ }),
779
+ openWork: z.array(OpenWorkItemSchema).optional().openapi({
780
+ description:
781
+ "The agent's open tasks and PRs on those repos that removing them would block; empty when no open-work port is wired.",
782
+ }),
783
+ warnings: z.array(z.string()).optional(),
784
+ })
785
+ .openapi("GithubLostAccessPreview");
786
+
787
+ const GithubLostAccessRemoveBodySchema = z
788
+ .object({
789
+ repos: z.array(RepoFullNameSchema).min(1).max(100).openapi({
790
+ description:
791
+ "The repos (owner/repo) the admin confirmed from the preview. Each is re-checked; only those the user still cannot push to are removed.",
792
+ }),
793
+ confirmRemovals: z.boolean().optional().openapi({
794
+ description: "Required when more than 10 repos would be removed.",
795
+ }),
796
+ })
797
+ .openapi("GithubLostAccessRemoveBody");
798
+
799
+ const GithubLostAccessRemoveResultSchema = z
800
+ .object({
801
+ status: z.enum(["applied", "noop", "skipped"]),
802
+ reason: z.string().optional(),
803
+ auditId: z.string().optional(),
804
+ repos: z.array(z.string()).optional(),
805
+ installationRemoves: z.array(z.string()).optional(),
806
+ configRemoves: z.array(z.string()).optional(),
807
+ notRemoved: z
808
+ .array(z.object({ repo: z.string(), reason: z.string() }))
809
+ .optional()
810
+ .openapi({
811
+ description:
812
+ "Named repos left alone: the user can still push, the org was skipped, or the repo is on neither the installation nor the agent.",
813
+ }),
814
+ skippedOrgs: SkippedOrgsSchema.optional(),
815
+ warnings: z.array(z.string()).optional(),
816
+ })
817
+ .openapi("GithubLostAccessRemoveResult");
818
+
742
819
  // ─── Route definitions ──────────────────────────────────────────────────────────
743
820
 
744
821
  const reconcileAgentsRoute = createRoute({
@@ -1803,6 +1880,59 @@ const removeInstallationReposRoute = createRoute({
1803
1880
  },
1804
1881
  });
1805
1882
 
1883
+ const lostAccessErrors = {
1884
+ 401: { description: "Unauthorized", ...jsonError },
1885
+ 403: { description: "Platform admin required", ...jsonError },
1886
+ 404: { description: "Agent not found", ...jsonError },
1887
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1888
+ 503: { description: "GitHub Apps are not configured", ...jsonError },
1889
+ };
1890
+
1891
+ const githubLostAccessPreviewRoute = createRoute({
1892
+ method: "get",
1893
+ path: "/agents/{id}/github-lost-access/preview",
1894
+ summary: "Preview removing the repos the bound user can no longer push to",
1895
+ description:
1896
+ "Platform-admin only (session members, ops keys and agent keys get 403). Read-only: nothing is changed or audited. Lists the repos on the agent App's installation or in the agent's repos that the bound githubUsername can no longer push to, and the agent's open tasks and PRs on them (via the optional open-work port; a port failure is a warning). Orgs whose access listing is missing, partial or failed, or whose lookup App is installed on selected repositories only, are skipped and reported. 200 with `status: skipped` when the user is unbound, not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured.",
1897
+ request: { params: AgentIdParamSchema },
1898
+ responses: {
1899
+ 200: {
1900
+ description: "Lost-access removal preview",
1901
+ content: {
1902
+ "application/json": { schema: GithubLostAccessPreviewSchema },
1903
+ },
1904
+ },
1905
+ ...lostAccessErrors,
1906
+ },
1907
+ });
1908
+
1909
+ const githubLostAccessRemoveRoute = createRoute({
1910
+ method: "post",
1911
+ path: "/agents/{id}/github-lost-access/remove",
1912
+ summary: "Remove the confirmed repos the bound user can no longer push to",
1913
+ description:
1914
+ "Platform-admin only. Never adds repos. Takes the repos the admin confirmed from the preview, re-checks each against the bound user's current access, and removes only those still without push access: first from the agent App's installation, then from the agent's repos; then writes one audit entry (GitHubReconcileAudit, planHash `lost-access:remove`) and blocks the agent's open work on the removed repos through the optional open-work port (a failure there is a warning). Named repos left alone are reported in `notRemoved`. Same skip rules as the preview: a skipped call (200 `status: skipped`) changes and audits nothing; `noop` when nothing named still lacks access. 422 when more than 10 repos would be removed without `confirmRemovals: true`. 502 when GitHub refuses (a failed audit entry records only what landed).",
1915
+ request: {
1916
+ params: AgentIdParamSchema,
1917
+ body: {
1918
+ required: true,
1919
+ content: {
1920
+ "application/json": { schema: GithubLostAccessRemoveBodySchema },
1921
+ },
1922
+ },
1923
+ },
1924
+ responses: {
1925
+ 200: {
1926
+ description: "Removal result",
1927
+ content: {
1928
+ "application/json": { schema: GithubLostAccessRemoveResultSchema },
1929
+ },
1930
+ },
1931
+ ...lostAccessErrors,
1932
+ 422: { description: "Removal cap needs confirmRemovals", ...jsonError },
1933
+ },
1934
+ });
1935
+
1806
1936
  /** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
1807
1937
  export const cronRunStatsQuerySchema = z
1808
1938
  .object({
@@ -3516,6 +3646,102 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3516
3646
  ),
3517
3647
  );
3518
3648
 
3649
+ // /agents/:id/github-lost-access/{preview,remove} — IRM-1.3. Platform admin
3650
+ // only; responses carry repo names and ids, never tokens.
3651
+ const lostAccessService = (c: { get(k: "isAdmin"): boolean | undefined }) => {
3652
+ if (c.get("isAdmin") !== true) {
3653
+ throw new ForbiddenError(
3654
+ "Admin access required to remove repos the bound user lost access to",
3655
+ );
3656
+ }
3657
+ const svc = deps.githubLostAccessRemoval;
3658
+ if (!svc) throw new ApiError(503, GITHUB_RECONCILE_UNCONFIGURED);
3659
+ return svc;
3660
+ };
3661
+
3662
+ app.openapi(githubLostAccessPreviewRoute, async (c) => {
3663
+ const svc = lostAccessService(c);
3664
+ const { id: agentId } = c.req.valid("param");
3665
+ const result = await svc.preview(agentId);
3666
+ if (result.status === "agent_not_found") {
3667
+ throw new NotFoundError(`agent ${agentId} not found`);
3668
+ }
3669
+ if (result.status === "skipped") {
3670
+ return c.json({ status: "skipped" as const, reason: result.reason }, 200);
3671
+ }
3672
+ const { plan } = result;
3673
+ return c.json(
3674
+ {
3675
+ status: "previewed" as const,
3676
+ repos: plan.repos,
3677
+ installationRemoves: plan.installationRemoves,
3678
+ configRemoves: plan.configRemoves,
3679
+ skippedOrgs: plan.skippedOrgs,
3680
+ openWork: result.openWork,
3681
+ warnings: result.warnings,
3682
+ },
3683
+ 200,
3684
+ );
3685
+ });
3686
+
3687
+ app.openapi(githubLostAccessRemoveRoute, async (c) => {
3688
+ const svc = lostAccessService(c);
3689
+ const { id: agentId } = c.req.valid("param");
3690
+ const body = c.req.valid("json");
3691
+ const caller = c.get("caller")?.name ?? "anonymous";
3692
+ const result = await svc.remove({
3693
+ agentId,
3694
+ caller,
3695
+ repos: body.repos,
3696
+ confirmRemovals: body.confirmRemovals,
3697
+ });
3698
+ switch (result.status) {
3699
+ case "agent_not_found":
3700
+ throw new NotFoundError(`agent ${agentId} not found`);
3701
+ case "skipped":
3702
+ return c.json(
3703
+ { status: "skipped" as const, reason: result.reason },
3704
+ 200,
3705
+ );
3706
+ case "removal_cap":
3707
+ throw new UnprocessableEntityError(
3708
+ `${result.removals} repos would be removed; resend with confirmRemovals: true to apply`,
3709
+ );
3710
+ case "failed":
3711
+ console.log(
3712
+ `[agents-api] github lost-access removal failed: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3713
+ );
3714
+ throw new BadGatewayError(
3715
+ `GitHub refused the removal; audit ${result.auditId} records the failure: ${result.error}`,
3716
+ );
3717
+ case "noop":
3718
+ case "applied": {
3719
+ const { plan } = result;
3720
+ if (result.status === "applied") {
3721
+ console.log(
3722
+ `[agents-api] github lost-access removal applied: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3723
+ );
3724
+ }
3725
+ return c.json(
3726
+ {
3727
+ status: result.status,
3728
+ ...(result.status === "applied" ? { auditId: result.auditId } : {}),
3729
+ repos: plan.repos,
3730
+ installationRemoves: plan.installationRemoves,
3731
+ configRemoves: plan.configRemoves,
3732
+ notRemoved: plan.notRemoved,
3733
+ skippedOrgs: plan.skippedOrgs,
3734
+ warnings:
3735
+ result.status === "applied"
3736
+ ? [...plan.warnings, ...result.warnings]
3737
+ : plan.warnings,
3738
+ },
3739
+ 200,
3740
+ );
3741
+ }
3742
+ }
3743
+ });
3744
+
3519
3745
  // GET /agents/:id/github-installations — latest snapshot, 404 if none yet
3520
3746
  app.openapi(getGitHubInstallationsRoute, async (c) => {
3521
3747
  const { id: agentId } = c.req.valid("param");
@@ -25,6 +25,7 @@ import {
25
25
  InstallationReposService,
26
26
  type InstallationReposPort,
27
27
  } from "./installation-repos-service.ts";
28
+ import { LostAccessRemovalService } from "./lost-access-removal.ts";
28
29
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
29
30
 
30
31
  export interface GithubReconcileWiringDeps {
@@ -120,3 +121,24 @@ export function createGithubInstallationRepos(
120
121
  audit: new PrismaReconcileAudit(deps.prisma),
121
122
  });
122
123
  }
124
+
125
+ /**
126
+ * The `githubLostAccessRemoval` dep for createAdminApp (IRM-1.3): removes the
127
+ * repos the bound user can no longer push to from the agent App's
128
+ * installation and the agent's repos, blocking open work through the
129
+ * optional host OpenWorkPort.
130
+ */
131
+ export function createGithubLostAccessRemoval(
132
+ deps: InstallationReposWiringDeps,
133
+ ): LostAccessRemovalService {
134
+ const client = lazyInstallerClient(deps);
135
+ return new LostAccessRemovalService({
136
+ agents: new PrismaReconcileAgents(deps.prisma, deps.agentEnv),
137
+ access: deps.access,
138
+ installation:
139
+ deps.installationRepos ??
140
+ createInstallationReposPort(createInstallationPort(client), client),
141
+ audit: new PrismaReconcileAudit(deps.prisma),
142
+ ...(deps.openWork ? { openWork: deps.openWork } : {}),
143
+ });
144
+ }
@@ -0,0 +1,333 @@
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
+ }