@app-vitals/agent-admin 1.91.0 → 1.91.1

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.91.0",
3
+ "version": "1.91.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.91.0",
47
+ "@app-vitals/agent-lib": "1.91.1",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,235 @@
1
+ /**
2
+ * admin/src/github-app-api.unit.test.ts
3
+ * Unit tests for fetchPublicApp / fetchAuthenticatedApp. fetch is injected via
4
+ * `fetchFn`; the RSA key is generated in-test. No network, no fixtures.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { generateKeyPairSync } from "node:crypto";
9
+ import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
10
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
11
+
12
+ const { privateKey } = generateKeyPairSync("rsa", {
13
+ modulusLength: 2048,
14
+ privateKeyEncoding: { type: "pkcs1", format: "pem" },
15
+ publicKeyEncoding: { type: "spki", format: "pem" },
16
+ });
17
+ const NOW = new Date("2026-11-09T12:00:00Z");
18
+
19
+ interface Call {
20
+ url: string;
21
+ init: RequestInit;
22
+ }
23
+
24
+ function stubFetch(respond: () => Response | Promise<Response>): {
25
+ fetchFn: typeof fetch;
26
+ calls: Call[];
27
+ } {
28
+ const calls: Call[] = [];
29
+ const fetchFn = (async (url: string | URL | Request, init?: RequestInit) => {
30
+ calls.push({ url: String(url), init: init ?? {} });
31
+ return respond();
32
+ }) as typeof fetch;
33
+ return { fetchFn, calls };
34
+ }
35
+
36
+ function json(
37
+ body: unknown,
38
+ status = 200,
39
+ headers: Record<string, string> = {},
40
+ ) {
41
+ return new Response(JSON.stringify(body), {
42
+ status,
43
+ headers: { "content-type": "application/json", ...headers },
44
+ });
45
+ }
46
+
47
+ async function caught(p: Promise<unknown>): Promise<GithubEnterpriseError> {
48
+ try {
49
+ await p;
50
+ } catch (e) {
51
+ expect(e).toBeInstanceOf(GithubEnterpriseError);
52
+ return e as GithubEnterpriseError;
53
+ }
54
+ throw new Error("expected rejection");
55
+ }
56
+
57
+ describe("fetchPublicApp", () => {
58
+ it("returns slug and clientId and sends no credentials", async () => {
59
+ const { fetchFn, calls } = stubFetch(() =>
60
+ json({ slug: "my-app", client_id: "Iv1.abc" }),
61
+ );
62
+ const app = await fetchPublicApp("my-app", { fetchFn });
63
+ expect(app).toEqual({ slug: "my-app", clientId: "Iv1.abc" });
64
+ expect(calls).toHaveLength(1);
65
+ expect(calls[0].url).toBe("https://api.github.com/apps/my-app");
66
+ const headers = calls[0].init.headers as Record<string, string>;
67
+ expect(headers.Authorization).toBeUndefined();
68
+ expect(headers.Accept).toBe("application/vnd.github+json");
69
+ });
70
+
71
+ it("honours apiBase and url-encodes the slug", async () => {
72
+ const { fetchFn, calls } = stubFetch(() => json({}));
73
+ await fetchPublicApp("a/b", {
74
+ fetchFn,
75
+ apiBase: "https://ghe.example/api/v3",
76
+ });
77
+ expect(calls[0].url).toBe("https://ghe.example/api/v3/apps/a%2Fb");
78
+ });
79
+
80
+ it("falls back to the requested slug and null clientId when fields are missing", async () => {
81
+ const { fetchFn } = stubFetch(() => json({ client_id: "" }));
82
+ expect(await fetchPublicApp("x", { fetchFn })).toEqual({
83
+ slug: "x",
84
+ clientId: null,
85
+ });
86
+ });
87
+
88
+ it("tolerates a non-JSON success body", async () => {
89
+ const { fetchFn } = stubFetch(() => new Response("ok", { status: 200 }));
90
+ expect(await fetchPublicApp("x", { fetchFn })).toEqual({
91
+ slug: "x",
92
+ clientId: null,
93
+ });
94
+ });
95
+
96
+ it("maps 404 (private App) to a not_found GithubEnterpriseError", async () => {
97
+ const { fetchFn } = stubFetch(() => json({ message: "Not Found" }, 404));
98
+ const err = await caught(fetchPublicApp("private-app", { fetchFn }));
99
+ expect(err.kind).toBe("not_found");
100
+ expect(err.status).toBe(404);
101
+ expect(err.message).toContain("GitHub public App lookup");
102
+ });
103
+
104
+ it("maps 500 to server and rate-limited 403 to rate_limit with retryAfterSeconds", async () => {
105
+ const s = stubFetch(() => json({ message: "boom" }, 500));
106
+ expect(
107
+ (await caught(fetchPublicApp("x", { fetchFn: s.fetchFn }))).kind,
108
+ ).toBe("server");
109
+
110
+ const r = stubFetch(() =>
111
+ json({ message: "API rate limit exceeded" }, 403, {
112
+ "retry-after": "30",
113
+ }),
114
+ );
115
+ const err = await caught(fetchPublicApp("x", { fetchFn: r.fetchFn }));
116
+ expect(err.kind).toBe("rate_limit");
117
+ expect(err.retryAfterSeconds).toBe(30);
118
+ });
119
+
120
+ it("maps a thrown fetch to a network error without leaking the cause", async () => {
121
+ const { fetchFn } = stubFetch(() => {
122
+ throw new Error("ECONNRESET secret-detail");
123
+ });
124
+ const err = await caught(fetchPublicApp("x", { fetchFn }));
125
+ expect(err.kind).toBe("network");
126
+ expect(err.message).not.toContain("secret-detail");
127
+ });
128
+
129
+ it("maps an error with a non-JSON body to a typed error", async () => {
130
+ const { fetchFn } = stubFetch(
131
+ () => new Response("<html>", { status: 502 }),
132
+ );
133
+ expect((await caught(fetchPublicApp("x", { fetchFn }))).kind).toBe(
134
+ "server",
135
+ );
136
+ });
137
+ });
138
+
139
+ describe("fetchAuthenticatedApp", () => {
140
+ const base = { appId: "12345", privateKey, now: () => NOW };
141
+
142
+ it("returns permissions and sends a Bearer app JWT to /app", async () => {
143
+ const { fetchFn, calls } = stubFetch(() =>
144
+ json({ permissions: { metadata: "read", members: "read" } }),
145
+ );
146
+ const out = await fetchAuthenticatedApp({ ...base, fetchFn });
147
+ expect(out).toEqual({ permissions: { metadata: "read", members: "read" } });
148
+ expect(calls[0].url).toBe("https://api.github.com/app");
149
+ const auth = (calls[0].init.headers as Record<string, string>)
150
+ .Authorization;
151
+ expect(auth).toMatch(/^Bearer [\w-]+\.[\w-]+\.[\w-]+$/);
152
+ const payload = JSON.parse(
153
+ Buffer.from(auth.slice(7).split(".")[1], "base64url").toString(),
154
+ );
155
+ expect(payload.iss).toBe("12345");
156
+ });
157
+
158
+ it("returns empty permissions when the field is absent or not an object", async () => {
159
+ for (const body of [{}, { permissions: "nope" }, { permissions: null }]) {
160
+ const { fetchFn } = stubFetch(() => json(body));
161
+ expect(await fetchAuthenticatedApp({ ...base, fetchFn })).toEqual({
162
+ permissions: {},
163
+ });
164
+ }
165
+ });
166
+
167
+ it("maps 401 to unauthorized and 404 to not_found", async () => {
168
+ const u = stubFetch(() => json({ message: "Bad credentials" }, 401));
169
+ const e401 = await caught(
170
+ fetchAuthenticatedApp({ ...base, fetchFn: u.fetchFn }),
171
+ );
172
+ expect(e401.kind).toBe("unauthorized");
173
+ expect(e401.message).toContain("GitHub App lookup");
174
+
175
+ const n = stubFetch(() => json({ message: "Not Found" }, 404));
176
+ expect(
177
+ (await caught(fetchAuthenticatedApp({ ...base, fetchFn: n.fetchFn })))
178
+ .kind,
179
+ ).toBe("not_found");
180
+ });
181
+
182
+ it("maps a thrown fetch to a network error", async () => {
183
+ const { fetchFn } = stubFetch(() => {
184
+ throw new Error("down");
185
+ });
186
+ expect(
187
+ (await caught(fetchAuthenticatedApp({ ...base, fetchFn }))).kind,
188
+ ).toBe("network");
189
+ });
190
+
191
+ it("redacts the JWT and private key if the server echoes them in an error", async () => {
192
+ let jwt = "";
193
+ const stub = stubFetch(() =>
194
+ json({ message: `bad token ${jwt} key ${privateKey}` }, 401),
195
+ );
196
+ const capture = (async (
197
+ url: string | URL | Request,
198
+ init?: RequestInit,
199
+ ) => {
200
+ const { Authorization } = (init?.headers ?? {}) as Record<string, string>;
201
+ jwt = Authorization.slice(7);
202
+ return stub.fetchFn(url, init);
203
+ }) as typeof fetch;
204
+ const err = await caught(
205
+ fetchAuthenticatedApp({ ...base, fetchFn: capture }),
206
+ );
207
+ expect(jwt.length).toBeGreaterThan(0);
208
+ expect(err.message).toContain("[redacted]");
209
+ expect(err.message).not.toContain(jwt);
210
+ expect(err.message).not.toContain("PRIVATE KEY");
211
+ });
212
+
213
+ it("never puts the key in a result or an error for an unusable key", async () => {
214
+ const { fetchFn, calls } = stubFetch(() => json({}));
215
+ const bad =
216
+ "-----BEGIN RSA PRIVATE KEY-----\nnot-a-real-key\n-----END RSA PRIVATE KEY-----";
217
+ let message = "";
218
+ try {
219
+ await fetchAuthenticatedApp({ appId: "1", privateKey: bad, fetchFn });
220
+ } catch (e) {
221
+ message = (e as Error).message;
222
+ }
223
+ expect(message).toContain("invalid or unusable RSA private key");
224
+ expect(message).not.toContain("not-a-real-key");
225
+ expect(calls).toHaveLength(0);
226
+ });
227
+
228
+ it("the successful result does not contain the key", async () => {
229
+ const { fetchFn } = stubFetch(() =>
230
+ json({ permissions: { metadata: "read" } }),
231
+ );
232
+ const out = await fetchAuthenticatedApp({ ...base, fetchFn });
233
+ expect(JSON.stringify(out)).not.toContain("PRIVATE KEY");
234
+ });
235
+ });
@@ -12,7 +12,7 @@ export type GheValidationStatus = "valid" | "missing_permission" | "error";
12
12
  /** Warning code -> message. Codes are stable; the UI carries them in a redirect. */
