@app-vitals/agent-admin 1.28.0 → 1.30.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.
@@ -0,0 +1,202 @@
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
+
44
+ const buildApp = () => {
45
+ const reconcile = new ReconcileApplyService({
46
+ agents: new PrismaReconcileAgents(prisma),
47
+ access: async () => ({
48
+ status: "ok",
49
+ access: {
50
+ username: "dev",
51
+ outcome: "ok",
52
+ userVerified: true,
53
+ complete: true,
54
+ unresolved: 0,
55
+ checkedAt: "2026-11-11T00:00:00.000Z",
56
+ orgs: [
57
+ {
58
+ org: "acme",
59
+ status: "ok",
60
+ unresolved: 0,
61
+ repos: pushable.map((fullName) => ({
62
+ fullName,
63
+ level: "write" as const,
64
+ canPush: true,
65
+ })),
66
+ },
67
+ ],
68
+ },
69
+ }),
70
+ installation: {
71
+ listRepos: async () => ({ acme: [...installed] }),
72
+ addRepos: async () => {},
73
+ removeRepos: async () => {},
74
+ },
75
+ audit: new PrismaReconcileAudit(prisma),
76
+ });
77
+ return createAdminApp({
78
+ agentService: new AgentService(prisma),
79
+ agentEnvService: new AgentEnvService(prisma, identityCrypto),
80
+ agentCronJobService: new AgentCronJobService(prisma),
81
+ agentCronRunService: new AgentCronRunService(prisma),
82
+ agentCronRunStatsService: new AgentCronRunStatsService(prisma),
83
+ agentToolService: new AgentToolService(prisma),
84
+ agentTokenService: new AgentTokenService(prisma),
85
+ agentPluginService: new AgentPluginService(prisma),
86
+ agentMemberService: new AgentMemberService(prisma),
87
+ specialtyRegistry: {
88
+ getType: () => {
89
+ throw new Error("unused");
90
+ },
91
+ tryGetType: () => undefined,
92
+ listTypes: () => [],
93
+ },
94
+ agentChatTokenService: new AgentChatTokenService(prisma),
95
+ agentGitHubInstallationsService: new AgentGitHubInstallationsService(
96
+ prisma,
97
+ ),
98
+ prisma,
99
+ provisioner: new NoopAgentProvisioner(),
100
+ serviceIntegrations: [],
101
+ chatService: new NoopChatServiceProvisioningClient(),
102
+ slack: { deleteApp: async () => {} },
103
+ decrypt: (v: string) => v,
104
+ sessionSecret: "test-admin-session-secret-32-bytes!",
105
+ adminApiKeys: parseAdminApiKeys(`root:${KEY}:*`),
106
+ githubReconcile: reconcile,
107
+ });
108
+ };
109
+
110
+ const call = (
111
+ app: ReturnType<typeof createAdminApp>,
112
+ id: string,
113
+ action: "plan" | "apply",
114
+ body: unknown,
115
+ ) =>
116
+ app.request(`/agents/${id}/github-reconcile/${action}`, {
117
+ method: "POST",
118
+ headers: {
119
+ Authorization: `Bearer ${KEY}`,
120
+ "Content-Type": "application/json",
121
+ },
122
+ body: JSON.stringify(body),
123
+ });
124
+
125
+ beforeEach(async () => {
126
+ prisma = createAdminPrismaClient(TEST_DB as string);
127
+ await prisma.gitHubReconcileAudit.deleteMany();
128
+ await prisma.agentGitHubInstallationsSnapshot.deleteMany();
129
+ await prisma.agentWorkQueueSnapshot.deleteMany();
130
+ await prisma.agentChatTokenUsageDailyByModel.deleteMany();
131
+ await prisma.agentCronRun.deleteMany();
132
+ await prisma.agentToken.deleteMany();
133
+ await prisma.agentCronJob.deleteMany();
134
+ await prisma.agentTool.deleteMany();
135
+ await prisma.agentEnv.deleteMany();
136
+ await prisma.agentMember.deleteMany();
137
+ await prisma.agent.deleteMany();
138
+ pushable = [];
139
+ installed = [];
140
+ });
141
+
142
+ afterEach(async () => {
143
+ await prisma.$disconnect();
144
+ });
145
+
146
+ it("409 when the hash is stale, and nothing is written", async () => {
147
+ const agent = await prisma.agent.create({
148
+ data: { name: "A", repos: ["acme/a", "acme/b"], githubUsername: "dev" },
149
+ });
150
+ installed = ["acme/a", "acme/b"];
151
+ pushable = ["acme/a"];
152
+ const app = buildApp();
153
+ const plan = (await (await call(app, agent.id, "plan", {})).json()) as {
154
+ planHash: string;
155
+ };
156
+ pushable = []; // access changed after the plan was reviewed
157
+ const res = await call(app, agent.id, "apply", {
158
+ planHash: plan.planHash,
159
+ });
160
+ expect(res.status).toBe(409);
161
+ expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
162
+ const after = await prisma.agent.findUniqueOrThrow({
163
+ where: { id: agent.id },
164
+ });
165
+ expect(after.repos).toEqual(["acme/a", "acme/b"]);
166
+ });
167
+
168
+ it("422 over the removal cap, then applies with confirmRemovals", async () => {
169
+ const repos = Array.from(
170
+ { length: MAX_UNCONFIRMED_REMOVALS + 1 },
171
+ (_, i) => `acme/r${i}`,
172
+ );
173
+ const agent = await prisma.agent.create({
174
+ data: { name: "A", repos, githubUsername: "dev" },
175
+ });
176
+ installed = [...repos];
177
+ pushable = ["acme/keep"];
178
+ const app = buildApp();
179
+ const plan = (await (await call(app, agent.id, "plan", {})).json()) as {
180
+ planHash: string;
181
+ diff: { configRemoves: string[] };
182
+ };
183
+ expect(plan.diff.configRemoves).toHaveLength(repos.length);
184
+ const capped = await call(app, agent.id, "apply", {
185
+ planHash: plan.planHash,
186
+ });
187
+ expect(capped.status).toBe(422);
188
+ expect(await prisma.gitHubReconcileAudit.count()).toBe(0);
189
+
190
+ const ok = await call(app, agent.id, "apply", {
191
+ planHash: plan.planHash,
192
+ confirmRemovals: true,
193
+ });
194
+ expect(ok.status).toBe(200);
195
+ const body = (await ok.json()) as { status: string; auditId: string };
196
+ expect(body.status).toBe("applied");
197
+ const audit = await prisma.gitHubReconcileAudit.findUniqueOrThrow({
198
+ where: { id: body.auditId },
199
+ });
200
+ expect(audit.agentId).toBe(agent.id);
201
+ });
202
+ });
@@ -110,6 +110,9 @@ function makeMinimalDeps(overrides: Partial<AdminUIDeps>): AdminUIDeps {
110
110
  add: async () => {
111
111
  throw new Error("not implemented");
112
112
  },
113
+ remove: async () => {
114
+ throw new Error("not implemented");
115
+ },
113
116
  },
