@app-vitals/agent-admin 1.31.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.
package/src/agents-api.ts CHANGED
@@ -101,6 +101,7 @@ import {
101
101
  } from "./cron-run-transcripts.ts";
102
102
  import {
103
103
  ApiError,
104
+ BadGatewayError,
104
105
  BadRequestError,
105
106
  ConflictError,
106
107
  ForbiddenError,
@@ -164,7 +165,13 @@ import {
164
165
  UpsertAgentMarketplaceBodySchema,
165
166
  UpsertChatTokenDailyBodySchema,
166
167
  } from "./openapi-schemas.ts";
168
+ import type { InstallationReposService } from "./installation-repos-service.ts";
167
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";
168
175
  import type { SelfServeConfig } from "./self-serve-config.ts";
169
176
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
170
177
  import type { SpecialtyTypeResolver } from "./specialty-types.ts";
@@ -268,6 +275,22 @@ export interface AdminDeps {
268
275
  * `skipped`.
269
276
  */
270
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;
285
+ /**
286
+ * IRM-1.2: backs the admin-only /agents/:id/github-installation/repos
287
+ * routes. Optional (additive); absent means the enterprise Apps are not
288
+ * wired and the routes answer 503.
289
+ */
290
+ githubInstallationRepos?: Pick<
291
+ InstallationReposService,
292
+ "list" | "add" | "remove"
293
+ >;
271
294
  /**
272
295
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
273
296
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -679,6 +702,43 @@ const GithubReconcileApplyResultSchema = z
679
702
  })
680
703
  .openapi("GithubReconcileApplyResult");
681
704
 
705
+ const InstallationReposBodySchema = z
706
+ .object({
707
+ repos: z.array(RepoFullNameSchema).min(1).max(100).openapi({
708
+ description:
709
+ "Repos (owner/repo) to change on the agent App's installation.",
710
+ }),
711
+ })
712
+ .openapi("GithubInstallationReposBody");
713
+
714
+ const GithubInstallationReposListSchema = z
715
+ .object({
716
+ appId: z.number().int(),
717
+ orgs: z.array(
718
+ z.object({
719
+ org: z.string(),
720
+ repos: z.array(
721
+ z.object({
722
+ fullName: z.string(),
723
+ userCanPush: z.boolean().optional().openapi({
724
+ description:
725
+ "Whether the agent's bound GitHub user can push. Omitted when no username is bound or the org's access lookup is incomplete; never reported as false for unknown.",
726
+ }),
727
+ }),
728
+ ),
729
+ }),
730
+ ),
731
+ })
732
+ .openapi("GithubInstallationReposList");
733
+
734
+ const GithubInstallationReposChangeSchema = z
735
+ .object({
736
+ status: z.enum(["applied"]),
737
+ auditId: z.string(),
738
+ repos: z.array(z.string()),
739
+ })
740
+ .openapi("GithubInstallationReposChange");
741
+
682
742
  // ─── Route definitions ──────────────────────────────────────────────────────────
683
743
 
684
744
  const reconcileAgentsRoute = createRoute({
@@ -855,7 +915,7 @@ const removeAgentRepoRoute = createRoute({
855
915
  path: "/agents/{id}/repos/{owner}/{name}",
856
916
  summary: "Remove a repo from an agent",
857
917
  description:
858
- "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.",
859
919
  request: { params: AgentRepoParamSchema },
860
920
  responses: {
861
921
  200: {
@@ -867,6 +927,37 @@ const removeAgentRepoRoute = createRoute({
867
927
  },
868
928
  });
869
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
+
870
961
  const deleteAgentRoute = createRoute({
871
962
  method: "delete",
872
963
  path: "/agents/{id}",
@@ -1630,6 +1721,88 @@ const githubReconcileApplyRoute = createRoute({
1630
1721
  },
1631
1722
  });
1632
1723
 
1724
+ const installationReposErrors = {
1725
+ 401: { description: "Unauthorized", ...jsonError },
1726
+ 403: { description: "Platform admin required", ...jsonError },
1727
+ 404: { description: "Agent not found", ...jsonError },
1728
+ 422: {
1729
+ description: "Agent has no GH_APP_ID (its own GitHub App is not set up)",
1730
+ ...jsonError,
1731
+ },
1732
+ 503: { description: "GitHub Apps are not configured", ...jsonError },
1733
+ };
1734
+
1735
+ const listInstallationReposRoute = createRoute({
1736
+ method: "get",
1737
+ path: "/agents/{id}/github-installation/repos",
1738
+ summary: "List the repos on the agent App's installation",
1739
+ description:
1740
+ "Platform-admin only (session members, ops keys and agent keys get 403). Per org the agent's own GitHub App (its GH_APP_ID) is installed on, lists the installation's repos. When the agent has a bound githubUsername, each repo carries `userCanPush` from the access lookup only when that org's lookup result is complete; otherwise the field is omitted (never false). 404 for an unknown agent; 422 when the agent has no GH_APP_ID.",
1741
+ request: { params: AgentIdParamSchema },
1742
+ responses: {
1743
+ 200: {
1744
+ description: "Installation repos",
1745
+ content: {
1746
+ "application/json": { schema: GithubInstallationReposListSchema },
1747
+ },
1748
+ },
1749
+ ...installationReposErrors,
1750
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1751
+ },
1752
+ });
1753
+
1754
+ const addInstallationReposRoute = createRoute({
1755
+ method: "post",
1756
+ path: "/agents/{id}/github-installation/repos",
1757
+ summary: "Add repos to the agent App's installation",
1758
+ description:
1759
+ "Platform-admin only. Grants the agent's own GitHub App installation access to the named repos, with no plan step; the agent's configured repos are not changed. Writes one audit entry (GitHubReconcileAudit, planHash `direct:add`) recording the caller and repos. 404 unknown agent; 422 no GH_APP_ID; 409 when the App is not installed on a repo's org (nothing is changed or audited); 502 when GitHub refuses (a failed audit entry is written).",
1760
+ request: {
1761
+ params: AgentIdParamSchema,
1762
+ body: {
1763
+ required: true,
1764
+ content: { "application/json": { schema: InstallationReposBodySchema } },
1765
+ },
1766
+ },
1767
+ responses: {
1768
+ 200: {
1769
+ description: "Repos added",
1770
+ content: {
1771
+ "application/json": { schema: GithubInstallationReposChangeSchema },
1772
+ },
1773
+ },
1774
+ ...installationReposErrors,
1775
+ 409: { description: "Agent App not installed on the org", ...jsonError },
1776
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1777
+ },
1778
+ });
1779
+
1780
+ const removeInstallationReposRoute = createRoute({
1781
+ method: "post",
1782
+ path: "/agents/{id}/github-installation/repos/remove",
1783
+ summary: "Remove repos from the agent App's installation",
1784
+ description:
1785
+ "Platform-admin only. Revokes the agent's own GitHub App installation access to the named repos, with no plan step; the agent's configured repos are not changed. Writes one audit entry (GitHubReconcileAudit, planHash `direct:remove`) recording the caller and repos. Same errors as the add route.",
1786
+ request: {
1787
+ params: AgentIdParamSchema,
1788
+ body: {
1789
+ required: true,
1790
+ content: { "application/json": { schema: InstallationReposBodySchema } },
1791
+ },
1792
+ },
1793
+ responses: {
1794
+ 200: {
1795
+ description: "Repos removed",
1796
+ content: {
1797
+ "application/json": { schema: GithubInstallationReposChangeSchema },
1798
+ },
1799
+ },
1800
+ ...installationReposErrors,
1801
+ 409: { description: "Agent App not installed on the org", ...jsonError },
1802
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1803
+ },
1804
+ });
1805
+
1633
1806
  /** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
1634
1807
  export const cronRunStatsQuerySchema = z
1635
1808
  .object({
@@ -2103,6 +2276,12 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2103
2276
  if (collision) {
2104
2277
  throw new BadRequestError(collision);
2105
2278
  }
2279
+ const droppedRepos =
2280
+ body.repos !== undefined
2281
+ ? ((await agentService.getDetail(agentId))?.repos ?? []).filter(
2282
+ (r) => !body.repos?.includes(r),
2283
+ )
2284
+ : [];
2106
2285
  const agent = await agentService
2107
2286
  .updateSelfHosted(agentId, {
2108
2287
  selfHosted: body.selfHosted,
@@ -2209,8 +2388,19 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2209
2388
  );
2210
2389
  }
2211
2390
  }
2391
+ const blockWarnings = await blockRepoRemovalWork(
2392
+ deps.openWork,
2393
+ agentId,
2394
+ droppedRepos,
2395
+ );
2212
2396
  const warning =
2213
- [slackWarning, reconcileWarning, specialtyWarning, podSaWarning]
2397
+ [
2398
+ slackWarning,
2399
+ reconcileWarning,
2400
+ specialtyWarning,
2401
+ podSaWarning,
2402
+ ...blockWarnings,
2403
+ ]
2214
2404
  .filter(Boolean)
2215
2405
  .join("; ") || undefined;
2216
2406
  return c.json(serializeAgent(agent, warning), 200);
@@ -2262,7 +2452,32 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2262
2452
  selfHosted: current.selfHosted,
2263
2453
  repos: current.repos.filter((r) => r !== repo),
2264
2454
  });
2265
- 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);
2266
2481
  });
2267
2482
 
2268
2483
  // DELETE /agents/:id — delete an agent and tear down its workload (admin only)
@@ -3207,6 +3422,100 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3207
3422
  }
3208
3423
  });
3209
3424
 
3425
+ // /agents/:id/github-installation/repos — IRM-1.2. Platform admin only;
3426
+ // responses carry repo names and ids, never tokens.
3427
+ const installationReposService = (c: {
3428
+ get(k: "isAdmin"): boolean | undefined;
3429
+ }) => {
3430
+ if (c.get("isAdmin") !== true) {
3431
+ throw new ForbiddenError(
3432
+ "Admin access required to manage installation repos",
3433
+ );
3434
+ }
3435
+ const svc = deps.githubInstallationRepos;
3436
+ if (!svc) throw new ApiError(503, GITHUB_RECONCILE_UNCONFIGURED);
3437
+ return svc;
3438
+ };
3439
+ const installationFailure = (
3440
+ agentId: string,
3441
+ result:
3442
+ | { status: "agent_not_found" }
3443
+ | { status: "no_app_id"; reason: string }
3444
+ | { status: "not_installed"; reason: string },
3445
+ ): never => {
3446
+ if (result.status === "agent_not_found") {
3447
+ throw new NotFoundError(`agent ${agentId} not found`);
3448
+ }
3449
+ if (result.status === "no_app_id") {
3450
+ throw new UnprocessableEntityError(result.reason);
3451
+ }
3452
+ throw new ConflictError(result.reason);
3453
+ };
3454
+
3455
+ app.openapi(listInstallationReposRoute, async (c) => {
3456
+ const svc = installationReposService(c);
3457
+ const { id: agentId } = c.req.valid("param");
3458
+ const result = await svc.list(agentId);
3459
+ if (result.status !== "ok") return installationFailure(agentId, result);
3460
+ return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3461
+ });
3462
+
3463
+ const changeInstallationRepos = async (
3464
+ kind: "add" | "remove",
3465
+ c: {
3466
+ get(k: "isAdmin"): boolean | undefined;
3467
+ get(k: "caller"): { name: string } | undefined;
3468
+ },
3469
+ agentId: string,
3470
+ repos: string[],
3471
+ ) => {
3472
+ const svc = installationReposService(c);
3473
+ const caller = c.get("caller")?.name ?? "anonymous";
3474
+ const result = await svc[kind](agentId, caller, repos);
3475
+ if (
3476
+ result.status === "agent_not_found" ||
3477
+ result.status === "no_app_id" ||
3478
+ result.status === "not_installed"
3479
+ ) {
3480
+ return installationFailure(agentId, result);
3481
+ }
3482
+ console.log(
3483
+ `[agents-api] github installation repos ${kind} ${result.status}: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3484
+ );
3485
+ if (result.status === "failed") {
3486
+ throw new BadGatewayError(
3487
+ `GitHub refused the ${kind}; audit ${result.auditId} records the failure: ${result.error}`,
3488
+ );
3489
+ }
3490
+ return {
3491
+ status: "applied" as const,
3492
+ auditId: result.auditId,
3493
+ repos: result.repos,
3494
+ };
3495
+ };
3496
+ app.openapi(addInstallationReposRoute, async (c) =>
3497
+ c.json(
3498
+ await changeInstallationRepos(
3499
+ "add",
3500
+ c,
3501
+ c.req.valid("param").id,
3502
+ c.req.valid("json").repos,
3503
+ ),
3504
+ 200,
3505
+ ),
3506
+ );
3507
+ app.openapi(removeInstallationReposRoute, async (c) =>
3508
+ c.json(
3509
+ await changeInstallationRepos(
3510
+ "remove",
3511
+ c,
3512
+ c.req.valid("param").id,
3513
+ c.req.valid("json").repos,
3514
+ ),
3515
+ 200,
3516
+ ),
3517
+ );
3518
+
3210
3519
  // GET /agents/:id/github-installations — latest snapshot, 404 if none yet
3211
3520
  app.openapi(getGitHubInstallationsRoute, async (c) => {
3212
3521
  const { id: agentId } = c.req.valid("param");
@@ -40,10 +40,11 @@ describeOrSkip("github reconcile routes (integration)", () => {
40
40
  let prisma: PrismaClient;
41
41
  let pushable: string[];
42
42
  let installed: string[];
43
+ let envService: AgentEnvService;
43
44
 
44
45
  const buildApp = () => {
45
46
  const reconcile = new ReconcileApplyService({
46
- agents: new PrismaReconcileAgents(prisma),
47
+ agents: new PrismaReconcileAgents(prisma, envService),
47
48
  access: async () => ({
48
49
  status: "ok",
49
50
  access: {
@@ -76,7 +77,7 @@ describeOrSkip("github reconcile routes (integration)", () => {
76
77
  });
77
78
  return createAdminApp({
78
79
  agentService: new AgentService(prisma),
79
- agentEnvService: new AgentEnvService(prisma, identityCrypto),
80
+ agentEnvService: envService,
80
81
  agentCronJobService: new AgentCronJobService(prisma),
81
82
  agentCronRunService: new AgentCronRunService(prisma),
82
83
  agentCronRunStatsService: new AgentCronRunStatsService(prisma),
@@ -124,6 +125,7 @@ describeOrSkip("github reconcile routes (integration)", () => {
124
125
 
125
126
  beforeEach(async () => {
126
127
  prisma = createAdminPrismaClient(TEST_DB as string);
128
+ envService = new AgentEnvService(prisma, identityCrypto);
127
129
  await prisma.gitHubReconcileAudit.deleteMany();
128
130
  await prisma.agentGitHubInstallationsSnapshot.deleteMany();
129
131
  await prisma.agentWorkQueueSnapshot.deleteMany();
@@ -147,6 +149,7 @@ describeOrSkip("github reconcile routes (integration)", () => {
147
149
  const agent = await prisma.agent.create({
148
150
  data: { name: "A", repos: ["acme/a", "acme/b"], githubUsername: "dev" },
149
151
  });
152
+ await envService.patch(agent.id, { GH_APP_ID: "42" });
150
153
  installed = ["acme/a", "acme/b"];
151
154
  pushable = ["acme/a"];
152
155
  const app = buildApp();
@@ -173,6 +176,7 @@ describeOrSkip("github reconcile routes (integration)", () => {
173
176
  const agent = await prisma.agent.create({
174
177
  data: { name: "A", repos, githubUsername: "dev" },
175
178
  });
179
+ await envService.patch(agent.id, { GH_APP_ID: "42" });
176
180
  installed = [...repos];
177
181
  pushable = ["acme/keep"];
178
182
  const app = buildApp();
@@ -2,12 +2,12 @@
2
2
  * admin/src/github-reconcile-wiring.ts
3
3
  * Composition of the GitHub reconcile service for admin boot (GHE-3.9).
4
4
  * Builds ReconcileApplyService from the stored enterprise Apps and an
5
- * optional host-supplied OpenWorkPort. Without an agent App id the reconcile
6
- * is not wired (routes report `skipped`); without an open-work port nothing is
7
- * listed or blocked.
5
+ * optional host-supplied OpenWorkPort. The agent App id comes from each agent's
6
+ * own stored GH_APP_ID; without an open-work port nothing is listed or blocked.
8
7
  */
9
8
 
10
9
  import type { PrismaClient } from "../prisma/client/client.ts";
10
+ import type { AgentEnvService } from "./agent-envs.ts";
11
11
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
12
12
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
13
13
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
@@ -19,14 +19,20 @@ import {
19
19
  ReconcileApplyService,
20
20
  type ReconcileInstallationPort,
21
21
  } from "./reconcile-apply-service.ts";
22
+ import {
23
+ createInstallationReposPort,
24
+ type InstalledOrgsClient,
25
+ InstallationReposService,
26
+ type InstallationReposPort,
27
+ } from "./installation-repos-service.ts";
22
28
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
23
29
 
24
30
  export interface GithubReconcileWiringDeps {
25
31
  prisma: PrismaClient;
26
32
  appService: Pick<GitHubEnterpriseAppService, "get" | "getPrivateKey">;
27
33
  access: GithubAccessPreviewFn;
28
- /** Numeric id of the agent App whose installations are reconciled. */
29
- agentAppId: number | undefined;
34
+ /** Reads each agent's stored GH_APP_ID (its own GitHub App). */
35
+ agentEnv: Pick<AgentEnvService, "getConfigBundle">;
30
36
  openWork?: OpenWorkPort;
31
37
  /** Test seam: replaces the installer-App-backed installation port. */
32
38
  installation?: ReconcileInstallationPort;
@@ -36,19 +42,13 @@ export interface GithubReconcileWiringDeps {
36
42
  now?: () => Date;
37
43
  }
38
44
 
39
- /** Parses SHIPWRIGHT_GITHUB_AGENT_APP_ID; unset or non-numeric -> undefined. */
40
- export function parseAgentAppId(raw: string | undefined): number | undefined {
41
- const n = Number(raw?.trim());
42
- return Number.isInteger(n) && n > 0 ? n : undefined;
43
- }
44
-
45
45
  /** Builds the installer client per call so key rotations are picked up. */
46
46
  function lazyInstallerClient(
47
47
  deps: Pick<
48
48
  GithubReconcileWiringDeps,
49
49
  "appService" | "fetchFn" | "apiBase" | "now"
50
50
  >,
51
- ): InstallationRepoClient {
51
+ ): InstallationRepoClient & InstalledOrgsClient {
52
52
  const client = async (): Promise<GithubEnterpriseClient> => {
53
53
  const [installer, privateKey] = await Promise.all([
54
54
  deps.appService.get("installer"),
@@ -67,6 +67,8 @@ function lazyInstallerClient(
67
67
  });
68
68
  };
69
69
  return {
70
+ listInstallableOrganizations: async () =>
71
+ (await client()).listInstallableOrganizations(),
70
72
  listOrgInstallations: async (org) =>
71
73
  (await client()).listOrgInstallations(org),
72
74
  listInstallationRepositories: async (org, id) =>
@@ -78,18 +80,43 @@ function lazyInstallerClient(
78
80
  };
79
81
  }
80
82
 
81
- /** The `githubReconcile` dep for createAdminApp, or undefined when unwired. */
83
+ /**
84
+ * The `githubReconcile` dep for createAdminApp. The agent App id is resolved
85
+ * per agent from its stored GH_APP_ID, so this is always wired.
86
+ */
82
87
  export function createGithubReconcile(
83
88
  deps: GithubReconcileWiringDeps,
84
- ): ReconcileApplyService | undefined {
85
- if (deps.agentAppId === undefined) return undefined;
89
+ ): ReconcileApplyService {
86
90
  return new ReconcileApplyService({
87
- agents: new PrismaReconcileAgents(deps.prisma),
91
+ agents: new PrismaReconcileAgents(deps.prisma, deps.agentEnv),
88
92
  access: deps.access,
89
93
  installation:
90
- deps.installation ??
91
- createInstallationPort(lazyInstallerClient(deps), deps.agentAppId),
94
+ deps.installation ?? createInstallationPort(lazyInstallerClient(deps)),
92
95
  audit: new PrismaReconcileAudit(deps.prisma),
93
96
  ...(deps.openWork ? { openWork: deps.openWork } : {}),
94
97
  });
95
98
  }
99
+
100
+ export interface InstallationReposWiringDeps extends GithubReconcileWiringDeps {
101
+ /** Test seam: replaces the installer-App-backed port. */
102
+ installationRepos?: InstallationReposPort;
103
+ }
104
+
105
+ /**
106
+ * The `githubInstallationRepos` dep for createAdminApp (IRM-1.2): direct
107
+ * list/add/remove on the agent App's installation, audited in the reconcile
108
+ * audit table.
109
+ */
110
+ export function createGithubInstallationRepos(
111
+ deps: InstallationReposWiringDeps,
112
+ ): InstallationReposService {
113
+ const client = lazyInstallerClient(deps);
114
+ return new InstallationReposService({
115
+ agents: new PrismaReconcileAgents(deps.prisma, deps.agentEnv),
116
+ access: deps.access,
117
+ installation:
118
+ deps.installationRepos ??
119
+ createInstallationReposPort(createInstallationPort(client), client),
120
+ audit: new PrismaReconcileAudit(deps.prisma),
121
+ });
122
+ }
@@ -1,10 +1,8 @@
1
1
  import { describe, expect, it } from "bun:test";
2
2
  import type { PrismaClient } from "../prisma/client/client.ts";
3
3
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
4
- import {
5
- createGithubReconcile,
6
- parseAgentAppId,
7
- } from "./github-reconcile-wiring.ts";
4
+ import { createGithubReconcile } from "./github-reconcile-wiring.ts";
5
+ import type { ReconcileInstallationPort } from "./reconcile-apply-service.ts";
8
6
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
9
7
 
10
8
  export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
@@ -70,7 +68,12 @@ export function fakeOpenWork() {
70
68
  return { port, calls };
71
69
  }
72
70
 
73
- const installation = {
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 = {
74
77
  listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
75
78
  addRepos: async () => {},
76
79
  removeRepos: async () => {},
@@ -82,7 +85,7 @@ const build = (openWork?: OpenWorkPort) => {
82
85
  prisma,
83
86
  appService: { get: async () => null, getPrivateKey: async () => null },
84
87
  access: accessFor(["acme/api"]),
85
- agentAppId: 42,
88
+ agentEnv: envWith({ GH_APP_ID: "42" }),
86
89
  installation,
87
90
  openWork,
88
91
  });
@@ -90,26 +93,47 @@ const build = (openWork?: OpenWorkPort) => {
90
93
  return { svc, state };
91
94
  };
92
95
 
93
- describe("parseAgentAppId", () => {
94
- it("parses a positive integer and rejects everything else", () => {
95
- expect(parseAgentAppId(" 123 ")).toBe(123);
96
- for (const bad of [undefined, "", "abc", "0", "-4", "1.5"]) {
97
- expect(parseAgentAppId(bad)).toBeUndefined();
98
- }
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);
99
116
  });
100
- });
101
117
 
102
- describe("createGithubReconcile", () => {
103
- it("is unwired without an agent App id", () => {
104
- const { prisma } = fakePrisma([]);
105
- expect(
106
- createGithubReconcile({
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({
107
127
  prisma,
108
128
  appService: { get: async () => null, getPrivateKey: async () => null },
109
129
  access: accessFor([]),
110
- agentAppId: undefined,
111
- }),
112
- ).toBeUndefined();
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
+ }
113
137
  });
114
138
 
115
139
  it("with a port: plan lists affected open work and apply blocks it", async () => {