@app-vitals/agent-admin 1.29.0 → 1.31.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.29.0",
3
+ "version": "1.31.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.29.0",
45
+ "@app-vitals/agent-lib": "1.31.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -99,12 +99,16 @@ import { CronRunNowService } from "./cron-run-now.ts";
99
99
  import { parseCronRunNowConfig } from "./cron-run-now-config.ts";
100
100
  import { CronRunTranscriptService } from "./cron-run-transcripts.ts";
101
101
  import { isDevAuthAllowed } from "./dev-auth-guard.ts";
102
+ import { HttpGithubAppProvisioningClient } from "./github-app-provisioning-client.ts";
102
103
  import {
103
104
  createGithubAccessPreview,
104
105
  createGithubEnterpriseApp,
105
106
  } from "./github-enterprise-api.ts";
106
107
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
107
- import { HttpGithubAppProvisioningClient } from "./github-app-provisioning-client.ts";
108
+ import {
109
+ createGithubReconcile,
110
+ parseAgentAppId,
111
+ } from "./github-reconcile-wiring.ts";
108
112
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
109
113
  import { HttpChatClient } from "./http-chat-client.ts";
110
114
  import { HttpOktaAuthClient } from "./okta-auth-client.ts";
@@ -466,10 +470,21 @@ export async function startAdmin(
466
470
  prisma,
467
471
  makeStrictTokenCrypto(),
468
472
  );