13
13
  export const GHE_WARNINGS = {
14
14
  installer_repositories_write:
15
- "The installer App lacks enterprise_organization_installation_repositories (write). It is not needed yet but will be required for repository management.",
15
+ "The installer App lacks enterprise_organization_installation_repositories (write). Sync needs it to add, remove and switch the agent App's repositories; without it those changes fail. Validation still passes.",
16
16
  lookup_members_read:
17
17
  "The lookup App lacks the Organization Members (read) permission. Validation still passes; grant it to let the lookup see organization membership.",
18
18
  } as const;
@@ -20,6 +20,13 @@ describe("permissionWarnings", () => {
20
20
  ).toEqual([]);
21
21
  });
22
22
 
23
+ it("installer warning says the repositories permission is needed for Sync", () => {
24
+ const msg = GHE_WARNINGS.installer_repositories_write;
25
+ expect(msg).toContain("enterprise_organization_installation_repositories (write)");
26
+ expect(msg).toContain("Sync");
27
+ expect(msg).not.toContain("not needed yet");
28
+ });
29
+
23
30
  it("lookup: warns unless members is read or write", () => {
24
31
  expect(permissionWarnings("lookup", { metadata: "read" })).toEqual([GHE_WARNINGS.lookup_members_read]);
25
32
  expect(permissionWarnings("lookup", { members: "read" })).toEqual([]);
@@ -207,7 +207,10 @@ export function createGithubSync(
207
207
  completedAt: s.completedAt,
208
208
  lastError: s.lastError,
209
209
  rateLimitResetAt: s.rateLimitResetAt,
210
- repos: s.repos.map((r) => r.fullName),
210
+ // Archived repos are read-only: never an add, and kept apart so
211
+ // GitHub Sync leaves them alone (see CachedLookupOrg.archivedRepos).
212
+ repos: s.repos.filter((r) => !r.archived).map((r) => r.fullName),
213
+ archivedRepos: s.repos.filter((r) => r.archived).map((r) => r.fullName),
211
214
  }));
