@app-vitals/agent-admin 1.25.0 → 1.27.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.
@@ -0,0 +1,191 @@
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
+ repos: string[];
41
+ pushable: string[];
42
+ installed?: string[];
43
+ openWork?: OpenWorkPort;
44
+ preview?: GithubAccessPreview;
45
+ }) {
46
+ const state = { repos: [...opts.repos] };
47
+ const calls: string[] = [];
48
+ const audits: unknown[] = [];
49
+ const deps: ReconcileApplyDeps = {
50
+ agents: {
51
+ get: async () => ({
52
+ id: "a1",
53
+ repos: state.repos,
54
+ githubUsername: "dev",
55
+ }),
56
+ setRepos: async (_id, repos) => {
57
+ calls.push("config");
58
+ state.repos = repos;
59
+ },
60
+ },
61
+ access: async () =>
62
+ opts.preview ?? { status: "ok", access: access(opts.pushable) },
63
+ installation: {
64
+ listRepos: async () => ({ acme: opts.installed ?? opts.repos }),
65
+ addRepos: async () => {
66
+ calls.push("inst-add");
67
+ },
68
+ removeRepos: async () => {
69
+ calls.push("inst-remove");
70
+ },
71
+ },
72
+ audit: {
73
+ write: async (e) => {
74
+ audits.push(e);
75
+ return "audit-1";
76
+ },
77
+ },
78
+ openWork: opts.openWork,
79
+ };
80
+ return { svc: new ReconcileApplyService(deps), state, calls, audits };
81
+ }
82
+
83
+ describe("ReconcileApplyService (unit)", () => {
84
+ it("calls blockOpenWork with the reconcile reason for each removed repo", async () => {
85
+ const blocked: { repos: readonly string[]; reason: string }[] = [];
86
+ const openWork: OpenWorkPort = {
87
+ listOpenWork: async (_a, repos) =>
88
+ repos.map((repo) => ({ id: `t-${repo}`, repo })),
89
+ blockOpenWork: async (_a, repos, reason) => {
90
+ blocked.push({ repos, reason });
91
+ },
92
+ };
93
+ const { svc } = build({
94
+ repos: ["acme/a", "acme/b"],
95
+ pushable: ["acme/a"],
96
+ openWork,
97
+ });
98
+ const plan = await svc.plan("a1");
99
+ const res = await svc.apply({
100
+ agentId: "a1",
101
+ caller: "dan@x.io",
102
+ planHash: plan.planHash,
103
+ });
104
+ expect(res.status).toBe("applied");
105
+ expect(blocked).toEqual([
106
+ {
107
+ repos: ["acme/b"],
108
+ reason: "repo removed from agent by GitHub reconcile (acme/b)",
109
+ },
110
+ ]);
111
+ });
112
+
113
+ it("succeeds with no port and does not block", async () => {
114
+ const { svc } = build({
115
+ repos: ["acme/a", "acme/b"],
116
+ pushable: ["acme/a"],
117
+ });
118
+ const plan = await svc.plan("a1");
119
+ const res = await svc.apply({
120
+ agentId: "a1",
121
+ caller: "c",
122
+ planHash: plan.planHash,
123
+ });
124
+ expect(res.status).toBe("applied");
125
+ });
126
+
127
+ it("a port failure does not fail an applied reconcile", async () => {
128
+ const openWork: OpenWorkPort = {
129
+ listOpenWork: async () => [],
130
+ blockOpenWork: async () => {
131
+ throw new Error("store down");
132
+ },
133
+ };
134
+ const { svc } = build({
135
+ repos: ["acme/a", "acme/b"],
136
+ pushable: ["acme/a"],
137
+ openWork,
138
+ });
139
+ const plan = await svc.plan("a1");
140
+ const res = await svc.apply({
141
+ agentId: "a1",
142
+ caller: "c",
143
+ planHash: plan.planHash,
144
+ });
145
+ expect(res.status).toBe("applied");
146
+ expect(res.status === "applied" && res.warnings.join()).toContain(
147
+ "store down",
148
+ );
149
+ });
150
+
151
+ it("skipped plan (unconfigured) changes nothing and writes no audit", async () => {
152
+ const { svc, calls, audits } = build({
153
+ repos: ["acme/a"],
154
+ pushable: [],
155
+ preview: { status: "unconfigured" },
156
+ });
157
+ const res = await svc.apply({ agentId: "a1", caller: "c", planHash: "x" });
158
+ expect(res.status).toBe("skipped");
159
+ expect(calls).toEqual([]);
160
+ expect(audits).toEqual([]);
161
+ });
162
+ });
163
+
164
+ describe("createInstallationPort (unit)", () => {
165
+ it("scopes to the agent App installation and sends simple names", async () => {
166
+ const seen: string[] = [];
167
+ const port = createInstallationPort(
168
+ {
169
+ listOrgInstallations: async () => [
170
+ { id: 1, appId: 10 },
171
+ { id: 2, appId: 20 },
172
+ ],
173
+ listInstallationRepositories: async (_o, id) => {
174
+ seen.push(`list:${id}`);
175
+ return [{ fullName: "acme/a" }];
176
+ },
177
+ addRepositories: async (_o, id, names) => {
178
+ seen.push(`add:${id}:${names.join(",")}`);
179
+ },
180
+ removeRepositories: async (_o, id, names) => {
181
+ seen.push(`rm:${id}:${names.join(",")}`);
182
+ },
183
+ },
184
+ 20,
185
+ );
186
+ expect(await port.listRepos(["acme"])).toEqual({ acme: ["acme/a"] });
187
+ await port.addRepos("acme", ["acme/b"]);
188
+ await port.removeRepos("acme", ["acme/c", "acme/d"]);
189
+ expect(seen).toEqual(["list:2", "add:2:b", "rm:2:c,d"]);
190
+ });
191
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * admin/src/reconcile-open-work.ts
3
+ * Optional open-work port for the GitHub reconcile (GHE-3.3). The admin
4
+ * package knows nothing about task stores; a consumer that does (shipwright)
5
+ * may supply this port so work on repos removed from an agent gets blocked.
6
+ * Additive and optional: with no port, nothing is listed or blocked.
7
+ */
8
+
9
+ export interface OpenWorkItem {
10
+ /** Consumer-defined id (e.g. a task id). */
11
+ id: string;
12
+ /** owner/repo the item belongs to. */
13
+ repo: string;
14
+ title?: string;
15
+ }
16
+
17
+ export interface OpenWorkPort {
18
+ /** Open work the agent holds on any of `repos` (owner/repo). */
19
+ listOpenWork(
20
+ agentId: string,
21
+ repos: readonly string[],
22
+ ): Promise<OpenWorkItem[]>;
23
+ /** Block the agent's open work on `repos`; `reason` is shown to humans. */
24
+ blockOpenWork(
25
+ agentId: string,
26
+ repos: readonly string[],
27
+ reason: string,
28
+ ): Promise<void>;
29
+ }
30
+
31
+ export function removedRepoBlockReason(repo: string): string {
32
+ return `repo removed from agent by GitHub reconcile (${repo})`;
33
+ }
@@ -0,0 +1,249 @@
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
+ function orgSkipReason(
88
+ result: OrgAccessResult | undefined,
89
+ ): string | undefined {
90
+ if (!result) return "org was not checked";
91
+ if (result.reason === SELECTED_REPOS_REASON) {
92
+ return "lookup app is installed on selected repositories only";
93
+ }
94
+ if (result.status === "partial") return "access listing is incomplete";
95
+ if (result.status !== "ok") return `access lookup failed: ${result.status}`;
96
+ return undefined;
97
+ }
98
+
99
+ function hashPlan(
100
+ username: string,
101
+ diff: ReconcileDiff,
102
+ skippedOrgs: OrgSkip[],
103
+ rejectedAdds: RejectedAdd[],
104
+ skipReason: string | undefined,
105
+ ): string {
106
+ const canonical = JSON.stringify({
107
+ username: username.toLowerCase(),
108
+ diff,
109
+ skippedOrgs,
110
+ rejectedAdds,
111
+ skipReason: skipReason ?? null,
112
+ });
113
+ return createHash("sha256").update(canonical).digest("hex");
114
+ }
115
+
116
+ function finish(
117
+ username: string,
118
+ plan: Omit<ReconcilePlan, "empty" | "planHash">,
119
+ ): ReconcilePlan {
120
+ const d = plan.diff;
121
+ const empty =
122
+ d.installationAdds.length +
123
+ d.installationRemoves.length +
124
+ d.configAdds.length +
125
+ d.configRemoves.length ===
126
+ 0;
127
+ return {
128
+ ...plan,
129
+ empty,
130
+ planHash: hashPlan(
131
+ username,
132
+ d,
133
+ plan.skippedOrgs,
134
+ plan.rejectedAdds,
135
+ plan.skipReason,
136
+ ),
137
+ };
138
+ }
139
+
140
+ function skippedPlan(username: string, reason: string): ReconcilePlan {
141
+ return finish(username, {
142
+ skipped: true,
143
+ skipReason: reason,
144
+ diff: EMPTY_DIFF(),
145
+ skippedOrgs: [],
146
+ rejectedAdds: [],
147
+ warnings: [],
148
+ });
149
+ }
150
+
151
+ export function planReconcile(input: ReconcilePlanInput): ReconcilePlan {
152
+ const username = input.username?.trim() ?? "";
153
+ if (!username)
154
+ return skippedPlan("", "no GitHub username bound to the agent");
155
+ const access = input.access;
156
+ if (!access) return skippedPlan(username, "access was not resolved");
157
+ if (access.outcome === "user_not_found") {
158
+ return skippedPlan(username, "GitHub user not found");
159
+ }
160
+ if (!access.userVerified) {
161
+ return skippedPlan(username, "GitHub user could not be verified");
162
+ }
163
+
164
+ const orgResults = new Map(access.orgs.map((o) => [o.org, o]));
165
+ const pushable = new Set<string>();
166
+ for (const o of access.orgs) {
167
+ for (const r of o.repos) if (r.canPush) pushable.add(r.fullName);
168
+ }
169
+
170
+ const installation = new Set<string>();
171
+ for (const repos of Object.values(input.installationRepos)) {
172
+ for (const r of repos) installation.add(r);
173
+ }
174
+
175
+ const warnings: string[] = [];
176
+ const skipReasons = new Map<string, string>();
177
+ const checkOrg = (org: string): string | undefined => {
178
+ if (!skipReasons.has(org)) {
179
+ const reason = orgSkipReason(orgResults.get(org));
180
+ if (reason) skipReasons.set(org, reason);
181
+ }
182
+ return skipReasons.get(org);
183
+ };
184
+
185
+ const agentRepos = new Set(input.agentRepos);
186
+ const configRemoves = new Set<string>();
187
+ for (const repo of sorted(agentRepos)) {
188
+ const org = repoOrg(repo);
189
+ if (checkOrg(org)) continue; // Unknown is never none.
190
+ if (!pushable.has(repo)) {
191
+ configRemoves.add(repo);
192
+ } else if (!installation.has(repo)) {
193
+ // Keeps agent repos a subset of installation repos.
194
+ configRemoves.add(repo);
195
+ warnings.push(`${repo} is not in the agent installation; dropping it`);
196
+ }
197
+ }
198
+ const kept = new Set([...agentRepos].filter((r) => !configRemoves.has(r)));
199
+
200
+ const configAdds = new Set<string>();
201
+ const installationAdds = new Set<string>();
202
+ const rejectedAdds: RejectedAdd[] = [];
203
+ const reject = (repo: string, reason: string) =>
204
+ rejectedAdds.push({ repo, reason });
205
+ const basenames = new Map<string, string>();
206
+ for (const r of sorted(kept)) basenames.set(repoBasename(r), r);
207
+
208
+ for (const repo of sorted(new Set(input.namedAdds ?? []))) {
209
+ if (kept.has(repo)) continue; // Already present: nothing to add.
210
+ if (!pushable.has(repo)) {
211
+ reject(repo, "user cannot push to this repo");
212
+ continue;
213
+ }
214
+ const clash = basenames.get(repoBasename(repo));
215
+ if (clash) {
216
+ reject(repo, `basename collides with ${clash}`);
217
+ continue;
218
+ }
219
+ basenames.set(repoBasename(repo), repo);
220
+ configAdds.add(repo);
221
+ if (!installation.has(repo)) installationAdds.add(repo);
222
+ }
223
+
224
+ // Installation removals follow config removals, only for installed repos.
225
+ const installationRemoves = [...configRemoves].filter((r) =>
226
+ installation.has(r),
227
+ );
228
+
229
+ const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
230
+ org,
231
+ reason: skipReasons.get(org) as string,
232
+ }));
233
+ for (const s of skippedOrgs) {
234
+ warnings.push(`${s.org}: removals skipped (${s.reason})`);
235
+ }
236
+
237
+ return finish(username, {
238
+ skipped: false,
239
+ diff: {
240
+ installationAdds: sorted(installationAdds),
241
+ installationRemoves: sorted(installationRemoves),
242
+ configAdds: sorted(configAdds),
243
+ configRemoves: sorted(configRemoves),
244
+ },
245
+ skippedOrgs,
246
+ rejectedAdds,
247
+ warnings,
248
+ });
249
+ }