@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
@@ -1,279 +0,0 @@
1
- /**
2
- * admin/src/reconcile-apply-service.unit.test.ts
3
- * Unit tests for the open-work port call and the apply guards (fakes only).
4
- */
5
-
6
- import { describe, expect, it } from "bun:test";
7
- import type { GithubAccessPreview } from "./github-access-preview.ts";
8
- import {
9
- createInstallationPort,
10
- type ReconcileApplyDeps,
11
- ReconcileApplyService,
12
- } from "./reconcile-apply-service.ts";
13
- import type { OpenWorkPort } from "./reconcile-open-work.ts";
14
- import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
15
-
16
- function access(pushable: string[]): UserRepoAccessResult {
17
- return {
18
- username: "dev",
19
- outcome: "ok",
20
- userVerified: true,
21
- complete: true,
22
- unresolved: 0,
23
- checkedAt: "2026-11-11T00:00:00.000Z",
24
- orgs: [
25
- {
26
- org: "acme",
27
- status: "ok",
28
- unresolved: 0,
29
- repos: pushable.map((fullName) => ({
30
- fullName,
31
- level: "write" as const,
32
- canPush: true,
33
- })),
34
- },
35
- ],
36
- };
37
- }
38
-
39
- function build(opts: {
40
- appId?: number | null;
41
- repos: string[];
42
- pushable: string[];
43
- installed?: string[];
44
- openWork?: OpenWorkPort;
45
- preview?: GithubAccessPreview;
46
- }) {
47
- const state = { repos: [...opts.repos] };
48
- const calls: string[] = [];
49
- const audits: unknown[] = [];
50
- const deps: ReconcileApplyDeps = {
51
- agents: {
52
- get: async () => ({
53
- id: "a1",
54
- repos: state.repos,
55
- githubUsername: "dev",
56
- ...(opts.appId === null ? {} : { appId: opts.appId ?? 42 }),
57
- }),
58
- setRepos: async (_id, repos) => {
59
- calls.push("config");
60
- state.repos = repos;
61
- },
62
- },
63
- access: async () =>
64
- opts.preview ?? { status: "ok", access: access(opts.pushable) },
65
- installation: {
66
- listRepos: async (_app, _orgs) => ({
67
- acme: opts.installed ?? opts.repos,
68
- }),
69
- addRepos: async (_app) => {
70
- calls.push("inst-add");
71
- },
72
- removeRepos: async () => {
73
- calls.push("inst-remove");
74
- },
75
- },
76
- audit: {
77
- write: async (e) => {
78
- audits.push(e);
79
- return "audit-1";
80
- },
81
- },
82
- openWork: opts.openWork,
83
- };
84
- return { svc: new ReconcileApplyService(deps), state, calls, audits };
85
- }
86
-
87
- describe("ReconcileApplyService (unit)", () => {
88
- it("calls blockOpenWork with the reconcile reason for each removed repo", async () => {
89
- const blocked: { repos: readonly string[]; reason: string }[] = [];
90
- const openWork: OpenWorkPort = {
91
- listOpenWork: async (_a, repos) =>
92
- repos.map((repo) => ({ id: `t-${repo}`, repo })),
93
- blockOpenWork: async (_a, repos, reason) => {
94
- blocked.push({ repos, reason });
95
- },
96
- };
97
- const { svc } = build({
98
- repos: ["acme/a", "acme/b"],
99
- pushable: ["acme/a"],
100
- openWork,
101
- });
102
- const plan = await svc.plan("a1");
103
- const res = await svc.apply({
104
- agentId: "a1",
105
- caller: "dan@x.io",
106
- planHash: plan.planHash,
107
- });
108
- expect(res.status).toBe("applied");
109
- expect(blocked).toEqual([
110
- {
111
- repos: ["acme/b"],
112
- reason: "repo removed from agent by GitHub reconcile (acme/b)",
113
- },
114
- ]);
115
- });
116
-
117
- it("succeeds with no port and does not block", async () => {
118
- const { svc } = build({
119
- repos: ["acme/a", "acme/b"],
120
- pushable: ["acme/a"],
121
- });
122
- const plan = await svc.plan("a1");
123
- const res = await svc.apply({
124
- agentId: "a1",
125
- caller: "c",
126
- planHash: plan.planHash,
127
- });
128
- expect(res.status).toBe("applied");
129
- });
130
-
131
- it("a port failure does not fail an applied reconcile", async () => {
132
- const openWork: OpenWorkPort = {
133
- listOpenWork: async () => [],
134
- blockOpenWork: async () => {
135
- throw new Error("store down");
136
- },
137
- };
138
- const { svc } = build({
139
- repos: ["acme/a", "acme/b"],
140
- pushable: ["acme/a"],
141
- openWork,
142
- });
143
- const plan = await svc.plan("a1");
144
- const res = await svc.apply({
145
- agentId: "a1",
146
- caller: "c",
147
- planHash: plan.planHash,
148
- });
149
- expect(res.status).toBe("applied");
150
- expect(res.status === "applied" && res.warnings.join()).toContain(
151
- "store down",
152
- );
153
- });
154
-
155
- it("agent without GH_APP_ID is skipped with a reason naming GH_APP_ID", async () => {
156
- const { svc, calls } = build({
157
- appId: null,
158
- repos: ["acme/a"],
159
- pushable: ["acme/a"],
160
- });
161
- const plan = await svc.plan("a1");
162
- expect(plan.skipped).toBe(true);
163
- expect(plan.skipReason).toContain("GH_APP_ID");
164
- expect(plan.skipReason).not.toContain("not configured");
165
- const res = await svc.apply({ agentId: "a1", caller: "c", planHash: "x" });
166
- expect(res.status).toBe("skipped");
167
- expect(calls).toEqual([]);
168
- });
169
-
170
- it("passes the agent's own App id to the installation port", async () => {
171
- const seen: number[] = [];
172
- const { svc } = build({
173
- appId: 77,
174
- repos: ["acme/a"],
175
- pushable: ["acme/a"],
176
- });
177
- // @ts-expect-error reach into deps to spy
178
- const inst = svc.deps.installation;
179
- const orig = inst.listRepos;
180
- inst.listRepos = async (app: number, orgs: readonly string[]) => {
181
- seen.push(app);
182
- return orig(app, orgs);
183
- };
184
- await svc.plan("a1");
185
- expect(seen).toEqual([77]);
186
- });
187
-
188
- it("skipped plan (unconfigured) changes nothing and writes no audit", async () => {
189
- const { svc, calls, audits } = build({
190
- repos: ["acme/a"],
191
- pushable: [],
192
- preview: { status: "unconfigured" },
193
- });
194
- const res = await svc.apply({ agentId: "a1", caller: "c", planHash: "x" });
195
- expect(res.status).toBe("skipped");
196
- expect(calls).toEqual([]);
197
- expect(audits).toEqual([]);
198
- });
199
- });
200
-
201
- describe("createInstallationPort (unit)", () => {
202
- it("scopes to the given App's installation per call and sends simple names", async () => {
203
- const seen: string[] = [];
204
- const port = createInstallationPort({
205
- listOrgInstallations: async () => [
206
- { id: 1, appId: 10 },
207
- { id: 2, appId: 20 },
208
- ],
209
- listInstallationRepositories: async (_o, id) => {
210
- seen.push(`list:${id}`);
211
- return [{ fullName: "acme/a" }];
212
- },
213
- addRepositories: async (_o, id, names) => {
214
- seen.push(`add:${id}:${names.join(",")}`);
215
- },
216
- removeRepositories: async (_o, id, names) => {
217
- seen.push(`rm:${id}:${names.join(",")}`);
218
- },
219
- });
220
- expect(await port.listRepos(20, ["acme"])).toEqual({ acme: ["acme/a"] });
221
- await port.addRepos(20, "acme", ["acme/b"]);
222
- await port.removeRepos(10, "acme", ["acme/c", "acme/d"]);
223
- expect(seen).toEqual(["list:2", "add:2:b", "rm:1:c,d"]);
224
- });
225
-
226
- it("names the org when the App is not installed there", async () => {
227
- const port = createInstallationPort({
228
- listOrgInstallations: async () => [{ id: 1, appId: 10 }],
229
- listInstallationRepositories: async () => [],
230
- addRepositories: async () => {},
231
- removeRepositories: async () => {},
232
- });
233
- await expect(port.listRepos(99, ["acme"])).rejects.toThrow(
234
- /99.*not installed on org acme/,
235
- );
236
- });
237
- });
238
-
239
- describe("ReconcileApplyService.planWithOpenWork (unit)", () => {
240
- const removing = { repos: ["acme/a", "acme/b"], pushable: ["acme/a"] };
241
-
242
- it("lists open work on the repos the plan removes", async () => {
243
- const seen: (readonly string[])[] = [];
244
- const { svc } = build({
245
- ...removing,
246
- openWork: {
247
- listOpenWork: async (_a, repos) => {
248
- seen.push(repos);
249
- return [{ id: "t1", repo: "acme/b", title: "x" }];
250
- },
251
- blockOpenWork: async () => {},
252
- },
253
- });
254
- const res = await svc.planWithOpenWork("a1");
255
- expect(seen).toEqual([["acme/b"]]);
256
- expect(res.openWork).toEqual([{ id: "t1", repo: "acme/b", title: "x" }]);
257
- expect(res.plan.diff.configRemoves).toEqual(["acme/b"]);
258
- });
259
-
260
- it("returns an empty list with no port", async () => {
261
- const { svc } = build(removing);
262
- expect((await svc.planWithOpenWork("a1")).openWork).toEqual([]);
263
- });
264
-
265
- it("a port failure becomes a warning, not an error", async () => {
266
- const { svc } = build({
267
- ...removing,
268
- openWork: {
269
- listOpenWork: async () => {
270
- throw new Error("store down");
271
- },
272
- blockOpenWork: async () => {},
273
- },
274
- });
275
- const res = await svc.planWithOpenWork("a1");
276
- expect(res.openWork).toEqual([]);
277
- expect(res.plan.warnings.join(" ")).toContain("store down");
278
- });
279
- });
@@ -1,264 +0,0 @@
1
- /**
2
- * admin/src/reconcile-planner.ts
3
- * ReconcilePlanner: pure planning half of the repo reconcile (GHE-3.2). Turns
4
- * a UserRepoAccessResolver result, the agent's repos and the agent App's
5
- * installation repositories into a diff plus a stable plan hash. No I/O.
6
- *
7
- * Rules:
8
- * - Desired agent repos = current repos kept only where the bound user can
9
- * push. Newly accessible repos are never added; adds happen only when the
10
- * admin names them, and only if push-capable and not basename-colliding.
11
- * - Removals never come from incomplete knowledge: an org whose resolver
12
- * result is missing, partial, failed, or whose lookup installation is
13
- * selected-only is skipped (with a reason); so is everything when the
14
- * user is unbound, not found or unverified.
15
- * - Agent repos stay a subset of installation repos. A removed repo leaves
16
- * the installation too; an add is installed first when absent.
17
- * - Planning over an already-reconciled state is an empty diff with the same
18
- * hash.
19
- */
20
-
21
- import { createHash } from "node:crypto";
22
- import {
23
- type OrgAccessResult,
24
- SELECTED_REPOS_REASON,
25
- type UserRepoAccessResult,
26
- } from "./user-repo-access-resolver.ts";
27
-
28
- export interface ReconcilePlanInput {
29
- /** Bound GitHub username; null/empty yields a skipped plan. */
30
- username: string | null | undefined;
31
- /** Null when the resolver was not run (no bound user). */
32
- access: UserRepoAccessResult | null;
33
- /** The agent's configured repos, owner/repo. */
34
- agentRepos: readonly string[];
35
- /** Repos the agent App's installation covers, per org login. */
36
- installationRepos: Readonly<Record<string, readonly string[]>>;
37
- /** Repos the admin explicitly asks to add, owner/repo. */
38
- namedAdds?: readonly string[];
39
- }
40
-
41
- export interface OrgSkip {
42
- org: string;
43
- reason: string;
44
- }
45
-
46
- export interface RejectedAdd {
47
- repo: string;
48
- reason: string;
49
- }
50
-
51
- export interface ReconcileDiff {
52
- installationAdds: string[];
53
- installationRemoves: string[];
54
- configAdds: string[];
55
- configRemoves: string[];
56
- }
57
-
58
- export interface ReconcilePlan {
59
- skipped: boolean;
60
- /** Set when the whole plan is skipped. */
61
- skipReason?: string;
62
- diff: ReconcileDiff;
63
- skippedOrgs: OrgSkip[];
64
- rejectedAdds: RejectedAdd[];
65
- warnings: string[];
66
- empty: boolean;
67
- planHash: string;
68
- }
69
-
70
- const EMPTY_DIFF = (): ReconcileDiff => ({
71
- installationAdds: [],
72
- installationRemoves: [],
73
- configAdds: [],
74
- configRemoves: [],
75
- });
76
-
77
- export function repoOrg(fullName: string): string {
78
- return fullName.split("/")[0] ?? "";
79
- }
80
-
81
- export function repoBasename(fullName: string): string {
82
- return (fullName.split("/")[1] ?? fullName).toLowerCase();
83
- }
84
-
85
- const sorted = (xs: Iterable<string>): string[] => [...xs].sort();
86
-
87
- /**
88
- * Why removals in one org must be skipped (unknown is never none): the org
89
- * was not checked, its listing is partial or failed, or the lookup App is
90
- * installed on selected repositories only. Undefined when the listing is
91
- * complete. Shared with the lost-access removal (IRM-1.3).
92
- */
93
- export function orgSkipReason(
94
- result: OrgAccessResult | undefined,
95
- ): string | undefined {
96
- if (!result) return "org was not checked";
97
- if (result.reason === SELECTED_REPOS_REASON) {
98
- return "lookup app is installed on selected repositories only";
99
- }
100
- if (result.status === "partial") return "access listing is incomplete";
101
- if (result.status !== "ok") return `access lookup failed: ${result.status}`;
102
- return undefined;
103
- }
104
-
105
- function hashPlan(
106
- username: string,
107
- diff: ReconcileDiff,
108
- skippedOrgs: OrgSkip[],
109
- rejectedAdds: RejectedAdd[],
110
- skipReason: string | undefined,
111
- ): string {
112
- const canonical = JSON.stringify({
113
- username: username.toLowerCase(),
114
- diff,
115
- skippedOrgs,
116
- rejectedAdds,
117
- skipReason: skipReason ?? null,
118
- });
119
- return createHash("sha256").update(canonical).digest("hex");
120
- }
121
-
122
- function finish(
123
- username: string,
124
- plan: Omit<ReconcilePlan, "empty" | "planHash">,
125
- ): ReconcilePlan {
126
- const d = plan.diff;
127
- const empty =
128
- d.installationAdds.length +
129
- d.installationRemoves.length +
130
- d.configAdds.length +
131
- d.configRemoves.length ===
132
- 0;
133
- return {
134
- ...plan,
135
- empty,
136
- planHash: hashPlan(
137
- username,
138
- d,
139
- plan.skippedOrgs,
140
- plan.rejectedAdds,
141
- plan.skipReason,
142
- ),
143
- };
144
- }
145
-
146
- function skippedPlan(username: string, reason: string): ReconcilePlan {
147
- return finish(username, {
148
- skipped: true,
149
- skipReason: reason,
150
- diff: EMPTY_DIFF(),
151
- skippedOrgs: [],
152
- rejectedAdds: [],
153
- warnings: [],
154
- });
155
- }
156
-
157
- /**
158
- * Why a whole plan must be skipped: no bound user, access not resolved, user
159
- * not found or not verified. Undefined when the access result is usable.
160
- * Shared with the lost-access removal (IRM-1.3).
161
- */
162
- export function accessSkipReason(
163
- username: string | null | undefined,
164
- access: UserRepoAccessResult | null,
165
- ): string | undefined {
166
- if (!username?.trim()) return "no GitHub username bound to the agent";
167
- if (!access) return "access was not resolved";
168
- if (access.outcome === "user_not_found") return "GitHub user not found";
169
- if (!access.userVerified) return "GitHub user could not be verified";
170
- return undefined;
171
- }
172
-
173
- export function planReconcile(input: ReconcilePlanInput): ReconcilePlan {
174
- const username = input.username?.trim() ?? "";
175
- const skipReason = accessSkipReason(username, input.access);
176
- if (skipReason) return skippedPlan(username, skipReason);
177
- const access = input.access as UserRepoAccessResult;
178
-
179
- const orgResults = new Map(access.orgs.map((o) => [o.org, o]));
180
- const pushable = new Set<string>();
181
- for (const o of access.orgs) {
182
- for (const r of o.repos) if (r.canPush) pushable.add(r.fullName);
183
- }
184
-
185
- const installation = new Set<string>();
186
- for (const repos of Object.values(input.installationRepos)) {
187
- for (const r of repos) installation.add(r);
188
- }
189
-
190
- const warnings: string[] = [];
191
- const skipReasons = new Map<string, string>();
192
- const checkOrg = (org: string): string | undefined => {
193
- if (!skipReasons.has(org)) {
194
- const reason = orgSkipReason(orgResults.get(org));
195
- if (reason) skipReasons.set(org, reason);
196
- }
197
- return skipReasons.get(org);
198
- };
199
-
200
- const agentRepos = new Set(input.agentRepos);
201
- const configRemoves = new Set<string>();
202
- for (const repo of sorted(agentRepos)) {
203
- const org = repoOrg(repo);
204
- if (checkOrg(org)) continue; // Unknown is never none.
205
- if (!pushable.has(repo)) {
206
- configRemoves.add(repo);
207
- } else if (!installation.has(repo)) {
208
- // Keeps agent repos a subset of installation repos.
209
- configRemoves.add(repo);
210
- warnings.push(`${repo} is not in the agent installation; dropping it`);
211
- }
212
- }
213
- const kept = new Set([...agentRepos].filter((r) => !configRemoves.has(r)));
214
-
215
- const configAdds = new Set<string>();
216
- const installationAdds = new Set<string>();
217
- const rejectedAdds: RejectedAdd[] = [];
218
- const reject = (repo: string, reason: string) =>
219
- rejectedAdds.push({ repo, reason });
220
- const basenames = new Map<string, string>();
221
- for (const r of sorted(kept)) basenames.set(repoBasename(r), r);
222
-
223
- for (const repo of sorted(new Set(input.namedAdds ?? []))) {
224
- if (kept.has(repo)) continue; // Already present: nothing to add.
225
- if (!pushable.has(repo)) {
226
- reject(repo, "user cannot push to this repo");
227
- continue;
228
- }
229
- const clash = basenames.get(repoBasename(repo));
230
- if (clash) {
231
- reject(repo, `basename collides with ${clash}`);
232
- continue;
233
- }
234
- basenames.set(repoBasename(repo), repo);
235
- configAdds.add(repo);
236
- if (!installation.has(repo)) installationAdds.add(repo);
237
- }
238
-
239
- // Installation removals follow config removals, only for installed repos.
240
- const installationRemoves = [...configRemoves].filter((r) =>
241
- installation.has(r),
242
- );
243
-
244
- const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
245
- org,
246
- reason: skipReasons.get(org) as string,
247
- }));
248
- for (const s of skippedOrgs) {
249
- warnings.push(`${s.org}: removals skipped (${s.reason})`);
250
- }
251
-
252
- return finish(username, {
253
- skipped: false,
254
- diff: {
255
- installationAdds: sorted(installationAdds),
256
- installationRemoves: sorted(installationRemoves),
257
- configAdds: sorted(configAdds),
258
- configRemoves: sorted(configRemoves),
259
- },
260
- skippedOrgs,
261
- rejectedAdds,
262
- warnings,
263
- });
264
- }