473
+ const githubAccessPreview = createGithubAccessPreview({
474
+ appService: githubEnterpriseAppService,
475
+ });
476
+ // GHE-3.9: the reconcile routes' service, with the extension's optional
477
+ // open-work port. Unwired (routes report `skipped`) without an agent App id.
478
+ const githubReconcile = createGithubReconcile({
479
+ prisma,
480
+ appService: githubEnterpriseAppService,
481
+ access: githubAccessPreview,
482
+ agentAppId: parseAgentAppId(process.env.SHIPWRIGHT_GITHUB_AGENT_APP_ID),
483
+ openWork: resolvedExtensions.openWork,
484
+ });
469
485
  const adminApiApp = createAdminApp({
470
- githubAccessPreview: createGithubAccessPreview({
471
- appService: githubEnterpriseAppService,
472
- }),
486
+ githubAccessPreview,
487
+ ...(githubReconcile ? { githubReconcile } : {}),
473
488
  agentService,
474
489
  agentEnvService,
475
490
  agentCronJobService,
@@ -62,6 +62,7 @@ import type { AdminDeps, parseAdminApiKeys } from "./agents-api.ts";
62
62
  import type { AgentPhaseMethodologyServiceLike } from "./api.ts";
63
63
  import type { createCallerScopeResolver } from "./caller-scope.ts";
64
64
  import type { PushService } from "./push-service.ts";
65
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
65
66
  import type { ServiceIntegration } from "./service-integration.ts";
66
67
  import type {
67
68
  SpecialtyDefaults,
@@ -128,6 +129,12 @@ export interface AdminExtensionServices {
128
129
  * the runtime app omits the field.
129
130
  */
130
131
  agentPhaseMethodologyService?: AgentPhaseMethodologyServiceLike;
132
+ /**
133
+ * Supplies the GitHub reconcile's open-work port (GHE-3.9): plan lists the
134
+ * open work on repos it would remove and apply blocks it. Absent from every
135
+ * extension → nothing is listed or blocked.
136
+ */
137
+ openWork?: OpenWorkPort;
131
138
  }
132
139
 
133
140
  export interface AgentDetailCardContext {
@@ -212,6 +219,7 @@ export interface ResolvedAdminExtensions {
212
219
  apiDeps: Partial<AdminDeps>;
213
220
  uiDeps: Partial<AdminUIDeps>;
214
221
  agentPhaseMethodologyService?: AgentPhaseMethodologyServiceLike;
222
+ openWork?: OpenWorkPort;
215
223
  apiRoutes: AdminRouteContribution[];
216
224
  adminUiRoutes: AdminRouteContribution[];
217
225
  agentDetailCards: AgentDetailCardSlot[];
@@ -238,8 +246,13 @@ export function resolveAdminExtensions(
238
246
  .map((s) => s.agentPhaseMethodologyService)
239
247
  .filter((svc) => svc !== undefined)
240
248
  .at(-1);
249
+ const openWork = services
250
+ .map((s) => s.openWork)
251
+ .filter((port) => port !== undefined)
252
+ .at(-1);
241
253
  return {
242
254
  ...(agentPhaseMethodologyService ? { agentPhaseMethodologyService } : {}),
255
+ ...(openWork ? { openWork } : {}),
243
256
  apiDeps: Object.assign({}, ...services.map((s) => s.api ?? {})),
244
257
  uiDeps: Object.assign({}, ...services.map((s) => s.ui ?? {})),
245
258
  apiRoutes,
@@ -18,12 +18,32 @@ import {
18
18
  startBackgroundPasses,
19
19
  withExtensionAgentTypes,
20
20
  } from "./admin-extension.ts";
21
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
21
22
 
22
23
  // The seam only hands the context through to hooks, so an opaque stand-in is
23
24
  // enough — no hook under test reads from it.
24
25
  const ctx = { env: {} } as unknown as AdminExtensionContext;
25
26
 
26
27
  describe("resolveAdminExtensions", () => {
28
+ it("openWork: absent from every extension is omitted; the last supplier wins", () => {
29
+ const mk = (id: string): OpenWorkPort => ({
30
+ listOpenWork: async () => [{ id, repo: "acme/x" }],
31
+ blockOpenWork: async () => {},
32
+ });
33
+ expect("openWork" in resolveAdminExtensions([{}], ctx)).toBe(false);
34
+ const first = mk("first");
35
+ const last = mk("last");
36
+ const resolved = resolveAdminExtensions(
37
+ [
38
+ { services: () => ({ openWork: first }) },
39
+ { services: () => ({}) },
40
+ { services: () => ({ openWork: last }) },
41
+ ],
42
+ ctx,
43
+ );
44
+ expect(resolved.openWork).toBe(last);
45
+ });
46
+
27
47
  it("no extensions resolves to empty contributions", () => {
28
48
  expect(resolveAdminExtensions([], ctx)).toEqual({
29
49
  apiDeps: {},
@@ -6,12 +6,12 @@
6
6
  */
7
7
 
8
8
  import { beforeAll, describe, expect, it } from "bun:test";
9
- import { createAdminUIApp } from "./admin-ui.ts";
10
9
  import {
11
10
  AGENT_ID,
12
11
  makeMockDeps,
13
12
  makeSessionCookie,
14
13
  } from "./admin-ui.fixtures.ts";
14
+ import { createAdminUIApp } from "./admin-ui.ts";
15
15
  import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
16
16
 
17
17
  const json = (b: unknown, status = 200) =>
@@ -202,4 +202,118 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
202
202
  expect(res.status).toBe(403);
203
203
  expect(calls.length).toBe(0);
204
204
  });
205
+
206
+ it("GHE-3.5: shows the Reconcile card to an admin with a bound username", async () => {
207
+ const { app } = setup({});
208
+ const html = await (await get(app, admin)).text();
209
+ expect(html).toContain('id="github-reconcile-card"');
210
+ });
211
+
212
+ it("GHE-3.5: hides the Reconcile card when the apps are unconfigured", async () => {
213
+ const { app } = setup({ configured: false });
214
+ const html = await (await get(app, admin)).text();
215
+ expect(html).not.toContain("github-reconcile-card");
216
+ });
217
+
218
+ it("GHE-3.5: hides the Reconcile card from a non-admin", async () => {
219
+ const { app } = setup({});
220
+ const html = await (await get(app, member)).text();
221
+ expect(html).not.toContain("github-reconcile-card");
222
+ });
223
+
224
+ it("GHE-3.5: plan route proxies the API and renders the diff", async () => {
225
+ const { app, calls } = setup({
226
+ agentsApi: () =>
227
+ json({
228
+ status: "planned",
229
+ planHash: "h1",
230
+ empty: false,
231
+ diff: {
232
+ installationAdds: [],
233
+ installationRemoves: [],
234
+ configAdds: ["acme/new"],
235
+ configRemoves: [],
236
+ },
237
+ }),
238
+ });
239
+ const res = await app.request(
240
+ `/admin/agents/${AGENT_ID}/github-reconcile/plan`,
241
+ {
242
+ method: "POST",
243
+ headers: {
244
+ Cookie: `admin_session=${admin}`,
245
+ "Content-Type": "application/json",
246
+ },
247
+ body: JSON.stringify({ addRepos: ["acme/new"] }),
248
+ },
249
+ );
250
+ expect(res.status).toBe(200);
251
+ const html = await res.text();
252
+ expect(calls.at(-1)?.path).toBe(
253
+ `/agents/${AGENT_ID}/github-reconcile/plan`,
254
+ );
255
+ expect(JSON.parse(String(calls.at(-1)?.init?.body))).toEqual({
256
+ addRepos: ["acme/new"],
257
+ });
258
+ expect(html).toContain('data-plan-hash="h1"');
259
+ expect(html).toContain('data-add-repos="acme/new"');
260
+ });
261
+
262
+ it("GHE-3.5: apply route forwards the confirmation and renders the result", async () => {
263
+ const { app, calls } = setup({
264
+ agentsApi: () => json({ status: "applied", auditId: "aud-9" }),
265
+ });
266
+ const payload = { planHash: "h1", addRepos: [], confirmRemovals: true };
267
+ const res = await app.request(
268
+ `/admin/agents/${AGENT_ID}/github-reconcile/apply`,
269
+ {
270
+ method: "POST",
271
+ headers: {
272
+ Cookie: `admin_session=${admin}`,
273
+ "Content-Type": "application/json",
274
+ },
275
+ body: JSON.stringify(payload),
276
+ },
277
+ );
278
+ expect(await res.text()).toContain("aud-9");
279
+ expect(JSON.parse(String(calls.at(-1)?.init?.body))).toEqual(payload);
280
+ });
281
+
282
+ it("GHE-3.5: apply surfaces a 409 stale plan error", async () => {
283
+ const { app } = setup({
284
+ agentsApi: () => json({ error: "the plan changed" }, 409),
285
+ });
286
+ const res = await app.request(
287
+ `/admin/agents/${AGENT_ID}/github-reconcile/apply`,
288
+ {
289
+ method: "POST",
290
+ headers: {
291
+ Cookie: `admin_session=${admin}`,
292
+ "Content-Type": "application/json",
293
+ },
294
+ body: JSON.stringify({ planHash: "old" }),
295
+ },
296
+ );
297
+ expect(res.status).toBe(409);
298
+ expect(await res.text()).toContain("the plan changed");
299
+ });
300
+
301
+ it("GHE-3.5: plan and apply routes are forbidden for a non-admin", async () => {
302
+ const { app, calls } = setup({});
303
+ for (const step of ["plan", "apply"]) {
304
+ const res = await app.request(
305
+ `/admin/agents/${AGENT_ID}/github-reconcile/${step}`,
306
+ {
307
+ method: "POST",
308
+ headers: {
309
+ Cookie: `admin_session=${member}`,
310
+ "Content-Type": "application/json",
311
+ },
312
+ body: "{}",
313
+ },
314
+ );
315
+ expect(res.status).toBe(403);
316
+ }
317
+ expect(calls.length).toBe(0);
318
+ });
205
319
  });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * admin/src/admin-ui-github-reconcile-pages.ts
3
+ * Pure renderers for the agent detail page's GitHub Reconcile card (GHE-3.5).
4
+ * Platform-admin only; the caller renders the card only when a GitHub username
5
+ * is bound and the enterprise apps are configured. The card posts to the
6
+ * admin UI's plan/apply proxy routes; these renderers produce the fragments
7
+ * those routes return. Every dynamic value is escaped. Inputs carry repo names
8
+ * and ids only (no token or key ever reaches this module).
9
+ */
10
+
11
+ import { escapeHtml } from "./admin-ui-styles.ts";
12
+
13
+ /** Mirrors MAX_UNCONFIRMED_REMOVALS in reconcile-apply-service.ts. */
14
+ export const RECONCILE_REMOVAL_CAP = 10;
15
+
16
+ export interface GithubReconcileDiffView {
17
+ installationAdds: string[];
18
+ installationRemoves: string[];
19
+ configAdds: string[];
20
+ configRemoves: string[];
21
+ }
22
+
23
+ /** JSON body of POST /agents/:id/github-reconcile/plan. */
24
+ export interface GithubReconcilePlanView {
25
+ status: "planned" | "skipped";
26
+ reason?: string;
27
+ planHash?: string;
28
+ empty?: boolean;
29
+ diff?: GithubReconcileDiffView;
30
+ skippedOrgs?: { org: string; reason: string }[];
31
+ rejectedAdds?: { repo: string; reason: string }[];
32
+ warnings?: string[];
33
+ affectedOpenWork?: { id: string; repo: string; title?: string }[];
34
+ }
35
+
36
+ /** JSON body of POST /agents/:id/github-reconcile/apply. */
37
+ export interface GithubReconcileApplyView {
38
+ status: "applied" | "failed" | "noop" | "skipped";
39
+ reason?: string;
40
+ auditId?: string;
41
+ error?: string;
42
+ warnings?: string[];
43
+ }
44
+
45
+ /** The Reconcile card; the buttons talk to the UI plan/apply routes. */
46
+ export function renderGithubReconcileCard(agentId: string): string {
47
+ const base = `/admin/agents/${escapeHtml(agentId)}/github-reconcile`;
48
+ return `<div class="card" id="github-reconcile-card">
49
+ <div class="card-title">Reconcile</div>
50
+ <p style="color:#6b7280;font-size:12px;margin:0 0 12px">Plans the repo changes needed to match this agent's GitHub user access. Nothing changes until you review the plan and confirm.</p>
51
+ <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
52
+ <input name="addRepos" id="github-reconcile-add" type="text" class="form-input mono" placeholder="Repos to add (owner/repo, comma separated; optional)" style="min-width:320px" />
53
+ <button type="button" class="btn btn-primary" id="github-reconcile-plan-btn" data-plan-url="${base}/plan" data-apply-url="${base}/apply">Plan</button>
54
+ </div>
55
+ <div id="github-reconcile-result" style="margin-top:12px"></div>
56
+ <script>
57
+ (function() {
58
+ var btn = document.getElementById('github-reconcile-plan-btn');
59
+ var out = document.getElementById('github-reconcile-result');
60
+ var input = document.getElementById('github-reconcile-add');
61
+ if (!btn || !out || !input) return;
62
+ function show(r) { return r.text().then(function(t) { out.innerHTML = t; }); }
63
+ function fail() { out.textContent = 'The request failed.'; }
64
+ function adds() {
65
+ return input.value.split(/[\\s,]+/).filter(function(s) { return s; });
66
+ }
67
+ btn.addEventListener('click', function() {
68
+ btn.disabled = true;
69
+ out.textContent = 'Loading...';
70
+ fetch(btn.getAttribute('data-plan-url'), {
71
+ method: 'POST',
72
+ credentials: 'same-origin',
73
+ headers: { 'content-type': 'application/json' },
74
+ body: JSON.stringify({ addRepos: adds() })
75
+ }).then(show).catch(fail).then(function() { btn.disabled = false; });
76
+ });
77
+ function sync() {
78
+ var plan = out.querySelector('#github-reconcile-plan');
79
+ var apply = out.querySelector('#github-reconcile-apply-btn');
80
+ var ok = out.querySelector('#github-reconcile-confirm');
81
+ var cap = out.querySelector('#github-reconcile-confirm-removals');
82
+ if (!plan || !apply || !ok) return;
83
+ apply.disabled = !(ok.checked && (!cap || cap.checked));
84
+ }
85
+ out.addEventListener('change', sync);
86
+ out.addEventListener('click', function(e) {
87
+ var t = e.target;
88
+ if (!t || t.id !== 'github-reconcile-apply-btn') return;
89
+ var plan = out.querySelector('#github-reconcile-plan');
90
+ var cap = out.querySelector('#github-reconcile-confirm-removals');
91
+ var add = plan.getAttribute('data-add-repos');
92
+ t.disabled = true;
93
+ fetch(btn.getAttribute('data-apply-url'), {
94
+ method: 'POST',
95
+ credentials: 'same-origin',
96
+ headers: { 'content-type': 'application/json' },
97
+ body: JSON.stringify({
98
+ planHash: plan.getAttribute('data-plan-hash'),
99
+ addRepos: add ? add.split(',') : [],
100
+ confirmRemovals: !!(cap && cap.checked)
101
+ })
102
+ }).then(show).catch(fail);
103
+ });
104
+ })();
105
+ </script>
106
+ </div>`;
107
+ }
108
+
109
+ function repoList(repos: string[]): string {
110
+ return repos.length === 0
111
+ ? `<span style="color:#9ca3af">none</span>`
112
+ : repos.map((r) => `<div class="mono">${escapeHtml(r)}</div>`).join("");
113
+ }
114
+
115
+ function diffTable(diff: GithubReconcileDiffView): string {
116
+ const row = (label: string, adds: string[], removes: string[]) =>
117
+ `<tr><td style="width:200px">${label}</td><td>${repoList(adds)}</td><td>${repoList(removes)}</td></tr>`;
118
+ return `<table class="detail-table"><thead><tr><th>Change</th><th>Add</th><th>Remove</th></tr></thead><tbody>${row("Installation", diff.installationAdds, diff.installationRemoves)}${row("Agent config", diff.configAdds, diff.configRemoves)}</tbody></table>`;
119
+ }
120
+
121
+ function section(title: string, body: string): string {
122
+ return `<div style="margin-top:12px"><div style="font-weight:600;margin-bottom:6px">${title}</div>${body}</div>`;
123
+ }
124
+
125
+ /**
126
+ * Fragment for the plan result. `addRepos` is the named-add list the plan was
127
+ * made with; apply must resend it, so it rides along on the plan element.
128
+ */
129
+ export function renderGithubReconcilePlanResult(
130
+ plan: GithubReconcilePlanView,
131
+ addRepos: string[],
132
+ ): string {
133
+ if (plan.status === "skipped" || !plan.diff || !plan.planHash) {
134
+ return `<div class="alert alert-warning">Reconcile skipped: ${escapeHtml(plan.reason ?? "no plan was produced")}.</div>`;
135
+ }
136
+ const parts: string[] = [];
137
+ if (plan.skippedOrgs?.length) {
138
+ parts.push(
139
+ `<div class="alert alert-warning">Skipped organizations:<ul style="margin:6px 0 0 18px">${plan.skippedOrgs.map((o) => `<li><span class="mono">${escapeHtml(o.org)}</span>: ${escapeHtml(o.reason)}</li>`).join("")}</ul></div>`,
140
+ );
141
+ }
142
+ if (plan.rejectedAdds?.length) {
143
+ parts.push(
144
+ `<div class="alert alert-warning">Rejected additions:<ul style="margin:6px 0 0 18px">${plan.rejectedAdds.map((r) => `<li><span class="mono">${escapeHtml(r.repo)}</span>: ${escapeHtml(r.reason)}</li>`).join("")}</ul></div>`,
145
+ );
146
+ }
147
+ if (plan.warnings?.length) {
148
+ parts.push(
149
+ `<div class="alert alert-warning">${plan.warnings.map((w) => `<div>${escapeHtml(w)}</div>`).join("")}</div>`,
150
+ );
151
+ }
152
+ if (plan.empty) {
153
+ parts.push(
154
+ `<p class="empty-state">Nothing to change: the agent already matches its GitHub access.</p>`,
155
+ );
156
+ return parts.join("");
157
+ }
158
+ parts.push(diffTable(plan.diff));
159
+ if (plan.affectedOpenWork?.length) {
160
+ const rows = plan.affectedOpenWork
161
+ .map(
162
+ (w) =>
163
+ `<tr><td class="mono">${escapeHtml(w.id)}</td><td class="mono">${escapeHtml(w.repo)}</td><td>${escapeHtml(w.title ?? "")}</td></tr>`,
164
+ )
165
+ .join("");
166
+ parts.push(
167
+ section(
168
+ "Open tasks and PRs affected by the removals",
169
+ `<table class="detail-table"><thead><tr><th>Id</th><th>Repo</th><th>Title</th></tr></thead><tbody>${rows}</tbody></table>`,
170
+ ),
171
+ );
172
+ }
173
+ const removals = plan.diff.configRemoves.length;
174
+ const overCap = removals > RECONCILE_REMOVAL_CAP;
175
+ const capConfirm = overCap
176
+ ? `<label style="display:block;margin-bottom:8px"><input type="checkbox" id="github-reconcile-confirm-removals" /> This plan removes ${removals} repos (more than ${RECONCILE_REMOVAL_CAP}). I confirm the removals.</label>`
177
+ : "";
178
+ parts.push(
179
+ `<div id="github-reconcile-plan" style="margin-top:12px" data-plan-hash="${escapeHtml(plan.planHash)}" data-add-repos="${escapeHtml(addRepos.join(","))}" data-over-cap="${overCap}">
180
+ <label style="display:block;margin-bottom:8px"><input type="checkbox" id="github-reconcile-confirm" /> I have reviewed this plan and want to apply it.</label>
181
+ ${capConfirm}
182
+ <button type="button" class="btn btn-danger" id="github-reconcile-apply-btn" disabled>Apply</button>
183
+ </div>`,
184
+ );
185
+ return parts.join("");
186
+ }
187
+
188
+ /** Fragment for the apply result. */
189
+ export function renderGithubReconcileApplyResult(
190
+ res: GithubReconcileApplyView,
191
+ ): string {
192
+ const audit = res.auditId
193
+ ? ` Audit id: <span class="mono">${escapeHtml(res.auditId)}</span>.`
194
+ : "";
195
+ const warnings = (res.warnings ?? [])
196
+ .map((w) => `<div>${escapeHtml(w)}</div>`)
197
+ .join("");
198
+ switch (res.status) {
199
+ case "applied":
200
+ return `<div class="alert alert-success">Reconcile applied.${audit}${warnings}</div>`;
201
+ case "noop":
202
+ return `<div class="alert alert-warning">Nothing to change.${warnings}</div>`;
203
+ case "failed":
204
+ return `<div class="alert alert-error">Reconcile failed${res.error ? `: ${escapeHtml(res.error)}` : ""}.${audit}${warnings}</div>`;
205
+ default:
206
+ return `<div class="alert alert-warning">Reconcile skipped${res.reason ? `: ${escapeHtml(res.reason)}` : ""}.</div>`;
207
+ }
208
+ }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * admin/src/admin-ui-github-reconcile-pages.unit.test.ts
3
+ * Unit tests for the GHE-3.5 Reconcile card and its plan/apply fragments, and
4
+ * for the card's placement in renderAgentDetailPage (inert, plan, over-cap).
5
+ */
6
+
7
+ import { describe, expect, test } from "bun:test";
8
+ import {
9
+ type GithubReconcilePlanView,
10
+ renderGithubReconcileApplyResult,
11
+ renderGithubReconcileCard,
12
+ renderGithubReconcilePlanResult,
13
+ } from "./admin-ui-github-reconcile-pages.ts";
14
+ import { type AgentDetail, renderAgentDetailPage } from "./admin-ui-pages.ts";
15
+
16
+ const AGENT: AgentDetail = {
17
+ id: "agent-123",
18
+ name: "Test Agent",
19
+ slackId: "U12345",
20
+ selfHosted: false,
21
+ createdAt: new Date("2024-01-01T00:00:00Z"),
22
+ updatedAt: new Date("2024-01-02T00:00:00Z"),
23
+ repos: [],
24
+ authorAllowlist: [],
25
+ patchAuthorAllowlist: [],
26
+ restrictSlackToMembers: false,
27
+ specialty: "coding",
28
+ missingRequiredEnv: [],
29
+ autoPostReviews: true,
30
+ allowSelfReview: false,
31
+ minConfidence: 75,
32
+ maxFindings: 5,
33
+ cleanupMergedWorktrees: true,
34
+ cleanupAfterDays: 14,
35
+ };
36
+
37
+ function page(
38
+ isAdmin: boolean,
39
+ configured: boolean,
40
+ githubUsername: string | null,
41
+ ): string {
42
+ return renderAgentDetailPage(
43
+ { ...AGENT, githubUsername },
44
+ {},
45
+ [],
46
+ [],
47
+ [],
48
+ [],
49
+ [],
50
+ "u@x.com",
51
+ isAdmin,
52
+ { timezone: "UTC", githubEnterpriseConfigured: configured },
53
+ );
54
+ }
55
+
56
+ const plan = (over: Partial<GithubReconcilePlanView> = {}) =>
57
+ ({
58
+ status: "planned",
59
+ planHash: "hash-1",
60
+ empty: false,
61
+ diff: {
62
+ installationAdds: ["acme/new"],
63
+ installationRemoves: ["acme/old"],
64
+ configAdds: ["acme/new"],
65
+ configRemoves: ["acme/old"],
66
+ },
67
+ ...over,
68
+ }) as GithubReconcilePlanView;
69
+
70
+ describe("Reconcile card — inert state", () => {
71
+ test("absent when no username is bound", () => {
72
+ const html = page(true, true, null);
73
+ expect(html).not.toContain("github-reconcile-card");
74
+ expect(html).not.toContain("Reconcile");
75
+ });
76
+
77
+ test("absent when the apps are not configured", () => {
78
+ expect(page(true, false, "octo")).not.toContain("github-reconcile-card");
79
+ });
80
+
81
+ test("absent for a non-admin", () => {
82
+ expect(page(false, true, "octo")).not.toContain("github-reconcile-card");
83
+ });
84
+
85
+ test("present for an admin with a username and configured apps", () => {
86
+ const html = page(true, true, "octo");
87
+ expect(html).toContain('id="github-reconcile-card"');
88
+ expect(html).toContain('id="github-reconcile-plan-btn"');
89
+ expect(html).toContain('name="addRepos"');
90
+ });
91
+
92
+ test("card wires escaped plan and apply URLs and holds no key material", () => {
93
+ const html = renderGithubReconcileCard('a"b');
94
+ expect(html).toContain("/admin/agents/a&quot;b/github-reconcile/plan");
95
+ expect(html).toContain("/admin/agents/a&quot;b/github-reconcile/apply");
96
+ expect(html).not.toMatch(/BEGIN|token|private/i);
97
+ });
98
+ });
99
+
100
+ describe("renderGithubReconcilePlanResult — plan state", () => {
101
+ test("renders the diff table, hash and a confirm gate", () => {
102
+ const html = renderGithubReconcilePlanResult(plan(), []);
103
+ expect(html).toContain("acme/new");
104
+ expect(html).toContain("acme/old");
105
+ expect(html).toContain('data-plan-hash="hash-1"');
106
+ expect(html).toContain('id="github-reconcile-confirm"');
107
+ expect(html).toMatch(/id="github-reconcile-apply-btn"[^>]*disabled/);
108
+ expect(html).not.toContain("github-reconcile-confirm-removals");
109
+ });
110
+
111
+ test("carries the named adds for apply", () => {
112
+ const html = renderGithubReconcilePlanResult(plan(), ["acme/x", "acme/y"]);
113
+ expect(html).toContain('data-add-repos="acme/x,acme/y"');
114
+ });
115
+
116
+ test("renders skip reasons, rejected adds, warnings and open work", () => {
117
+ const html = renderGithubReconcilePlanResult(
118
+ plan({
119
+ skippedOrgs: [{ org: "beta", reason: "lookup app not installed" }],
120
+ rejectedAdds: [{ repo: "zed/q", reason: "not accessible" }],
121
+ warnings: ["careful <b>now</b>"],
122
+ affectedOpenWork: [
123
+ { id: "T-1", repo: "acme/old", title: "Fix <i>it</i>" },
124
+ ],
125
+ }),
126
+ [],
127
+ );
128
+ expect(html).toContain("beta");
129
+ expect(html).toContain("lookup app not installed");
130
+ expect(html).toContain("zed/q");
131
+ expect(html).toContain("careful &lt;b&gt;now&lt;/b&gt;");
132
+ expect(html).toContain("T-1");
133
+ expect(html).toContain("Fix &lt;i&gt;it&lt;/i&gt;");
134
+ expect(html).not.toContain("<b>now</b>");
135
+ });
136
+
137
+ test("empty plan has nothing to apply", () => {
138
+ const html = renderGithubReconcilePlanResult(
139
+ plan({
140
+ empty: true,
141
+ diff: {
142
+ installationAdds: [],
143
+ installationRemoves: [],
144
+ configAdds: [],
145
+ configRemoves: [],
146
+ },
147
+ }),
148
+ [],
149
+ );
150
+ expect(html).toContain("Nothing to change");
151
+ expect(html).not.toContain("github-reconcile-apply-btn");
152
+ });
153
+
154
+ test("skipped plan shows the reason and no apply", () => {
155
+ const html = renderGithubReconcilePlanResult(
156
+ { status: "skipped", reason: "GitHub Apps are not configured" },
157
+ [],
158
+ );
159
+ expect(html).toContain("GitHub Apps are not configured");
160
+ expect(html).not.toContain("github-reconcile-apply-btn");
161
+ });
162
+ });
163
+
164
+ describe("renderGithubReconcilePlanResult — over-cap confirm", () => {
165
+ const many = Array.from({ length: 11 }, (_, i) => `acme/r${i}`);
166
+ const over = plan({
167
+ diff: {
168
+ installationAdds: [],
169
+ installationRemoves: many,
170
+ configAdds: [],
171
+ configRemoves: many,
172
+ },
173
+ });
174
+
175
+ test("more than 10 config removals requires a second confirmation", () => {
176
+ const html = renderGithubReconcilePlanResult(over, []);
177
+ expect(html).toContain('data-over-cap="true"');
178
+ expect(html).toContain('id="github-reconcile-confirm-removals"');
179
+ expect(html).toContain("11 repos");
180
+ });
181
+
182
+ test("exactly 10 removals does not", () => {
183
+ const ten = many.slice(0, 10);
184
+ const html = renderGithubReconcilePlanResult(
185
+ plan({
186
+ diff: {
187
+ installationAdds: [],
188
+ installationRemoves: ten,
189
+ configAdds: [],
190
+ configRemoves: ten,
191
+ },
192
+ }),
193
+ [],
194
+ );
195
+ expect(html).toContain('data-over-cap="false"');
196
+ expect(html).not.toContain("github-reconcile-confirm-removals");
197
+ });
198
+ });
199
+
200
+ describe("renderGithubReconcileApplyResult", () => {
201
+ test.each([
202
+ ["applied", "alert-success"],
203
+ ["noop", "alert-warning"],
204
+ ["failed", "alert-error"],
205
+ ["skipped", "alert-warning"],
206
+ ] as const)("%s", (status, cls) => {
207
+ const html = renderGithubReconcileApplyResult({
208
+ status,
209
+ auditId: "aud-1",
210
+ reason: "r <x>",
211
+ error: "boom <x>",
212
+ });
213
+ expect(html).toContain(cls);
214
+ expect(html).not.toContain("<x>");
215
+ });
216
+
217
+ test("applied shows the audit id", () => {
218
+ expect(
219
+ renderGithubReconcileApplyResult({ status: "applied", auditId: "aud-1" }),
220
+ ).toContain("aud-1");
221
+ });
222
+ });
@@ -16,6 +16,7 @@ import {
16
16
  renderGithubAccessCard,
17
17
  renderGithubUsernameRow,
18
18
  } from "./admin-ui-github-identity-pages.ts";
19
+ import { renderGithubReconcileCard } from "./admin-ui-github-reconcile-pages.ts";
19
20
  import { renderAdminPage } from "./admin-ui-layout.ts";
20
21
  import {
21
22
  BREAKPOINT_MOBILE_MAX,
@@ -1806,7 +1807,7 @@ export function renderAgentDetailPage(
1806
1807
  ${identityRow("Federation rule ID", agent.anthropicFederationRuleId, true)}
1807
1808
  ${showGithubIdentity ? renderGithubUsernameRow(agent.id, agent.githubUsername) : ""}
1808
1809
  </tbody></table>
1809
- </div>${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}`;
1810
+ </div>${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubIdentity && agent.githubUsername ? renderGithubReconcileCard(agent.id) : ""}`;
1810
1811
 
1811
1812
  // Only agents with a GitHub App can make API-signed commits. Checked state
1812
1813
  // is the SHIPWRIGHT_SIGNED_COMMITS env row; when the box is hidden the field
package/src/admin-ui.ts CHANGED
@@ -51,12 +51,18 @@ import {
51
51
  } from "./admin-ui-account-nav.ts";
52
52
  import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
53
53
  import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
54
+ import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
54
55
  import {
55
56
  type GithubAccessPreviewView,
56
57
  renderGithubAccessError,
57
58
  renderGithubAccessResult,
58
59
  } from "./admin-ui-github-identity-pages.ts";
59
- import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
60
+ import {
61
+ type GithubReconcileApplyView,
62
+ type GithubReconcilePlanView,
63
+ renderGithubReconcileApplyResult,
64
+ renderGithubReconcilePlanResult,
65
+ } from "./admin-ui-github-reconcile-pages.ts";
60
66
  import {
61
67
  type AgentDetail,
62
68
  type AgentOption,
@@ -78,8 +84,8 @@ import type { DeleteAgentFullyDeps } from "./agent-deletion.ts";
78
84
  import { deleteAgentFully } from "./agent-deletion.ts";
79
85
  import type { ManualStep } from "./agent-deletion-checklist.ts";
80
86
  import type { AgentEnvService } from "./agent-envs.ts";
81
- import type { AgentMemberService } from "./agent-members.ts";
82
87
  import type { AgentMarketplaceService } from "./agent-marketplaces.ts";
88
+ import type { AgentMemberService } from "./agent-members.ts";
83
89
  import type { AgentPluginService } from "./agent-plugins.ts";
84
90
  import type { AgentProvisioner } from "./agent-provisioner.ts";
85
91
  import type { AgentTokenService } from "./agent-tokens.ts";
@@ -1903,6 +1909,82 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1903
1909
  );
1904
1910
  });
1905
1911
 
1912
+ // GHE-3.5: thin proxies over the GHE-3.4 plan/apply routes. They return
1913
+ // HTML fragments for the Reconcile card; the agents API enforces admin too.
1914
+ const reconcileProxy = async (
1915
+ c: Context<AdminUIEnv>,
1916
+ step: "plan" | "apply",
1917
+ ): Promise<{ res: Response | null; body: Record<string, unknown> }> => {
1918
+ let body: Record<string, unknown> = {};
1919
+ try {
1920
+ const parsed = await c.req.json();
1921
+ if (parsed && typeof parsed === "object") body = parsed;
1922
+ } catch {
1923
+ // empty body
1924
+ }
1925
+ const res = await callApi(
1926
+ c,
1927
+ agentsApi as NonNullable<typeof agentsApi>,
1928
+ `/agents/${encodeURIComponent(c.req.param("id") ?? "")}/github-reconcile/${step}`,
1929
+ {
1930
+ method: "POST",
1931
+ headers: { "content-type": "application/json" },
1932
+ body: JSON.stringify(body),
1933
+ },
1934
+ );
1935
+ return { res, body };
1936
+ };
1937
+ const reconcileError = async (res: Response | null) => {
1938
+ let message = "The reconcile request failed.";
1939
+ try {
1940
+ const j = (await res?.json()) as { error?: unknown };
1941
+ if (typeof j.error === "string" && j.error) message = j.error;
1942
+ } catch {
1943
+ // keep the generic message
1944
+ }
1945
+ return html(renderGithubAccessError(message), {
1946
+ status: res && res.status >= 400 ? res.status : 502,
1947
+ });
1948
+ };
1949
+
1950
+ app.post(
1951
+ "/admin/agents/:id/github-reconcile/plan",
1952
+ requireAuth,
1953
+ async (c) => {
1954
+ if (!c.var.isAdmin || !agentsApi) {
1955
+ return new Response("Forbidden", { status: 403 });
1956
+ }
1957
+ const { res, body } = await reconcileProxy(c, "plan");
1958
+ if (!res?.ok) return reconcileError(res);
1959
+ const adds = Array.isArray(body.addRepos)
1960
+ ? body.addRepos.filter((r): r is string => typeof r === "string")
1961
+ : [];
1962
+ return html(
1963
+ renderGithubReconcilePlanResult(
1964
+ (await res.json()) as GithubReconcilePlanView,
1965
+ adds,
1966
+ ),
1967
+ );
1968
+ },
1969
+ );
1970
+
1971
+ app.post(
1972
+ "/admin/agents/:id/github-reconcile/apply",
1973
+ requireAuth,
1974
+ async (c) => {
1975
+ if (!c.var.isAdmin || !agentsApi) {
1976
+ return new Response("Forbidden", { status: 403 });
1977
+ }
1978
+ const { res } = await reconcileProxy(c, "apply");
1979
+ if (!res?.ok) return reconcileError(res);
1980
+ return html(
1981
+ renderGithubReconcileApplyResult(
1982
+ (await res.json()) as GithubReconcileApplyView,
1983
+ ),
1984
+ );
1985
+ },
1986
+ );
1987
+
1906
1988
  app.get("/admin/agents/:id", requireAuth, async (c) => {
1907
1989
  const agentId = c.req.param("id");
1908
1990
  const agent = await agentService.getDetail(agentId);
@@ -22,6 +22,12 @@ import type { AgentTokenService } from "./agent-tokens.ts";
22
22
  import type { AdminDeps } from "./agents-api.ts";
23
23
  import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
24
24
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
25
+ import { createGithubReconcile } from "./github-reconcile-wiring.ts";
26
+ import {
27
+ accessFor,
28
+ fakeOpenWork,
29
+ fakePrisma,
30
+ } from "./github-reconcile-wiring.unit.test.ts";
25
31
  import type { SpecialtyType } from "./specialty-types.ts";
26
32
  import { identityCrypto } from "./token-crypto.ts";
27
33
 
@@ -7178,3 +7184,52 @@ describe("admin API — GitHub reconcile routes (GHE-3.4)", () => {
7178
7184
  expect((await post(app, "apply", asAdmin, {})).status).toBe(400);
7179
7185
  });
7180
7186
  });
7187
+
7188
+ describe("admin API — reconcile open-work seam, in-process composition (GHE-3.9)", () => {
7189
+ const compose = (openWork?: ReturnType<typeof fakeOpenWork>["port"]) => {
7190
+ const { prisma, state } = fakePrisma(["acme/old"]);
7191
+ const githubReconcile = createGithubReconcile({
7192
+ prisma,
7193
+ appService: { get: async () => null, getPrivateKey: async () => null },
7194
+ access: accessFor(["acme/api"]),
7195
+ agentAppId: 42,
7196
+ installation: {
7197
+ listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
7198
+ addRepos: async () => {},
7199
+ removeRepos: async () => {},
7200
+ },
7201
+ openWork,
7202
+ });
7203
+ const app = createAdminApp({
7204
+ ...makeMockDeps(),
7205
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7206
+ githubReconcile,
7207
+ });
7208
+ const plan = () =>
7209
+ app.request(`/agents/${AGENT_ID}/github-reconcile/plan`, {
7210
+ method: "POST",
7211
+ headers: { Authorization: `Bearer ${ADMIN_API_KEY}` },
7212
+ });
7213
+ return { plan, state };
7214
+ };
7215
+
7216
+ it("plan returns the port's items and retires nothing", async () => {
7217
+ const { port, calls } = fakeOpenWork();
7218
+ const { plan, state } = compose(port);
7219
+ const res = await plan();
7220
+ expect(res.status).toBe(200);
7221
+ const body = (await res.json()) as { affectedOpenWork: unknown[] };
7222
+ expect(body.affectedOpenWork).toEqual([
7223
+ { id: "T-1", repo: "acme/old", title: "fix it" },
7224
+ ]);
7225
+ expect(calls.map((c) => c.fn)).toEqual(["list"]);
7226
+ expect(state.repos).toEqual(["acme/old"]);
7227
+ });
7228
+
7229
+ it("without a port plan lists nothing", async () => {
7230
+ const res = await compose().plan();
7231
+ expect(res.status).toBe(200);
7232
+ const body = (await res.json()) as { affectedOpenWork: unknown[] };
7233
+ expect(body.affectedOpenWork).toEqual([]);
7234
+ });
7235
+ });
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * admin/src/github-enterprise-isolation.unit.test.ts
3
3
  * Isolation exception guard (GHE-1.3): the GitHub Enterprise App private key
4
- * is reachable only from the enterprise service, its admin API and the boot
5
- * wiring. Agent config bundle, agent-bearer routes and env serialization must
4
+ * is reachable only from the enterprise service, its admin API, the boot
5
+ * wiring and the reconcile wiring. Agent config bundle, agent-bearer routes and env serialization must
6
6
  * never import the service, touch its table or call getPrivateKey().
7
7
  */
8
8
 
@@ -17,6 +17,7 @@ const ALLOWED = new Set([
17
17
  "admin/src/github-enterprise-apps.ts",
18
18
  "admin/src/github-enterprise-api.ts",
19
19
  "admin/src/admin-boot.ts",
20
+ "admin/src/github-reconcile-wiring.ts",
20
21
  ]);
21
22
 
22
23
  function sources(dir: string, out: string[] = []): string[] {
@@ -66,13 +67,16 @@ describe("GitHub Enterprise key isolation", () => {
66
67
  expect(offenders).toEqual([]);
67
68
  });
68
69
 
69
- it("getPrivateKey() is only called by the enterprise API", () => {
70
+ it("getPrivateKey() is only called by the enterprise API and reconcile wiring", () => {
70
71
  const callers = files
71
72
  .map((f) => relative(REPO, f))
72
73
  .filter((rel) =>
73
74
  /\.getPrivateKey\(/.test(readFileSync(join(REPO, rel), "utf-8")),
74
75
  );
75
- expect(callers).toEqual(["admin/src/github-enterprise-api.ts"]);
76
+ expect(callers.sort()).toEqual([
77
+ "admin/src/github-enterprise-api.ts",
78
+ "admin/src/github-reconcile-wiring.ts",
79
+ ]);
76
80
  });
77
81
 
78
82
  it("the config bundle and env serializers never read the enterprise table", () => {
@@ -0,0 +1,95 @@
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. 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.
8
+ */
9
+
10
+ import type { PrismaClient } from "../prisma/client/client.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 type { OpenWorkPort } from "./reconcile-open-work.ts";
23
+
24
+ export interface GithubReconcileWiringDeps {
25
+ prisma: PrismaClient;
26
+ appService: Pick<GitHubEnterpriseAppService, "get" | "getPrivateKey">;
27
+ access: GithubAccessPreviewFn;
28
+ /** Numeric id of the agent App whose installations are reconciled. */
29
+ agentAppId: number | undefined;
30
+ openWork?: OpenWorkPort;
31
+ /** Test seam: replaces the installer-App-backed installation port. */
32
+ installation?: ReconcileInstallationPort;
33
+ /** Test seams; default to the real GitHub API. */
34
+ fetchFn?: typeof fetch;
35
+ apiBase?: string;
36
+ now?: () => Date;
37
+ }
38
+
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
+ /** 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 {
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
+ listOrgInstallations: async (org) =>
71
+ (await client()).listOrgInstallations(org),
72
+ listInstallationRepositories: async (org, id) =>
73
+ (await client()).listInstallationRepositories(org, id),
74
+ addRepositories: async (org, id, names) =>
75
+ (await client()).addRepositories(org, id, names),
76
+ removeRepositories: async (org, id, names) =>
77
+ (await client()).removeRepositories(org, id, names),
78
+ };
79
+ }
80
+
81
+ /** The `githubReconcile` dep for createAdminApp, or undefined when unwired. */
82
+ export function createGithubReconcile(
83
+ deps: GithubReconcileWiringDeps,
84
+ ): ReconcileApplyService | undefined {
85
+ if (deps.agentAppId === undefined) return undefined;
86
+ return new ReconcileApplyService({
87
+ agents: new PrismaReconcileAgents(deps.prisma),
88
+ access: deps.access,
89
+ installation:
90
+ deps.installation ??
91
+ createInstallationPort(lazyInstallerClient(deps), deps.agentAppId),
92
+ audit: new PrismaReconcileAudit(deps.prisma),
93
+ ...(deps.openWork ? { openWork: deps.openWork } : {}),
94
+ });
95
+ }
@@ -0,0 +1,146 @@
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 {
5
+ createGithubReconcile,
6
+ parseAgentAppId,
7
+ } from "./github-reconcile-wiring.ts";
8
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
9
+
10
+ export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
11
+ return async () => ({
12
+ status: "ok",
13
+ access: {
14
+ username: "dev",
15
+ outcome: "ok",
16
+ userVerified: true,
17
+ complete: true,
18
+ unresolved: 0,
19
+ checkedAt: "2026-11-11T00:00:00.000Z",
20
+ orgs: [
21
+ {
22
+ org: "acme",
23
+ status: "ok",
24
+ unresolved: 0,
25
+ repos: pushable.map((fullName) => ({
26
+ fullName,
27
+ level: "write" as const,
28
+ canPush: true,
29
+ })),
30
+ },
31
+ ],
32
+ },
33
+ });
34
+ };
35
+
36
+ export function fakePrisma(repos: string[]) {
37
+ const state = { repos: [...repos], audits: 0 };
38
+ const prisma = {
39
+ agent: {
40
+ findUnique: async () => ({
41
+ id: "a1",
42
+ repos: state.repos,
43
+ githubUsername: "dev",
44
+ }),
45
+ update: async (args: { data: { repos: string[] } }) => {
46
+ state.repos = args.data.repos;
47
+ },
48
+ },
49
+ gitHubReconcileAudit: {
50
+ create: async () => {
51
+ state.audits += 1;
52
+ return { id: "audit-1" };
53
+ },
54
+ },
55
+ } as unknown as PrismaClient;
56
+ return { prisma, state };
57
+ }
58
+
59
+ export function fakeOpenWork() {
60
+ const calls: { fn: string; args: unknown[] }[] = [];
61
+ const port: OpenWorkPort = {
62
+ listOpenWork: async (...args) => {
63
+ calls.push({ fn: "list", args });
64
+ return [{ id: "T-1", repo: "acme/old", title: "fix it" }];
65
+ },
66
+ blockOpenWork: async (...args) => {
67
+ calls.push({ fn: "block", args });
68
+ },
69
+ };
70
+ return { port, calls };
71
+ }
72
+
73
+ const installation = {
74
+ listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
75
+ addRepos: async () => {},
76
+ removeRepos: async () => {},
77
+ };
78
+
79
+ const build = (openWork?: OpenWorkPort) => {
80
+ const { prisma, state } = fakePrisma(["acme/old"]);
81
+ const svc = createGithubReconcile({
82
+ prisma,
83
+ appService: { get: async () => null, getPrivateKey: async () => null },
84
+ access: accessFor(["acme/api"]),
85
+ agentAppId: 42,
86
+ installation,
87
+ openWork,
88
+ });
89
+ if (!svc) throw new Error("expected a reconcile service");
90
+ return { svc, state };
91
+ };
92
+
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
+ }
99
+ });
100
+ });
101
+
102
+ describe("createGithubReconcile", () => {
103
+ it("is unwired without an agent App id", () => {
104
+ const { prisma } = fakePrisma([]);
105
+ expect(
106
+ createGithubReconcile({
107
+ prisma,
108
+ appService: { get: async () => null, getPrivateKey: async () => null },
109
+ access: accessFor([]),
110
+ agentAppId: undefined,
111
+ }),
112
+ ).toBeUndefined();
113
+ });
114
+
115
+ it("with a port: plan lists affected open work and apply blocks it", async () => {
116
+ const { port, calls } = fakeOpenWork();
117
+ const { svc } = build(port);
118
+ const { plan, openWork } = await svc.planWithOpenWork("a1");
119
+ expect(plan.diff.configRemoves).toEqual(["acme/old"]);
120
+ expect(openWork).toEqual([
121
+ { id: "T-1", repo: "acme/old", title: "fix it" },
122
+ ]);
123
+ const res = await svc.apply({
124
+ agentId: "a1",
125
+ caller: "root",
126
+ planHash: plan.planHash,
127
+ });
128
+ expect(res.status).toBe("applied");
129
+ const block = calls.find((c) => c.fn === "block");
130
+ expect(block?.args[0]).toBe("a1");
131
+ expect(block?.args[1]).toEqual(["acme/old"]);
132
+ });
133
+
134
+ it("without a port: nothing is listed or blocked, apply still works", async () => {
135
+ const { svc, state } = build();
136
+ const { plan, openWork } = await svc.planWithOpenWork("a1");
137
+ expect(openWork).toEqual([]);
138
+ const res = await svc.apply({
139
+ agentId: "a1",
140
+ caller: "root",
141
+ planHash: plan.planHash,
142
+ });
143
+ expect(res.status).toBe("applied");
144
+ expect(state.repos).toEqual([]);
145
+ });
146
+ });