212
215
  },
213
216
  // One permission call per removal candidate; undefined on any failure.
@@ -133,7 +133,7 @@ export interface FakeLookupSnapshot {
133
133
  appRef: string;
134
134
  org: string;
135
135
  completedAt: Date;
136
- repos: { fullName: string }[];
136
+ repos: { fullName: string; archived?: boolean }[];
137
137
  }
138
138
 
139
139
  /**
@@ -82,6 +82,38 @@ describeOrSkip("GitHubRepoCacheService (integration)", () => {
82
82
  ]);
83
83
  });
84
84
 
85
+ it("excludeArchived leaves archived repos out of the list", async () => {
86
+ const snap = await svc.upsertSnapshot(key);
87
+ await svc.upsertRepos(snap.id, [
88
+ { githubId: 1, fullName: "acme/api" },
89
+ { githubId: 2, fullName: "acme/old", archived: true },
90
+ ]);
91
+ expect(await svc.listRepoFullNames(snap.id)).toEqual([
92
+ "acme/api",
93
+ "acme/old",
94
+ ]);
95
+ expect(
96
+ await svc.listRepoFullNames(snap.id, { excludeArchived: true }),
97
+ ).toEqual(["acme/api"]);
98
+ });
99
+
100
+ it("lookup org snapshots carry each repo's archived flag", async () => {
101
+ const snap = await svc.upsertSnapshot(key);
102
+ await svc.upsertRepos(snap.id, [
103
+ { githubId: 1, fullName: "acme/api" },
104
+ { githubId: 2, fullName: "acme/old", archived: true },
105
+ ]);
106
+ const [org] = await svc.listLookupOrgSnapshots([key.accountId], key.appRef);
107
+ expect(
108
+ [...(org?.repos ?? [])].sort((a, b) =>
109
+ a.fullName.localeCompare(b.fullName),
110
+ ),
111
+ ).toEqual([
112
+ { fullName: "acme/api", archived: false },
113
+ { fullName: "acme/old", archived: true },
114
+ ]);
115
+ });
116
+
85
117
  it("sweep deletes only rows seen before crawlStartedAt", async () => {
86
118
  const snap = await svc.upsertSnapshot(key, { crawlStartedAt: min(10) });
87
119
  await svc.upsertRepos(
@@ -158,7 +158,7 @@ export class GitHubRepoCacheService {
158
158
  requireNonEmpty("appRef", appRef);
159
159
  const rows = await this.prisma.gitHubRepoSnapshot.findMany({
160
160
  where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
161
- include: { repos: { select: { fullName: true } } },
161
+ include: { repos: { select: { fullName: true, archived: true } } },
162
162
  orderBy: { org: "asc" },
163
163
  });
164
164
  return rows.map((r) => ({
@@ -243,11 +243,20 @@ export class GitHubRepoCacheService {
243
243
  });
244
244
  }
245
245
 
246
- /** Full names (owner/repo) of every repo cached for the snapshot, sorted. */
247
- async listRepoFullNames(snapshotId: string): Promise<string[]> {
246
+ /**
247
+ * Full names (owner/repo) of the repos cached for the snapshot, sorted.
248
+ * Every repo by default; `excludeArchived` leaves out archived ones.
249
+ */
250
+ async listRepoFullNames(
251
+ snapshotId: string,
252
+ opts: { excludeArchived?: boolean } = {},
253
+ ): Promise<string[]> {
248
254
  requireNonEmpty("snapshotId", snapshotId);
249
255
  const rows = await this.prisma.gitHubCachedRepo.findMany({
250
- where: { snapshotId },
256
+ where: {
257
+ snapshotId,
258
+ ...(opts.excludeArchived ? { archived: false } : {}),
259
+ },
251
260
  select: { fullName: true },
252
261
  orderBy: { fullName: "asc" },
253
262
  });
@@ -190,7 +190,20 @@ export function createRefreshDiscovery(
190
190
  shouldStop: ctx.shouldStop,
191
191
  }),
192
192
  ...(users.length > 0
193
- ? { access: { probe: lookup.client, users } }
193
+ ? {
194
+ access: {
195
+ probe: lookup.client,
196
+ users,
197
+ installationKeys: bound.map(
198
+ (a): SnapshotKey => ({
199
+ accountId: scopeKeyOf(a.accountId),
200
+ appKind: "agent",
201
+ appRef: String(a.appId),
202
+ org,
203
+ }),
204
+ ),
205
+ },
206
+ }
194
207
  : {}),
195
208
  });
