@app-vitals/agent-admin 1.35.0 → 1.36.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.
Files changed (36) hide show
  1. package/openapi.platform.json +136 -766
  2. package/package.json +2 -2
  3. package/src/admin-boot.ts +4 -15
  4. package/src/admin-extension.ts +3 -3
  5. package/src/admin-ui-github-identity.smoke.test.ts +24 -116
  6. package/src/admin-ui-installation-repos-pages.ts +198 -231
  7. package/src/admin-ui-installation-repos-pages.unit.test.ts +199 -0
  8. package/src/admin-ui-installation-repos.smoke.test.ts +166 -173
  9. package/src/admin-ui-pages.ts +2 -2
  10. package/src/admin-ui.ts +103 -171
  11. package/src/agents-api.smoke.test.ts +195 -642
  12. package/src/agents-api.ts +86 -477
  13. package/src/github-enterprise-isolation.unit.test.ts +4 -4
  14. package/src/{github-reconcile-wiring.ts → github-installation-wiring.ts} +24 -46
  15. package/src/github-installation-wiring.unit.test.ts +115 -0
  16. package/src/github-installation.fixtures.ts +76 -0
  17. package/src/github-sync.ts +407 -0
  18. package/src/{lost-access-removal.unit.test.ts → github-sync.unit.test.ts} +220 -115
  19. package/src/installation-ports.integration.test.ts +89 -0
  20. package/src/installation-ports.ts +207 -0
  21. package/src/installation-ports.unit.test.ts +51 -0
  22. package/src/installation-repos-service.ts +10 -105
  23. package/src/installation-repos-service.unit.test.ts +5 -90
  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 -226
  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/lost-access-removal.ts +0 -333
  32. package/src/reconcile-apply-service.integration.test.ts +0 -271
  33. package/src/reconcile-apply-service.ts +0 -439
  34. package/src/reconcile-apply-service.unit.test.ts +0 -279
  35. package/src/reconcile-planner.ts +0 -264
  36. package/src/reconcile-planner.unit.test.ts +0 -274
package/src/agents-api.ts CHANGED
@@ -166,8 +166,7 @@ import {
166
166
  UpsertChatTokenDailyBodySchema,
167
167
  } from "./openapi-schemas.ts";
168
168
  import type { InstallationReposService } from "./installation-repos-service.ts";
