@app-vitals/agent-admin 1.31.0 → 1.32.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.
@@ -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 () => {
@@ -0,0 +1,237 @@
1
+ /**
2
+ * admin/src/installation-repos-service.ts
3
+ * Direct management of the repos on an agent's own GitHub App installation
4
+ * (IRM-1.2): list, add and remove without a reconcile plan step. Uses the
5
+ * installer App through the reconcile installation port, and writes every
6
+ * add/remove to the existing GitHubReconcileAudit table (no schema change):
7
+ * `planHash` is "direct:add" / "direct:remove" and the changed repos land in
8
+ * the diff's installationAdds / installationRemoves.
9
+ */
10
+
11
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
12
+ import {
13
+ AppNotInstalledError,
14
+ MISSING_APP_ID_REASON,
15
+ type ReconcileAgentsPort,
16
+ type ReconcileAuditPort,
17
+ type ReconcileInstallationPort,
18
+ } from "./reconcile-apply-service.ts";
19
+ import { repoOrg } from "./reconcile-planner.ts";
20
+ import type {
21
+ OrgAccessResult,
22
+ UserRepoAccessResult,
23
+ } from "./user-repo-access-resolver.ts";
24
+
25
+ /** Installation port plus discovery of the orgs the agent App is installed on. */
26
+ export interface InstallationReposPort extends ReconcileInstallationPort {
27
+ listInstalled(appId: number): Promise<{ org: string; repos: string[] }[]>;
28
+ }
29
+
30
+ export interface InstallationRepoView {
31
+ fullName: string;
32
+ /** Present only when the bound user's access to this repo is known. */
33
+ userCanPush?: boolean;
34
+ }
35
+
36
+ export interface InstallationOrgView {
37
+ org: string;
38
+ repos: InstallationRepoView[];
39
+ }
40
+
41
+ export type InstallationListResult =
42
+ | { status: "agent_not_found" }
43
+ | { status: "no_app_id"; reason: string }
44
+ | { status: "ok"; appId: number; orgs: InstallationOrgView[] };
45
+
46
+ export type InstallationChangeResult =
47
+ | { status: "agent_not_found" }
48
+ | { status: "no_app_id"; reason: string }
49
+ | { status: "not_installed"; org: string; reason: string }
50
+ | { status: "applied"; auditId: string; repos: string[] }
51
+ | { status: "failed"; auditId: string; error: string };
52
+
53
+ export interface InstallationReposDeps {
54
+ agents: Pick<ReconcileAgentsPort, "get">;
55
+ access: GithubAccessPreviewFn;
56
+ installation: InstallationReposPort;
57
+ audit: ReconcileAuditPort;
58
+ }
59
+
60
+ const orgKey = (org: string): string => org.toLowerCase();
61
+
62
+ /**
63
+ * The user-can-push hint for one org: true/false per repo only when the bound
64
+ * user is verified and this org's lookup result is complete ("ok", nothing
65
+ * unresolved). A repo the lookup did not list is unknown, so it gets no hint
66
+ * (never false).
67
+ */
68
+ export function userPushHints(
69
+ access: UserRepoAccessResult | undefined,
70
+ org: string,
71
+ repos: readonly string[],
72
+ ): InstallationRepoView[] {
73
+ const orgResult: OrgAccessResult | undefined = access?.orgs.find(
74
+ (o) => orgKey(o.org) === orgKey(org),
75
+ );
76
+ const complete =
77
+ access !== undefined &&
78
+ access.outcome === "ok" &&
79
+ access.userVerified &&
80
+ orgResult !== undefined &&
81
+ orgResult.status === "ok" &&
82
+ orgResult.unresolved === 0;
83
+ const pushByName = new Map<string, boolean>();
84
+ if (complete) {
85
+ for (const r of orgResult.repos) {
86
+ pushByName.set(r.fullName.toLowerCase(), r.canPush);
87
+ }
88
+ }
89
+ return repos.map((fullName) => {
90
+ const hint = pushByName.get(fullName.toLowerCase());
91
+ return hint === undefined ? { fullName } : { fullName, userCanPush: hint };
92
+ });
93
+ }
94
+
95
+ function groupByOrg(repos: readonly string[]): Map<string, string[]> {
96
+ const byOrg = new Map<string, string[]>();
97
+ for (const r of repos) {
98
+ const org = repoOrg(r);
99
+ byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
100
+ }
101
+ return byOrg;
102
+ }
103
+
104
+ export class InstallationReposService {
105
+ constructor(private readonly deps: InstallationReposDeps) {}
106
+
107
+ async list(agentId: string): Promise<InstallationListResult> {
108
+ const agent = await this.deps.agents.get(agentId);
109
+ if (!agent) return { status: "agent_not_found" };
110
+ if (agent.appId === undefined) {
111
+ return { status: "no_app_id", reason: MISSING_APP_ID_REASON };
112
+ }
113
+ const installed = await this.deps.installation.listInstalled(agent.appId);
114
+ const username = agent.githubUsername?.trim();
115
+ let access: UserRepoAccessResult | undefined;
116
+ if (username) {
117
+ try {
118
+ const preview = await this.deps.access(username);
119
+ if (preview.status === "ok") access = preview.access;
120
+ } catch {
121
+ // The hint is advisory: a failed lookup omits it.
122
+ }
123
+ }
124
+ return {
125
+ status: "ok",
126
+ appId: agent.appId,
127
+ orgs: installed.map(({ org, repos }) => ({
128
+ org,
129
+ repos: userPushHints(access, org, repos),
130
+ })),
131
+ };
132
+ }
133
+
134
+ add(
135
+ agentId: string,
136
+ caller: string,
137
+ repos: readonly string[],
138
+ ): Promise<InstallationChangeResult> {
139
+ return this.change("add", agentId, caller, repos);
140
+ }
141
+
142
+ remove(
143
+ agentId: string,
144
+ caller: string,
145
+ repos: readonly string[],
146
+ ): Promise<InstallationChangeResult> {
147
+ return this.change("remove", agentId, caller, repos);
148
+ }
149
+
150
+ private async change(
151
+ kind: "add" | "remove",
152
+ agentId: string,
153
+ caller: string,
154
+ input: readonly string[],
155
+ ): Promise<InstallationChangeResult> {
156
+ const agent = await this.deps.agents.get(agentId);
157
+ if (!agent) return { status: "agent_not_found" };
158
+ if (agent.appId === undefined) {
159
+ return { status: "no_app_id", reason: MISSING_APP_ID_REASON };
160
+ }
161
+ const appId = agent.appId;
162
+ const repos = [...new Set(input)];
163
+ const byOrg = groupByOrg(repos);
164
+ const { installation } = this.deps;
165
+ // Nothing is written (or audited) when an org has no installation.
166
+ try {
167
+ await installation.listRepos(appId, [...byOrg.keys()]);
168
+ } catch (err) {
169
+ if (err instanceof AppNotInstalledError) {
170
+ return { status: "not_installed", org: err.org, reason: err.message };
171
+ }
172
+ throw err;
173
+ }
174
+ const changed: string[] = [];
175
+ let error: string | undefined;
176
+ try {
177
+ for (const [org, orgRepos] of byOrg) {
178
+ if (kind === "add") await installation.addRepos(appId, org, orgRepos);
179
+ else await installation.removeRepos(appId, org, orgRepos);
180
+ changed.push(...orgRepos);
181
+ }
182
+ } catch (err) {
183
+ error = err instanceof Error ? err.message : String(err);
184
+ }
185
+ // Record what actually changed; on failure, only the repos that landed.
186
+ const done = error === undefined ? repos : changed;
187
+ const auditId = await this.deps.audit.write({
188
+ agentId,
189
+ caller,
190
+ planHash: `direct:${kind}`,
191
+ diff: {
192
+ installationAdds: kind === "add" ? done : [],
193
+ installationRemoves: kind === "remove" ? done : [],
194
+ configAdds: [],
195
+ configRemoves: [],
196
+ },
197
+ result:
198
+ error === undefined
199
+ ? { status: "applied" }
200
+ : { status: "failed", error },
201
+ });
202
+ return error === undefined
203
+ ? { status: "applied", auditId, repos }
204
+ : { status: "failed", auditId, error };
205
+ }
206
+ }
207
+
208
+ /** The slice of the installer client the installation-repos port needs. */
209
+ export interface InstalledOrgsClient {
210
+ listInstallableOrganizations(): Promise<{ login: string }[]>;
211
+ }
212
+
213
+ /**
214
+ * Port over the reconcile installation port plus org discovery: the orgs the
215
+ * installer can reach that carry an installation of the agent's App.
216
+ */
217
+ export function createInstallationReposPort(
218
+ base: ReconcileInstallationPort,
219
+ client: InstalledOrgsClient,
220
+ ): InstallationReposPort {
221
+ return {
222
+ ...base,
223
+ async listInstalled(appId) {
224
+ const out: { org: string; repos: string[] }[] = [];
225
+ for (const { login } of await client.listInstallableOrganizations()) {
226
+ try {
227
+ const repos = await base.listRepos(appId, [login]);
228
+ out.push({ org: login, repos: repos[login] ?? [] });
229
+ } catch (err) {
230
+ if (err instanceof AppNotInstalledError) continue;
231
+ throw err;
232
+ }
233
+ }
234
+ return out;
235
+ },
236
+ };
237
+ }