196
209
  }
@@ -127,7 +127,10 @@ export interface RefreshStore extends AccessBackfillStore {
127
127
  ttlMs: number,
128
128
  ): Promise<boolean>;
129
129
  releaseLease(snapshotId: string, holder: string): Promise<void>;
130
- listRepoFullNames(snapshotId: string): Promise<string[]>;
130
+ listRepoFullNames(
131
+ snapshotId: string,
132
+ opts?: { excludeArchived?: boolean },
133
+ ): Promise<string[]>;
131
134
  }
132
135
 
133
136
  /** What a crawl or backfill step reported. */
@@ -143,7 +146,12 @@ export interface RefreshTarget {
143
146
  /** One resumable crawl run of this snapshot's repo list. */
144
147
  crawl(ctx: { shouldStop: () => boolean }): Promise<StepOutcome>;
145
148
  /** Present on lookup targets with GitHub-user-bound agents. */
146
- access?: { probe: AccessProbe; users: BackfillUser[] };
149
+ access?: {
150
+ probe: AccessProbe;
151
+ users: BackfillUser[];
152
+ /** Agent-installation snapshots of this org; their archived repos are probed too. */
153
+ installationKeys?: SnapshotKey[];
154
+ };
147
155
  }
148
156
 
149
157
  export interface RefreshDiscovery {
@@ -441,9 +449,41 @@ export class GithubRepoRefresher {
441
449
  return { target, snapshot, steps };
442
450
  }
443
451
 
452
+ /**
453
+ * The repos whose access the backfill checks: the snapshot's non-archived
454
+ * repos, plus any archived repo an agent bound to one of the target's users
455
+ * has configured or that is on one of those agents' installations (GitHub
456
+ * Sync needs an answer for those: an installed archived repo is removed once
457
+ * the user loses access). Checking every archived repo is wasted calls.
458
+ */
444
459
  private async repoNames(target: RefreshTarget, snapshotId: string) {
445
460
  const prefix = `${target.key.org.toLowerCase()}/`;
446
- return (await this.deps.store.listRepoFullNames(snapshotId))
461
+ const { store } = this.deps;
462
+ const configured = new Set(
463
+ (target.access?.users ?? []).flatMap((u) =>
464
+ (u.configuredRepos ?? []).map((r) => r.toLowerCase()),
465
+ ),
466
+ );
467
+ for (const k of target.access?.installationKeys ?? []) {
468
+ const snap = await store.getSnapshot(k);
469
+ if (!snap) continue;
470
+ for (const n of await store.listRepoFullNames(snap.id)) {
471
+ configured.add(n.slice(n.indexOf("/") + 1).toLowerCase());
472
+ }
473
+ }
474
+ const active = await store.listRepoFullNames(snapshotId, {
475
+ excludeArchived: true,
476
+ });
477
+ let names = active;
478
+ if (configured.size > 0) {
479
+ const activeSet = new Set(active);
480
+ names = (await store.listRepoFullNames(snapshotId)).filter(
481
+ (n) =>
482
+ activeSet.has(n) ||
483
+ configured.has(n.slice(n.indexOf("/") + 1).toLowerCase()),
484
+ );
485
+ }
486
+ return names
447
487
  .filter((n) => n.toLowerCase().startsWith(prefix))
448
488
  .map((n) => n.slice(prefix.length));
449
489
  }
@@ -114,8 +114,16 @@ class MemoryStore implements RefreshStore {
114
114
  }
115
115
  }
