@app-vitals/agent-admin 1.32.0 → 1.33.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.
@@ -4547,7 +4547,7 @@
4547
4547
  "/agents/{id}/repos/{owner}/{name}": {
4548
4548
  "delete": {
4549
4549
  "summary": "Remove a repo from an agent",
4550
- "description": "Admin, the agent's own key, or platform.ops. Removes one `owner/name` repo from the agent's `repos`, preserving the order of the rest. 404 when the agent does not have that repo. Returns the full updated agent.",
4550
+ "description": "Admin, the agent's own key, or platform.ops. Removes one `owner/name` repo from the agent's `repos`, preserving the order of the rest. The agent's open work on the repo is blocked through the optional open-work port (a failure there is a warning; the removal still succeeds), whoever the caller is; re-adding the repo never unblocks it. 404 when the agent does not have that repo. Returns the full updated agent.",
4551
4551
  "parameters": [
4552
4552
  {
4553
4553
  "schema": {
@@ -4611,6 +4611,110 @@
4611
4611
  }
4612
4612
  }
4613
4613
  },
4614
+ "/agents/{id}/repos/{owner}/{name}/removal-preview": {
4615
+ "get": {
4616
+ "summary": "Preview the open work blocked by removing a repo from an agent",
4617
+ "description": "Admin or session member. Read-only: lists the agent's open tasks and PRs that removing `owner/name` from its repos would block (via the optional open-work port); nothing is changed. `openWork` is empty when no port is wired; a port failure is reported in `warnings`. 404 when the agent does not have that repo.",
4618
+ "parameters": [
4619
+ {
4620
+ "schema": {
4621
+ "type": "string",
4622
+ "example": "clx1234567890"
4623
+ },
4624
+ "required": true,
4625
+ "name": "id",
4626
+ "in": "path"
4627
+ },
4628
+ {
4629
+ "schema": {
4630
+ "type": "string",
4631
+ "example": "my-org"
4632
+ },
4633
+ "required": true,
4634
+ "name": "owner",
4635
+ "in": "path"
4636
+ },
4637
+ {
4638
+ "schema": {
4639
+ "type": "string",
4640
+ "example": "my-repo"
4641
+ },
4642
+ "required": true,
4643
+ "name": "name",
4644
+ "in": "path"
4645
+ }
4646
+ ],
4647
+ "responses": {
4648
+ "200": {
4649
+ "description": "Open work that would be blocked",
4650
+ "content": {
4651
+ "application/json": {
4652
+ "schema": {
4653
+ "type": "object",
4654
+ "properties": {
4655
+ "repo": {
4656
+ "type": "string"
4657
+ },
4658
+ "openWork": {
4659
+ "type": "array",
4660
+ "items": {
4661
+ "type": "object",
4662
+ "properties": {
4663
+ "id": {
4664
+ "type": "string"
4665
+ },
4666
+ "repo": {
4667
+ "type": "string"
4668
+ },
4669
+ "title": {
4670
+ "type": "string"
4671
+ }
4672
+ },
4673
+ "required": [
4674
+ "id",
4675
+ "repo"
4676
+ ]
4677
+ }
4678
+ },
4679
+ "warnings": {
4680
+ "type": "array",
4681
+ "items": {
4682
+ "type": "string"
4683
+ }
4684
+ }
4685
+ },
4686
+ "required": [
4687
+ "repo",
4688
+ "openWork",
4689
+ "warnings"
4690
+ ]
4691
+ }
4692
+ }
4693
+ }
4694
+ },
4695
+ "403": {
4696
+ "description": "Forbidden",
4697
+ "content": {
4698
+ "application/json": {
4699
+ "schema": {
4700
+ "$ref": "#/components/schemas/Error"
4701
+ }
4702
+ }
4703
+ }
4704
+ },
4705
+ "404": {
4706
+ "description": "Agent or repo not found",
4707
+ "content": {
4708
+ "application/json": {
4709
+ "schema": {
4710
+ "$ref": "#/components/schemas/Error"
4711
+ }
4712
+ }
4713
+ }
4714
+ }
4715
+ }
4716
+ }
4717
+ },
4614
4718
  "/agents": {
4615
4719
  "get": {
4616
4720
  "summary": "List all agents",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.32.0",
3
+ "version": "1.33.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.32.0",
45
+ "@app-vitals/agent-lib": "1.33.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -491,6 +491,9 @@ export async function startAdmin(
491
491
  const adminApiApp = createAdminApp({
492
492
  githubAccessPreview,
493
493
  githubReconcile,
494
+ ...(resolvedExtensions.openWork
495
+ ? { openWork: resolvedExtensions.openWork }
496
+ : {}),
494
497
  githubInstallationRepos,
495
498
  agentService,
496
499
  agentEnvService,
@@ -34,6 +34,8 @@ import {
34
34
  fakeOpenWork,
35
35
  fakePrisma,
36
36
  } from "./github-reconcile-wiring.unit.test.ts";
37
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
38
+ import { repoRemovedFromAgentBlockReason } from "./repo-removal-open-work.ts";
37
39
  import type { SpecialtyType } from "./specialty-types.ts";
38
40
  import { identityCrypto } from "./token-crypto.ts";
39
41
 
@@ -6045,6 +6047,224 @@ describe("admin API — POST/DELETE /agents/:id/repos", () => {
6045
6047
  });
6046
6048
  });
6047
6049
 
6050
+ // ─── Repo removal blocks open work (IRM-1.7) ─────────────────────────────────
6051
+
6052
+ describe("admin API — repo removal blocks open work", () => {
6053
+ const MEMBER_EMAIL = "member@example.com";
6054
+ const ADMIN_KEY = "irm-admin-key";
6055
+ const ITEMS = [{ id: "T-1", repo: "a/one", title: "work" }];
6056
+ const makeApp = (initial: string[], port?: Partial<OpenWorkPort> | null) => {
6057
+ let repos = [...initial];
6058
+ const calls: unknown[][] = [];
6059
+ const base = makeMockDeps();
6060
+ const detail = () => ({
6061
+ id: AGENT_ID,
6062
+ name: "Existing Agent",
6063
+ slackId: null,
6064
+ selfHosted: false,
6065
+ repos: [...repos],
6066
+ reviewAuthorAllowlist: [],
6067
+ patchAuthorAllowlist: [],
6068
+ restrictSlackToMembers: false,
6069
+ specialty: "coding",
6070
+ createdAt: new Date("2024-01-01"),
6071
+ updatedAt: new Date("2024-01-01"),
6072
+ missingRequiredEnv: [],
6073
+ });
6074
+ const openWork: OpenWorkPort | undefined =
6075
+ port === null
6076
+ ? undefined
6077
+ : {
6078
+ listOpenWork: async (...a) => {
6079
+ calls.push(["list", ...a]);
6080
+ return ITEMS;
6081
+ },
6082
+ blockOpenWork: async (...a) => {
6083
+ calls.push(["block", ...a]);
6084
+ },
6085
+ ...port,
6086
+ };
6087
+ const app = createAdminApp({
6088
+ ...base,
6089
+ ...(openWork ? { openWork } : {}),
6090
+ adminApiKeys: parseAdminApiKeys(`admin:${ADMIN_KEY}:*`),
6091
+ agentMemberService: {
6092
+ ...base.agentMemberService,
6093
+ exists: async (agentId: string, email: string) =>
6094
+ agentId === AGENT_ID && email === MEMBER_EMAIL,
6095
+ listByEmail: async (email: string) =>
6096
+ email === MEMBER_EMAIL
6097
+ ? [
6098
+ {
6099
+ id: "m1",
6100
+ agentId: AGENT_ID,
6101
+ email,
6102
+ createdAt: new Date("2024-01-01"),
6103
+ },
6104
+ ]
6105
+ : [],
6106
+ },
6107
+ agentService: {
6108
+ ...base.agentService,
6109
+ exists: async () => true,
6110
+ getDetail: async (id: string) => (id === AGENT_ID ? detail() : null),
6111
+ updateSelfHosted: async (_id: string, input: { repos?: string[] }) => {
6112
+ if (input.repos) repos = input.repos;
6113
+ return detail();
6114
+ },
6115
+ },
6116
+ });
6117
+ return { app, calls, repos: () => repos };
6118
+ };
6119
+ const adminCall = (
6120
+ app: ReturnType<typeof createAdminApp>,
6121
+ method: string,
6122
+ path: string,
6123
+ body?: unknown,
6124
+ ) =>
6125
+ app.request(path, {
6126
+ method,
6127
+ body: body === undefined ? undefined : JSON.stringify(body),
6128
+ headers: {
6129
+ "Content-Type": "application/json",
6130
+ Authorization: `Bearer ${ADMIN_KEY}`,
6131
+ },
6132
+ });
6133
+ const memberCall = async (
6134
+ app: ReturnType<typeof createAdminApp>,
6135
+ method: string,
6136
+ path: string,
6137
+ body?: unknown,
6138
+ ) => {
6139
+ const cookie = await sign(
6140
+ {
6141
+ isAdmin: false,
6142
+ userId: "user-m",
6143
+ email: MEMBER_EMAIL,
6144
+ iat: Math.floor(Date.now() / 1000),
6145
+ exp: Math.floor(Date.now() / 1000) + 3600,
6146
+ },
6147
+ SESSION_SECRET,
6148
+ "HS256",
6149
+ );
6150
+ return app.request(path, {
6151
+ method,
6152
+ body: body === undefined ? undefined : JSON.stringify(body),
6153
+ headers: {
6154
+ "Content-Type": "application/json",
6155
+ Cookie: `admin_session=${cookie}`,
6156
+ },
6157
+ });
6158
+ };
6159
+ const url = `/agents/${AGENT_ID}/repos`;
6160
+ const blockCall = (repo: string) => [
6161
+ "block",
6162
+ AGENT_ID,
6163
+ [repo],
6164
+ repoRemovedFromAgentBlockReason(repo),
6165
+ ];
6166
+
6167
+ it("DELETE as platform admin blocks open work with a reason naming the repo", async () => {
6168
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6169
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6170
+ expect(res.status).toBe(200);
6171
+ expect((await res.json()).repos).toEqual(["b/two"]);
6172
+ expect(calls).toEqual([blockCall("a/one")]);
6173
+ });
6174
+
6175
+ it("DELETE as a session member blocks open work too", async () => {
6176
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6177
+ const res = await memberCall(app, "DELETE", `${url}/a/one`);
6178
+ expect(res.status).toBe(200);
6179
+ expect(calls).toEqual([blockCall("a/one")]);
6180
+ });
6181
+
6182
+ it("a port failure is a warning and the removal still succeeds", async () => {
6183
+ const { app, repos } = makeApp(["a/one"], {
6184
+ blockOpenWork: async () => {
6185
+ throw new Error("store down");
6186
+ },
6187
+ });
6188
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6189
+ expect(res.status).toBe(200);
6190
+ const body = await res.json();
6191
+ expect(body.repos).toEqual([]);
6192
+ expect(body.warning).toContain("store down");
6193
+ expect(repos()).toEqual([]);
6194
+ });
6195
+
6196
+ it("DELETE without a port just removes the repo", async () => {
6197
+ const { app } = makeApp(["a/one"], null);
6198
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6199
+ expect(res.status).toBe(200);
6200
+ expect((await res.json()).warning).toBeUndefined();
6201
+ });
6202
+
6203
+ it("PATCH that drops repos blocks only the dropped ones", async () => {
6204
+ const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6205
+ const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6206
+ repos: ["b/two"],
6207
+ });
6208
+ expect(res.status).toBe(200);
6209
+ expect(calls).toEqual([blockCall("a/one"), blockCall("c/three")]);
6210
+ });
6211
+
6212
+ it("adding a repo (POST, or PATCH that only adds) never touches open work", async () => {
6213
+ const { app, calls } = makeApp(["a/one"]);
6214
+ expect(
6215
+ (await adminCall(app, "POST", url, { repos: ["b/two"] })).status,
6216
+ ).toBe(200);
6217
+ expect(
6218
+ (
6219
+ await adminCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6220
+ repos: ["a/one", "b/two", "c/three"],
6221
+ })
6222
+ ).status,
6223
+ ).toBe(200);
6224
+ expect(calls).toEqual([]);
6225
+ });
6226
+
6227
+ it("preview lists open work for admin and member without changing anything", async () => {
6228
+ const { app, calls, repos } = makeApp(["a/one", "b/two"]);
6229
+ for (const res of [
6230
+ await adminCall(app, "GET", `${url}/a/one/removal-preview`),
6231
+ await memberCall(app, "GET", `${url}/a/one/removal-preview`),
6232
+ ]) {
6233
+ expect(res.status).toBe(200);
6234
+ expect(await res.json()).toEqual({
6235
+ repo: "a/one",
6236
+ openWork: ITEMS,
6237
+ warnings: [],
6238
+ });
6239
+ }
6240
+ expect(calls.every((c) => c[0] === "list")).toBe(true);
6241
+ expect(repos()).toEqual(["a/one", "b/two"]);
6242
+ });
6243
+
6244
+ it("preview is empty with no port, warns on a port failure, 404s for a repo the agent lacks", async () => {
6245
+ const none = makeApp(["a/one"], null);
6246
+ expect(
6247
+ await (
6248
+ await adminCall(none.app, "GET", `${url}/a/one/removal-preview`)
6249
+ ).json(),
6250
+ ).toEqual({ repo: "a/one", openWork: [], warnings: [] });
6251
+ const failing = makeApp(["a/one"], {
6252
+ listOpenWork: async () => {
6253
+ throw new Error("nope");
6254
+ },
6255
+ });
6256
+ const body = await (
6257
+ await adminCall(failing.app, "GET", `${url}/a/one/removal-preview`)
6258
+ ).json();
6259
+ expect(body.openWork).toEqual([]);
6260
+ expect(body.warnings[0]).toContain("nope");
6261
+ expect(
6262
+ (await adminCall(failing.app, "GET", `${url}/z/nope/removal-preview`))
6263
+ .status,
6264
+ ).toBe(404);
6265
+ });
6266
+ });
6267
+
6048
6268
  // ─── Platform scopes (COS-28.1) ─────────────────────────────────────────────