114
117
  agentMemberService: {
115
118
  listByEmail: async () => [],
@@ -111,6 +111,9 @@ function makeMinimalDeps(overrides?: Partial<AdminUIDeps>): AdminUIDeps {
111
111
  add: async () => {
112
112
  throw new Error("not implemented");
113
113
  },
114
+ remove: async () => {
115
+ throw new Error("not implemented");
116
+ },
114
117
  },
115
118
  agentMemberService: {
116
119
  listByEmail: async () => [],
@@ -14,6 +14,7 @@
14
14
  import type { PrismaClient } from "../prisma/client/client.ts";
15
15
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
16
16
  import {
17
+ type OpenWorkItem,
17
18
  type OpenWorkPort,
18
19
  removedRepoBlockReason,
19
20
  } from "./reconcile-open-work.ts";
@@ -128,6 +129,35 @@ export class ReconcileApplyService {
128
129
  return this.planFor(agent, namedAdds);
129
130
  }
130
131
 
132
+ /**
133
+ * Plan plus the open work the removals would affect (GHE-3.4). Read-only.
134
+ * Without a port the list is empty; a port failure adds a plan warning
135
+ * rather than failing the preview.
136
+ */
137
+ async planWithOpenWork(
138
+ agentId: string,
139
+ namedAdds?: readonly string[],
140
+ ): Promise<{ plan: ReconcilePlan; openWork: OpenWorkItem[] }> {
141
+ const plan = await this.plan(agentId, namedAdds);
142
+ const port = this.deps.openWork;
143
+ const removed = plan.diff.configRemoves;
144
+ if (!port || plan.skipped || removed.length === 0) {
145
+ return { plan, openWork: [] };
146
+ }
147
+ try {
148
+ return { plan, openWork: await port.listOpenWork(agentId, removed) };
149
+ } catch (err) {
150
+ const msg = err instanceof Error ? err.message : String(err);
151
+ return {
152
+ plan: {
153
+ ...plan,
154
+ warnings: [...plan.warnings, `open work could not be listed: ${msg}`],
155
+ },
156
+ openWork: [],
157
+ };
158
+ }
159
+ }
160
+
131
161
  private async planFor(
132
162
  agent: ReconcileAgentRecord,
133
163
  namedAdds?: readonly string[],
@@ -189,3 +189,45 @@ describe("createInstallationPort (unit)", () => {
189
189
  expect(seen).toEqual(["list:2", "add:2:b", "rm:2:c,d"]);
190
190
  });
191
191
  });
192
+
193
+ describe("ReconcileApplyService.planWithOpenWork (unit)", () => {
194
+ const removing = { repos: ["acme/a", "acme/b"], pushable: ["acme/a"] };
195
+
196
+ it("lists open work on the repos the plan removes", async () => {
197
+ const seen: (readonly string[])[] = [];
198
+ const { svc } = build({
199
+ ...removing,
200
+ openWork: {
201
+ listOpenWork: async (_a, repos) => {
202
+ seen.push(repos);
203
+ return [{ id: "t1", repo: "acme/b", title: "x" }];
204
+ },
205
+ blockOpenWork: async () => {},
206
+ },
207
+ });
208
+ const res = await svc.planWithOpenWork("a1");
209
+ expect(seen).toEqual([["acme/b"]]);
210
+ expect(res.openWork).toEqual([{ id: "t1", repo: "acme/b", title: "x" }]);
211
+ expect(res.plan.diff.configRemoves).toEqual(["acme/b"]);
212
+ });
213
+
214
+ it("returns an empty list with no port", async () => {
215
+ const { svc } = build(removing);
216
+ expect((await svc.planWithOpenWork("a1")).openWork).toEqual([]);
217
+ });
218
+
219
+ it("a port failure becomes a warning, not an error", async () => {
220
+ const { svc } = build({
221
+ ...removing,
222
+ openWork: {
223
+ listOpenWork: async () => {
224
+ throw new Error("store down");
225
+ },
226
+ blockOpenWork: async () => {},
227
+ },
228
+ });
229
+ const res = await svc.planWithOpenWork("a1");
230
+ expect(res.openWork).toEqual([]);
231
+ expect(res.plan.warnings.join(" ")).toContain("store down");
232
+ });
233
+ });
@@ -194,7 +194,11 @@ function buildComposedApp() {
194
194
  create: notImplemented,
195
195
  revoke: notImplemented,
196
196
  },
197
- agentPluginService: { list: notImplemented, add: notImplemented },
197
+ agentPluginService: {
198
+ list: notImplemented,
199
+ add: notImplemented,
200
+ remove: notImplemented,
201
+ },
198
202
  agentMemberService: {
199
203
  listByEmail: notImplemented,
200
204
  exists: notImplemented,
@@ -209,6 +209,9 @@ function makeMockDeps(
209
209
  add: async () => {
210
210
  throw new Error("not implemented");
211
211
  },
212
+ remove: async () => {
213
+ throw new Error("not implemented");
214
+ },
212
215
  },
213
216
  agentMemberService: {
214
217
  listByEmail: async () => [],