@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.
@@ -33,7 +33,48 @@ export const accessFor = (pushable: string[]): GithubAccessPreviewFn => {
33
33
  });
34
34
  };
35
35
 
36
- export function fakePrisma(repos: string[]) {
36
+ /** Cached rows the fake prisma serves (GLC-2.3 sync reads them). */
37
+ export interface FakeCache {
38
+ snapshots?: unknown[];
39
+ access?: unknown[];
40
+ }
41
+
42
+ /** A completed agent-App snapshot plus ok access rows for `repos` in `org`, all checked at `checkedAt`. */
43
+ export function freshCache(
44
+ org: string,
45
+ repos: string[],
46
+ pushable: string[],
47
+ checkedAt: Date,
48
+ ): FakeCache {
49
+ return {
50
+ snapshots: [
51
+ {
52
+ org,
53
+ completedAt: checkedAt,
54
+ totalCount: repos.length,
55
+ lastError: null,
56
+ rateLimitResetAt: null,
57
+ attempts: 0,
58
+ nextAttemptAt: null,
59
+ leaseHolder: null,
60
+ leasedUntil: null,
61
+ lastTickAt: null,
62
+ repos: repos.map((fullName) => ({ fullName })),
63
+ },
64
+ ],
65
+ access: repos.map((f) => ({
66
+ repo: f.slice(f.indexOf("/") + 1),
67
+ status: "ok",
68
+ canPush: pushable.includes(f),
69
+ level: pushable.includes(f) ? "write" : "none",
70
+ checkedAt,
71
+ attempts: 0,
72
+ lastError: null,
73
+ })),
74
+ };
75
+ }
76
+
77
+ export function fakePrisma(repos: string[], cache: FakeCache = {}) {
37
78
  const state = {
38
79
  repos: [...repos],
39
80
  audits: 0,
@@ -53,10 +94,10 @@ export function fakePrisma(repos: string[]) {
53
94
  gitHubRepoSnapshot: {
54
95
  findMany: async (args: unknown) => {
55
96
  state.snapshotQueries.push(args);
56
- return [];
97
+ return cache.snapshots ?? [];
57
98
  },
58
99
  },
59
- gitHubRepoAccess: { findMany: async () => [] },
100
+ gitHubRepoAccess: { findMany: async () => cache.access ?? [] },
60
101
  gitHubReconcileAudit: {
61
102
  create: async () => {
62
103
  state.audits += 1;
@@ -146,6 +146,21 @@ export class GitHubRepoCacheService {
146
146
  }));
147
147
  }
148
148
 
149
+ /** Lookup-App snapshots with their org and repos (GitHub Sync, GLC-2.3). Reads only the cache. */
150
+ async listLookupOrgSnapshots(accountIds: string[], appRef: string) {
151
+ requireNonEmpty("appRef", appRef);
152
+ const rows = await this.prisma.gitHubRepoSnapshot.findMany({
153
+ where: { accountId: { in: accountIds }, appKind: "lookup", appRef },
154
+ include: { repos: { select: { fullName: true } } },
155
+ orderBy: { org: "asc" },
156
+ });
157
+ return rows.map((r) => ({
158
+ org: r.org,
159
+ completedAt: r.completedAt,
160
+ repos: r.repos,
161
+ }));
162
+ }
163
+
149
164
  /** Agent-App installation snapshots (with their repos) for one account scope and App id. Reads only the cache. */
150
165
  async listAgentSnapshots(accountId: string, appRef: string) {
151
166
  requireNonEmpty("accountId", accountId);
@@ -0,0 +1,134 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ accessFor,
4
+ envWith,
5
+ fakePrisma,
6
+ freshCache,
7
+ } from "./github-installation.fixtures.ts";
8
+ import {
9
+ createGithubInstallationRepos,
10
+ createGithubSync,
11
+ } from "./github-installation-wiring.ts";
12
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
13
+
14
+ // Sync preview over the real cache service (fake prisma): complete, partial, stale.
15
+
16
+ const REPOS = ["acme/a", "acme/b", "acme/c"];
17
+ const PUSHABLE = ["acme/a"];
18
+ const HOUR = 3_600_000;
19
+
20
+ const port: InstallationReposPort = {
21
+ listRepos: async () => ({ acme: REPOS }),
22
+ listInstalled: async () => ({
23
+ status: "found",
24
+ orgs: [{ org: "acme", repos: REPOS }],
25
+ }),
26
+ addRepos: async () => {},
27
+ removeRepos: async () => {},
28
+ };
29
+
30
+ function preview(cache: ReturnType<typeof freshCache>, now = new Date()) {
31
+ const { prisma } = fakePrisma(REPOS, cache);
32
+ const svc = createGithubSync({
33
+ prisma,
34
+ appService: { get: async () => null, getPrivateKey: async () => null },
35
+ access: accessFor([]), // the live resolver must not be consulted
36
+ agentEnv: envWith({ GH_APP_ID: "42" }),
37
+ installationRepos: port,
38
+ now: () => now,
39
+ syncOverrides: {
40
+ lookupRepos: async () => [
41
+ {
42
+ org: "acme",
43
+ completedAt: new Date(now.getTime() - 1000),
44
+ repos: REPOS,
45
+ },
46
+ ],
47
+ },
48
+ });
49
+ return svc.preview("a1");
50
+ }
51
+
52
+ describe("sync preview over the cache", () => {
53
+ it("proposes removals from a complete, fresh org", async () => {
54
+ const now = new Date();
55
+ const r = await preview(freshCache("acme", REPOS, PUSHABLE, now), now);
56
+ if (r.status !== "previewed") throw new Error(r.status);
57
+ expect(r.plan.appRemoves).toEqual(["acme/b", "acme/c"]);
58
+ expect(r.plan.skippedOrgs).toEqual([]);
59
+ });
60
+
61
+ it("skips a partial org (a repo has no ok row) and says it is incomplete", async () => {
62
+ const now = new Date();
63
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
64
+ cache.access = (cache.access as { repo: string }[]).filter(
65
+ (r) => r.repo !== "c",
66
+ );
67
+ const r = await preview(cache, now);
68
+ if (r.status !== "previewed") throw new Error(r.status);
69
+ expect(r.plan.removedRepos).toEqual([]);
70
+ expect(r.plan.skippedOrgs).toEqual([
71
+ { org: "acme", reason: "access data is incomplete" },
72
+ ]);
73
+ });
74
+
75
+ it("skips an org whose crawl has not completed", async () => {
76
+ const now = new Date();
77
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
78
+ (cache.snapshots as { completedAt: Date | null }[])[0]!.completedAt = null;
79
+ const r = await preview(cache, now);
80
+ if (r.status !== "previewed") throw new Error(r.status);
81
+ expect(r.plan.removedRepos).toEqual([]);
82
+ expect(r.plan.skippedOrgs[0]?.reason).toBe("access data is incomplete");
83
+ });
84
+
85
+ it("skips a stale org and reports when it was checked", async () => {
86
+ const now = new Date();
87
+ const checked = new Date(now.getTime() - 7 * HOUR);
88
+ const r = await preview(freshCache("acme", REPOS, PUSHABLE, checked), now);
89
+ if (r.status !== "previewed") throw new Error(r.status);
90
+ expect(r.plan.removedRepos).toEqual([]);
91
+ expect(r.plan.skippedOrgs[0]?.reason).toBe(
92
+ `access data is stale (checked ${checked.toISOString()})`,
93
+ );
94
+ expect(r.warnings.join()).toContain("stale");
95
+ });
96
+
97
+ it("an errored access row makes the org incomplete, never 'no access'", async () => {
98
+ const now = new Date();
99
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
100
+ (cache.access as { repo: string; status: string }[])[1]!.status = "error";
101
+ const r = await preview(cache, now);
102
+ if (r.status !== "previewed") throw new Error(r.status);
103
+ expect(r.plan.removedRepos).toEqual([]);
104
+ });
105
+ });
106
+
107
+ describe("installation list access detail", () => {
108
+ it("adds checkedAt, attempts and last error per repo", async () => {
109
+ const now = new Date("2026-11-21T00:00:00.000Z");
110
+ const cache = freshCache("acme", REPOS, PUSHABLE, now);
111
+ Object.assign((cache.access as Record<string, unknown>[])[1] as object, {
112
+ status: "error",
113
+ attempts: 2,
114
+ lastError: "boom",
115
+ });
116
+ const { prisma } = fakePrisma(REPOS, cache);
117
+ const svc = createGithubInstallationRepos({
118
+ prisma,
119
+ appService: { get: async () => null, getPrivateKey: async () => null },
120
+ access: accessFor([]),
121
+ agentEnv: envWith({ GH_APP_ID: "42" }),
122
+ installationRepos: port,
123
+ });
124
+ const r = await svc.list("a1");
125
+ if (r.status !== "ok") throw new Error(r.status);
126
+ const repos = r.orgs[0]?.repos ?? [];
127
+ expect(repos[0]?.accessCheckedAt).toBe(now.toISOString());
128
+ expect(repos[1]).toMatchObject({
129
+ accessAttempts: 2,
130
+ accessError: "boom",
131
+ });
132
+ expect(repos[1]?.userCanPush).toBeUndefined();
133
+ });
134
+ });
@@ -0,0 +1,125 @@
1
+ /**
2
+ * admin/src/github-sync-cached-access.ts
3
+ * Builds the bound user's access result for GitHub Sync from the repo/access
4
+ * cache (GLC-2.3). No GitHub call, no I/O: callers pass the cached rows.
5
+ *
6
+ * An org is usable (status ok) only when its data is complete and fresh:
7
+ * - every required crawl snapshot has completed;
8
+ * - every repo in the org has an ok access row;
9
+ * - every one of those rows (and each completed crawl) was checked within
10
+ * maxAgeMs of now.
11
+ * Otherwise the org is reported partial with a reason and no repos, so the
12
+ * shared access rules skip it (unknown is never none): incomplete data wins
13
+ * over stale data when both apply.
14
+ */
15
+
16
+ import type { CachedAccessRow } from "./installation-repos-service.ts";
17
+ import {
18
+ INCOMPLETE_ACCESS_REASON,
19
+ staleAccessReason,
20
+ } from "./repo-access-rules.ts";
21
+ import {
22
+ canPushForRole,
23
+ type OrgAccessResult,
24
+ type ResolvedRepoAccess,
25
+ type UserRepoAccessResult,
26
+ } from "./user-repo-access-resolver.ts";
27
+ import type { RepoRole } from "./github-lookup-client.ts";
28
+
29
+ export interface CachedOrgInput {
30
+ org: string;
31
+ /** completedAt of each crawl snapshot this org depends on; null = not completed. Empty = none needed. */
32
+ crawls: { completedAt: Date | null }[];
33
+ /** True when a crawl snapshot that must exist does not. */
34
+ crawlMissing?: boolean;
35
+ /** Every repo (full name) that needs an answer. */
36
+ repos: string[];
37
+ /** Cached access rows for the user over those repos. */
38
+ rows: readonly CachedAccessRow[];
39
+ }
40
+
41
+ const ROLES = new Set<string>([
42
+ "admin",
43
+ "maintain",
44
+ "write",
45
+ "triage",
46
+ "read",
47
+ "none",
48
+ ]);
49
+
50
+ const nameOf = (fullName: string): string =>
51
+ fullName.slice(fullName.indexOf("/") + 1).toLowerCase();
52
+
53
+ export function buildCachedAccess(opts: {
54
+ username: string;
55
+ now: Date;
56
+ maxAgeMs: number;
57
+ orgs: readonly CachedOrgInput[];
58
+ }): UserRepoAccessResult {
59
+ const staleBefore = opts.now.getTime() - opts.maxAgeMs;
60
+ const orgs: OrgAccessResult[] = [];
61
+ for (const o of opts.orgs) {
62
+ const byRepo = new Map(o.rows.map((r) => [r.repo.toLowerCase(), r]));
63
+ const answers = o.repos.map((f) => ({
64
+ fullName: f,
65
+ row: byRepo.get(nameOf(f)),
66
+ }));
67
+ const missing = answers.filter((a) => a.row?.status !== "ok");
68
+ const incomplete =
69
+ o.crawlMissing === true ||
70
+ o.crawls.some((c) => c.completedAt === null) ||
71
+ missing.length > 0;
72
+ if (incomplete) {
73
+ orgs.push({
74
+ org: o.org,
75
+ status: "partial",
76
+ repos: [],
77
+ unresolved: missing.length,
78
+ reason: INCOMPLETE_ACCESS_REASON,
79
+ });
80
+ continue;
81
+ }
82
+ const times = [
83
+ ...o.crawls.map((c) => c.completedAt as Date),
84
+ ...answers.map((a) => a.row?.checkedAt),
85
+ ];
86
+ const unknownTime = times.some((t) => t === undefined);
87
+ const known = times.filter((t): t is Date => t !== undefined);
88
+ const oldest = known.sort((a, b) => a.getTime() - b.getTime())[0];
89
+ if (unknownTime || (oldest && oldest.getTime() < staleBefore)) {
90
+ orgs.push({
91
+ org: o.org,
92
+ status: "partial",
93
+ repos: [],
94
+ unresolved: 0,
95
+ reason: staleAccessReason(unknownTime ? undefined : oldest),
96
+ });
97
+ continue;
98
+ }
99
+ const repos: ResolvedRepoAccess[] = answers.map(({ fullName, row }) => {
100
+ const level: RepoRole = ROLES.has(row?.level ?? "")
101
+ ? (row?.level as RepoRole)
102
+ : row?.canPush
103
+ ? "write"
104
+ : "read";
105
+ return {
106
+ fullName,
107
+ level,
108
+ canPush: row?.canPush ?? canPushForRole(level),
109
+ };
110
+ });
111
+ orgs.push({ org: o.org, status: "ok", repos, unresolved: 0 });
112
+ }
113
+ const unresolved = orgs.reduce((a, o) => a + o.unresolved, 0);
114
+ return {
115
+ username: opts.username,
116
+ outcome: "ok",
117
+ // Per-org gating decides what is usable; a nonexistent user is also
118
+ // caught by the live re-check before any removal is applied.
119
+ userVerified: true,
120
+ orgs,
121
+ unresolved,
122
+ complete: orgs.length > 0 && orgs.every((o) => o.status === "ok"),
123
+ checkedAt: opts.now.toISOString(),
124
+ };
125
+ }
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ GithubSyncService,
4
+ REVERIFY_FAILED_REASON,
5
+ STILL_PUSHABLE_REASON,
6
+ } from "./github-sync.ts";
7
+ import type { InstallationCachePort } from "./installation-repos-service.ts";
8
+ import { MAX_UNCONFIRMED_REMOVALS } from "./installation-ports.ts";
9
+
10
+ const NOW = new Date("2026-11-21T00:00:00.000Z");
11
+ const names = (n: number) => Array.from({ length: n }, (_, i) => `acme/r${i}`);
12
+
13
+ function build(
14
+ repos: string[],
15
+ verify: (repo: string) => Promise<boolean | undefined>,
16
+ ) {
17
+ const removed: string[][] = [];
18
+ const cache: InstallationCachePort = {
19
+ listAgentSnapshots: async () => [
20
+ {
21
+ org: "acme",
22
+ completedAt: NOW,
23
+ totalCount: repos.length,
24
+ lastError: null,
25
+ rateLimitResetAt: null,
26
+ repos: repos.map((fullName) => ({ fullName })),
27
+ },
28
+ ],
29
+ getAccessRows: async () =>
30
+ repos.map((f) => ({
31
+ repo: f.slice(5),
32
+ status: "ok",
33
+ canPush: false,
34
+ level: "none",
35
+ checkedAt: NOW,
36
+ })),
37
+ };
38
+ const svc = new GithubSyncService({
39
+ agents: {
40
+ get: async () => ({
41
+ id: "ag",
42
+ githubUsername: "octo",
43
+ appId: 7,
44
+ repos: [],
45
+ }),
46
+ setRepos: async () => {},
47
+ },
48
+ access: async () => {
49
+ throw new Error("live resolver must not be called");
50
+ },
51
+ cache,
52
+ now: () => NOW,
53
+ verifyPush: (_u, repo) => verify(repo),
54
+ installation: {
55
+ listInstalled: async () => ({
56
+ status: "found",
57
+ orgs: [{ org: "acme", repos }],
58
+ }),
59
+ addRepos: async () => {},
60
+ removeRepos: async (_a, _o, r) => {
61
+ removed.push([...r]);
62
+ },
63
+ },
64
+ audit: { write: async () => "audit-1" },
65
+ });
66
+ return { svc, removed };
67
+ }
68
+
69
+ const input = (appRemoves: string[], extra = {}) => ({
70
+ agentId: "ag",
71
+ caller: "root",
72
+ appAdds: [],
73
+ appRemoves,
74
+ agentRemoves: [],
75
+ ...extra,
76
+ });
77
+
78
+ describe("GithubSyncService live re-verify of removals", () => {
79
+ it("removes only candidates the live call says cannot push, one call each", async () => {
80
+ const calls: string[] = [];
81
+ const { svc, removed } = build(["acme/a", "acme/b"], async (r) => {
82
+ calls.push(r);
83
+ return false;
84
+ });
85
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
86
+ expect(res.status).toBe("applied");
87
+ expect(calls).toEqual(["acme/a", "acme/b"]);
88
+ expect(removed).toEqual([["acme/a", "acme/b"]]);
89
+ });
90
+
91
+ it("drops a candidate that is still pushable and reports it", async () => {
92
+ const { svc, removed } = build(
93
+ ["acme/a", "acme/b"],
94
+ async (r) => r === "acme/a",
95
+ );
96
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
97
+ if (res.status !== "applied") throw new Error(res.status);
98
+ expect(removed).toEqual([["acme/b"]]);
99
+ expect(res.plan.notApplied).toEqual([
100
+ { repo: "acme/a", reason: STILL_PUSHABLE_REASON },
101
+ ]);
102
+ });
103
+
104
+ it("drops a candidate when the call returns undefined or throws (unknown is never none)", async () => {
105
+ const { svc, removed } = build(["acme/a", "acme/b"], async (r) => {
106
+ if (r === "acme/b") throw new Error("boom");
107
+ return undefined;
108
+ });
109
+ const res = await svc.apply(input(["acme/a", "acme/b"]));
110
+ if (res.status !== "noop") throw new Error(res.status);
111
+ expect(removed).toEqual([]);
112
+ expect(res.plan.notApplied.map((n) => n.reason)).toEqual([
113
+ REVERIFY_FAILED_REASON,
114
+ REVERIFY_FAILED_REASON,
115
+ ]);
116
+ });
117
+
118
+ it("preview makes no live calls", async () => {
119
+ let calls = 0;
120
+ const { svc } = build(["acme/a"], async () => {
121
+ calls += 1;
122
+ return false;
123
+ });
124
+ const r = await svc.preview("ag");
125
+ if (r.status !== "previewed") throw new Error(r.status);
126
+ expect(r.plan.appRemoves).toEqual(["acme/a"]);
127
+ expect(calls).toBe(0);
128
+ });
129
+
130
+ it("the removal cap counts what survives the re-check", async () => {
131
+ const repos = names(MAX_UNCONFIRMED_REMOVALS + 1);
132
+ const { svc } = build(repos, async (r) => r === repos[0]);
133
+ const res = await svc.apply(input(repos));
134
+ expect(res.status).toBe("applied");
135
+ const { svc: svc2 } = build(repos, async () => false);
136
+ expect((await svc2.apply(input(repos))).status).toBe("removal_cap");
137
+ });
138
+ });