@app-vitals/agent-admin 1.27.0 → 1.29.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
@@ -164,6 +164,7 @@ import {
164
164
  UpsertAgentMarketplaceBodySchema,
165
165
  UpsertChatTokenDailyBodySchema,
166
166
  } from "./openapi-schemas.ts";
167
+ import type { ReconcileApplyService } from "./reconcile-apply-service.ts";
167
168
  import type { SelfServeConfig } from "./self-serve-config.ts";
168
169
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
169
170
  import type { SpecialtyTypeResolver } from "./specialty-types.ts";
@@ -261,6 +262,12 @@ export interface AdminDeps {
261
262
  * means the enterprise Apps are not wired, reported as `unconfigured`.
262
263
  */
263
264
  githubAccessPreview?: GithubAccessPreviewFn;
265
+ /**
266
+ * GHE-3.4: backs POST /agents/:id/github-reconcile/{plan,apply}. Optional
267
+ * (additive); absent means the enterprise Apps are not wired, reported as
268
+ * `skipped`.
269
+ */
270
+ githubReconcile?: Pick<ReconcileApplyService, "planWithOpenWork" | "apply">;
264
271
  /**
265
272
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
266
273
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -591,6 +598,87 @@ const GithubAccessPreviewSchema = z
591
598
  })
592
599
  .openapi("GithubAccessPreview");
593
600
 
601
+ const GITHUB_RECONCILE_UNCONFIGURED = "GitHub Apps are not configured";
602
+
603
+ const RepoFullNameSchema = z
604
+ .string()
605
+ .regex(/^[^/\s]+\/[^/\s]+$/, "must be owner/repo");
606
+
607
+ const GithubReconcilePlanBodySchema = z
608
+ .object({
609
+ addRepos: z.array(RepoFullNameSchema).optional().openapi({
610
+ description:
611
+ "Repos (owner/repo) to explicitly add to the agent's config and installation.",
612
+ }),
613
+ })
614
+ .openapi("GithubReconcilePlanBody");
615
+
616
+ const GithubReconcileApplyBodySchema = z
617
+ .object({
618
+ planHash: z.string().min(1).openapi({
619
+ description: "planHash of the plan the admin reviewed.",
620
+ }),
621
+ addRepos: z.array(RepoFullNameSchema).optional().openapi({
622
+ description: "Must match the addRepos used when the plan was made.",
623
+ }),
624
+ confirmRemovals: z.boolean().optional().openapi({
625
+ description: "Required when the plan removes more than 10 repos.",
626
+ }),
627
+ })
628
+ .openapi("GithubReconcileApplyBody");
629
+
630
+ const GithubReconcileDiffSchema = z.object({
631
+ installationAdds: z.array(z.string()),
632
+ installationRemoves: z.array(z.string()),
633
+ configAdds: z.array(z.string()),
634
+ configRemoves: z.array(z.string()),
635
+ });
636
+
637
+ const GithubReconcilePlanResultSchema = z
638
+ .object({
639
+ status: z.enum(["planned", "skipped"]).openapi({
640
+ description:
641
+ "`skipped` (not an error) when no GitHub username is bound or the Apps are not configured; `reason` says why.",
642
+ }),
643
+ reason: z.string().optional(),
644
+ planHash: z.string().optional(),
645
+ empty: z.boolean().optional(),
646
+ diff: GithubReconcileDiffSchema.optional(),
647
+ skippedOrgs: z
648
+ .array(z.object({ org: z.string(), reason: z.string() }))
649
+ .optional(),
650
+ rejectedAdds: z
651
+ .array(z.object({ repo: z.string(), reason: z.string() }))
652
+ .optional(),
653
+ warnings: z.array(z.string()).optional(),
654
+ affectedOpenWork: z
655
+ .array(
656
+ z.object({
657
+ id: z.string(),
658
+ repo: z.string(),
659
+ title: z.string().optional(),
660
+ }),
661
+ )
662
+ .optional()
663
+ .openapi({
664
+ description:
665
+ "Open work the removals would block; empty when no open-work port is wired.",
666
+ }),
667
+ })
668
+ .openapi("GithubReconcilePlanResult");
669
+
670
+ const GithubReconcileApplyResultSchema = z
671
+ .object({
672
+ status: z.enum(["applied", "failed", "noop", "skipped"]),
673
+ reason: z.string().optional(),
674
+ auditId: z.string().optional(),
675
+ planHash: z.string().optional(),
676
+ diff: GithubReconcileDiffSchema.optional(),
677
+ warnings: z.array(z.string()).optional(),
678
+ error: z.string().optional(),
679
+ })
680
+ .openapi("GithubReconcileApplyResult");
681
+
594
682
  // ─── Route definitions ──────────────────────────────────────────────────────────
595
683
 
596
684
  const reconcileAgentsRoute = createRoute({
@@ -1484,6 +1572,64 @@ const getGithubAccessRoute = createRoute({
1484
1572
  },
1485
1573
  });
1486
1574
 
1575
+ const githubReconcilePlanRoute = createRoute({
1576
+ method: "post",
1577
+ path: "/agents/{id}/github-reconcile/plan",
1578
+ summary: "Plan a GitHub repo reconcile for the agent",
1579
+ description:
1580
+ "Platform-admin only (session members, ops keys and agent keys get 403). Read-only: nothing is persisted or changed. Returns the diff, warnings, `planHash` and the open work the removals would affect. 200 with `status: skipped` and a `reason` when no githubUsername is bound or the enterprise Apps are not configured. 404 for an unknown agent.",
1581
+ request: {
1582
+ params: AgentIdParamSchema,
1583
+ body: {
1584
+ required: false,
1585
+ content: {
1586
+ "application/json": { schema: GithubReconcilePlanBodySchema },
1587
+ },
1588
+ },
1589
+ },
1590
+ responses: {
1591
+ 200: {
1592
+ description: "Reconcile plan",
1593
+ content: {
1594
+ "application/json": { schema: GithubReconcilePlanResultSchema },
1595
+ },
1596
+ },
1597
+ 401: { description: "Unauthorized", ...jsonError },
1598
+ 403: { description: "Platform admin required", ...jsonError },
1599
+ 404: { description: "Agent not found", ...jsonError },
1600
+ },
1601
+ });
1602
+
1603
+ const githubReconcileApplyRoute = createRoute({
1604
+ method: "post",
1605
+ path: "/agents/{id}/github-reconcile/apply",
1606
+ summary: "Apply a reviewed GitHub repo reconcile plan",
1607
+ description:
1608
+ "Platform-admin only (session members, ops keys and agent keys get 403). Re-plans server-side and applies only when the fresh plan still matches `planHash` (409 otherwise). More than 10 removals need `confirmRemovals: true` (422 otherwise). Returns the audit id and result. 200 with `status: skipped` (unbound user or unconfigured Apps) or `status: noop` (nothing to change) is not an error. Open work on removed repos is blocked through the optional open-work port; a failure there is a warning.",
1609
+ request: {
1610
+ params: AgentIdParamSchema,
1611
+ body: {
1612
+ required: true,
1613
+ content: {
1614
+ "application/json": { schema: GithubReconcileApplyBodySchema },
1615
+ },
1616
+ },
1617
+ },
1618
+ responses: {
1619
+ 200: {
1620
+ description: "Apply result",
1621
+ content: {
1622
+ "application/json": { schema: GithubReconcileApplyResultSchema },
1623
+ },
1624
+ },
1625
+ 401: { description: "Unauthorized", ...jsonError },
1626
+ 403: { description: "Platform admin required", ...jsonError },
1627
+ 404: { description: "Agent not found", ...jsonError },
1628
+ 409: { description: "Plan hash is stale; re-plan", ...jsonError },
1629
+ 422: { description: "Removal cap needs confirmRemovals", ...jsonError },
1630
+ },
1631
+ });
1632
+
1487
1633
  /** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
1488
1634
  export const cronRunStatsQuerySchema = z
1489
1635
  .object({
@@ -2937,6 +3083,130 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2937
3083
  return c.json(preview, 200);
2938
3084
  });
2939
3085
 
3086
+ // POST /agents/:id/github-reconcile/{plan,apply} — GHE-3.4. Platform admin
3087
+ // only. Responses carry repo names and ids, never tokens; logs carry ids only.
3088
+ app.openapi(githubReconcilePlanRoute, async (c) => {
3089
+ if (c.get("isAdmin") !== true) {
3090
+ throw new ForbiddenError(
3091
+ "Admin access required to plan a GitHub reconcile",
3092
+ );
3093
+ }
3094
+ const { id: agentId } = c.req.valid("param");
3095
+ const body = c.req.valid("json");
3096
+ const reconcile = deps.githubReconcile;
3097
+ if (!reconcile) {
3098
+ return c.json(
3099
+ { status: "skipped" as const, reason: GITHUB_RECONCILE_UNCONFIGURED },
3100
+ 200,
3101
+ );
3102
+ }
3103
+ let result: Awaited<ReturnType<typeof reconcile.planWithOpenWork>>;
3104
+ try {
3105
+ result = await reconcile.planWithOpenWork(agentId, body?.addRepos);
3106
+ } catch (err) {
3107
+ if (
3108
+ err instanceof Error &&
3109
+ err.message === `agent ${agentId} not found`
3110
+ ) {
3111
+ throw new NotFoundError(`agent ${agentId} not found`);
3112
+ }
3113
+ throw err;
3114
+ }
3115
+ const { plan, openWork } = result;
3116
+ if (plan.skipped) {
3117
+ return c.json(
3118
+ {
3119
+ status: "skipped" as const,
3120
+ reason: plan.skipReason ?? "reconcile skipped",
3121
+ },
3122
+ 200,
3123
+ );
3124
+ }
3125
+ return c.json(
3126
+ {
3127
+ status: "planned" as const,
3128
+ planHash: plan.planHash,
3129
+ empty: plan.empty,
3130
+ diff: plan.diff,
3131
+ skippedOrgs: plan.skippedOrgs,
3132
+ rejectedAdds: plan.rejectedAdds,
3133
+ warnings: plan.warnings,
3134
+ affectedOpenWork: openWork,
3135
+ },
3136
+ 200,
3137
+ );
3138
+ });
3139
+
3140
+ app.openapi(githubReconcileApplyRoute, async (c) => {
3141
+ if (c.get("isAdmin") !== true) {
3142
+ throw new ForbiddenError(
3143
+ "Admin access required to apply a GitHub reconcile",
3144
+ );
3145
+ }
3146
+ const { id: agentId } = c.req.valid("param");
3147
+ const body = c.req.valid("json");
3148
+ const reconcile = deps.githubReconcile;
3149
+ if (!reconcile) {
3150
+ return c.json(
3151
+ { status: "skipped" as const, reason: GITHUB_RECONCILE_UNCONFIGURED },
3152
+ 200,
3153
+ );
3154
+ }
3155
+ const caller = c.get("caller")?.name ?? "anonymous";
3156
+ const result = await reconcile.apply({
3157
+ agentId,
3158
+ caller,
3159
+ planHash: body.planHash,
3160
+ namedAdds: body.addRepos,
3161
+ confirmRemovals: body.confirmRemovals,
3162
+ });
3163
+ switch (result.status) {
3164
+ case "agent_not_found":
3165
+ throw new NotFoundError(`agent ${agentId} not found`);
3166
+ case "stale_plan":
3167
+ throw new ConflictError(
3168
+ "the plan changed since it was reviewed; re-run plan and review it again",
3169
+ );
3170
+ case "removal_cap":
3171
+ throw new UnprocessableEntityError(
3172
+ `plan removes ${result.removals} repos; resend with confirmRemovals: true to apply`,
3173
+ );
3174
+ case "skipped":
3175
+ return c.json(
3176
+ {
3177
+ status: "skipped" as const,
3178
+ reason: result.plan.skipReason ?? "reconcile skipped",
3179
+ },
3180
+ 200,
3181
+ );
3182
+ case "noop":
3183
+ return c.json(
3184
+ {
3185
+ status: "noop" as const,
3186
+ planHash: result.plan.planHash,
3187
+ diff: result.plan.diff,
3188
+ },
3189
+ 200,
3190
+ );
3191
+ case "applied":
3192
+ case "failed":
3193
+ console.log(
3194
+ `[agents-api] github reconcile ${result.status}: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3195
+ );
3196
+ return c.json(
3197
+ {
3198
+ status: result.status,
3199
+ auditId: result.auditId,
3200
+ planHash: result.plan.planHash,
3201
+ diff: result.plan.diff,
3202
+ warnings: result.status === "applied" ? result.warnings : [],
3203
+ ...(result.status === "failed" ? { error: result.error } : {}),
3204
+ },
3205
+ 200,
3206
+ );
3207
+ }
3208
+ });
3209
+
2940
3210
  // GET /agents/:id/github-installations — latest snapshot, 404 if none yet
2941
3211
  app.openapi(getGitHubInstallationsRoute, async (c) => {
2942
3212
  const { id: agentId } = c.req.valid("param");
@@ -335,6 +335,7 @@ function makeBaseDeps(overrides?: Partial<AdminUIDeps>): AdminUIDeps {
335
335
  add: async () => {
336
336
  throw new Error("not implemented");
337
337
  },
338
+ remove: async () => {},
338
339
  },
339
340
  agentMemberService: {
340
341
  listByEmail: async () => [],
@@ -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 () => [],