6049
6269
 
6050
6270
  describe("platform.read / platform.ops keys over the real route table", () => {
package/src/agents-api.ts CHANGED
@@ -167,6 +167,11 @@ import {
167
167
  } from "./openapi-schemas.ts";
168
168
  import type { InstallationReposService } from "./installation-repos-service.ts";
169
169
  import type { ReconcileApplyService } from "./reconcile-apply-service.ts";
170
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
171
+ import {
172
+ blockRepoRemovalWork,
173
+ previewRepoRemovalWork,
174
+ } from "./repo-removal-open-work.ts";
170
175
  import type { SelfServeConfig } from "./self-serve-config.ts";
171
176
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
172
177
  import type { SpecialtyTypeResolver } from "./specialty-types.ts";
@@ -270,6 +275,13 @@ export interface AdminDeps {
270
275
  * `skipped`.
271
276
  */
272
277
  githubReconcile?: Pick<ReconcileApplyService, "planWithOpenWork" | "apply">;
278
+ /**
279
+ * IRM-1.7: optional host-supplied open-work port. When an agent's own repos
280
+ * lose a repo (DELETE /agents/{id}/repos/{owner}/{name} or a PATCH that
281
+ * drops repos) its open work there is blocked; absent means nothing is
282
+ * listed or blocked.
283
+ */
284
+ openWork?: OpenWorkPort;
273
285
  /**
274
286
  * IRM-1.2: backs the admin-only /agents/:id/github-installation/repos
275
287
  * routes. Optional (additive); absent means the enterprise Apps are not
@@ -903,7 +915,7 @@ const removeAgentRepoRoute = createRoute({
903
915
  path: "/agents/{id}/repos/{owner}/{name}",
904
916
  summary: "Remove a repo from an agent",
905
917
  description:
906
- "Admin, the agent's own key, or platform.ops. Removes one `owner/name` repo from the agent's `repos`, preserving the order of the rest. 404 when the agent does not have that repo. Returns the full updated agent.",
918
+ "Admin, the agent's own key, or platform.ops. Removes one `owner/name` repo from the agent's `repos`, preserving the order of the rest. The agent's open work on the repo is blocked through the optional open-work port (a failure there is a warning; the removal still succeeds), whoever the caller is; re-adding the repo never unblocks it. 404 when the agent does not have that repo. Returns the full updated agent.",
907
919
  request: { params: AgentRepoParamSchema },
908
920
  responses: {
909
921
  200: {
@@ -915,6 +927,37 @@ const removeAgentRepoRoute = createRoute({
915
927
  },
916
928
  });
917
929
 
930
+ const repoRemovalPreviewRoute = createRoute({
931
+ method: "get",
932
+ path: "/agents/{id}/repos/{owner}/{name}/removal-preview",
933
+ summary: "Preview the open work blocked by removing a repo from an agent",
934
+ description:
935
+ "Admin or session member. Read-only: lists the agent's open tasks and PRs that removing `owner/name` from its repos would block (via the optional open-work port); nothing is changed. `openWork` is empty when no port is wired; a port failure is reported in `warnings`. 404 when the agent does not have that repo.",
936
+ request: { params: AgentRepoParamSchema },
937
+ responses: {
938
+ 200: {
939
+ description: "Open work that would be blocked",
940
+ content: {
941
+ "application/json": {
942
+ schema: z.object({
943
+ repo: z.string(),
944
+ openWork: z.array(
945
+ z.object({
946
+ id: z.string(),
947
+ repo: z.string(),
948
+ title: z.string().optional(),
949
+ }),
950
+ ),
951
+ warnings: z.array(z.string()),
952
+ }),
953
+ },
954
+ },
955
+ },
956
+ 403: { description: "Forbidden", ...jsonError },
957
+ 404: { description: "Agent or repo not found", ...jsonError },
958
+ },
959
+ });
960
+
918
961
  const deleteAgentRoute = createRoute({
919
962
  method: "delete",
920
963
  path: "/agents/{id}",
@@ -2233,6 +2276,12 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2233
2276
  if (collision) {
2234
2277
  throw new BadRequestError(collision);
2235
2278
  }
2279
+ const droppedRepos =
2280
+ body.repos !== undefined
2281
+ ? ((await agentService.getDetail(agentId))?.repos ?? []).filter(
2282
+ (r) => !body.repos?.includes(r),
2283
+ )
2284
+ : [];
2236
2285
  const agent = await agentService
2237
2286
  .updateSelfHosted(agentId, {
2238
2287
  selfHosted: body.selfHosted,
@@ -2339,8 +2388,19 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2339
2388
  );
2340
2389
  }
2341
2390
  }
2391
+ const blockWarnings = await blockRepoRemovalWork(
2392
+ deps.openWork,
2393
+ agentId,
2394
+ droppedRepos,
2395
+ );
2342
2396
  const warning =
2343
- [slackWarning, reconcileWarning, specialtyWarning, podSaWarning]
2397
+ [
2398
+ slackWarning,
2399
+ reconcileWarning,
2400
+ specialtyWarning,
2401
+ podSaWarning,
2402
+ ...blockWarnings,
2403
+ ]
2344
2404
  .filter(Boolean)
2345
2405
  .join("; ") || undefined;
2346
2406
  return c.json(serializeAgent(agent, warning), 200);
@@ -2392,7 +2452,32 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2392
2452
  selfHosted: current.selfHosted,
2393
2453
  repos: current.repos.filter((r) => r !== repo),
2394
2454
  });
2395
- return c.json(serializeAgent(agent), 200);
2455
+ const warning =
2456
+ (await blockRepoRemovalWork(deps.openWork, agentId, [repo])).join("; ") ||
2457
+ undefined;
2458
+ return c.json(serializeAgent(agent, warning), 200);
2459
+ });
2460
+
2461
+ // GET /agents/:id/repos/:owner/:name/removal-preview — read-only.
2462
+ app.openapi(repoRemovalPreviewRoute, async (c) => {
2463
+ if (!isAdminOrSessionMember(c)) {
2464
+ throw new ForbiddenError("Admin access required to preview repo removal");
2465
+ }
2466
+ const { id: agentId, owner, name } = c.req.valid("param");
2467
+ const current = await agentService.getDetail(agentId);
2468
+ if (!current) {
2469
+ throw new NotFoundError(`agent ${agentId} not found`);
2470
+ }
2471
+ const repo = `${owner}/${name}`;
2472
+ if (!current.repos.includes(repo)) {
2473
+ throw new NotFoundError(`agent ${agentId} does not have repo ${repo}`);
2474
+ }
2475
+ const { openWork, warnings } = await previewRepoRemovalWork(
2476
+ deps.openWork,
2477
+ agentId,
2478
+ [repo],
2479
+ );
2480
+ return c.json({ repo, openWork, warnings }, 200);
2396
2481
  });
2397
2482
 
2398
2483
  // DELETE /agents/:id — delete an agent and tear down its workload (admin only)
@@ -0,0 +1,59 @@
1
+ /**
2
+ * admin/src/repo-removal-open-work.ts
3
+ * Shared preview + block logic for open work on a repo removed from an agent's
4
+ * own repos (IRM-1.7; reused by IRM-1.3). Both helpers are no-ops without a
5
+ * port, and a port failure is returned as a warning, never thrown, so the
6
+ * removal itself always succeeds. Re-adding a repo never unblocks anything.
7
+ */
8
+
9
+ import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
10
+
11
+ export function repoRemovedFromAgentBlockReason(repo: string): string {
12
+ return `repo ${repo} was removed from the agent's repos`;
13
+ }
14
+
15
+ export interface RepoRemovalPreview {
16
+ openWork: OpenWorkItem[];
17
+ warnings: string[];
18
+ }
19
+
20
+ /** Read-only: the open work that removing `repos` would block. */
21
+ export async function previewRepoRemovalWork(
22
+ port: OpenWorkPort | undefined,
23
+ agentId: string,
24
+ repos: readonly string[],
25
+ ): Promise<RepoRemovalPreview> {
26
+ if (!port || repos.length === 0) return { openWork: [], warnings: [] };
27
+ try {
28
+ return { openWork: await port.listOpenWork(agentId, repos), warnings: [] };
29
+ } catch (err) {
30
+ const msg = err instanceof Error ? err.message : String(err);
31
+ return {
32
+ openWork: [],
33
+ warnings: [`open work could not be listed: ${msg}`],
34
+ };
35
+ }
36
+ }
37
+
38
+ /** Blocks the agent's open work on each removed repo; returns warnings. */
39
+ export async function blockRepoRemovalWork(
40
+ port: OpenWorkPort | undefined,
41
+ agentId: string,
42
+ repos: readonly string[],
43
+ ): Promise<string[]> {
44
+ if (!port) return [];
45
+ const warnings: string[] = [];
46
+ for (const repo of repos) {
47
+ try {
48
+ await port.blockOpenWork(
49
+ agentId,
50
+ [repo],
51
+ repoRemovedFromAgentBlockReason(repo),
52
+ );
53
+ } catch (err) {
54
+ const msg = err instanceof Error ? err.message : String(err);
55
+ warnings.push(`open work for ${repo} was not blocked: ${msg}`);
56
+ }
57
+ }
58
+ return warnings;
59
+ }
@@ -0,0 +1,81 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
3
+ import {
4
+ blockRepoRemovalWork,
5
+ previewRepoRemovalWork,
6
+ repoRemovedFromAgentBlockReason,
7
+ } from "./repo-removal-open-work.ts";
8
+
9
+ const ITEMS = [{ id: "T-1", repo: "a/one", title: "t" }];
10
+
11
+ function port(over: Partial<OpenWorkPort> = {}) {
12
+ const calls: unknown[][] = [];
13
+ const p: OpenWorkPort = {
14
+ listOpenWork: async (...a) => {
15
+ calls.push(["list", ...a]);
16
+ return ITEMS;
17
+ },
18
+ blockOpenWork: async (...a) => {
19
+ calls.push(["block", ...a]);
20
+ },
21
+ ...over,
22
+ };
23
+ return { p, calls };
24
+ }
25
+
26
+ describe("previewRepoRemovalWork", () => {
27
+ it("lists open work from the port", async () => {
28
+ const { p } = port();
29
+ expect(await previewRepoRemovalWork(p, "ag", ["a/one"])).toEqual({
30
+ openWork: ITEMS,
31
+ warnings: [],
32
+ });
33
+ });
34
+ it("is empty without a port", async () => {
35
+ expect(await previewRepoRemovalWork(undefined, "ag", ["a/one"])).toEqual({
36
+ openWork: [],
37
+ warnings: [],
38
+ });
39
+ });
40
+ it("turns a port failure into a warning", async () => {
41
+ const { p } = port({
42
+ listOpenWork: async () => {
43
+ throw new Error("down");
44
+ },
45
+ });
46
+ const r = await previewRepoRemovalWork(p, "ag", ["a/one"]);
47
+ expect(r.openWork).toEqual([]);
48
+ expect(r.warnings[0]).toContain("down");
49
+ });
50
+ it("never blocks", async () => {
51
+ const { p, calls } = port();
52
+ await previewRepoRemovalWork(p, "ag", ["a/one"]);
53
+ expect(calls.some((c) => c[0] === "block")).toBe(false);
54
+ });
55
+ });
56
+
57
+ describe("blockRepoRemovalWork", () => {
58
+ it("blocks each repo with a reason naming it", async () => {
59
+ const { p, calls } = port();
60
+ expect(await blockRepoRemovalWork(p, "ag", ["a/one", "b/two"])).toEqual([]);
61
+ expect(calls).toEqual([
62
+ ["block", "ag", ["a/one"], repoRemovedFromAgentBlockReason("a/one")],
63
+ ["block", "ag", ["b/two"], repoRemovedFromAgentBlockReason("b/two")],
64
+ ]);
65
+ expect(repoRemovedFromAgentBlockReason("a/one")).toContain("a/one");
66
+ });
67
+ it("does nothing without a port", async () => {
68
+ expect(await blockRepoRemovalWork(undefined, "ag", ["a/one"])).toEqual([]);
69
+ });
70
+ it("warns on port failure and continues with the next repo", async () => {
71
+ let n = 0;
72
+ const { p } = port({
73
+ blockOpenWork: async () => {
74
+ if (n++ === 0) throw new Error("boom");
75
+ },
76
+ });
77
+ const w = await blockRepoRemovalWork(p, "ag", ["a/one", "b/two"]);
78
+ expect(w).toHaveLength(1);
79
+ expect(w[0]).toContain("a/one");
80
+ });
81
+ });