@app-vitals/agent-admin 1.34.0 → 1.35.1

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 (35) hide show
  1. package/openapi.platform.json +2 -392
  2. package/package.json +2 -2
  3. package/src/admin-boot.ts +1 -12
  4. package/src/admin-extension.ts +3 -3
  5. package/src/admin-ui-github-identity.smoke.test.ts +0 -114
  6. package/src/admin-ui-installation-repos-pages.ts +404 -0
  7. package/src/admin-ui-installation-repos-pages.unit.test.ts +57 -0
  8. package/src/admin-ui-installation-repos.smoke.test.ts +496 -0
  9. package/src/admin-ui-pages.ts +57 -9
  10. package/src/admin-ui.ts +236 -50
  11. package/src/agents-api.smoke.test.ts +2 -352
  12. package/src/agents-api.ts +5 -269
  13. package/src/github-enterprise-isolation.unit.test.ts +4 -4
  14. package/src/{github-reconcile-wiring.ts → github-installation-wiring.ts} +18 -38
  15. package/src/github-installation-wiring.unit.test.ts +111 -0
  16. package/src/github-installation.fixtures.ts +76 -0
  17. package/src/installation-ports.integration.test.ts +89 -0
  18. package/src/installation-ports.ts +207 -0
  19. package/src/installation-ports.unit.test.ts +51 -0
  20. package/src/installation-repos-service.ts +12 -12
  21. package/src/installation-repos-service.unit.test.ts +3 -3
  22. package/src/lost-access-removal.ts +9 -9
  23. package/src/lost-access-removal.unit.test.ts +7 -7
  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 -222
  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/reconcile-apply-service.integration.test.ts +0 -271
  32. package/src/reconcile-apply-service.ts +0 -439
  33. package/src/reconcile-apply-service.unit.test.ts +0 -279
  34. package/src/reconcile-planner.ts +0 -264
  35. 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,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
- });