169
- import type { LostAccessRemovalService } from "./lost-access-removal.ts";
170
- import type { ReconcileApplyService } from "./reconcile-apply-service.ts";
169
+ import type { GithubSyncService } from "./github-sync.ts";
171
170
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
172
171
  import {
173
172
  blockRepoRemovalWork,
@@ -270,12 +269,6 @@ export interface AdminDeps {
270
269
  * means the enterprise Apps are not wired, reported as `unconfigured`.
271
270
  */
272
271
  githubAccessPreview?: GithubAccessPreviewFn;
273
- /**
274
- * GHE-3.4: backs POST /agents/:id/github-reconcile/{plan,apply}. Optional
275
- * (additive); absent means the enterprise Apps are not wired, reported as
276
- * `skipped`.
277
- */
278
- githubReconcile?: Pick<ReconcileApplyService, "planWithOpenWork" | "apply">;
279
272
  /**
280
273
  * IRM-1.7: optional host-supplied open-work port. When an agent's own repos
281
274
  * lose a repo (DELETE /agents/{id}/repos/{owner}/{name} or a PATCH that
@@ -284,23 +277,17 @@ export interface AdminDeps {
284
277
  */
285
278
  openWork?: OpenWorkPort;
286
279
  /**
287
- * IRM-1.2: backs the admin-only /agents/:id/github-installation/repos
288
- * routes. Optional (additive); absent means the enterprise Apps are not
289
- * wired and the routes answer 503.
280
+ * IRM-1.2: backs the admin-only GET /agents/:id/github-installation/repos
281
+ * route. Optional (additive); absent means the enterprise Apps are not
282
+ * wired and the route answers 503.
290
283
  */
291
- githubInstallationRepos?: Pick<
292
- InstallationReposService,
293
- "list" | "add" | "remove"
294
- >;
284
+ githubInstallationRepos?: Pick<InstallationReposService, "list">;
295
285
  /**
296
- * IRM-1.3: backs the admin-only /agents/:id/github-lost-access/{preview,remove}
286
+ * IRM-3.1: backs the admin-only /agents/:id/github-sync/{preview,apply}
297
287
  * routes. Optional (additive); absent means the enterprise Apps are not
298
288
  * wired and the routes answer 503.
299
289
  */
300
- githubLostAccessRemoval?: Pick<
301
- LostAccessRemovalService,
302
- "preview" | "remove"
303
- >;
290
+ githubSync?: Pick<GithubSyncService, "preview" | "apply">;
304
291
  /**
305
292
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
306
293
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -631,96 +618,12 @@ const GithubAccessPreviewSchema = z
631
618
  })
632
619
  .openapi("GithubAccessPreview");
633
620
 
634
- const GITHUB_RECONCILE_UNCONFIGURED = "GitHub Apps are not configured";
621
+ const GITHUB_APPS_UNCONFIGURED = "GitHub Apps are not configured";
635
622
 
636
623
  const RepoFullNameSchema = z
637
624
  .string()
638
625
  .regex(/^[^/\s]+\/[^/\s]+$/, "must be owner/repo");
639
626
 
640
- const GithubReconcilePlanBodySchema = z
641
- .object({
642
- addRepos: z.array(RepoFullNameSchema).optional().openapi({
643
- description:
644
- "Repos (owner/repo) to explicitly add to the agent's config and installation.",
645
- }),
646
- })
647
- .openapi("GithubReconcilePlanBody");
648
-
649
- const GithubReconcileApplyBodySchema = z
650
- .object({
651
- planHash: z.string().min(1).openapi({
652
- description: "planHash of the plan the admin reviewed.",
653
- }),
654
- addRepos: z.array(RepoFullNameSchema).optional().openapi({
655
- description: "Must match the addRepos used when the plan was made.",
656
- }),
657
- confirmRemovals: z.boolean().optional().openapi({
658
- description: "Required when the plan removes more than 10 repos.",
659
- }),
660
- })
661
- .openapi("GithubReconcileApplyBody");
662
-
663
- const GithubReconcileDiffSchema = z.object({
664
- installationAdds: z.array(z.string()),
665
- installationRemoves: z.array(z.string()),
666
- configAdds: z.array(z.string()),
667
- configRemoves: z.array(z.string()),
668
- });
669
-
670
- const GithubReconcilePlanResultSchema = z
671
- .object({
672
- status: z.enum(["planned", "skipped"]).openapi({
673
- description:
674
- "`skipped` (not an error) when no GitHub username is bound or the Apps are not configured; `reason` says why.",
675
- }),
676
- reason: z.string().optional(),
677
- planHash: z.string().optional(),
678
- empty: z.boolean().optional(),
679
- diff: GithubReconcileDiffSchema.optional(),
680
- skippedOrgs: z
681
- .array(z.object({ org: z.string(), reason: z.string() }))
682
- .optional(),
683
- rejectedAdds: z
684
- .array(z.object({ repo: z.string(), reason: z.string() }))
685
- .optional(),
686
- warnings: z.array(z.string()).optional(),
687
- affectedOpenWork: z
688
- .array(
689
- z.object({
690
- id: z.string(),
691
- repo: z.string(),
692
- title: z.string().optional(),
693
- }),
694
- )
695
- .optional()
696
- .openapi({
697
- description:
698
- "Open work the removals would block; empty when no open-work port is wired.",
699
- }),
700
- })
701
- .openapi("GithubReconcilePlanResult");
702
-
703
- const GithubReconcileApplyResultSchema = z
704
- .object({
705
- status: z.enum(["applied", "failed", "noop", "skipped"]),
706
- reason: z.string().optional(),
707
- auditId: z.string().optional(),
708
- planHash: z.string().optional(),
709
- diff: GithubReconcileDiffSchema.optional(),
710
- warnings: z.array(z.string()).optional(),
711
- error: z.string().optional(),
712
- })
713
- .openapi("GithubReconcileApplyResult");
714
-
715
- const InstallationReposBodySchema = z
716
- .object({
717
- repos: z.array(RepoFullNameSchema).min(1).max(100).openapi({
718
- description:
719
- "Repos (owner/repo) to change on the agent App's installation.",
720
- }),
721
- })
722
- .openapi("GithubInstallationReposBody");
723
-
724
627
  const GithubInstallationReposListSchema = z
725
628
  .object({
726
629
  appId: z.number().int(),
@@ -741,14 +644,6 @@ const GithubInstallationReposListSchema = z
741
644
  })
742
645
  .openapi("GithubInstallationReposList");
743
646
 
744
- const GithubInstallationReposChangeSchema = z
745
- .object({
746
- status: z.enum(["applied"]),
747
- auditId: z.string(),
748
- repos: z.array(z.string()),
749
- })
750
- .openapi("GithubInstallationReposChange");
751
-
752
647
  const OpenWorkItemSchema = z.object({
753
648
  id: z.string(),
754
649
  repo: z.string(),
@@ -759,62 +654,76 @@ const SkippedOrgsSchema = z.array(
759
654
  z.object({ org: z.string(), reason: z.string() }),
760
655
  );
761
656
 
762
- const GithubLostAccessPreviewSchema = z
657
+ const GithubSyncPreviewSchema = z
763
658
  .object({
764
659
  status: z.enum(["previewed", "skipped"]).openapi({
765
660
  description:
766
661
  "`skipped` (not an error) when no GitHub username is bound, the user is not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured; `reason` says why.",
767
662
  }),
768
663
  reason: z.string().optional(),
769
- repos: z.array(z.string()).optional().openapi({
664
+ appAdds: z.array(z.string()).optional().openapi({
770
665
  description:
771
- "Every repo the bound user can no longer push to that would be removed from the installation or the agent's repos.",
666
+ "Repos the bound user can push to, in orgs the agent App is installed on with a complete access listing, that are not on the installation. No cap.",
667
+ }),
668
+ appRemoves: z.array(z.string()).optional().openapi({
669
+ description: "Installation repos the bound user can no longer push to.",
670
+ }),
671
+ agentRemoves: z.array(z.string()).optional().openapi({
672
+ description:
673
+ "Configured agent repos the bound user can no longer push to. The agent's repos are never added to.",
772
674
  }),
773
- installationRemoves: z.array(z.string()).optional(),
774
- configRemoves: z.array(z.string()).optional(),
775
675
  skippedOrgs: SkippedOrgsSchema.optional().openapi({
776
676
  description:
777
- "Orgs whose access listing is missing, partial or failed, or whose lookup App is installed on selected repositories only; nothing there is removed.",
677
+ "Orgs whose access listing is missing, partial or failed, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed.",
778
678
  }),
779
679
  openWork: z.array(OpenWorkItemSchema).optional().openapi({
780
680
  description:
781
- "The agent's open tasks and PRs on those repos that removing them would block; empty when no open-work port is wired.",
681
+ "The agent's open tasks and PRs on the removed repos that the removals would block; empty when no open-work port is wired.",
782
682
  }),
783
683
  warnings: z.array(z.string()).optional(),
784
684
  })
785
- .openapi("GithubLostAccessPreview");
685
+ .openapi("GithubSyncPreview");
786
686
 
787
- const GithubLostAccessRemoveBodySchema = z
687
+ const GithubSyncApplyBodySchema = z
788
688
  .object({
789
- repos: z.array(RepoFullNameSchema).min(1).max(100).openapi({
689
+ appAdds: z.array(RepoFullNameSchema).max(500).default([]).openapi({
690
+ description:
691
+ "Repos (owner/repo) the admin confirmed to add to the agent App's installation.",
692
+ }),
693
+ appRemoves: z.array(RepoFullNameSchema).max(500).default([]).openapi({
790
694
  description:
791
- "The repos (owner/repo) the admin confirmed from the preview. Each is re-checked; only those the user still cannot push to are removed.",
695
+ "Repos the admin confirmed to remove from the agent App's installation.",
696
+ }),
697
+ agentRemoves: z.array(RepoFullNameSchema).max(500).default([]).openapi({
698
+ description:
699
+ "Repos the admin confirmed to remove from the agent's repos.",
792
700
  }),
793
701
  confirmRemovals: z.boolean().optional().openapi({
794
- description: "Required when more than 10 repos would be removed.",
702
+ description:
703
+ "Required when more than 10 distinct repos would be removed.",
795
704
  }),
796
705
  })
797
- .openapi("GithubLostAccessRemoveBody");
706
+ .openapi("GithubSyncApplyBody");
798
707
 
799
- const GithubLostAccessRemoveResultSchema = z
708
+ const GithubSyncApplyResultSchema = z
800
709
  .object({
801
710
  status: z.enum(["applied", "noop", "skipped"]),
802
711
  reason: z.string().optional(),
803
712
  auditId: z.string().optional(),
804
- repos: z.array(z.string()).optional(),
805
- installationRemoves: z.array(z.string()).optional(),
806
- configRemoves: z.array(z.string()).optional(),
807
- notRemoved: z
713
+ appAdds: z.array(z.string()).optional(),
714
+ appRemoves: z.array(z.string()).optional(),
715
+ agentRemoves: z.array(z.string()).optional(),
716
+ notApplied: z
808
717
  .array(z.object({ repo: z.string(), reason: z.string() }))
809
718
  .optional()
810
719
  .openapi({
811
720
  description:
812
- "Named repos left alone: the user can still push, the org was skipped, or the repo is on neither the installation nor the agent.",
721
+ "Confirmed repos left alone: access changed since the preview, the org was skipped, or the repo is not where the change expected it.",
813
722
  }),
814
723
  skippedOrgs: SkippedOrgsSchema.optional(),
815
724
  warnings: z.array(z.string()).optional(),
816
725
  })
817
- .openapi("GithubLostAccessRemoveResult");
726
+ .openapi("GithubSyncApplyResult");
818
727
 
819
728
  // ─── Route definitions ──────────────────────────────────────────────────────────
820
729
 
@@ -1740,64 +1649,6 @@ const getGithubAccessRoute = createRoute({
1740
1649
  },
1741
1650
  });
1742
1651
 
1743
- const githubReconcilePlanRoute = createRoute({
1744
- method: "post",
1745
- path: "/agents/{id}/github-reconcile/plan",
1746
- summary: "Plan a GitHub repo reconcile for the agent",
1747
- description:
1748
- "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.",
1749
- request: {
1750
- params: AgentIdParamSchema,
1751
- body: {
1752
- required: false,
1753
- content: {
1754
- "application/json": { schema: GithubReconcilePlanBodySchema },
1755
- },
1756
- },
1757
- },
1758
- responses: {
1759
- 200: {
1760
- description: "Reconcile plan",
1761
- content: {
1762
- "application/json": { schema: GithubReconcilePlanResultSchema },
1763
- },
1764
- },
1765
- 401: { description: "Unauthorized", ...jsonError },
1766
- 403: { description: "Platform admin required", ...jsonError },
1767
- 404: { description: "Agent not found", ...jsonError },
1768
- },
1769
- });
1770
-
1771
- const githubReconcileApplyRoute = createRoute({
1772
- method: "post",
1773
- path: "/agents/{id}/github-reconcile/apply",
1774
- summary: "Apply a reviewed GitHub repo reconcile plan",
1775
- description:
1776
- "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.",
1777
- request: {
1778
- params: AgentIdParamSchema,
1779
- body: {
1780
- required: true,
1781
- content: {
1782
- "application/json": { schema: GithubReconcileApplyBodySchema },
1783
- },
1784
- },
1785
- },
1786
- responses: {
1787
- 200: {
1788
- description: "Apply result",
1789
- content: {
1790
- "application/json": { schema: GithubReconcileApplyResultSchema },
1791
- },
1792
- },
1793
- 401: { description: "Unauthorized", ...jsonError },
1794
- 403: { description: "Platform admin required", ...jsonError },
1795
- 404: { description: "Agent not found", ...jsonError },
1796
- 409: { description: "Plan hash is stale; re-plan", ...jsonError },
1797
- 422: { description: "Removal cap needs confirmRemovals", ...jsonError },
1798
- },
1799
- });
1800
-
1801
1652
  const installationReposErrors = {
1802
1653
  401: { description: "Unauthorized", ...jsonError },
1803
1654
  403: { description: "Platform admin required", ...jsonError },
@@ -1828,59 +1679,7 @@ const listInstallationReposRoute = createRoute({
1828
1679
  },
1829
1680
  });
1830
1681
 
1831
- const addInstallationReposRoute = createRoute({
1832
- method: "post",
1833
- path: "/agents/{id}/github-installation/repos",
1834
- summary: "Add repos to the agent App's installation",
1835
- description:
1836
- "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).",
1837
- request: {
1838
- params: AgentIdParamSchema,
1839
- body: {
1840
- required: true,
1841
- content: { "application/json": { schema: InstallationReposBodySchema } },
1842
- },
1843
- },
1844
- responses: {
1845
- 200: {
1846
- description: "Repos added",
1847
- content: {
1848
- "application/json": { schema: GithubInstallationReposChangeSchema },
1849
- },
1850
- },
1851
- ...installationReposErrors,
1852
- 409: { description: "Agent App not installed on the org", ...jsonError },
1853
- 502: { description: "GitHub unavailable or refused", ...jsonError },
1854
- },
1855
- });
1856
-
1857
- const removeInstallationReposRoute = createRoute({
1858
- method: "post",
1859
- path: "/agents/{id}/github-installation/repos/remove",
1860
- summary: "Remove repos from the agent App's installation",
1861
- description:
1862
- "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.",
1863
- request: {
1864
- params: AgentIdParamSchema,
1865
- body: {
1866
- required: true,
1867
- content: { "application/json": { schema: InstallationReposBodySchema } },
1868
- },
1869
- },
1870
- responses: {
1871
- 200: {
1872
- description: "Repos removed",
1873
- content: {
1874
- "application/json": { schema: GithubInstallationReposChangeSchema },
1875
- },
1876
- },
1877
- ...installationReposErrors,
1878
- 409: { description: "Agent App not installed on the org", ...jsonError },
1879
- 502: { description: "GitHub unavailable or refused", ...jsonError },
1880
- },
1881
- });
1882
-
1883
- const lostAccessErrors = {
1682
+ const syncErrors = {
1884
1683
  401: { description: "Unauthorized", ...jsonError },
1885
1684
  403: { description: "Platform admin required", ...jsonError },
1886
1685
  404: { description: "Agent not found", ...jsonError },
@@ -1888,47 +1687,41 @@ const lostAccessErrors = {
1888
1687
  503: { description: "GitHub Apps are not configured", ...jsonError },
1889
1688
  };
1890
1689
 
1891
- const githubLostAccessPreviewRoute = createRoute({
1690
+ const githubSyncPreviewRoute = createRoute({
1892
1691
  method: "get",
1893
- path: "/agents/{id}/github-lost-access/preview",
1894
- summary: "Preview removing the repos the bound user can no longer push to",
1692
+ path: "/agents/{id}/github-sync/preview",
1693
+ summary: "Preview syncing the agent's GitHub access with its bound user",
1895
1694
  description:
1896
- "Platform-admin only (session members, ops keys and agent keys get 403). Read-only: nothing is changed or audited. Lists the repos on the agent App's installation or in the agent's repos that the bound githubUsername can no longer push to, and the agent's open tasks and PRs on them (via the optional open-work port; a port failure is a warning). Orgs whose access listing is missing, partial or failed, or whose lookup App is installed on selected repositories only, are skipped and reported. 200 with `status: skipped` when the user is unbound, not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured.",
1695
+ "Platform-admin only (session members, ops keys and agent keys get 403). Read-only: nothing is changed or audited. Lists (1) repos to add to the agent App's installation, (2) installation repos to remove and (3) agent repos to remove, based on what the bound githubUsername can push to, plus the agent's open tasks and PRs the removals would block (via the optional open-work port; a port failure is a warning). The agent's repos are never added to. Orgs whose access listing is missing, partial or failed, or whose lookup App is not installed or installed on selected repositories only, are skipped (adds included) and reported. 200 with `status: skipped` when the user is unbound, not found or unverified, the agent has no GH_APP_ID, or the Apps are not configured.",
1897
1696
  request: { params: AgentIdParamSchema },
1898
1697
  responses: {
1899
1698
  200: {
1900
- description: "Lost-access removal preview",
1901
- content: {
1902
- "application/json": { schema: GithubLostAccessPreviewSchema },
1903
- },
1699
+ description: "Sync preview",
1700
+ content: { "application/json": { schema: GithubSyncPreviewSchema } },
1904
1701
  },
1905
- ...lostAccessErrors,
1702
+ ...syncErrors,
1906
1703
  },
1907
1704
  });
1908
1705
 
1909
- const githubLostAccessRemoveRoute = createRoute({
1706
+ const githubSyncApplyRoute = createRoute({
1910
1707
  method: "post",
1911
- path: "/agents/{id}/github-lost-access/remove",
1912
- summary: "Remove the confirmed repos the bound user can no longer push to",
1708
+ path: "/agents/{id}/github-sync/apply",
1709
+ summary: "Apply the confirmed sync changes",
1913
1710
  description:
1914
- "Platform-admin only. Never adds repos. Takes the repos the admin confirmed from the preview, re-checks each against the bound user's current access, and removes only those still without push access: first from the agent App's installation, then from the agent's repos; then writes one audit entry (GitHubReconcileAudit, planHash `lost-access:remove`) and blocks the agent's open work on the removed repos through the optional open-work port (a failure there is a warning). Named repos left alone are reported in `notRemoved`. Same skip rules as the preview: a skipped call (200 `status: skipped`) changes and audits nothing; `noop` when nothing named still lacks access. 422 when more than 10 repos would be removed without `confirmRemovals: true`. 502 when GitHub refuses (a failed audit entry records only what landed).",
1711
+ "Platform-admin only. Takes the exact lists the admin confirmed from the preview, re-checks each against the bound user's current access, and applies only what still qualifies: installation adds, installation removes, then agent-repo removes. Writes one audit entry (GitHubReconcileAudit, planHash `sync:apply`) and blocks the agent's open work on the removed repos through the optional open-work port (a failure there is a warning). Confirmed repos left alone are reported in `notApplied`. Same skip rules as the preview: a skipped call (200 `status: skipped`) changes and audits nothing; `noop` when nothing confirmed still applies. 422 when more than 10 repos would be removed without `confirmRemovals: true`. 502 when GitHub refuses (a failed audit entry records only what landed).",
1915
1712
  request: {
1916
1713
  params: AgentIdParamSchema,
1917
1714
  body: {
1918
1715
  required: true,
1919
- content: {
1920
- "application/json": { schema: GithubLostAccessRemoveBodySchema },
1921
- },
1716
+ content: { "application/json": { schema: GithubSyncApplyBodySchema } },
1922
1717
  },
1923
1718
  },
1924
1719
  responses: {
1925
1720
  200: {
1926
- description: "Removal result",
1927
- content: {
1928
- "application/json": { schema: GithubLostAccessRemoveResultSchema },
1929
- },
1721
+ description: "Sync result",
1722
+ content: { "application/json": { schema: GithubSyncApplyResultSchema } },
1930
1723
  },
1931
- ...lostAccessErrors,
1724
+ ...syncErrors,
1932
1725
  422: { description: "Removal cap needs confirmRemovals", ...jsonError },
1933
1726
  },
1934
1727
  });
@@ -3428,130 +3221,6 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3428
3221
  return c.json(preview, 200);
3429
3222
  });
3430
3223
 
3431
- // POST /agents/:id/github-reconcile/{plan,apply} — GHE-3.4. Platform admin
3432
- // only. Responses carry repo names and ids, never tokens; logs carry ids only.
3433
- app.openapi(githubReconcilePlanRoute, async (c) => {
3434
- if (c.get("isAdmin") !== true) {
3435
- throw new ForbiddenError(
3436
- "Admin access required to plan a GitHub reconcile",
3437
- );
3438
- }
3439
- const { id: agentId } = c.req.valid("param");
3440
- const body = c.req.valid("json");
3441
- const reconcile = deps.githubReconcile;
3442
- if (!reconcile) {
3443
- return c.json(
3444
- { status: "skipped" as const, reason: GITHUB_RECONCILE_UNCONFIGURED },
3445
- 200,
3446
- );
3447
- }
3448
- let result: Awaited<ReturnType<typeof reconcile.planWithOpenWork>>;
3449
- try {
3450
- result = await reconcile.planWithOpenWork(agentId, body?.addRepos);
3451
- } catch (err) {
3452
- if (
3453
- err instanceof Error &&
3454
- err.message === `agent ${agentId} not found`
3455
- ) {
3456
- throw new NotFoundError(`agent ${agentId} not found`);
3457
- }
3458
- throw err;
3459
- }
3460
- const { plan, openWork } = result;
3461
- if (plan.skipped) {
3462
- return c.json(
3463
- {
3464
- status: "skipped" as const,
3465
- reason: plan.skipReason ?? "reconcile skipped",
3466
- },
3467
- 200,
3468
- );
3469
- }
3470
- return c.json(
3471
- {
3472
- status: "planned" as const,
3473
- planHash: plan.planHash,
3474
- empty: plan.empty,
3475
- diff: plan.diff,
3476
- skippedOrgs: plan.skippedOrgs,
3477
- rejectedAdds: plan.rejectedAdds,
3478
- warnings: plan.warnings,
3479
- affectedOpenWork: openWork,
3480
- },
3481
- 200,
3482
- );
3483
- });
3484
-
3485
- app.openapi(githubReconcileApplyRoute, async (c) => {
3486
- if (c.get("isAdmin") !== true) {
3487
- throw new ForbiddenError(
3488
- "Admin access required to apply a GitHub reconcile",
3489
- );
3490
- }
3491
- const { id: agentId } = c.req.valid("param");
3492
- const body = c.req.valid("json");
3493
- const reconcile = deps.githubReconcile;
3494
- if (!reconcile) {
3495
- return c.json(
3496
- { status: "skipped" as const, reason: GITHUB_RECONCILE_UNCONFIGURED },
3497
- 200,
3498
- );
3499
- }
3500
- const caller = c.get("caller")?.name ?? "anonymous";
3501
- const result = await reconcile.apply({
3502
- agentId,
3503
- caller,
3504
- planHash: body.planHash,
3505
- namedAdds: body.addRepos,
3506
- confirmRemovals: body.confirmRemovals,
3507
- });
3508
- switch (result.status) {
3509
- case "agent_not_found":
3510
- throw new NotFoundError(`agent ${agentId} not found`);
3511
- case "stale_plan":
3512
- throw new ConflictError(
3513
- "the plan changed since it was reviewed; re-run plan and review it again",
3514
- );
3515
- case "removal_cap":
3516
- throw new UnprocessableEntityError(
3517
- `plan removes ${result.removals} repos; resend with confirmRemovals: true to apply`,
3518
- );
3519
- case "skipped":
3520
- return c.json(
3521
- {
3522
- status: "skipped" as const,
3523
- reason: result.plan.skipReason ?? "reconcile skipped",
3524
- },
3525
- 200,
3526
- );
3527
- case "noop":
3528
- return c.json(
3529
- {
3530
- status: "noop" as const,
3531
- planHash: result.plan.planHash,
3532
- diff: result.plan.diff,
3533
- },
3534
- 200,
3535
- );
3536
- case "applied":
3537
- case "failed":
3538
- console.log(
3539
- `[agents-api] github reconcile ${result.status}: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3540
- );
3541
- return c.json(
3542
- {
3543
- status: result.status,
3544
- auditId: result.auditId,
3545
- planHash: result.plan.planHash,
3546
- diff: result.plan.diff,
3547
- warnings: result.status === "applied" ? result.warnings : [],
3548
- ...(result.status === "failed" ? { error: result.error } : {}),
3549
- },
3550
- 200,
3551
- );
3552
- }
3553
- });
3554
-
3555
3224
  // /agents/:id/github-installation/repos — IRM-1.2. Platform admin only;
3556
3225
  // responses carry repo names and ids, never tokens.
3557
3226
  const installationReposService = (c: {
@@ -3559,27 +3228,23 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3559
3228
  }) => {
3560
3229
  if (c.get("isAdmin") !== true) {
3561
3230
  throw new ForbiddenError(
3562
- "Admin access required to manage installation repos",
3231
+ "Admin access required to list installation repos",
3563
3232
  );
3564
3233
  }
3565
3234
  const svc = deps.githubInstallationRepos;
3566
- if (!svc) throw new ApiError(503, GITHUB_RECONCILE_UNCONFIGURED);
3235
+ if (!svc) throw new ApiError(503, GITHUB_APPS_UNCONFIGURED);
3567
3236
  return svc;
3568
3237
  };
3569
3238
  const installationFailure = (
3570
3239
  agentId: string,
3571
3240
  result:
3572
3241
  | { status: "agent_not_found" }
3573
- | { status: "no_app_id"; reason: string }
3574
- | { status: "not_installed"; reason: string },
3242
+ | { status: "no_app_id"; reason: string },
3575
3243
  ): never => {
3576
3244
  if (result.status === "agent_not_found") {
3577
3245
  throw new NotFoundError(`agent ${agentId} not found`);
3578
3246
  }
3579
- if (result.status === "no_app_id") {
3580
- throw new UnprocessableEntityError(result.reason);
3581
- }
3582
- throw new ConflictError(result.reason);
3247
+ throw new UnprocessableEntityError(result.reason);
3583
3248
  };
3584
3249
 
3585
3250
  app.openapi(listInstallationReposRoute, async (c) => {
@@ -3590,77 +3255,19 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3590
3255
  return c.json({ appId: result.appId, orgs: result.orgs }, 200);
3591
3256
  });
3592
3257
 
3593
- const changeInstallationRepos = async (
3594
- kind: "add" | "remove",
3595
- c: {
3596
- get(k: "isAdmin"): boolean | undefined;
3597
- get(k: "caller"): { name: string } | undefined;
3598
- },
3599
- agentId: string,
3600
- repos: string[],
3601
- ) => {
3602
- const svc = installationReposService(c);
3603
- const caller = c.get("caller")?.name ?? "anonymous";
3604
- const result = await svc[kind](agentId, caller, repos);
3605
- if (
3606
- result.status === "agent_not_found" ||
3607
- result.status === "no_app_id" ||
3608
- result.status === "not_installed"
3609
- ) {
3610
- return installationFailure(agentId, result);
3611
- }
3612
- console.log(
3613
- `[agents-api] github installation repos ${kind} ${result.status}: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3614
- );
3615
- if (result.status === "failed") {
3616
- throw new BadGatewayError(
3617
- `GitHub refused the ${kind}; audit ${result.auditId} records the failure: ${result.error}`,
3618
- );
3619
- }
3620
- return {
3621
- status: "applied" as const,
3622
- auditId: result.auditId,
3623
- repos: result.repos,
3624
- };
3625
- };
3626
- app.openapi(addInstallationReposRoute, async (c) =>
3627
- c.json(
3628
- await changeInstallationRepos(
3629
- "add",
3630
- c,
3631
- c.req.valid("param").id,
3632
- c.req.valid("json").repos,
3633
- ),
3634
- 200,
3635
- ),
3636
- );
3637
- app.openapi(removeInstallationReposRoute, async (c) =>
3638
- c.json(
3639
- await changeInstallationRepos(
3640
- "remove",
3641
- c,
3642
- c.req.valid("param").id,
3643
- c.req.valid("json").repos,
3644
- ),
3645
- 200,
3646
- ),
3647
- );
3648
-
3649
- // /agents/:id/github-lost-access/{preview,remove} — IRM-1.3. Platform admin
3650
- // only; responses carry repo names and ids, never tokens.
3651
- const lostAccessService = (c: { get(k: "isAdmin"): boolean | undefined }) => {
3258
+ // /agents/:id/github-sync/{preview,apply} — IRM-3.1. Platform admin only;
3259
+ // responses carry repo names and ids, never tokens.
3260
+ const syncService = (c: { get(k: "isAdmin"): boolean | undefined }) => {
3652
3261
  if (c.get("isAdmin") !== true) {
3653
- throw new ForbiddenError(
3654
- "Admin access required to remove repos the bound user lost access to",
3655
- );
3262
+ throw new ForbiddenError("Admin access required to sync GitHub repos");
3656
3263
  }
3657
- const svc = deps.githubLostAccessRemoval;
3658
- if (!svc) throw new ApiError(503, GITHUB_RECONCILE_UNCONFIGURED);
3264
+ const svc = deps.githubSync;
3265
+ if (!svc) throw new ApiError(503, GITHUB_APPS_UNCONFIGURED);
3659
3266
  return svc;
3660
3267
  };
3661
3268
 
3662
- app.openapi(githubLostAccessPreviewRoute, async (c) => {
3663
- const svc = lostAccessService(c);
3269
+ app.openapi(githubSyncPreviewRoute, async (c) => {
3270
+ const svc = syncService(c);
3664
3271
  const { id: agentId } = c.req.valid("param");
3665
3272
  const result = await svc.preview(agentId);
3666
3273
  if (result.status === "agent_not_found") {
@@ -3673,9 +3280,9 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3673
3280
  return c.json(
3674
3281
  {
3675
3282
  status: "previewed" as const,
3676
- repos: plan.repos,
3677
- installationRemoves: plan.installationRemoves,
3678
- configRemoves: plan.configRemoves,
3283
+ appAdds: plan.appAdds,
3284
+ appRemoves: plan.appRemoves,
3285
+ agentRemoves: plan.agentRemoves,
3679
3286
  skippedOrgs: plan.skippedOrgs,
3680
3287
  openWork: result.openWork,
3681
3288
  warnings: result.warnings,
@@ -3684,15 +3291,17 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3684
3291
  );
3685
3292
  });
3686
3293
 
3687
- app.openapi(githubLostAccessRemoveRoute, async (c) => {
3688
- const svc = lostAccessService(c);
3294
+ app.openapi(githubSyncApplyRoute, async (c) => {
3295
+ const svc = syncService(c);
3689
3296
  const { id: agentId } = c.req.valid("param");
3690
3297
  const body = c.req.valid("json");
3691
3298
  const caller = c.get("caller")?.name ?? "anonymous";
3692
- const result = await svc.remove({
3299
+ const result = await svc.apply({
3693
3300
  agentId,
3694
3301
  caller,
3695
- repos: body.repos,
3302
+ appAdds: body.appAdds,
3303
+ appRemoves: body.appRemoves,
3304
+ agentRemoves: body.agentRemoves,
3696
3305
  confirmRemovals: body.confirmRemovals,
3697
3306
  });
3698
3307
  switch (result.status) {
@@ -3709,27 +3318,27 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3709
3318
  );
3710
3319
  case "failed":
3711
3320
  console.log(
3712
- `[agents-api] github lost-access removal failed: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3321
+ `[agents-api] github sync failed: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3713
3322
  );
3714
3323
  throw new BadGatewayError(
3715
- `GitHub refused the removal; audit ${result.auditId} records the failure: ${result.error}`,
3324
+ `GitHub refused the sync; audit ${result.auditId} records the failure: ${result.error}`,
3716
3325
  );
3717
3326
  case "noop":
3718
3327
  case "applied": {
3719
3328
  const { plan } = result;
3720
3329
  if (result.status === "applied") {
3721
3330
  console.log(
3722
- `[agents-api] github lost-access removal applied: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3331
+ `[agents-api] github sync applied: agent=${agentId} audit=${result.auditId} caller=${caller}`,
3723
3332
  );
3724
3333
  }
3725
3334
  return c.json(
3726
3335
  {
3727
3336
  status: result.status,
3728
3337
  ...(result.status === "applied" ? { auditId: result.auditId } : {}),
3729
- repos: plan.repos,
3730
- installationRemoves: plan.installationRemoves,
3731
- configRemoves: plan.configRemoves,
3732
- notRemoved: plan.notRemoved,
3338
+ appAdds: plan.appAdds,
3339
+ appRemoves: plan.appRemoves,
3340
+ agentRemoves: plan.agentRemoves,
3341
+ notApplied: plan.notApplied,
3733
3342
  skippedOrgs: plan.skippedOrgs,
3734
3343
  warnings:
3735
3344
  result.status === "applied"