@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,271 +0,0 @@
1
- /**
2
- * admin/src/reconcile-apply-service.integration.test.ts
3
- * Integration tests for ReconcileApplyService against a real DB (audit table,
4
- * agent config); GitHub is faked.
5
- *
6
- * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
7
- */
8
-
9
- import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
- import type { PrismaClient } from "../prisma/client/client.ts";
11
- import { AgentEnvService } from "./agent-envs.ts";
12
- import type { GithubAccessPreview } from "./github-access-preview.ts";
13
- import { createAdminPrismaClient } from "./prisma-client.ts";
14
- import {
15
- PrismaReconcileAgents,
16
- PrismaReconcileAudit,
17
- ReconcileApplyService,
18
- } from "./reconcile-apply-service.ts";
19
- import { identityCrypto } from "./token-crypto.ts";
20
-
21
- const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
22
- const describeOrSkip = TEST_DB ? describe : describe.skip;
23
-
24
- function accessFor(pushable: string[]): GithubAccessPreview {
25
- return {
26
- status: "ok",
27
- access: {
28
- username: "dev",
29
- outcome: "ok",
30
- userVerified: true,
31
- complete: true,
32
- unresolved: 0,
33
- checkedAt: "2026-11-11T00:00:00.000Z",
34
- orgs: [
35
- {
36
- org: "acme",
37
- status: "ok",
38
- unresolved: 0,
39
- repos: pushable.map((fullName) => ({
40
- fullName,
41
- level: "write" as const,
42
- canPush: true,
43
- })),
44
- },
45
- ],
46
- },
47
- };
48
- }
49
-
50
- describeOrSkip("ReconcileApplyService (integration)", () => {
51
- let prisma: PrismaClient;
52
- let calls: string[];
53
- let installed: string[];
54
- let pushable: string[];
55
- let unconfigured: boolean;
56
-
57
- const service = (): ReconcileApplyService =>
58
- new ReconcileApplyService({
59
- agents: {
60
- get: (id) => new PrismaReconcileAgents(prisma, envService()).get(id),
61
- setRepos: async (id, repos) => {
62
- calls.push("config");
63
- await new PrismaReconcileAgents(prisma, envService()).setRepos(
64
- id,
65
- repos,
66
- );
67
- },
68
- },
69
- access: async () =>
70
- unconfigured ? { status: "unconfigured" } : accessFor(pushable),
71
- installation: {
72
- listRepos: async () => ({ acme: [...installed] }),
73
- addRepos: async (_o, repos) => {
74
- calls.push("inst-add");
75
- installed.push(...repos);
76
- },
77
- removeRepos: async (_o, repos) => {
78
- calls.push("inst-remove");
79
- installed = installed.filter((r) => !repos.includes(r));
80
- },
81
- },
82
- audit: new PrismaReconcileAudit(prisma),
83
- });
84
-
85
- const envService = () => new AgentEnvService(prisma, identityCrypto);
86
-
87
- async function makeAgent(
88
- repos: string[],
89
- githubUsername: string | null = "dev",
90
- ) {
91
- const a = await prisma.agent.create({
92
- data: { name: "A", repos, githubUsername },
93
- });
94
- await envService().patch(a.id, { GH_APP_ID: "42" });
95
- installed = [...repos];
96
- return a.id;
97
- }
98
-
99
- beforeEach(async () => {
100
- prisma = createAdminPrismaClient(TEST_DB as string);
101
- await prisma.gitHubReconcileAudit.deleteMany();
102
- await prisma.agentGitHubInstallationsSnapshot.deleteMany();
103
- await prisma.agentWorkQueueSnapshot.deleteMany();
104
- await prisma.agentChatTokenUsageDailyByModel.deleteMany();
105
- await prisma.agentCronRun.deleteMany();
106
- await prisma.agentToken.deleteMany();
107
- await prisma.agentCronJob.deleteMany();
108
- await prisma.agentTool.deleteMany();
109
- await prisma.agentEnv.deleteMany();
110
- await prisma.agentMember.deleteMany();
111
- await prisma.agent.deleteMany();
112
- calls = [];
113
- installed = [];
114
- pushable = [];
115
- unconfigured = false;
116
- });
117
-
118
- afterEach(async () => {
119
- await prisma.$disconnect();
120
- });
121
-
122
- it("applies installation changes before agent config and writes an audit entry", async () => {
123
- const id = await makeAgent(["acme/a", "acme/b"]);
124
- pushable = ["acme/a", "acme/c"];
125
- const svc = service();
126
- const plan = await svc.plan(id, ["acme/c"]);
127
- const res = await svc.apply({
128
- agentId: id,
129
- caller: "dan@x.io",
130
- planHash: plan.planHash,
131
- namedAdds: ["acme/c"],
132
- });
133
- expect(res.status).toBe("applied");
134
- expect(calls).toEqual(["inst-add", "inst-remove", "config"]);
135
- const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
136
- expect(agent.repos).toEqual(["acme/a", "acme/c"]);
137
- const audits = await prisma.gitHubReconcileAudit.findMany();
138
- expect(audits).toHaveLength(1);
139
- expect(audits[0]).toMatchObject({
140
- agentId: id,
141
- caller: "dan@x.io",
142
- planHash: plan.planHash,
143
- result: { status: "applied" },
144
- });
145
- expect(audits[0]?.diff).toMatchObject({
146
- configAdds: ["acme/c"],
147
- configRemoves: ["acme/b"],
148
- });
149
- });
150
-
151
- it("refuses a stale plan hash and changes nothing", async () => {
152
- const id = await makeAgent(["acme/a", "acme/b"]);
153
- pushable = ["acme/a"];
154
- const res = await service().apply({
155
- agentId: id,
156
- caller: "c",
157
- planHash: "stale",
158
- });
159
- expect(res.status).toBe("stale_plan");
160
- expect(calls).toEqual([]);
161
- expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
162
- const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
163
- expect(agent.repos).toEqual(["acme/a", "acme/b"]);
164
- });
165
-
166
- it("refuses more than 10 removals unless confirmRemovals is set", async () => {
167
- const repos = Array.from({ length: 11 }, (_, i) => `acme/r${i}`);
168
- const id = await makeAgent(repos);
169
- pushable = [];
170
- const svc = service();
171
- const plan = await svc.plan(id);
172
- const refused = await svc.apply({
173
- agentId: id,
174
- caller: "c",
175
- planHash: plan.planHash,
176
- });
177
- expect(refused.status).toBe("removal_cap");
178
- expect(calls).toEqual([]);
179
- expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
180
-
181
- const ok = await svc.apply({
182
- agentId: id,
183
- caller: "c",
184
- planHash: plan.planHash,
185
- confirmRemovals: true,
186
- });
187
- expect(ok.status).toBe("applied");
188
- const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
189
- expect(agent.repos).toEqual([]);
190
- });
191
-
192
- it("allows exactly 10 removals without confirmation", async () => {
193
- const repos = Array.from({ length: 10 }, (_, i) => `acme/r${i}`);
194
- const id = await makeAgent(repos);
195
- const svc = service();
196
- const plan = await svc.plan(id);
197
- const res = await svc.apply({
198
- agentId: id,
199
- caller: "c",
200
- planHash: plan.planHash,
201
- });
202
- expect(res.status).toBe("applied");
203
- });
204
-
205
- it("is idempotent: a second apply with no drift does nothing", async () => {
206
- const id = await makeAgent(["acme/a", "acme/b"]);
207
- pushable = ["acme/a"];
208
- const svc = service();
209
- const plan = await svc.plan(id);
210
- await svc.apply({ agentId: id, caller: "c", planHash: plan.planHash });
211
- calls = [];
212
- const again = await svc.apply({
213
- agentId: id,
214
- caller: "c",
215
- planHash: plan.planHash,
216
- });
217
- expect(again.status).toBe("noop");
218
- expect(calls).toEqual([]);
219
- expect(await prisma.gitHubReconcileAudit.count()).toBe(1);
220
- });
221
-
222
- it("a skipped plan writes no audit entry and changes nothing", async () => {
223
- const noUser = await makeAgent(["acme/a"], null);
224
- const r1 = await service().apply({
225
- agentId: noUser,
226
- caller: "c",
227
- planHash: "x",
228
- });
229
- expect(r1.status).toBe("skipped");
230
-
231
- unconfigured = true;
232
- const bound = await makeAgent(["acme/a"]);
233
- const r2 = await service().apply({
234
- agentId: bound,
235
- caller: "c",
236
- planHash: "x",
237
- });
238
- expect(r2.status).toBe("skipped");
239
- expect(calls).toEqual([]);
240
- expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
241
- });
242
-
243
- it("records a failed audit when an installation call fails and leaves config alone", async () => {
244
- const id = await makeAgent(["acme/a", "acme/b"]);
245
- pushable = ["acme/a"];
246
- const base = service();
247
- const plan = await base.plan(id);
248
- const failing = new ReconcileApplyService({
249
- agents: new PrismaReconcileAgents(prisma, envService()),
250
- access: async () => accessFor(pushable),
251
- installation: {
252
- listRepos: async () => ({ acme: [...installed] }),
253
- addRepos: async () => {},
254
- removeRepos: async () => {
255
- throw new Error("422 last repository");
256
- },
257
- },
258
- audit: new PrismaReconcileAudit(prisma),
259
- });
260
- const res = await failing.apply({
261
- agentId: id,
262
- caller: "c",
263
- planHash: plan.planHash,
264
- });
265
- expect(res.status).toBe("failed");
266
- const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
267
- expect(agent.repos).toEqual(["acme/a", "acme/b"]);
268
- const [audit] = await prisma.gitHubReconcileAudit.findMany();
269
- expect(audit?.result).toMatchObject({ status: "failed" });
270
- });
271
- });
@@ -1,439 +0,0 @@
1
- /**
2
- * admin/src/reconcile-apply-service.ts
3
- * ReconcileApplyService (GHE-3.3): the applying half of the GitHub repo
4
- * reconcile. Re-plans server-side with planReconcile and applies only when the
5
- * fresh plan still matches the hash the admin reviewed.
6
- *
7
- * Order of checks: skipped plan (nothing changes, no audit) -> empty plan
8
- * (idempotent no-op) -> stale hash -> removal cap -> apply. Apply runs
9
- * installation changes first (adds, then removes), then the agent config, then
10
- * writes the audit entry. Open work on removed repos is blocked last, through
11
- * the optional OpenWorkPort; a port failure is a warning, never a failed apply.
12
- */
13
-
14
- import type { PrismaClient } from "../prisma/client/client.ts";
15
- import type { AgentEnvService } from "./agent-envs.ts";
16
- import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
17
- import {
18
- type OpenWorkItem,
19
- type OpenWorkPort,
20
- removedRepoBlockReason,
21
- } from "./reconcile-open-work.ts";
22
- import {
23
- planReconcile,
24
- type ReconcileDiff,
25
- type ReconcilePlan,
26
- repoOrg,
27
- } from "./reconcile-planner.ts";
28
-
29
- /** Parses a stored GH_APP_ID; unset or non-numeric -> undefined. */
30
- function parseAppId(raw: string | undefined): number | undefined {
31
- const n = Number(raw?.trim());
32
- return Number.isInteger(n) && n > 0 ? n : undefined;
33
- }
34
-
35
- /** More removals than this need confirmRemovals. */
36
- export const MAX_UNCONFIRMED_REMOVALS = 10;
37
-
38
- export interface ReconcileAgentRecord {
39
- id: string;
40
- repos: string[];
41
- githubUsername: string | null;
42
- /** The agent's own GitHub App id (its stored GH_APP_ID); undefined when unset or not numeric. */
43
- appId?: number;
44
- }
45
-
46
- export interface ReconcileAgentsPort {
47
- get(agentId: string): Promise<ReconcileAgentRecord | null>;
48
- setRepos(agentId: string, repos: string[]): Promise<void>;
49
- }
50
-
51
- /**
52
- * Repo access on an agent App's installations, per org login. Each agent has
53
- * its own App, so every call names the App (`appId`) whose installation is used.
54
- */
55
- export interface ReconcileInstallationPort {
56
- /** Repos the agent App covers in each org; only the named orgs are needed. */
57
- listRepos(
58
- appId: number,
59
- orgs: readonly string[],
60
- ): Promise<Record<string, string[]>>;
61
- /** Grant the installation access to repos (owner/repo, all in `org`). */
62
- addRepos(appId: number, org: string, repos: readonly string[]): Promise<void>;
63
- removeRepos(
64
- appId: number,
65
- org: string,
66
- repos: readonly string[],
67
- ): Promise<void>;
68
- }
69
-
70
- export interface ReconcileAuditEntry {
71
- agentId: string;
72
- caller: string;
73
- planHash: string;
74
- diff: ReconcileDiff;
75
- result: ReconcileAuditResult;
76
- }
77
-
78
- export interface ReconcileAuditResult {
79
- status: "applied" | "failed";
80
- error?: string;
81
- }
82
-
83
- export interface ReconcileAuditPort {
84
- write(entry: ReconcileAuditEntry): Promise<string>;
85
- }
86
-
87
- export interface ReconcileApplyDeps {
88
- agents: ReconcileAgentsPort;
89
- /** Resolves the bound user's access; "unconfigured" skips the plan. */
90
- access: GithubAccessPreviewFn;
91
- installation: ReconcileInstallationPort;
92
- audit: ReconcileAuditPort;
93
- /** Optional: with none, nothing is listed or blocked. */
94
- openWork?: OpenWorkPort;
95
- }
96
-
97
- export interface ReconcileApplyInput {
98
- agentId: string;
99
- /** Who asked for the apply (audit trail). */
100
- caller: string;
101
- /** Hash of the plan the admin reviewed. */
102
- planHash: string;
103
- namedAdds?: readonly string[];
104
- confirmRemovals?: boolean;
105
- }
106
-
107
- export type ReconcileApplyResult =
108
- | { status: "agent_not_found" }
109
- | { status: "skipped"; plan: ReconcilePlan }
110
- | { status: "noop"; plan: ReconcilePlan }
111
- | { status: "stale_plan"; plan: ReconcilePlan }
112
- | { status: "removal_cap"; plan: ReconcilePlan; removals: number }
113
- | {
114
- status: "applied";
115
- plan: ReconcilePlan;
116
- auditId: string;
117
- warnings: string[];
118
- }
119
- | {
120
- status: "failed";
121
- plan: ReconcilePlan;
122
- auditId: string;
123
- error: string;
124
- };
125
-
126
- /** Skip reason when the agent has no usable GH_APP_ID in its stored env. */
127
- export const MISSING_APP_ID_REASON =
128
- "agent has no GH_APP_ID in its stored env (its own GitHub App is not set up)";
129
-
130
- const orgsOf = (repos: readonly string[]): string[] =>
131
- [...new Set(repos.map(repoOrg))].sort();
132
-
133
- function groupByOrg(repos: readonly string[]): Map<string, string[]> {
134
- const byOrg = new Map<string, string[]>();
135
- for (const r of repos) {
136
- const org = repoOrg(r);
137
- byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
138
- }
139
- return byOrg;
140
- }
141
-
142
- export class ReconcileApplyService {
143
- constructor(private readonly deps: ReconcileApplyDeps) {}
144
-
145
- /** Plan only: no writes. Throws when the agent does not exist. */
146
- async plan(
147
- agentId: string,
148
- namedAdds?: readonly string[],
149
- ): Promise<ReconcilePlan> {
150
- const agent = await this.deps.agents.get(agentId);
151
- if (!agent) throw new Error(`agent ${agentId} not found`);
152
- return this.planFor(agent, namedAdds);
153
- }
154
-
155
- /**
156
- * Plan plus the open work the removals would affect (GHE-3.4). Read-only.
157
- * Without a port the list is empty; a port failure adds a plan warning
158
- * rather than failing the preview.
159
- */
160
- async planWithOpenWork(
161
- agentId: string,
162
- namedAdds?: readonly string[],
163
- ): Promise<{ plan: ReconcilePlan; openWork: OpenWorkItem[] }> {
164
- const plan = await this.plan(agentId, namedAdds);
165
- const port = this.deps.openWork;
166
- const removed = plan.diff.configRemoves;
167
- if (!port || plan.skipped || removed.length === 0) {
168
- return { plan, openWork: [] };
169
- }
170
- try {
171
- return { plan, openWork: await port.listOpenWork(agentId, removed) };
172
- } catch (err) {
173
- const msg = err instanceof Error ? err.message : String(err);
174
- return {
175
- plan: {
176
- ...plan,
177
- warnings: [...plan.warnings, `open work could not be listed: ${msg}`],
178
- },
179
- openWork: [],
180
- };
181
- }
182
- }
183
-
184
- private async planFor(
185
- agent: ReconcileAgentRecord,
186
- namedAdds?: readonly string[],
187
- ): Promise<ReconcilePlan> {
188
- const username = agent.githubUsername?.trim();
189
- const preview = username ? await this.deps.access(username) : null;
190
- // Unbound user or unconfigured Apps: a skipped plan, no installation calls.
191
- if (!preview || preview.status === "unconfigured") {
192
- const plan = planReconcile({
193
- username,
194
- access: null,
195
- agentRepos: agent.repos,
196
- installationRepos: {},
197
- });
198
- return preview
199
- ? { ...plan, skipReason: "GitHub Apps are not configured" }
200
- : plan;
201
- }
202
- if (agent.appId === undefined) {
203
- const plan = planReconcile({
204
- username,
205
- access: null,
206
- agentRepos: agent.repos,
207
- installationRepos: {},
208
- });
209
- return { ...plan, skipReason: MISSING_APP_ID_REASON };
210
- }
211
- const installationRepos = await this.deps.installation.listRepos(
212
- agent.appId,
213
- orgsOf([...agent.repos, ...(namedAdds ?? [])]),
214
- );
215
- return planReconcile({
216
- username,
217
- access: preview.access,
218
- agentRepos: agent.repos,
219
- installationRepos,
220
- namedAdds,
221
- });
222
- }
223
-
224
- async apply(input: ReconcileApplyInput): Promise<ReconcileApplyResult> {
225
- const agent = await this.deps.agents.get(input.agentId);
226
- if (!agent) return { status: "agent_not_found" };
227
-
228
- const plan = await this.planFor(agent, input.namedAdds);
229
- if (plan.skipped) return { status: "skipped", plan };
230
- if (plan.empty) return { status: "noop", plan };
231
- if (plan.planHash !== input.planHash) return { status: "stale_plan", plan };
232
-
233
- const removals = plan.diff.configRemoves.length;
234
- if (removals > MAX_UNCONFIRMED_REMOVALS && !input.confirmRemovals) {
235
- return { status: "removal_cap", plan, removals };
236
- }
237
-
238
- const entry = {
239
- agentId: input.agentId,
240
- caller: input.caller,
241
- planHash: plan.planHash,
242
- diff: plan.diff,
243
- };
244
- try {
245
- await this.applyInstallation(agent, plan.diff);
246
- await this.applyConfig(agent, plan.diff);
247
- } catch (err) {
248
- const error = err instanceof Error ? err.message : String(err);
249
- const auditId = await this.deps.audit.write({
250
- ...entry,
251
- result: { status: "failed", error },
252
- });
253
- return { status: "failed", plan, auditId, error };
254
- }
255
- const auditId = await this.deps.audit.write({
256
- ...entry,
257
- result: { status: "applied" },
258
- });
259
- const warnings = await this.blockRemoved(
260
- input.agentId,
261
- plan.diff.configRemoves,
262
- );
263
- return { status: "applied", plan, auditId, warnings };
264
- }
265
-
266
- private async applyInstallation(
267
- agent: ReconcileAgentRecord,
268
- diff: ReconcileDiff,
269
- ): Promise<void> {
270
- const { installation } = this.deps;
271
- const hasChanges =
272
- diff.installationAdds.length + diff.installationRemoves.length > 0;
273
- if (agent.appId === undefined) {
274
- if (hasChanges) throw new Error(MISSING_APP_ID_REASON);
275
- return;
276
- }
277
- for (const [org, repos] of groupByOrg(diff.installationAdds)) {
278
- await installation.addRepos(agent.appId, org, repos);
279
- }
280
- for (const [org, repos] of groupByOrg(diff.installationRemoves)) {
281
- await installation.removeRepos(agent.appId, org, repos);
282
- }
283
- }
284
-
285
- private async applyConfig(
286
- agent: ReconcileAgentRecord,
287
- diff: ReconcileDiff,
288
- ): Promise<void> {
289
- const removed = new Set(diff.configRemoves);
290
- const next = agent.repos.filter((r) => !removed.has(r));
291
- for (const r of diff.configAdds) if (!next.includes(r)) next.push(r);
292
- await this.deps.agents.setRepos(agent.id, next);
293
- }
294
-
295
- private async blockRemoved(
296
- agentId: string,
297
- removed: readonly string[],
298
- ): Promise<string[]> {
299
- const port = this.deps.openWork;
300
- if (!port || removed.length === 0) return [];
301
- const warnings: string[] = [];
302
- for (const repo of removed) {
303
- try {
304
- await port.listOpenWork(agentId, [repo]);
305
- await port.blockOpenWork(agentId, [repo], removedRepoBlockReason(repo));
306
- } catch (err) {
307
- const msg = err instanceof Error ? err.message : String(err);
308
- warnings.push(`open work for ${repo} was not blocked: ${msg}`);
309
- }
310
- }
311
- return warnings;
312
- }
313
- }
314
-
315
- /** Prisma-backed audit store (GitHubReconcileAudit). */
316
- export class PrismaReconcileAudit implements ReconcileAuditPort {
317
- constructor(private readonly prisma: PrismaClient) {}
318
-
319
- async write(entry: ReconcileAuditEntry): Promise<string> {
320
- const row = await this.prisma.gitHubReconcileAudit.create({
321
- data: {
322
- agentId: entry.agentId,
323
- caller: entry.caller,
324
- planHash: entry.planHash,
325
- diff: entry.diff as unknown as object,
326
- result: entry.result as unknown as object,
327
- },
328
- });
329
- return row.id;
330
- }
331
- }
332
-
333
- /** Prisma-backed agent reads/writes for the reconcile. */
334
- export class PrismaReconcileAgents implements ReconcileAgentsPort {
335
- constructor(
336
- private readonly prisma: PrismaClient,
337
- private readonly env: Pick<AgentEnvService, "getConfigBundle">,
338
- ) {}
339
-
340
- async get(agentId: string): Promise<ReconcileAgentRecord | null> {
341
- const agent = await this.prisma.agent.findUnique({
342
- where: { id: agentId },
343
- select: { id: true, repos: true, githubUsername: true },
344
- });
345
- if (!agent) return null;
346
- const raw = (await this.env.getConfigBundle(agentId))?.env.GH_APP_ID;
347
- const appId = parseAppId(raw);
348
- return appId === undefined ? agent : { ...agent, appId };
349
- }
350
-
351
- async setRepos(agentId: string, repos: string[]): Promise<void> {
352
- await this.prisma.agent.update({
353
- where: { id: agentId },
354
- data: { repos },
355
- });
356
- }
357
- }
358
-
359
- /** The slice of GithubEnterpriseClient the installation port needs. */
360
- export interface InstallationRepoClient {
361
- listOrgInstallations(org: string): Promise<{ id: number; appId: number }[]>;
362
- listInstallationRepositories(
363
- org: string,
364
- installationId: number,
365
- ): Promise<{ fullName: string }[]>;
366
- addRepositories(
367
- org: string,
368
- installationId: number,
369
- names: readonly string[],
370
- ): Promise<unknown>;
371
- removeRepositories(
372
- org: string,
373
- installationId: number,
374
- names: readonly string[],
375
- ): Promise<unknown>;
376
- }
377
-
378
- /** The agent App has no installation on the org (distinct from a GitHub failure). */
379
- export class AppNotInstalledError extends Error {
380
- constructor(
381
- readonly appId: number,
382
- readonly org: string,
383
- ) {
384
- super(
385
- `agent App ${appId} (the agent's GH_APP_ID) is not installed on org ${org}`,
386
- );
387
- this.name = "AppNotInstalledError";
388
- }
389
- }
390
-
391
- const baseName = (fullName: string): string => fullName.split("/")[1] ?? "";
392
-
393
- /**
394
- * ReconcileInstallationPort over GithubEnterpriseClient (GHE-3.1). Each call
395
- * is scoped to the named agent App's installation on the org.
396
- */
397
- export function createInstallationPort(
398
- client: InstallationRepoClient,
399
- ): ReconcileInstallationPort {
400
- const installationId = async (
401
- appId: number,
402
- org: string,
403
- ): Promise<number> => {
404
- const found = (await client.listOrgInstallations(org)).find(
405
- (i) => i.appId === appId,
406
- );
407
- if (!found) {
408
- throw new AppNotInstalledError(appId, org);
409
- }
410
- return found.id;
411
- };
412
- return {
413
- async listRepos(appId, orgs) {
414
- const out: Record<string, string[]> = {};
415
- for (const org of orgs) {
416
- const repos = await client.listInstallationRepositories(
417
- org,
418
- await installationId(appId, org),
419
- );
420
- out[org] = repos.map((r) => r.fullName);
421
- }
422
- return out;
423
- },
424
- async addRepos(appId, org, repos) {
425
- await client.addRepositories(
426
- org,
427
- await installationId(appId, org),
428
- repos.map(baseName),
429
- );
430
- },
431
- async removeRepos(appId, org, repos) {
432
- await client.removeRepositories(
433
- org,
434
- await installationId(appId, org),
435
- repos.map(baseName),
436
- );
437
- },
438
- };
439
- }