@app-vitals/agent-admin 1.25.0 → 1.27.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/package.json +2 -2
- package/prisma/client/browser.ts +5 -0
- package/prisma/client/client.ts +5 -0
- package/prisma/client/internal/class.ts +14 -4
- package/prisma/client/internal/prismaNamespace.ts +91 -2
- package/prisma/client/internal/prismaNamespaceBrowser.ts +15 -1
- package/prisma/client/models/GitHubReconcileAudit.ts +1193 -0
- package/prisma/client/models.ts +1 -0
- package/prisma/migrations/20261111000000_add_github_reconcile_audit/migration.sql +16 -0
- package/prisma/schema/schema.prisma +16 -0
- package/src/reconcile-apply-service.integration.test.ts +263 -0
- package/src/reconcile-apply-service.ts +343 -0
- package/src/reconcile-apply-service.unit.test.ts +191 -0
- package/src/reconcile-open-work.ts +33 -0
- package/src/reconcile-planner.ts +249 -0
- package/src/reconcile-planner.unit.test.ts +274 -0
package/prisma/client/models.ts
CHANGED
|
@@ -36,4 +36,5 @@ export type * from './models/PushSubscription.ts'
|
|
|
36
36
|
export type * from './models/ChatThreadWatch.ts'
|
|
37
37
|
export type * from './models/UserNotificationPrefs.ts'
|
|
38
38
|
export type * from './models/AgentMarketplace.ts'
|
|
39
|
+
export type * from './models/GitHubReconcileAudit.ts'
|
|
39
40
|
export type * from './commonInputTypes.ts'
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
-- GHE-3.3: audit trail for GitHub repo reconcile applies. Additive only: one new table, nothing existing is touched.
|
|
2
|
+
-- CreateTable
|
|
3
|
+
CREATE TABLE "GitHubReconcileAudit" (
|
|
4
|
+
"id" TEXT NOT NULL,
|
|
5
|
+
"agentId" TEXT NOT NULL,
|
|
6
|
+
"caller" TEXT NOT NULL,
|
|
7
|
+
"planHash" TEXT NOT NULL,
|
|
8
|
+
"diff" JSONB NOT NULL,
|
|
9
|
+
"result" JSONB NOT NULL,
|
|
10
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
11
|
+
|
|
12
|
+
CONSTRAINT "GitHubReconcileAudit_pkey" PRIMARY KEY ("id")
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
-- CreateIndex
|
|
16
|
+
CREATE INDEX "GitHubReconcileAudit_agentId_createdAt_idx" ON "GitHubReconcileAudit"("agentId", "createdAt");
|
|
@@ -614,3 +614,19 @@ model AgentMarketplace {
|
|
|
614
614
|
|
|
615
615
|
@@unique([agentId, name])
|
|
616
616
|
}
|
|
617
|
+
|
|
618
|
+
// ─── GitHubReconcileAudit ─────────────────────────────────────────────────────
|
|
619
|
+
// GHE-3.3: one row per applied (or failed) GitHub repo reconcile for an agent.
|
|
620
|
+
// agentId is deliberately not a relation: the audit trail outlives the agent.
|
|
621
|
+
|
|
622
|
+
model GitHubReconcileAudit {
|
|
623
|
+
id String @id @default(cuid())
|
|
624
|
+
agentId String
|
|
625
|
+
caller String
|
|
626
|
+
planHash String
|
|
627
|
+
diff Json
|
|
628
|
+
result Json
|
|
629
|
+
createdAt DateTime @default(now())
|
|
630
|
+
|
|
631
|
+
@@index([agentId, createdAt])
|
|
632
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
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 type { GithubAccessPreview } from "./github-access-preview.ts";
|
|
12
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
13
|
+
import {
|
|
14
|
+
PrismaReconcileAgents,
|
|
15
|
+
PrismaReconcileAudit,
|
|
16
|
+
ReconcileApplyService,
|
|
17
|
+
} from "./reconcile-apply-service.ts";
|
|
18
|
+
|
|
19
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
20
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
21
|
+
|
|
22
|
+
function accessFor(pushable: string[]): GithubAccessPreview {
|
|
23
|
+
return {
|
|
24
|
+
status: "ok",
|
|
25
|
+
access: {
|
|
26
|
+
username: "dev",
|
|
27
|
+
outcome: "ok",
|
|
28
|
+
userVerified: true,
|
|
29
|
+
complete: true,
|
|
30
|
+
unresolved: 0,
|
|
31
|
+
checkedAt: "2026-11-11T00:00:00.000Z",
|
|
32
|
+
orgs: [
|
|
33
|
+
{
|
|
34
|
+
org: "acme",
|
|
35
|
+
status: "ok",
|
|
36
|
+
unresolved: 0,
|
|
37
|
+
repos: pushable.map((fullName) => ({
|
|
38
|
+
fullName,
|
|
39
|
+
level: "write" as const,
|
|
40
|
+
canPush: true,
|
|
41
|
+
})),
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describeOrSkip("ReconcileApplyService (integration)", () => {
|
|
49
|
+
let prisma: PrismaClient;
|
|
50
|
+
let calls: string[];
|
|
51
|
+
let installed: string[];
|
|
52
|
+
let pushable: string[];
|
|
53
|
+
let unconfigured: boolean;
|
|
54
|
+
|
|
55
|
+
const service = (): ReconcileApplyService =>
|
|
56
|
+
new ReconcileApplyService({
|
|
57
|
+
agents: {
|
|
58
|
+
get: (id) => new PrismaReconcileAgents(prisma).get(id),
|
|
59
|
+
setRepos: async (id, repos) => {
|
|
60
|
+
calls.push("config");
|
|
61
|
+
await new PrismaReconcileAgents(prisma).setRepos(id, repos);
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
access: async () =>
|
|
65
|
+
unconfigured ? { status: "unconfigured" } : accessFor(pushable),
|
|
66
|
+
installation: {
|
|
67
|
+
listRepos: async () => ({ acme: [...installed] }),
|
|
68
|
+
addRepos: async (_o, repos) => {
|
|
69
|
+
calls.push("inst-add");
|
|
70
|
+
installed.push(...repos);
|
|
71
|
+
},
|
|
72
|
+
removeRepos: async (_o, repos) => {
|
|
73
|
+
calls.push("inst-remove");
|
|
74
|
+
installed = installed.filter((r) => !repos.includes(r));
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
audit: new PrismaReconcileAudit(prisma),
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
async function makeAgent(
|
|
81
|
+
repos: string[],
|
|
82
|
+
githubUsername: string | null = "dev",
|
|
83
|
+
) {
|
|
84
|
+
const a = await prisma.agent.create({
|
|
85
|
+
data: { name: "A", repos, githubUsername },
|
|
86
|
+
});
|
|
87
|
+
installed = [...repos];
|
|
88
|
+
return a.id;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
beforeEach(async () => {
|
|
92
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
93
|
+
await prisma.gitHubReconcileAudit.deleteMany();
|
|
94
|
+
await prisma.agentGitHubInstallationsSnapshot.deleteMany();
|
|
95
|
+
await prisma.agentWorkQueueSnapshot.deleteMany();
|
|
96
|
+
await prisma.agentChatTokenUsageDailyByModel.deleteMany();
|
|
97
|
+
await prisma.agentCronRun.deleteMany();
|
|
98
|
+
await prisma.agentToken.deleteMany();
|
|
99
|
+
await prisma.agentCronJob.deleteMany();
|
|
100
|
+
await prisma.agentTool.deleteMany();
|
|
101
|
+
await prisma.agentEnv.deleteMany();
|
|
102
|
+
await prisma.agentMember.deleteMany();
|
|
103
|
+
await prisma.agent.deleteMany();
|
|
104
|
+
calls = [];
|
|
105
|
+
installed = [];
|
|
106
|
+
pushable = [];
|
|
107
|
+
unconfigured = false;
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
afterEach(async () => {
|
|
111
|
+
await prisma.$disconnect();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("applies installation changes before agent config and writes an audit entry", async () => {
|
|
115
|
+
const id = await makeAgent(["acme/a", "acme/b"]);
|
|
116
|
+
pushable = ["acme/a", "acme/c"];
|
|
117
|
+
const svc = service();
|
|
118
|
+
const plan = await svc.plan(id, ["acme/c"]);
|
|
119
|
+
const res = await svc.apply({
|
|
120
|
+
agentId: id,
|
|
121
|
+
caller: "dan@x.io",
|
|
122
|
+
planHash: plan.planHash,
|
|
123
|
+
namedAdds: ["acme/c"],
|
|
124
|
+
});
|
|
125
|
+
expect(res.status).toBe("applied");
|
|
126
|
+
expect(calls).toEqual(["inst-add", "inst-remove", "config"]);
|
|
127
|
+
const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
|
|
128
|
+
expect(agent.repos).toEqual(["acme/a", "acme/c"]);
|
|
129
|
+
const audits = await prisma.gitHubReconcileAudit.findMany();
|
|
130
|
+
expect(audits).toHaveLength(1);
|
|
131
|
+
expect(audits[0]).toMatchObject({
|
|
132
|
+
agentId: id,
|
|
133
|
+
caller: "dan@x.io",
|
|
134
|
+
planHash: plan.planHash,
|
|
135
|
+
result: { status: "applied" },
|
|
136
|
+
});
|
|
137
|
+
expect(audits[0]?.diff).toMatchObject({
|
|
138
|
+
configAdds: ["acme/c"],
|
|
139
|
+
configRemoves: ["acme/b"],
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("refuses a stale plan hash and changes nothing", async () => {
|
|
144
|
+
const id = await makeAgent(["acme/a", "acme/b"]);
|
|
145
|
+
pushable = ["acme/a"];
|
|
146
|
+
const res = await service().apply({
|
|
147
|
+
agentId: id,
|
|
148
|
+
caller: "c",
|
|
149
|
+
planHash: "stale",
|
|
150
|
+
});
|
|
151
|
+
expect(res.status).toBe("stale_plan");
|
|
152
|
+
expect(calls).toEqual([]);
|
|
153
|
+
expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
|
|
154
|
+
const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
|
|
155
|
+
expect(agent.repos).toEqual(["acme/a", "acme/b"]);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("refuses more than 10 removals unless confirmRemovals is set", async () => {
|
|
159
|
+
const repos = Array.from({ length: 11 }, (_, i) => `acme/r${i}`);
|
|
160
|
+
const id = await makeAgent(repos);
|
|
161
|
+
pushable = [];
|
|
162
|
+
const svc = service();
|
|
163
|
+
const plan = await svc.plan(id);
|
|
164
|
+
const refused = await svc.apply({
|
|
165
|
+
agentId: id,
|
|
166
|
+
caller: "c",
|
|
167
|
+
planHash: plan.planHash,
|
|
168
|
+
});
|
|
169
|
+
expect(refused.status).toBe("removal_cap");
|
|
170
|
+
expect(calls).toEqual([]);
|
|
171
|
+
expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
|
|
172
|
+
|
|
173
|
+
const ok = await svc.apply({
|
|
174
|
+
agentId: id,
|
|
175
|
+
caller: "c",
|
|
176
|
+
planHash: plan.planHash,
|
|
177
|
+
confirmRemovals: true,
|
|
178
|
+
});
|
|
179
|
+
expect(ok.status).toBe("applied");
|
|
180
|
+
const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
|
|
181
|
+
expect(agent.repos).toEqual([]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("allows exactly 10 removals without confirmation", async () => {
|
|
185
|
+
const repos = Array.from({ length: 10 }, (_, i) => `acme/r${i}`);
|
|
186
|
+
const id = await makeAgent(repos);
|
|
187
|
+
const svc = service();
|
|
188
|
+
const plan = await svc.plan(id);
|
|
189
|
+
const res = await svc.apply({
|
|
190
|
+
agentId: id,
|
|
191
|
+
caller: "c",
|
|
192
|
+
planHash: plan.planHash,
|
|
193
|
+
});
|
|
194
|
+
expect(res.status).toBe("applied");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("is idempotent: a second apply with no drift does nothing", async () => {
|
|
198
|
+
const id = await makeAgent(["acme/a", "acme/b"]);
|
|
199
|
+
pushable = ["acme/a"];
|
|
200
|
+
const svc = service();
|
|
201
|
+
const plan = await svc.plan(id);
|
|
202
|
+
await svc.apply({ agentId: id, caller: "c", planHash: plan.planHash });
|
|
203
|
+
calls = [];
|
|
204
|
+
const again = await svc.apply({
|
|
205
|
+
agentId: id,
|
|
206
|
+
caller: "c",
|
|
207
|
+
planHash: plan.planHash,
|
|
208
|
+
});
|
|
209
|
+
expect(again.status).toBe("noop");
|
|
210
|
+
expect(calls).toEqual([]);
|
|
211
|
+
expect(await prisma.gitHubReconcileAudit.count()).toBe(1);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("a skipped plan writes no audit entry and changes nothing", async () => {
|
|
215
|
+
const noUser = await makeAgent(["acme/a"], null);
|
|
216
|
+
const r1 = await service().apply({
|
|
217
|
+
agentId: noUser,
|
|
218
|
+
caller: "c",
|
|
219
|
+
planHash: "x",
|
|
220
|
+
});
|
|
221
|
+
expect(r1.status).toBe("skipped");
|
|
222
|
+
|
|
223
|
+
unconfigured = true;
|
|
224
|
+
const bound = await makeAgent(["acme/a"]);
|
|
225
|
+
const r2 = await service().apply({
|
|
226
|
+
agentId: bound,
|
|
227
|
+
caller: "c",
|
|
228
|
+
planHash: "x",
|
|
229
|
+
});
|
|
230
|
+
expect(r2.status).toBe("skipped");
|
|
231
|
+
expect(calls).toEqual([]);
|
|
232
|
+
expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("records a failed audit when an installation call fails and leaves config alone", async () => {
|
|
236
|
+
const id = await makeAgent(["acme/a", "acme/b"]);
|
|
237
|
+
pushable = ["acme/a"];
|
|
238
|
+
const base = service();
|
|
239
|
+
const plan = await base.plan(id);
|
|
240
|
+
const failing = new ReconcileApplyService({
|
|
241
|
+
agents: new PrismaReconcileAgents(prisma),
|
|
242
|
+
access: async () => accessFor(pushable),
|
|
243
|
+
installation: {
|
|
244
|
+
listRepos: async () => ({ acme: [...installed] }),
|
|
245
|
+
addRepos: async () => {},
|
|
246
|
+
removeRepos: async () => {
|
|
247
|
+
throw new Error("422 last repository");
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
audit: new PrismaReconcileAudit(prisma),
|
|
251
|
+
});
|
|
252
|
+
const res = await failing.apply({
|
|
253
|
+
agentId: id,
|
|
254
|
+
caller: "c",
|
|
255
|
+
planHash: plan.planHash,
|
|
256
|
+
});
|
|
257
|
+
expect(res.status).toBe("failed");
|
|
258
|
+
const agent = await prisma.agent.findUniqueOrThrow({ where: { id } });
|
|
259
|
+
expect(agent.repos).toEqual(["acme/a", "acme/b"]);
|
|
260
|
+
const [audit] = await prisma.gitHubReconcileAudit.findMany();
|
|
261
|
+
expect(audit?.result).toMatchObject({ status: "failed" });
|
|
262
|
+
});
|
|
263
|
+
});
|
|
@@ -0,0 +1,343 @@
|
|
|
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 { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
16
|
+
import {
|
|
17
|
+
type OpenWorkPort,
|
|
18
|
+
removedRepoBlockReason,
|
|
19
|
+
} from "./reconcile-open-work.ts";
|
|
20
|
+
import {
|
|
21
|
+
planReconcile,
|
|
22
|
+
type ReconcileDiff,
|
|
23
|
+
type ReconcilePlan,
|
|
24
|
+
repoOrg,
|
|
25
|
+
} from "./reconcile-planner.ts";
|
|
26
|
+
|
|
27
|
+
/** More removals than this need confirmRemovals. */
|
|
28
|
+
export const MAX_UNCONFIRMED_REMOVALS = 10;
|
|
29
|
+
|
|
30
|
+
export interface ReconcileAgentRecord {
|
|
31
|
+
id: string;
|
|
32
|
+
repos: string[];
|
|
33
|
+
githubUsername: string | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ReconcileAgentsPort {
|
|
37
|
+
get(agentId: string): Promise<ReconcileAgentRecord | null>;
|
|
38
|
+
setRepos(agentId: string, repos: string[]): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Repo access on the agent App's installations, per org login. */
|
|
42
|
+
export interface ReconcileInstallationPort {
|
|
43
|
+
/** Repos the agent App covers in each org; only the named orgs are needed. */
|
|
44
|
+
listRepos(orgs: readonly string[]): Promise<Record<string, string[]>>;
|
|
45
|
+
/** Grant the installation access to repos (owner/repo, all in `org`). */
|
|
46
|
+
addRepos(org: string, repos: readonly string[]): Promise<void>;
|
|
47
|
+
removeRepos(org: string, repos: readonly string[]): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ReconcileAuditEntry {
|
|
51
|
+
agentId: string;
|
|
52
|
+
caller: string;
|
|
53
|
+
planHash: string;
|
|
54
|
+
diff: ReconcileDiff;
|
|
55
|
+
result: ReconcileAuditResult;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ReconcileAuditResult {
|
|
59
|
+
status: "applied" | "failed";
|
|
60
|
+
error?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface ReconcileAuditPort {
|
|
64
|
+
write(entry: ReconcileAuditEntry): Promise<string>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ReconcileApplyDeps {
|
|
68
|
+
agents: ReconcileAgentsPort;
|
|
69
|
+
/** Resolves the bound user's access; "unconfigured" skips the plan. */
|
|
70
|
+
access: GithubAccessPreviewFn;
|
|
71
|
+
installation: ReconcileInstallationPort;
|
|
72
|
+
audit: ReconcileAuditPort;
|
|
73
|
+
/** Optional: with none, nothing is listed or blocked. */
|
|
74
|
+
openWork?: OpenWorkPort;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface ReconcileApplyInput {
|
|
78
|
+
agentId: string;
|
|
79
|
+
/** Who asked for the apply (audit trail). */
|
|
80
|
+
caller: string;
|
|
81
|
+
/** Hash of the plan the admin reviewed. */
|
|
82
|
+
planHash: string;
|
|
83
|
+
namedAdds?: readonly string[];
|
|
84
|
+
confirmRemovals?: boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type ReconcileApplyResult =
|
|
88
|
+
| { status: "agent_not_found" }
|
|
89
|
+
| { status: "skipped"; plan: ReconcilePlan }
|
|
90
|
+
| { status: "noop"; plan: ReconcilePlan }
|
|
91
|
+
| { status: "stale_plan"; plan: ReconcilePlan }
|
|
92
|
+
| { status: "removal_cap"; plan: ReconcilePlan; removals: number }
|
|
93
|
+
| {
|
|
94
|
+
status: "applied";
|
|
95
|
+
plan: ReconcilePlan;
|
|
96
|
+
auditId: string;
|
|
97
|
+
warnings: string[];
|
|
98
|
+
}
|
|
99
|
+
| {
|
|
100
|
+
status: "failed";
|
|
101
|
+
plan: ReconcilePlan;
|
|
102
|
+
auditId: string;
|
|
103
|
+
error: string;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const orgsOf = (repos: readonly string[]): string[] =>
|
|
107
|
+
[...new Set(repos.map(repoOrg))].sort();
|
|
108
|
+
|
|
109
|
+
function groupByOrg(repos: readonly string[]): Map<string, string[]> {
|
|
110
|
+
const byOrg = new Map<string, string[]>();
|
|
111
|
+
for (const r of repos) {
|
|
112
|
+
const org = repoOrg(r);
|
|
113
|
+
byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
|
|
114
|
+
}
|
|
115
|
+
return byOrg;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export class ReconcileApplyService {
|
|
119
|
+
constructor(private readonly deps: ReconcileApplyDeps) {}
|
|
120
|
+
|
|
121
|
+
/** Plan only: no writes. Throws when the agent does not exist. */
|
|
122
|
+
async plan(
|
|
123
|
+
agentId: string,
|
|
124
|
+
namedAdds?: readonly string[],
|
|
125
|
+
): Promise<ReconcilePlan> {
|
|
126
|
+
const agent = await this.deps.agents.get(agentId);
|
|
127
|
+
if (!agent) throw new Error(`agent ${agentId} not found`);
|
|
128
|
+
return this.planFor(agent, namedAdds);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private async planFor(
|
|
132
|
+
agent: ReconcileAgentRecord,
|
|
133
|
+
namedAdds?: readonly string[],
|
|
134
|
+
): Promise<ReconcilePlan> {
|
|
135
|
+
const username = agent.githubUsername?.trim();
|
|
136
|
+
const preview = username ? await this.deps.access(username) : null;
|
|
137
|
+
// Unbound user or unconfigured Apps: a skipped plan, no installation calls.
|
|
138
|
+
if (!preview || preview.status === "unconfigured") {
|
|
139
|
+
const plan = planReconcile({
|
|
140
|
+
username,
|
|
141
|
+
access: null,
|
|
142
|
+
agentRepos: agent.repos,
|
|
143
|
+
installationRepos: {},
|
|
144
|
+
});
|
|
145
|
+
return preview
|
|
146
|
+
? { ...plan, skipReason: "GitHub Apps are not configured" }
|
|
147
|
+
: plan;
|
|
148
|
+
}
|
|
149
|
+
const installationRepos = await this.deps.installation.listRepos(
|
|
150
|
+
orgsOf([...agent.repos, ...(namedAdds ?? [])]),
|
|
151
|
+
);
|
|
152
|
+
return planReconcile({
|
|
153
|
+
username,
|
|
154
|
+
access: preview.access,
|
|
155
|
+
agentRepos: agent.repos,
|
|
156
|
+
installationRepos,
|
|
157
|
+
namedAdds,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async apply(input: ReconcileApplyInput): Promise<ReconcileApplyResult> {
|
|
162
|
+
const agent = await this.deps.agents.get(input.agentId);
|
|
163
|
+
if (!agent) return { status: "agent_not_found" };
|
|
164
|
+
|
|
165
|
+
const plan = await this.planFor(agent, input.namedAdds);
|
|
166
|
+
if (plan.skipped) return { status: "skipped", plan };
|
|
167
|
+
if (plan.empty) return { status: "noop", plan };
|
|
168
|
+
if (plan.planHash !== input.planHash) return { status: "stale_plan", plan };
|
|
169
|
+
|
|
170
|
+
const removals = plan.diff.configRemoves.length;
|
|
171
|
+
if (removals > MAX_UNCONFIRMED_REMOVALS && !input.confirmRemovals) {
|
|
172
|
+
return { status: "removal_cap", plan, removals };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const entry = {
|
|
176
|
+
agentId: input.agentId,
|
|
177
|
+
caller: input.caller,
|
|
178
|
+
planHash: plan.planHash,
|
|
179
|
+
diff: plan.diff,
|
|
180
|
+
};
|
|
181
|
+
try {
|
|
182
|
+
await this.applyInstallation(plan.diff);
|
|
183
|
+
await this.applyConfig(agent, plan.diff);
|
|
184
|
+
} catch (err) {
|
|
185
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
186
|
+
const auditId = await this.deps.audit.write({
|
|
187
|
+
...entry,
|
|
188
|
+
result: { status: "failed", error },
|
|
189
|
+
});
|
|
190
|
+
return { status: "failed", plan, auditId, error };
|
|
191
|
+
}
|
|
192
|
+
const auditId = await this.deps.audit.write({
|
|
193
|
+
...entry,
|
|
194
|
+
result: { status: "applied" },
|
|
195
|
+
});
|
|
196
|
+
const warnings = await this.blockRemoved(
|
|
197
|
+
input.agentId,
|
|
198
|
+
plan.diff.configRemoves,
|
|
199
|
+
);
|
|
200
|
+
return { status: "applied", plan, auditId, warnings };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private async applyInstallation(diff: ReconcileDiff): Promise<void> {
|
|
204
|
+
const { installation } = this.deps;
|
|
205
|
+
for (const [org, repos] of groupByOrg(diff.installationAdds)) {
|
|
206
|
+
await installation.addRepos(org, repos);
|
|
207
|
+
}
|
|
208
|
+
for (const [org, repos] of groupByOrg(diff.installationRemoves)) {
|
|
209
|
+
await installation.removeRepos(org, repos);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private async applyConfig(
|
|
214
|
+
agent: ReconcileAgentRecord,
|
|
215
|
+
diff: ReconcileDiff,
|
|
216
|
+
): Promise<void> {
|
|
217
|
+
const removed = new Set(diff.configRemoves);
|
|
218
|
+
const next = agent.repos.filter((r) => !removed.has(r));
|
|
219
|
+
for (const r of diff.configAdds) if (!next.includes(r)) next.push(r);
|
|
220
|
+
await this.deps.agents.setRepos(agent.id, next);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private async blockRemoved(
|
|
224
|
+
agentId: string,
|
|
225
|
+
removed: readonly string[],
|
|
226
|
+
): Promise<string[]> {
|
|
227
|
+
const port = this.deps.openWork;
|
|
228
|
+
if (!port || removed.length === 0) return [];
|
|
229
|
+
const warnings: string[] = [];
|
|
230
|
+
for (const repo of removed) {
|
|
231
|
+
try {
|
|
232
|
+
await port.listOpenWork(agentId, [repo]);
|
|
233
|
+
await port.blockOpenWork(agentId, [repo], removedRepoBlockReason(repo));
|
|
234
|
+
} catch (err) {
|
|
235
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
236
|
+
warnings.push(`open work for ${repo} was not blocked: ${msg}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return warnings;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Prisma-backed audit store (GitHubReconcileAudit). */
|
|
244
|
+
export class PrismaReconcileAudit implements ReconcileAuditPort {
|
|
245
|
+
constructor(private readonly prisma: PrismaClient) {}
|
|
246
|
+
|
|
247
|
+
async write(entry: ReconcileAuditEntry): Promise<string> {
|
|
248
|
+
const row = await this.prisma.gitHubReconcileAudit.create({
|
|
249
|
+
data: {
|
|
250
|
+
agentId: entry.agentId,
|
|
251
|
+
caller: entry.caller,
|
|
252
|
+
planHash: entry.planHash,
|
|
253
|
+
diff: entry.diff as unknown as object,
|
|
254
|
+
result: entry.result as unknown as object,
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
return row.id;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Prisma-backed agent reads/writes for the reconcile. */
|
|
262
|
+
export class PrismaReconcileAgents implements ReconcileAgentsPort {
|
|
263
|
+
constructor(private readonly prisma: PrismaClient) {}
|
|
264
|
+
|
|
265
|
+
async get(agentId: string): Promise<ReconcileAgentRecord | null> {
|
|
266
|
+
return this.prisma.agent.findUnique({
|
|
267
|
+
where: { id: agentId },
|
|
268
|
+
select: { id: true, repos: true, githubUsername: true },
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async setRepos(agentId: string, repos: string[]): Promise<void> {
|
|
273
|
+
await this.prisma.agent.update({
|
|
274
|
+
where: { id: agentId },
|
|
275
|
+
data: { repos },
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The slice of GithubEnterpriseClient the installation port needs. */
|
|
281
|
+
export interface InstallationRepoClient {
|
|
282
|
+
listOrgInstallations(org: string): Promise<{ id: number; appId: number }[]>;
|
|
283
|
+
listInstallationRepositories(
|
|
284
|
+
org: string,
|
|
285
|
+
installationId: number,
|
|
286
|
+
): Promise<{ fullName: string }[]>;
|
|
287
|
+
addRepositories(
|
|
288
|
+
org: string,
|
|
289
|
+
installationId: number,
|
|
290
|
+
names: readonly string[],
|
|
291
|
+
): Promise<unknown>;
|
|
292
|
+
removeRepositories(
|
|
293
|
+
org: string,
|
|
294
|
+
installationId: number,
|
|
295
|
+
names: readonly string[],
|
|
296
|
+
): Promise<unknown>;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const baseName = (fullName: string): string => fullName.split("/")[1] ?? "";
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* ReconcileInstallationPort over GithubEnterpriseClient (GHE-3.1), scoped to
|
|
303
|
+
* the agent App's installation (`agentAppId`) on each org.
|
|
304
|
+
*/
|
|
305
|
+
export function createInstallationPort(
|
|
306
|
+
client: InstallationRepoClient,
|
|
307
|
+
agentAppId: number,
|
|
308
|
+
): ReconcileInstallationPort {
|
|
309
|
+
const installationId = async (org: string): Promise<number> => {
|
|
310
|
+
const found = (await client.listOrgInstallations(org)).find(
|
|
311
|
+
(i) => i.appId === agentAppId,
|
|
312
|
+
);
|
|
313
|
+
if (!found) throw new Error(`agent App is not installed on ${org}`);
|
|
314
|
+
return found.id;
|
|
315
|
+
};
|
|
316
|
+
return {
|
|
317
|
+
async listRepos(orgs) {
|
|
318
|
+
const out: Record<string, string[]> = {};
|
|
319
|
+
for (const org of orgs) {
|
|
320
|
+
const repos = await client.listInstallationRepositories(
|
|
321
|
+
org,
|
|
322
|
+
await installationId(org),
|
|
323
|
+
);
|
|
324
|
+
out[org] = repos.map((r) => r.fullName);
|
|
325
|
+
}
|
|
326
|
+
return out;
|
|
327
|
+
},
|
|
328
|
+
async addRepos(org, repos) {
|
|
329
|
+
await client.addRepositories(
|
|
330
|
+
org,
|
|
331
|
+
await installationId(org),
|
|
332
|
+
repos.map(baseName),
|
|
333
|
+
);
|
|
334
|
+
},
|
|
335
|
+
async removeRepos(org, repos) {
|
|
336
|
+
await client.removeRepositories(
|
|
337
|
+
org,
|
|
338
|
+
await installationId(org),
|
|
339
|
+
repos.map(baseName),
|
|
340
|
+
);
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
}
|