@app-vitals/agent-admin 1.83.0 → 1.84.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/src/admin-spec.ts CHANGED
@@ -17,16 +17,10 @@
17
17
  * scripts/generate-admin-spec.ts to produce the composed admin/openapi.json.
18
18
  */
19
19
 
20
+ import { Hono } from "hono";
20
21
  import { NoopAgentProvisioner } from "./agent-provisioner.ts";
21
- import { createAgentTemplatesApp } from "./agent-templates-api.ts";
22
- import {
23
- type AdminDeps,
24
- createAdminApp,
25
- parseAdminApiKeys,
26
- } from "./agents-api.ts";
27
- import { createAgentRuntimeApp } from "./api.ts";
28
- import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
29
- import { createPrincipalsApp } from "./principals-api.ts";
22
+ import { type AdminDeps, parseAdminApiKeys } from "./agents-api.ts";
23
+ import { mountPlatformApis } from "./platform-routes.ts";
30
24
 
31
25
  /** The admin OpenAPI document shape the spec builders and generators share. */
32
26
  export interface AdminOpenApiDocument {
@@ -43,86 +37,115 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
43
37
  const SESSION_SECRET = "dummy-secret-32chars-for-spec-gen";
44
38
  const adminApiKeys = parseAdminApiKeys("codegen:codegen-key:*");
45
39
 
46
- const runtimeApp = createAgentRuntimeApp({
47
- agentEnvService: {
48
- async getConfigBundle() {
49
- return null;
40
+ const { mounted } = mountPlatformApis(new Hono(), {
41
+ runtime: {
42
+ agentEnvService: {
43
+ async getConfigBundle() {
44
+ return null;
45
+ },
50
46
  },
51
- },
52
- agentCronJobService: {
53
- async list() {
54
- return [];
47
+ agentCronJobService: {
48
+ async list() {
49
+ return [];
50
+ },
55
51
  },
56
- },
57
- agentService: {
58
- async getById() {
59
- return null;
52
+ agentService: {
53
+ async getById() {
54
+ return null;
55
+ },
60
56
  },
61
- },
62
- agentPluginService: {
63
- async listEnabled() {
64
- return [];
57
+ agentPluginService: {
58
+ async listEnabled() {
59
+ return [];
60
+ },
65
61
  },
62
+ adminApiKeys,
63
+ agentTokenService: { validate: async () => null },
64
+ sessionSecret: SESSION_SECRET,
66
65
  },
67
- adminApiKeys,
68
- agentTokenService: { validate: async () => null },
69
- sessionSecret: SESSION_SECRET,
70
- });
71
-
72
- const adminApp = createAdminApp({
73
- agentEnvService: {
74
- upsert: async () => {},
75
- patch: async () => {},
76
- getByAgentId: async () => null,
77
- deleteKey: async () => {},
78
- },
79
- agentCronJobService: {
80
- list: async () => [],
81
- listWithRunSummary: async () => [],
82
- create: async () => ({}) as never,
83
- update: async () => ({}) as never,
84
- delete: async () => {},
85
- get: async () => ({}) as never,
86
- setEnabled: async () => ({}) as never,
87
- updatePreCheck: async () => ({}) as never,
88
- reconcileSystemCrons: async () => ({
89
- created: 0,
90
- updated: 0,
91
- deleted: 0,
92
- }),
66
+ adminApi: {
67
+ agentEnvService: {
68
+ upsert: async () => {},
69
+ patch: async () => {},
70
+ getByAgentId: async () => null,
71
+ deleteKey: async () => {},
72
+ },
73
+ agentCronJobService: {
74
+ list: async () => [],
75
+ listWithRunSummary: async () => [],
76
+ create: async () => ({}) as never,
77
+ update: async () => ({}) as never,
78
+ delete: async () => {},
79
+ get: async () => ({}) as never,
80
+ setEnabled: async () => ({}) as never,
81
+ updatePreCheck: async () => ({}) as never,
82
+ reconcileSystemCrons: async () => ({
83
+ created: 0,
84
+ updated: 0,
85
+ deleted: 0,
86
+ }),
87
+ },
88
+ agentToolService: {
89
+ list: async () => [],
90
+ add: async () => ({}) as never,
91
+ remove: async () => {},
92
+ toggle: async () => ({}) as never,
93
+ },
94
+ agentTokenService: {
95
+ create: async () => ({}) as never,
96
+ listForAgent: async () => [],
97
+ revoke: async () => ({}) as never,
98
+ validate: async () => null,
99
+ },
100
+ agentPluginService: {
101
+ list: async () => [],
102
+ add: async () => ({}) as never,
103
+ remove: async () => {},
104
+ removeByName: async () => {},
105
+ },
106
+ prisma: {
107
+ agent: {
108
+ create: async () => ({}) as never,
109
+ findUnique: async () => null,
110
+ findMany: async () => [],
111
+ delete: async () => ({}) as never,
112
+ },
113
+ } as never,
114
+ provisioner: new NoopAgentProvisioner(),
115
+ sessionSecret: SESSION_SECRET,
116
+ adminApiKeys,
117
+ // Partial on purpose: route registration never calls the services, so
118
+ // only the deps a factory reads at construction time are stubbed.
119
+ } as unknown as AdminDeps,
120
+ accounts: {
121
+ accountService: {} as never,
122
+ accountLifecycle: {} as never,
123
+ sessionSecret: SESSION_SECRET,
124
+ adminApiKeys,
125
+ agentTokenService: { validate: async () => null },
93
126
  },
94
- agentToolService: {
95
- list: async () => [],
96
- add: async () => ({}) as never,
97
- remove: async () => {},
98
- toggle: async () => ({}) as never,
127
+ principals: {
128
+ lookup: {} as never,
129
+ sessionSecret: SESSION_SECRET,
130
+ adminApiKeys,
131
+ agentTokenService: { validate: async () => null },
99
132
  },
100
- agentTokenService: {
101
- create: async () => ({}) as never,
102
- listForAgent: async () => [],
103
- revoke: async () => ({}) as never,
104
- validate: async () => null,
133
+ templates: {
134
+ templateService: {} as never,
135
+ callerScopeResolver: async () => ({ kind: "all" }),
136
+ sessionSecret: SESSION_SECRET,
137
+ adminApiKeys,
138
+ agentTokenService: { validate: async () => null },
105
139
  },
106
- agentPluginService: {
107
- list: async () => [],
108
- add: async () => ({}) as never,
109
- remove: async () => {},
110
- removeByName: async () => {},
140
+ githubEnterprise: {
141
+ appService: {} as never,
142
+ agentService: {} as never,
143
+ agentEnvService: {} as never,
144
+ sessionSecret: SESSION_SECRET,
145
+ adminApiKeys,
146
+ agentTokenService: { validate: async () => null },
111
147
  },
112
- prisma: {
113
- agent: {
114
- create: async () => ({}) as never,
115
- findUnique: async () => null,
116
- findMany: async () => [],
117
- delete: async () => ({}) as never,
118
- },
119
- } as never,
120
- provisioner: new NoopAgentProvisioner(),
121
- sessionSecret: SESSION_SECRET,
122
- adminApiKeys,
123
- // Partial on purpose: route registration never calls the services, so only
124
- // the deps a factory reads at construction time are stubbed.
125
- } as unknown as AdminDeps);
148
+ });
126
149
 
127
150
  const docInfo = {
128
151
  openapi: "3.1.0" as const,
@@ -135,92 +158,39 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
135
158
  servers: [{ url: "http://localhost:3457", description: "Local dev" }],
136
159
  };
137
160
 
138
- // Admin app spec (uses OpenAPI {id} path notation)
139
- const adminSpec = adminApp.getOpenAPI31Document(docInfo);
140
-
141
- // Runtime app spec (uses Hono :id notation — paths are relative to sub-app root)
142
- const runtimeSpec = runtimeApp.getOpenAPI31Document({
143
- openapi: "3.1.0",
144
- info: { title: "runtime (internal)", version: "0.1.0" },
145
- });
146
-
147
- // The runtime app's routes are defined as `/:id/config` and `/:id/crons`.
148
- // When the spec is generated standalone, these appear as `/:id/config` etc.
149
- // We rewrite Hono colon params to OpenAPI curly brace params, then prefix
150
- // with `/agents` to match the root-mounted path.
161
+ // The admin app is the base document (it carries info/servers); every other
162
+ // spec'd app is folded in on top of it. Admin goes first so its paths lead.
163
+ const specApps = mounted.filter((m) => m.inSpec);
164
+ const adminEntry = specApps.find((m) => m.name === "admin");
165
+ if (!adminEntry) throw new Error("platform admin app is not mounted");
166
+ const adminSpec = adminEntry.app.getOpenAPI31Document(docInfo);
151
167
 
152
- // Build runtime paths with OpenAPI notation and /agents prefix.
153
- // Merge at the method level so paths shared between admin and runtime
154
- // (e.g. /agents/{id}/crons has both POST from admin and GET from runtime)
155
- // keep all their HTTP methods.
156
- const adminPaths = (adminSpec.paths ?? {}) as Record<
157
- string,
158
- Record<string, unknown>
159
- >;
160
168
  const mergedPaths: Record<string, Record<string, unknown>> = {
161
- ...adminPaths,
169
+ ...((adminSpec.paths ?? {}) as Record<string, Record<string, unknown>>),
170
+ };
171
+ const schemas: Record<string, unknown> = {
172
+ ...(adminSpec.components?.schemas ?? {}),
162
173
  };
163
174
 
164
- for (const [path, def] of Object.entries(runtimeSpec.paths ?? {})) {
165
- const openApiPath = `/agents${path.replace(/:(\w+)/g, "{$1}")}`;
166
- if (mergedPaths[openApiPath]) {
167
- // Merge methods — runtime GET on /agents/{id}/crons must coexist with
168
- // admin POST on the same path.
175
+ for (const entry of specApps) {
176
+ if (entry === adminEntry) continue;
177
+ const spec = entry.app.getOpenAPI31Document({
178
+ openapi: "3.1.0",
179
+ info: { title: `${entry.name} (internal)`, version: "0.1.0" },
180
+ });
181
+ // A sub-app's paths are relative to its mount prefix and use Hono `:id`
182
+ // params; rewrite to OpenAPI `{id}` and prefix them (runtime -> /agents).
183
+ // Merge at the method level so paths shared between apps (e.g.
184
+ // /agents/{id}/crons: admin POST + runtime GET) keep all their methods.
185
+ const prefix = entry.prefix === "/" ? "" : entry.prefix;
186
+ for (const [path, def] of Object.entries(spec.paths ?? {})) {
187
+ const openApiPath = `${prefix}${path.replace(/:(\w+)/g, "{$1}")}`;
169
188
  mergedPaths[openApiPath] = {
170
189
  ...mergedPaths[openApiPath],
171
190
  ...(def as Record<string, unknown>),
172
191
  };
173
- } else {
174
- mergedPaths[openApiPath] = def as Record<string, unknown>;
175
192
  }
176
- }
177
-
178
- // GHE-1.3: the /github-enterprise routes live in their own app (mounted at
179
- // the root in admin-boot.ts); fold their paths and schemas in.
180
- const gheSpec = createGithubEnterpriseApp({
181
- appService: {} as never,
182
- agentService: {} as never,
183
- agentEnvService: {} as never,
184
- sessionSecret: SESSION_SECRET,
185
- adminApiKeys,
186
- agentTokenService: { validate: async () => null },
187
- }).getOpenAPI31Document({
188
- openapi: "3.1.0",
189
- info: { title: "github-enterprise (internal)", version: "0.1.0" },
190
- });
191
- for (const [path, def] of Object.entries(gheSpec.paths ?? {})) {
192
- mergedPaths[path] = def as Record<string, unknown>;
193
- }
194
-
195
- // ATP-1.3: the /templates routes live in their own app (mounted at the root
196
- // in admin-boot.ts); fold their paths and schemas in.
197
- const templatesSpec = createAgentTemplatesApp({
198
- templateService: {} as never,
199
- callerScopeResolver: async () => ({ kind: "all" }),
200
- sessionSecret: SESSION_SECRET,
201
- adminApiKeys,
202
- agentTokenService: { validate: async () => null },
203
- }).getOpenAPI31Document({
204
- openapi: "3.1.0",
205
- info: { title: "templates (internal)", version: "0.1.0" },
206
- });
207
- for (const [path, def] of Object.entries(templatesSpec.paths ?? {})) {
208
- mergedPaths[path] = def as Record<string, unknown>;
209
- }
210
-
211
- // ACM-1.1: the /principals lookup routes live in their own app (mounted at
212
- // the root in admin-boot.ts); fold their paths and schemas in.
213
- const principalsSpec = createPrincipalsApp({
214
- lookup: {} as never,
215
- sessionSecret: SESSION_SECRET,
216
- adminApiKeys,
217
- agentTokenService: { validate: async () => null },
218
- }).getOpenAPI31Document({
219
- openapi: "3.1.0",
220
- info: { title: "principals (internal)", version: "0.1.0" },
221
- });
222
- for (const [path, def] of Object.entries(principalsSpec.paths ?? {})) {
223
- mergedPaths[path] = def as Record<string, unknown>;
193
+ Object.assign(schemas, spec.components?.schemas ?? {});
224
194
  }
225
195
 
226
196
  return {
@@ -228,13 +198,7 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
228
198
  paths: mergedPaths,
229
199
  components: {
230
200
  ...(adminSpec.components ?? {}),
231
- schemas: {
232
- ...(adminSpec.components?.schemas ?? {}),
233
- ...(runtimeSpec.components?.schemas ?? {}),
234
- ...(gheSpec.components?.schemas ?? {}),
235
- ...(templatesSpec.components?.schemas ?? {}),
236
- ...(principalsSpec.components?.schemas ?? {}),
237
- },
201
+ schemas,
238
202
  },
239
203
  };
240
204
  }
@@ -42,7 +42,13 @@ export interface InstallationReposView extends InstallationSyncView {
42
42
  appId?: number;
43
43
  orgs: ({
44
44
  org: string;
45
- repos: { fullName: string; userCanPush?: boolean }[];
45
+ repos: {
46
+ fullName: string;
47
+ userCanPush?: boolean;
48
+ accessCheckedAt?: string;
49
+ accessAttempts?: number;
50
+ accessError?: string;
51
+ }[];
46
52
  } & InstallationSyncView)[];
47
53
  }
48
54
 
@@ -310,7 +316,19 @@ export function renderInstallationReposBody(
310
316
  : r.userCanPush
311
317
  ? '<span class="badge badge-green" title="The bound user can push">user can push</span>'
312
318
  : '<span class="badge badge-warning" title="The bound user cannot push">user cannot push</span>';
313
- return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}</td></tr>`;
319
+ const detail = [
320
+ r.accessCheckedAt
321
+ ? `checked ${escapeHtml(r.accessCheckedAt)}`
322
+ : "",
323
+ r.accessAttempts
324
+ ? `${r.accessAttempts} failed attempts`
325
+ : "",
326
+ r.accessError ? `error: ${escapeHtml(r.accessError)}` : "",
327
+ ].filter(Boolean);
328
+ const meta = detail.length
329
+ ? ` <span style="color:#6b7280;font-size:12px">${detail.join("; ")}</span>`
330
+ : "";
331
+ return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}${meta}</td></tr>`;
314
332
  })
315
333
  .join("");
316
334
  return `<div class="github-installation-org" data-org="${escapeHtml(o.org)}" style="margin-bottom:16px"><div style="font-weight:600;margin-bottom:6px">${escapeHtml(o.org)}</div>${renderInstallationSyncStatus(o)}<table class="detail-table"><thead><tr><th>Repo</th><th>Bound user</th></tr></thead><tbody>${rows}</tbody></table></div>`;
@@ -7363,6 +7363,36 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7363
7363
  headers: { "Content-Type": "application/json" },
7364
7364
  });
7365
7365
  }) as typeof fetch;
7366
+ // Sync reads the cache (GLC-2.3): unless a test seeds its own rows, serve a
7367
+ // complete, fresh cache that mirrors `pushable` over the installed, agent
7368
+ // and pushable repos.
7369
+ const checkedAt = new Date();
7370
+ const pushableRepos = opts.pushable ?? [
7371
+ "acme-eng/repo-1",
7372
+ "acme-eng/repo-3",
7373
+ ];
7374
+ const universe = [
7375
+ ...new Set([...state.installed, ...state.repos, ...pushableRepos]),
7376
+ ];
7377
+ const defaultSnapshots = [
7378
+ {
7379
+ org: "acme-eng",
7380
+ completedAt: checkedAt,
7381
+ totalCount: state.installed.length,
7382
+ lastError: null,
7383
+ rateLimitResetAt: null,
7384
+ repos: state.installed.map((fullName) => ({ fullName })),
7385
+ },
7386
+ ];
7387
+ const defaultAccess = universe.map((f) => ({
7388
+ repo: f.split("/")[1],
7389
+ status: "ok",
7390
+ canPush: pushableRepos.includes(f),
7391
+ level: pushableRepos.includes(f) ? "write" : "none",
7392
+ checkedAt,
7393
+ attempts: 0,
7394
+ lastError: null,
7395
+ }));
7366
7396
  const prisma = {
7367
7397
  agent: {
7368
7398
  findUnique: async () =>
@@ -7380,10 +7410,10 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7380
7410
  },
7381
7411
  },
7382
7412
  gitHubRepoSnapshot: {
7383
- findMany: async () => opts.snapshots ?? [],
7413
+ findMany: async () => opts.snapshots ?? defaultSnapshots,
7384
7414
  },
7385
7415
  gitHubRepoAccess: {
7386
- findMany: async () => opts.accessRows ?? [],
7416
+ findMany: async () => opts.accessRows ?? defaultAccess,
7387
7417
  },
7388
7418
  gitHubReconcileAudit: {
7389
7419
  create: async (args: { data: Record<string, unknown> }) => {
@@ -7435,6 +7465,13 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7435
7465
  const githubSync = createGithubSync({
7436
7466
  ...wiring,
7437
7467
  ...(openWork ? { openWork } : {}),
7468
+ syncOverrides: {
7469
+ lookupRepos: async () => [
7470
+ { org: "acme-eng", completedAt: checkedAt, repos: universe },
7471
+ ],
7472
+ // The live permission call agrees with `pushable`.
7473
+ verifyPush: async (_user, repo) => pushableRepos.includes(repo),
7474
+ },
7438
7475
  });
7439
7476
  const base = makeMockDeps();
7440
7477
  const app = createAdminApp({
package/src/agents-api.ts CHANGED
@@ -670,12 +670,9 @@ const InstallationSyncDetailShape = {
670
670
  .int()
671
671
  .optional()
672
672
  .openapi({ description: "Failed refresh attempts; absent when zero." }),
673
- nextAttemptAt: z
674
- .string()
675
- .optional()
676
- .openapi({
677
- description: "Next refresh attempt while backing off (ISO 8601).",
678
- }),
673
+ nextAttemptAt: z.string().optional().openapi({
674
+ description: "Next refresh attempt while backing off (ISO 8601).",
675
+ }),
679
676
  leaseHolder: z
680
677
  .string()
681
678
  .optional()
@@ -701,6 +698,17 @@ const GithubInstallationReposListSchema = z
701
698
  description:
702
699
  "Whether the agent's bound GitHub user can push, from cached access rows. Omitted when no username is bound or the org's access data is incomplete (a missing or errored pair is never reported as false).",
703
700
  }),
701
+ accessCheckedAt: z.string().optional().openapi({
702
+ description:
703
+ "When the bound user's access to this repo was last checked (ISO 8601), when a cached row exists.",
704
+ }),
705
+ accessAttempts: z.number().int().optional().openapi({
706
+ description:
707
+ "Failed access checks for this repo since the last success, when any.",
708
+ }),
709
+ accessError: z.string().optional().openapi({
710
+ description: "Last access-check error for this repo, when any.",
711
+ }),
704
712
  }),
705
713
  ),
706
714
  }),
@@ -738,7 +746,7 @@ const GithubSyncPreviewSchema = z
738
746
  }),
739
747
  skippedOrgs: SkippedOrgsSchema.optional().openapi({
740
748
  description:
741
- "Orgs whose access listing is missing, partial or failed, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed.",
749
+ "Orgs whose access listing is missing, partial or failed, whose cached access data is incomplete or stale, or whose lookup App is not installed or installed on selected repositories only; nothing there is added or removed. `reason` says why (for stale data, when it was checked).",
742
750
  }),
743
751
  openWork: z.array(OpenWorkItemSchema).optional().openapi({
744
752
  description:
@@ -18,7 +18,8 @@ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
18
18
  import type { CrawlStore } from "./github-repo-crawler.ts";
19
19
  import { createRefreshDiscovery } from "./github-repo-refresh-discovery.ts";
20
20
  import type { RefreshDiscovery } from "./github-repo-refresher.ts";
21
- import { GithubSyncService } from "./github-sync.ts";
21
+ import { canPushForRole } from "./user-repo-access-resolver.ts";
22
+ import { type GithubSyncDeps, GithubSyncService } from "./github-sync.ts";
22
23
  import {
23
24
  createInstallationPort,
24
25
  type InstallationAgentRecord,
@@ -95,6 +96,8 @@ export interface InstallationReposWiringDeps
95
96
  extends GithubInstallationWiringDeps {
96
97
  /** Test seam: replaces the installer-App-backed port. */
97
98
  installationRepos?: InstallationReposPort;
99
+ /** Test seam: replaces the lookup-App-backed sync cache source and re-check. */
100
+ syncOverrides?: Pick<GithubSyncDeps, "lookupRepos" | "verifyPush">;
98
101
  }
99
102
 
100
103
  /**
@@ -125,9 +128,66 @@ export function createGithubSync(
125
128
  deps: InstallationReposWiringDeps,
126
129
  ): GithubSyncService {
127
130
  const client = lazyInstallerClient(deps);
131
+ const cache = new GitHubRepoCacheService(deps.prisma);
132
+ const lookupClients = new Map<string, GithubLookupClient>();
133
+ // The lookup client per App (and key version), reused with its installation tokens.
134
+ const lookupClient = async (accountId?: string | null) => {
135
+ const meta = await deps.appService.get("lookup", accountId);
136
+ if (!meta) return null;
137
+ const privateKey = await deps.appService.getPrivateKey("lookup", accountId);
138
+ if (!privateKey) return null;
139
+ const cacheKey = `${meta.accountId ?? ""}|${meta.appId}|${meta.updatedAt.getTime()}`;
140
+ let c = lookupClients.get(cacheKey);
141
+ if (!c) {
142
+ c = new GithubLookupClient({
143
+ appId: meta.appId,
144
+ privateKey,
145
+ apiBase: deps.apiBase,
146
+ fetchFn: deps.fetchFn,
147
+ now: deps.now,
148
+ });
149
+ lookupClients.set(cacheKey, c);
150
+ }
151
+ return { client: c, appId: meta.appId };
152
+ };
128
153
  return new GithubSyncService({
129
154
  agents: new PrismaInstallationAgents(deps.prisma, deps.agentEnv),
130
155
  access: deps.access,
156
+ cache,
157
+ ...(deps.now ? { now: deps.now } : {}),
158
+ lookupRepos: async (accountId) => {
159
+ const lookup = await lookupClient(accountId);
160
+ if (!lookup) return [];
161
+ // The crawler files a deployment-wide App's snapshots under accountId "".
162
+ const snapshots = await cache.listLookupOrgSnapshots(
163
+ accountId ? [accountId, ""] : [""],
164
+ lookup.appId,
165
+ );
166
+ return snapshots.map((s) => ({
167
+ org: s.org,
168
+ completedAt: s.completedAt,
169
+ repos: s.repos.map((r) => r.fullName),
170
+ }));
171
+ },
172
+ // One permission call per removal candidate; undefined on any failure.
173
+ verifyPush: async (username, repo, accountId) => {
174
+ try {
175
+ const lookup = await lookupClient(accountId);
176
+ if (!lookup) return undefined;
177
+ const [owner, name] = repo.split("/");
178
+ if (!owner || !name) return undefined;
179
+ const { role } =
180
+ await lookup.client.getCollaboratorPermissionWithRateLimit(
181
+ owner,
182
+ name,
183
+ username,
184
+ );
185
+ return canPushForRole(role);
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ },
190
+ ...deps.syncOverrides,
131
191
  installation:
132
192
  deps.installationRepos ??
133
193
  createInstallationReposPort(createInstallationPort(client), client),
@@ -4,6 +4,7 @@ import {
4
4
  envWith,
5
5
  fakeOpenWork,
6
6
  fakePrisma,
7
+ freshCache,
7
8
  } from "./github-installation.fixtures.ts";
8
9
  import {
9
10
  createGithubInstallationRepos,
@@ -72,17 +73,35 @@ describe("createGithubInstallationRepos", () => {
72
73
  });
73
74
 
74
75
  describe("createGithubSync", () => {
75
- const build = (openWork?: ReturnType<typeof fakeOpenWork>["port"]) => {
76
- const { prisma, state } = fakePrisma(["acme/old", "acme/api"]);
76
+ const ALL = ["acme/old", "acme/api"];
77
+ const build = (
78
+ openWork?: ReturnType<typeof fakeOpenWork>["port"],
79
+ opts: { checkedAt?: Date; verify?: boolean | undefined } = {},
80
+ ) => {
81
+ const checkedAt = opts.checkedAt ?? new Date();
82
+ const { prisma, state } = fakePrisma(
83
+ ALL,
84
+ freshCache("acme", ALL, ["acme/api"], checkedAt),
85
+ );
86
+ const verified: string[] = [];
77
87
  const svc = createGithubSync({
78
88
  prisma,
79
89
  appService: noApp,
80
90
  access: accessFor(["acme/api"]),
81
91
  agentEnv: envWith({ GH_APP_ID: "42" }),
82
92
  installationRepos: portWith([]),
93
+ syncOverrides: {
94
+ lookupRepos: async () => [
95
+ { org: "acme", completedAt: checkedAt, repos: ALL },
96
+ ],
97
+ verifyPush: async (_u, repo) => {
98
+ verified.push(repo);
99
+ return "verify" in opts ? opts.verify : false;
100
+ },
101
+ },
83
102
  openWork,
84
103
  });
85
- return { svc, state };
104
+ return { svc, state, verified };
86
105
  };
87
106
 
88
107
  it("with a port: preview lists affected open work and apply blocks it", async () => {
@@ -116,4 +135,37 @@ describe("createGithubSync", () => {
116
135
  expect(res.status).toBe("applied");
117
136
  expect(state.repos).toEqual(["acme/api"]);
118
137
  });
138
+
139
+ it("reads the cache: a stale org is skipped with the reason and nothing is removed", async () => {
140
+ const old = new Date(Date.now() - 24 * 3_600_000);
141
+ const { svc, state, verified } = build(undefined, { checkedAt: old });
142
+ const preview = await svc.preview("a1");
143
+ if (preview.status !== "previewed") throw new Error(preview.status);
144
+ expect(preview.plan.removedRepos).toEqual([]);
145
+ expect(preview.plan.skippedOrgs[0]?.reason).toContain("stale (checked");
146
+ const res = await svc.apply({
147
+ agentId: "a1",
148
+ caller: "root",
149
+ appAdds: [],
150
+ appRemoves: ["acme/old"],
151
+ agentRemoves: ["acme/old"],
152
+ });
153
+ expect(res.status).toBe("noop");
154
+ expect(verified).toEqual([]);
155
+ expect(state.repos).toEqual(ALL);
156
+ });
157
+
158
+ it("apply drops a candidate the live re-check still sees as pushable", async () => {
159
+ const { svc, state, verified } = build(undefined, { verify: true });
160
+ const res = await svc.apply({
161
+ agentId: "a1",
162
+ caller: "root",
163
+ appAdds: [],
164
+ appRemoves: [],
165
+ agentRemoves: ["acme/old"],
166
+ });
167
+ expect(res.status).toBe("noop");
168
+ expect(verified).toEqual(["acme/old"]);
169
+ expect(state.repos).toEqual(ALL);
170
+ });
119
171
  });