@app-vitals/agent-admin 1.30.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.
- package/openapi.platform.json +393 -0
- package/package.json +2 -2
- package/src/admin-boot.ts +26 -4
- package/src/admin-extension.ts +13 -0
- package/src/admin-extension.unit.test.ts +20 -0
- package/src/agents-api.smoke.test.ts +378 -0
- package/src/agents-api.ts +224 -0
- package/src/github-enterprise-isolation.unit.test.ts +8 -4
- package/src/github-reconcile-routes.integration.test.ts +6 -2
- package/src/github-reconcile-wiring.ts +122 -0
- package/src/github-reconcile-wiring.unit.test.ts +170 -0
- package/src/installation-repos-service.ts +237 -0
- package/src/installation-repos-service.unit.test.ts +270 -0
- package/src/reconcile-apply-service.integration.test.ts +11 -3
- package/src/reconcile-apply-service.ts +88 -22
- package/src/reconcile-apply-service.unit.test.ts +70 -24
|
@@ -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:
|
|
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();
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-reconcile-wiring.ts
|
|
3
|
+
* Composition of the GitHub reconcile service for admin boot (GHE-3.9).
|
|
4
|
+
* Builds ReconcileApplyService from the stored enterprise Apps and an
|
|
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.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
10
|
+
import type { AgentEnvService } from "./agent-envs.ts";
|
|
11
|
+
import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
12
|
+
import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
|
|
13
|
+
import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
|
|
14
|
+
import {
|
|
15
|
+
createInstallationPort,
|
|
16
|
+
type InstallationRepoClient,
|
|
17
|
+
PrismaReconcileAgents,
|
|
18
|
+
PrismaReconcileAudit,
|
|
19
|
+
ReconcileApplyService,
|
|
20
|
+
type ReconcileInstallationPort,
|
|
21
|
+
} from "./reconcile-apply-service.ts";
|
|
22
|
+
import {
|
|
23
|
+
createInstallationReposPort,
|
|
24
|
+
type InstalledOrgsClient,
|
|
25
|
+
InstallationReposService,
|
|
26
|
+
type InstallationReposPort,
|
|
27
|
+
} from "./installation-repos-service.ts";
|
|
28
|
+
import type { OpenWorkPort } from "./reconcile-open-work.ts";
|
|
29
|
+
|
|
30
|
+
export interface GithubReconcileWiringDeps {
|
|
31
|
+
prisma: PrismaClient;
|
|
32
|
+
appService: Pick<GitHubEnterpriseAppService, "get" | "getPrivateKey">;
|
|
33
|
+
access: GithubAccessPreviewFn;
|
|
34
|
+
/** Reads each agent's stored GH_APP_ID (its own GitHub App). */
|
|
35
|
+
agentEnv: Pick<AgentEnvService, "getConfigBundle">;
|
|
36
|
+
openWork?: OpenWorkPort;
|
|
37
|
+
/** Test seam: replaces the installer-App-backed installation port. */
|
|
38
|
+
installation?: ReconcileInstallationPort;
|
|
39
|
+
/** Test seams; default to the real GitHub API. */
|
|
40
|
+
fetchFn?: typeof fetch;
|
|
41
|
+
apiBase?: string;
|
|
42
|
+
now?: () => Date;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Builds the installer client per call so key rotations are picked up. */
|
|
46
|
+
function lazyInstallerClient(
|
|
47
|
+
deps: Pick<
|
|
48
|
+
GithubReconcileWiringDeps,
|
|
49
|
+
"appService" | "fetchFn" | "apiBase" | "now"
|
|
50
|
+
>,
|
|
51
|
+
): InstallationRepoClient & InstalledOrgsClient {
|
|
52
|
+
const client = async (): Promise<GithubEnterpriseClient> => {
|
|
53
|
+
const [installer, privateKey] = await Promise.all([
|
|
54
|
+
deps.appService.get("installer"),
|
|
55
|
+
deps.appService.getPrivateKey("installer"),
|
|
56
|
+
]);
|
|
57
|
+
if (!installer?.enterpriseSlug || !privateKey) {
|
|
58
|
+
throw new Error("installer App is not configured");
|
|
59
|
+
}
|
|
60
|
+
return new GithubEnterpriseClient({
|
|
61
|
+
appId: installer.appId,
|
|
62
|
+
enterprise: installer.enterpriseSlug,
|
|
63
|
+
privateKey,
|
|
64
|
+
apiBase: deps.apiBase,
|
|
65
|
+
fetchFn: deps.fetchFn,
|
|
66
|
+
now: deps.now,
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
listInstallableOrganizations: async () =>
|
|
71
|
+
(await client()).listInstallableOrganizations(),
|
|
72
|
+
listOrgInstallations: async (org) =>
|
|
73
|
+
(await client()).listOrgInstallations(org),
|
|
74
|
+
listInstallationRepositories: async (org, id) =>
|
|
75
|
+
(await client()).listInstallationRepositories(org, id),
|
|
76
|
+
addRepositories: async (org, id, names) =>
|
|
77
|
+
(await client()).addRepositories(org, id, names),
|
|
78
|
+
removeRepositories: async (org, id, names) =>
|
|
79
|
+
(await client()).removeRepositories(org, id, names),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
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
|
+
*/
|
|
87
|
+
export function createGithubReconcile(
|
|
88
|
+
deps: GithubReconcileWiringDeps,
|
|
89
|
+
): ReconcileApplyService {
|
|
90
|
+
return new ReconcileApplyService({
|
|
91
|
+
agents: new PrismaReconcileAgents(deps.prisma, deps.agentEnv),
|
|
92
|
+
access: deps.access,
|
|
93
|
+
installation:
|
|
94
|
+
deps.installation ?? createInstallationPort(lazyInstallerClient(deps)),
|
|
95
|
+
audit: new PrismaReconcileAudit(deps.prisma),
|
|
96
|
+
...(deps.openWork ? { openWork: deps.openWork } : {}),
|
|
97
|
+
});
|
|
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
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
3
|
+
import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
4
|
+
import { createGithubReconcile } from "./github-reconcile-wiring.ts";
|
|
5
|
+
import type { ReconcileInstallationPort } from "./reconcile-apply-service.ts";
|
|
6
|
+
import type { OpenWorkPort } from "./reconcile-open-work.ts";
|
|
7
|
+
|
|
8
|
+
export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
|
|
9
|
+
return async () => ({
|
|
10
|
+
status: "ok",
|
|
11
|
+
access: {
|
|
12
|
+
username: "dev",
|
|
13
|
+
outcome: "ok",
|
|
14
|
+
userVerified: true,
|
|
15
|
+
complete: true,
|
|
16
|
+
unresolved: 0,
|
|
17
|
+
checkedAt: "2026-11-11T00:00:00.000Z",
|
|
18
|
+
orgs: [
|
|
19
|
+
{
|
|
20
|
+
org: "acme",
|
|
21
|
+
status: "ok",
|
|
22
|
+
unresolved: 0,
|
|
23
|
+
repos: pushable.map((fullName) => ({
|
|
24
|
+
fullName,
|
|
25
|
+
level: "write" as const,
|
|
26
|
+
canPush: true,
|
|
27
|
+
})),
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function fakePrisma(repos: string[]) {
|
|
35
|
+
const state = { repos: [...repos], audits: 0 };
|
|
36
|
+
const prisma = {
|
|
37
|
+
agent: {
|
|
38
|
+
findUnique: async () => ({
|
|
39
|
+
id: "a1",
|
|
40
|
+
repos: state.repos,
|
|
41
|
+
githubUsername: "dev",
|
|
42
|
+
}),
|
|
43
|
+
update: async (args: { data: { repos: string[] } }) => {
|
|
44
|
+
state.repos = args.data.repos;
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
gitHubReconcileAudit: {
|
|
48
|
+
create: async () => {
|
|
49
|
+
state.audits += 1;
|
|
50
|
+
return { id: "audit-1" };
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
} as unknown as PrismaClient;
|
|
54
|
+
return { prisma, state };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function fakeOpenWork() {
|
|
58
|
+
const calls: { fn: string; args: unknown[] }[] = [];
|
|
59
|
+
const port: OpenWorkPort = {
|
|
60
|
+
listOpenWork: async (...args) => {
|
|
61
|
+
calls.push({ fn: "list", args });
|
|
62
|
+
return [{ id: "T-1", repo: "acme/old", title: "fix it" }];
|
|
63
|
+
},
|
|
64
|
+
blockOpenWork: async (...args) => {
|
|
65
|
+
calls.push({ fn: "block", args });
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
return { port, calls };
|
|
69
|
+
}
|
|
70
|
+
|
|
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 = {
|
|
77
|
+
listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
|
|
78
|
+
addRepos: async () => {},
|
|
79
|
+
removeRepos: async () => {},
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const build = (openWork?: OpenWorkPort) => {
|
|
83
|
+
const { prisma, state } = fakePrisma(["acme/old"]);
|
|
84
|
+
const svc = createGithubReconcile({
|
|
85
|
+
prisma,
|
|
86
|
+
appService: { get: async () => null, getPrivateKey: async () => null },
|
|
87
|
+
access: accessFor(["acme/api"]),
|
|
88
|
+
agentEnv: envWith({ GH_APP_ID: "42" }),
|
|
89
|
+
installation,
|
|
90
|
+
openWork,
|
|
91
|
+
});
|
|
92
|
+
if (!svc) throw new Error("expected a reconcile service");
|
|
93
|
+
return { svc, state };
|
|
94
|
+
};
|
|
95
|
+
|
|
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);
|
|
116
|
+
});
|
|
117
|
+
|
|
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({
|
|
127
|
+
prisma,
|
|
128
|
+
appService: { get: async () => null, getPrivateKey: async () => null },
|
|
129
|
+
access: accessFor([]),
|
|
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
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("with a port: plan lists affected open work and apply blocks it", async () => {
|
|
140
|
+
const { port, calls } = fakeOpenWork();
|
|
141
|
+
const { svc } = build(port);
|
|
142
|
+
const { plan, openWork } = await svc.planWithOpenWork("a1");
|
|
143
|
+
expect(plan.diff.configRemoves).toEqual(["acme/old"]);
|
|
144
|
+
expect(openWork).toEqual([
|
|
145
|
+
{ id: "T-1", repo: "acme/old", title: "fix it" },
|
|
146
|
+
]);
|
|
147
|
+
const res = await svc.apply({
|
|
148
|
+
agentId: "a1",
|
|
149
|
+
caller: "root",
|
|
150
|
+
planHash: plan.planHash,
|
|
151
|
+
});
|
|
152
|
+
expect(res.status).toBe("applied");
|
|
153
|
+
const block = calls.find((c) => c.fn === "block");
|
|
154
|
+
expect(block?.args[0]).toBe("a1");
|
|
155
|
+
expect(block?.args[1]).toEqual(["acme/old"]);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("without a port: nothing is listed or blocked, apply still works", async () => {
|
|
159
|
+
const { svc, state } = build();
|
|
160
|
+
const { plan, openWork } = await svc.planWithOpenWork("a1");
|
|
161
|
+
expect(openWork).toEqual([]);
|
|
162
|
+
const res = await svc.apply({
|
|
163
|
+
agentId: "a1",
|
|
164
|
+
caller: "root",
|
|
165
|
+
planHash: plan.planHash,
|
|
166
|
+
});
|
|
167
|
+
expect(res.status).toBe("applied");
|
|
168
|
+
expect(state.repos).toEqual([]);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
@@ -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
|
+
}
|