116
116
 
117
- async listRepoFullNames(id: string) {
118
- return [...(this.repos.get(id) ?? [])].sort();
117
+ /** Full names (owner/repo) the crawl reported as archived. */
118
+ archived = new Set<string>();
119
+
120
+ async listRepoFullNames(
121
+ id: string,
122
+ opts: { excludeArchived?: boolean } = {},
123
+ ) {
124
+ return [...(this.repos.get(id) ?? [])]
125
+ .filter((r) => !(opts.excludeArchived && this.archived.has(r)))
126
+ .sort();
119
127
  }
120
128
 
121
129
  async getAccessRows(q: {
@@ -432,6 +440,50 @@ describe("planOrgWork", () => {
432
440
 
433
441
  // ─── tick ────────────────────────────────────────────────────────────────────
434
442
 
443
+ describe("GithubRepoRefresher access backfill and archived repos", () => {
444
+ it("checks no archived repo when no agent has one configured", async () => {
445
+ const t = target("acme", { users: [{ username: "octocat" }] });
446
+ await seedCrawl(t.key, ["acme/a", "acme/b", "acme/c"], T0);
447
+ store.archived = new Set(["acme/b", "acme/c"]);
448
+ const res = await refresher([t]).tick();
449
+ expect(events).toEqual(["probe:acme/a@octocat"]);
450
+ expect(res.targets[0]?.steps).toEqual(["access:missing"]);
451
+ // Nothing is left missing afterwards, so the next tick has no work.
452
+ events = [];
453
+ clock.advance(MIN);
454
+ await refresher([t]).tick();
455
+ expect(events).toEqual([]);
456
+ });
457
+
458
+ it("still checks an archived repo an agent has configured", async () => {
459
+ const t = target("acme", {
460
+ users: [{ username: "octocat", configuredRepos: ["c"] }],
461
+ });
462
+ await seedCrawl(t.key, ["acme/a", "acme/b", "acme/c"], T0);
463
+ store.archived = new Set(["acme/b", "acme/c"]);
464
+ await refresher([t]).tick();
465
+ // Configured repos first; the unconfigured archived acme/b is skipped.
466
+ expect(events).toEqual(["probe:acme/c@octocat", "probe:acme/a@octocat"]);
467
+ });
468
+
469
+ it("checks an archived repo that is on a bound agent's installation", async () => {
470
+ const agentKey: SnapshotKey = {
471
+ accountId: "acct",
472
+ appKind: "agent",
473
+ appRef: "7",
474
+ org: "acme",
475
+ };
476
+ const t = target("acme", { users: [{ username: "octocat" }] });
477
+ t.access = { ...(t.access as NonNullable<typeof t.access>), installationKeys: [agentKey] };
478
+ await seedCrawl(t.key, ["acme/a", "acme/b", "acme/c"], T0);
479
+ await seedCrawl(agentKey, ["acme/c"], T0);
480
+ store.archived = new Set(["acme/b", "acme/c"]);
481
+ await refresher([t]).tick();
482
+ // Installed archived acme/c is probed; the other archived acme/b is not.
483
+ expect(events.sort()).toEqual(["probe:acme/a@octocat", "probe:acme/c@octocat"]);
484
+ });
485
+ });
486
+
435
487
  describe("GithubRepoRefresher.tick", () => {
436
488
  it("runs missing work before expired: crawl, unanswered pairs, then expired", async () => {
437
489
  const t = target("acme", {
@@ -188,3 +188,66 @@ describe("sync preview for a null-account agent over the real lookup read", () =
188
188
  ]);
189
189
  });
190
190
  });
191
+
192
+ // The refresher checks an archived repo only when an agent configured it or it
193
+ // is on the installation, so the sync must not require a row for any other
194
+ // archived repo, nor treat a missing row as no access.
195
+ describe("sync preview with archived repos over the real lookup read", () => {
196
+ it("never adds archived repos, removes an installed one the user cannot push, and still uses the org", async () => {
197
+ const now = new Date();
198
+ // Rows exist for the non-archived repos and the installed archived acme/old
199
+ // (not pushable); acme/frozen is archived and not installed: no row.
200
+ const cache = freshCache(
201
+ "acme",
202
+ ["acme/a", "acme/b", "acme/old"],
203
+ ["acme/a", "acme/b"],
204
+ now,
205
+ );
206
+ const { prisma } = fakePrisma(["acme/a"], cache);
207
+ withLookupSnapshots(prisma, [
208
+ {
209
+ accountId: "deployment",
210
+ appRef: "77",
211
+ org: "acme",
212
+ completedAt: new Date(now.getTime() - 1000),
213
+ repos: [
214
+ { fullName: "acme/a" },
215
+ { fullName: "acme/b" },
216
+ { fullName: "acme/old", archived: true },
217
+ { fullName: "acme/frozen", archived: true },
218
+ ],
219
+ },
220
+ ]);
221
+ const svc = createGithubSync({
222
+ prisma,
223
+ appService: {
224
+ get: async () =>
225
+ ({
226
+ accountId: null,
227
+ appId: "77",
228
+ updatedAt: now,
229
+ }) as unknown as GitHubEnterpriseAppMetadata,
230
+ getPrivateKey: async () => "test-key",
231
+ },
232
+ access: accessFor([]), // the live resolver must not be consulted
233
+ agentEnv: envWith({ GH_APP_ID: "42" }),
234
+ // acme/old is archived and already on the installation.
235
+ installationRepos: {
236
+ listRepos: async () => ({ acme: ["acme/a", "acme/old"] }),
237
+ listInstalled: async () => ({
238
+ status: "found",
239
+ orgs: [{ org: "acme", repos: ["acme/a", "acme/old"] }],
240
+ }),
241
+ addRepos: async () => {},
242
+ removeRepos: async () => {},
243
+ },
244
+ now: () => now,
245
+ });
246
+ const r = await svc.preview("a1");
247
+ if (r.status !== "previewed") throw new Error(r.status);
248
+ expect(r.plan.skippedOrgs).toEqual([]);
249
+ expect(r.plan.appAdds).toEqual(["acme/b"]);
250
+ expect(r.plan.appRemoves).toEqual(["acme/old"]);
251
+ expect(r.plan.removedRepos).toEqual(["acme/old"]);
252
+ });
253
+ });
@@ -34,30 +34,30 @@
34
34
  */
35
35
 
36
36
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
37
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
37
38
  import {
38
39
  GITHUB_APPS_STATE_REASONS,
39
40
  type GithubAppsState,
40
41
  type GithubAppsStateFn,
41
42
  } from "./github-apps-state.ts";
42
- import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
43
43
  import { DEFAULT_REFRESH_STALENESS_CAP_MS } from "./github-repo-refresher.ts";
44
44
  import {
45
45
  buildCachedAccess,
46
46
  type CachedOrgInput,
47
47
  } from "./github-sync-cached-access.ts";
48
48
  import {
49
- identityOf,
50
- type InstallationCachePort,
51
- type InstallationReposPort,
52
- NO_INSTALLATION_REASON,
53
- } from "./installation-repos-service.ts";
54
- import {
55
- MAX_UNCONFIRMED_REMOVALS,
56
- MISSING_APP_ID_REASON,
57
49
  type InstallationAgentRecord,
58
50
  type InstallationAgentsPort,
59
51
  type InstallationAuditPort,
52
+ MAX_UNCONFIRMED_REMOVALS,
53
+ MISSING_APP_ID_REASON,
60
54
  } from "./installation-ports.ts";
55
+ import {
56
+ type InstallationCachePort,
57
+ type InstallationReposPort,
58
+ identityOf,
59
+ NO_INSTALLATION_REASON,
60
+ } from "./installation-repos-service.ts";
61
61
  import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
62
62
  import {
63
63
  accessSkipReason,
@@ -88,6 +88,8 @@ export const REVERIFY_FAILED_REASON =
88
88
  "the live permission re-check failed, so the removal was dropped";
89
89
  export const NOT_PRESENT_REASON =
90
90
  "not on the agent installation or in the agent's repos";
91
+ export const ARCHIVED_REASON =
92
+ "the repo is archived (read-only), so it is not added to the installation";
91
93
 
92
94
  /** GitHub caps the repositories in a selection-switch PATCH at 50. */
93
95
  export const MAX_SELECTION_PATCH_REPOS = 50;
@@ -129,6 +131,13 @@ export interface GithubSyncPlanInput {
129
131
  * every eligible repo is a candidate.
130
132
  */
131
133
  requested?: SyncLists;
134
+ /**
135
+ * Archived repos (owner/repo). They are never an installation add: an
136
+ * archived repo is read-only. An archived repo already on the installation
137
+ * is still removed when the access answer says the user cannot push. The
138
+ * agent's own repos are unaffected.
139
+ */
140
+ archivedRepos?: readonly string[];
132
141
  }
133
142
 
134
143
  export interface NotAppliedRepo {
@@ -254,8 +263,18 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
254
263
  return false;
255
264
  };
256
265
 
266
+ const archived = new Set((input.archivedRepos ?? []).map(lower));
267
+ // Adds only; checked before orgUsable, so an archived repo never reports its
268
+ // org skipped. Removals of installed archived repos take the normal path.
269
+ const isArchived = (repo: string): boolean => {
270
+ if (!archived.has(lower(repo))) return false;
271
+ leave(repo, ARCHIVED_REASON);
272
+ return true;
273
+ };
274
+
257
275
  const appAdds = new Set<string>();
258
276
  for (const repo of new Set(addCandidates)) {
277
+ if (isArchived(repo)) continue;
259
278
  if (!orgUsable(repo)) continue;
260
279
  if (!installedOrgs.has(lower(repoOrg(repo)))) {
261
280
  leave(repo, NOT_INSTALLED_ORG_REASON);
@@ -294,6 +313,8 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
294
313
  }
295
314
  return out;
296
315
  };
316
+ // An archived repo still on the installation is removed like any other once
317
+ // the user lacks push (least privilege); only adds skip archived repos.
297
318
  const confirmedAppRemoves = removable(appRemoveCandidates, installed);
298
319
  const agentRemoves = removable(agentRemoveCandidates, configured);
299
320
 
@@ -336,7 +357,14 @@ export function planGithubSync(input: GithubSyncPlanInput): GithubSyncPlan {
336
357
  export interface CachedLookupOrg {
337
358
  org: string;
338
359
  completedAt: Date | null;
360
+ /** The org's non-archived repos (owner/repo). */
339
361
  repos: readonly string[];
362
+ /**
363
+ * The org's archived repos (owner/repo), kept out of `repos`. GitHub Sync
364
+ * never adds or removes them and needs no access answer for them, except
365
+ * for one the agent has configured.
366
+ */
367
+ archivedRepos?: readonly string[];
340
368
  lastError?: string | null;
341
369
  rateLimitResetAt?: Date | null;
342
370
  }
@@ -639,13 +667,20 @@ export class GithubSyncService {
639
667
  };
640
668
  }
641
669
 
642
- /** Access from the cache (complete and fresh orgs only), with the installed orgs. */
670
+ /**
671
+ * Access from the cache (complete and fresh orgs only), with the installed
672
+ * orgs, plus the archived repos the lookup crawl reported. An archived repo
673
+ * is left out of an org's required access rows unless the agent has it
674
+ * configured or it is on the installation (the refresher probes those so a
675
+ * removal has an answer), since it does not check the others.
676
+ */
643
677
  private async cachedAccess(
644
678
  agent: InstallationAgentRecord,
645
679
  username: string,
646
680
  installed: { org: string; repos: string[] }[],
647
681
  ): Promise<{
648
682
  access: UserRepoAccessResult;
683
+ archivedRepos: string[];
649
684
  selections: Record<string, "all" | "selected" | null>;
650
685
  }> {
651
686
  const cache = this.deps.cache as InstallationCachePort;
@@ -668,6 +703,10 @@ export class GithubSyncService {
668
703
  readFailed = true;
669
704
  }
670
705
  const key = (s: string) => s.toLowerCase();
706
+ const archivedRepos = lookup.flatMap((l) => l.archivedRepos ?? []);
707
+ const archived = new Set(archivedRepos.map(key));
708
+ const configuredKeys = new Set(agent.repos.map(key));
709
+ const installedKeys = new Set(installed.flatMap((i) => i.repos.map(key)));
671
710
  const orgNames = new Map<string, string>();
672
711
  for (const i of installed) orgNames.set(key(i.org), i.org);
673
712
  for (const r of agent.repos) {
@@ -685,6 +724,12 @@ export class GithubSyncService {
685
724
  ...agent.repos.filter((r) => key(repoOrg(r)) === k),
686
725
  ...lk.flatMap((l) => l.repos),
687
726
  ]) {
727
+ if (
728
+ archived.has(key(r)) &&
729
+ !configuredKeys.has(key(r)) &&
730
+ !installedKeys.has(key(r))
731
+ )
732
+ continue;
688
733
  repos.set(key(r), r);
689
734
  }
690
735
  const crawls = [
@@ -742,6 +787,7 @@ export class GithubSyncService {
742
787
  }
743
788
  return {
744
789
  access: buildCachedAccess({ username, now, maxAgeMs, orgs: inputs }),
790
+ archivedRepos,
745
791
  selections,
746
792
  };
747
793
  }
@@ -788,11 +834,11 @@ export class GithubSyncService {
788
834
  if (installed.status === "none") {
789
835
  return none(skippedPlan(NO_INSTALLATION_REASON));
790
836
  }
837
+ // The live resolver reports no archived flag, so only the cached path
838
+ // leaves archived repos alone.
791
839
  const cached = liveAccess
792
840
  ? undefined
793
841
  : await this.cachedAccess(agent, username, installed.orgs);
794
- const resolved =
795
- liveAccess ?? (cached as { access: UserRepoAccessResult }).access;
796
842
  // The live path never reads the crawl cache, so every selection is unknown.
797
843
  const selections = cached?.selections;
798
844
  const installationRepos = Object.fromEntries(
@@ -800,7 +846,10 @@ export class GithubSyncService {
800
846
  );
801
847
  const plan = planGithubSync({
802
848
  username,
803
- access: resolved,
849
+ access: liveAccess ?? (cached?.access as UserRepoAccessResult),
850
+ ...(cached && cached.archivedRepos.length > 0
851
+ ? { archivedRepos: cached.archivedRepos }
852
+ : {}),
804
853
  agentRepos: agent.repos,
805
854
  installationRepos,
806
855
  ...(selections ? { selections } : {}),
@@ -5,6 +5,7 @@ import type {
5
5
  } from "./installation-repos-service.ts";
6
6
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
7
7
  import {
8
+ ARCHIVED_REASON,
8
9
  GITHUB_SYNC_AUDIT_PLAN_HASH,
9
10
  type CachedLookupOrg,
10
11
  GithubSyncService,
@@ -250,6 +251,70 @@ describe("planGithubSync (confirmed lists)", () => {
250
251
  });
251
252
  });
252
253
 
254
+ describe("planGithubSync (archived repos)", () => {
255
+ // acme/d is pushable and acme/c is not; both are archived.
256
+ const archivedRepos = ["ACME/d", "acme/c"];
257
+
258
+ test("an archived repo is never an add, but an installed one the user cannot push is removed", () => {
259
+ const p = planGithubSync(base({ archivedRepos }));
260
+ expect(p.appAdds).toEqual(["acme/e"]);
261
+ expect(p.appRemoves).toEqual(["acme/b", "acme/c"]);
262
+ expect(p.skippedOrgs).toEqual([]);
263
+ });
264
+
265
+ test("the agent's own archived repo keeps the normal removal rule", () => {
266
+ const p = planGithubSync(
267
+ base({ archivedRepos, agentRepos: ["acme/a", "acme/c"] }),
268
+ );
269
+ expect(p.agentRemoves).toEqual(["acme/c"]);
270
+ expect(p.appRemoves).toEqual(["acme/b", "acme/c"]);
271
+ });
272
+
273
+ test("an archived add does not skip its org when the org has no access answer for it", () => {
274
+ const p = planGithubSync(
275
+ base({
276
+ archivedRepos: ["other/old"],
277
+ installationRepos: { acme: ["acme/a"] },
278
+ requested: { appAdds: ["other/old"], appRemoves: [], agentRemoves: [] },
279
+ }),
280
+ );
281
+ expect(p.skippedOrgs).toEqual([]);
282
+ expect(p.notApplied).toEqual([{ repo: "other/old", reason: ARCHIVED_REASON }]);
283
+ });
284
+
285
+ test("an installed archived repo in an unchecked org is kept, not removed", () => {
286
+ const p = planGithubSync(
287
+ base({
288
+ archivedRepos: ["other/old"],
289
+ installationRepos: { acme: ["acme/a"], other: ["other/old"] },
290
+ }),
291
+ );
292
+ expect(p.appRemoves).toEqual([]);
293
+ expect(p.skippedOrgs.map((o) => o.org)).toEqual(["other"]);
294
+ });
295
+
296
+ test("confirmed archived adds are reported as left alone; removals proceed", () => {
297
+ const p = planGithubSync(
298
+ base({
299
+ archivedRepos,
300
+ requested: {
301
+ appAdds: ["acme/d"],
302
+ appRemoves: ["acme/c"],
303
+ agentRemoves: [],
304
+ },
305
+ }),
306
+ );
307
+ expect([p.appAdds, p.appRemoves]).toEqual([[], ["acme/c"]]);
308
+ expect(p.notApplied).toEqual([{ repo: "acme/d", reason: ARCHIVED_REASON }]);
309
+ });
310
+
311
+ test("without archivedRepos nothing changes", () => {
312
+ expect(planGithubSync(base({ archivedRepos: [] }))).toEqual(
313
+ planGithubSync(base()),
314
+ );
315
+ });
316
+ });
317
+
253
318
  // ─── Service ────────────────────────────────────────────────────────────────
254
319
 
255
320
  function harness(