@app-vitals/agent-admin 1.74.0 → 1.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ /**
2
+ * admin/src/github-repo-cache.ts
3
+ * GitHubRepoCacheService — storage for the GitHub repo/access cache (GLC-1.1):
4
+ * a per-org crawl snapshot, the repos each crawl saw, and per-user push access.
5
+ *
6
+ * Crawl generations: a crawl stamps every repo it sees with `seenAt >=
7
+ * crawlStartedAt`; sweepGeneration() then deletes rows older than that, i.e.
8
+ * repos that disappeared since the previous crawl.
9
+ *
10
+ * Leases are a compare-and-set on `leasedUntil` (one UPDATE), so of several
11
+ * concurrent acquirers exactly one wins until the lease expires or is released.
12
+ */
13
+
14
+ import type { PrismaClient } from "../prisma/client/client.ts";
15
+ import { type Clock, SystemClock } from "./clock.ts";
16
+ import { BadRequestError } from "./errors.ts";
17
+
18
+ export const GITHUB_REPO_APP_KINDS = ["lookup", "agent"] as const;
19
+ export type GitHubRepoAppKind = (typeof GITHUB_REPO_APP_KINDS)[number];
20
+
21
+ export const GITHUB_ACCESS_STATUSES = ["ok", "error", "terminal"] as const;
22
+ export type GitHubAccessStatus = (typeof GITHUB_ACCESS_STATUSES)[number];
23
+
24
+ export interface SnapshotKey {
25
+ accountId: string;
26
+ appKind: GitHubRepoAppKind;
27
+ appRef: string;
28
+ org: string;
29
+ }
30
+
31
+ export type SnapshotProgress = Partial<{
32
+ crawlPage: number;
33
+ crawlStartedAt: Date | null;
34
+ completedAt: Date | null;
35
+ totalCount: number | null;
36
+ lastError: string | null;
37
+ attempts: number;
38
+ nextAttemptAt: Date | null;
39
+ rateLimitResetAt: Date | null;
40
+ lastTickAt: Date | null;
41
+ }>;
42
+
43
+ export interface CachedRepoInput {
44
+ githubId: number | bigint;
45
+ fullName: string;
46
+ archived?: boolean;
47
+ }
48
+
49
+ export interface AccessInput {
50
+ accountId: string;
51
+ org: string;
52
+ repo: string;
53
+ username: string;
54
+ canPush: boolean;
55
+ level?: string | null;
56
+ status: GitHubAccessStatus;
57
+ attempts?: number;
58
+ nextAttemptAt?: Date | null;
59
+ lastError?: string | null;
60
+ }
61
+
62
+ export interface AccessQuery {
63
+ accountId: string;
64
+ org: string;
65
+ username: string;
66
+ /** Repo names (without org) to consider. */
67
+ repos: string[];
68
+ /** Rows with status ok older than this are expired. */
69
+ maxAgeMs: number;
70
+ }
71
+
72
+ const REPO_BATCH_SIZE = 500;
73
+
74
+ function requireNonEmpty(name: string, value: unknown): void {
75
+ if (typeof value !== "string" || value.trim() === "") {
76
+ throw new BadRequestError(`${name} is required`);
77
+ }
78
+ }
79
+
80
+ function validateKey(key: SnapshotKey): void {
81
+ requireNonEmpty("accountId", key.accountId);
82
+ requireNonEmpty("appRef", key.appRef);
83
+ requireNonEmpty("org", key.org);
84
+ if (!(GITHUB_REPO_APP_KINDS as readonly string[]).includes(key.appKind)) {
85
+ throw new BadRequestError(
86
+ `appKind must be one of: ${GITHUB_REPO_APP_KINDS.join(", ")}`,
87
+ );
88
+ }
89
+ }
90
+
91
+ function validatePositiveMs(name: string, value: number): void {
92
+ if (!Number.isFinite(value) || value <= 0) {
93
+ throw new BadRequestError(`${name} must be a positive number`);
94
+ }
95
+ }
96
+
97
+ export class GitHubRepoCacheService {
98
+ constructor(
99
+ private readonly prisma: PrismaClient,
100
+ private readonly clock: Clock = SystemClock(),
101
+ ) {}
102
+
103
+ private where(key: SnapshotKey) {
104
+ return {
105
+ accountId_appKind_appRef_org: {
106
+ accountId: key.accountId,
107
+ appKind: key.appKind,
108
+ appRef: key.appRef,
109
+ org: key.org,
110
+ },
111
+ };
112
+ }
113
+
114
+ /** Create the snapshot row, or merge `progress` into the existing one. */
115
+ async upsertSnapshot(key: SnapshotKey, progress: SnapshotProgress = {}) {
116
+ validateKey(key);
117
+ return this.prisma.gitHubRepoSnapshot.upsert({
118
+ where: this.where(key),
119
+ create: { ...key, ...progress },
120
+ update: progress,
121
+ });
122
+ }
123
+
124
+ async getSnapshot(key: SnapshotKey) {
125
+ validateKey(key);
126
+ return this.prisma.gitHubRepoSnapshot.findUnique({
127
+ where: this.where(key),
128
+ });
129
+ }
130
+
131
+ /** Upsert repos for a snapshot in batches, stamping each with `seenAt`. */
132
+ async upsertRepos(
133
+ snapshotId: string,
134
+ repos: CachedRepoInput[],
135
+ seenAt: Date = this.clock.now(),
136
+ ): Promise<number> {
137
+ requireNonEmpty("snapshotId", snapshotId);
138
+ for (const r of repos) {
139
+ requireNonEmpty("fullName", r.fullName);
140
+ }
141
+ for (let i = 0; i < repos.length; i += REPO_BATCH_SIZE) {
142
+ const batch = repos.slice(i, i + REPO_BATCH_SIZE);
143
+ await this.prisma.$transaction(
144
+ batch.map((r) =>
145
+ this.prisma.gitHubCachedRepo.upsert({
146
+ where: {
147
+ snapshotId_githubId: {
148
+ snapshotId,
149
+ githubId: BigInt(r.githubId),
150
+ },
151
+ },
152
+ create: {
153
+ snapshotId,
154
+ githubId: BigInt(r.githubId),
155
+ fullName: r.fullName,
156
+ archived: r.archived ?? false,
157
+ seenAt,
158
+ },
159
+ update: {
160
+ fullName: r.fullName,
161
+ archived: r.archived ?? false,
162
+ seenAt,
163
+ },
164
+ }),
165
+ ),
166
+ );
167
+ }
168
+ return repos.length;
169
+ }
170
+
171
+ /**
172
+ * Delete repos last seen before the snapshot's crawlStartedAt. Returns the
173
+ * number deleted; 0 (and deletes nothing) when no crawl has started.
174
+ */
175
+ async sweepGeneration(snapshotId: string): Promise<number> {
176
+ requireNonEmpty("snapshotId", snapshotId);
177
+ const snap = await this.prisma.gitHubRepoSnapshot.findUnique({
178
+ where: { id: snapshotId },
179
+ select: { crawlStartedAt: true },
180
+ });
181
+ if (!snap?.crawlStartedAt) return 0;
182
+ const { count } = await this.prisma.gitHubCachedRepo.deleteMany({
183
+ where: { snapshotId, seenAt: { lt: snap.crawlStartedAt } },
184
+ });
185
+ return count;
186
+ }
187
+
188
+ /**
189
+ * Take the org's lease for `ttlMs`. True when this holder now owns it; false
190
+ * when another holder's lease is still live or the snapshot does not exist.
191
+ */
192
+ async acquireLease(
193
+ snapshotId: string,
194
+ holder: string,
195
+ ttlMs: number,
196
+ ): Promise<boolean> {
197
+ requireNonEmpty("snapshotId", snapshotId);
198
+ requireNonEmpty("holder", holder);
199
+ validatePositiveMs("ttlMs", ttlMs);
200
+ const now = this.clock.now();
201
+ const { count } = await this.prisma.gitHubRepoSnapshot.updateMany({
202
+ where: {
203
+ id: snapshotId,
204
+ OR: [{ leasedUntil: null }, { leasedUntil: { lte: now } }],
205
+ },
206
+ data: {
207
+ leaseHolder: holder,
208
+ leasedUntil: new Date(now.getTime() + ttlMs),
209
+ },
210
+ });
211
+ return count === 1;
212
+ }
213
+
214
+ /** Release the lease if `holder` still owns it. Idempotent. */
215
+ async releaseLease(snapshotId: string, holder: string): Promise<void> {
216
+ requireNonEmpty("snapshotId", snapshotId);
217
+ requireNonEmpty("holder", holder);
218
+ await this.prisma.gitHubRepoSnapshot.updateMany({
219
+ where: { id: snapshotId, leaseHolder: holder },
220
+ data: { leaseHolder: null, leasedUntil: null },
221
+ });
222
+ }
223
+
224
+ async upsertAccess(input: AccessInput) {
225
+ requireNonEmpty("accountId", input.accountId);
226
+ requireNonEmpty("org", input.org);
227
+ requireNonEmpty("repo", input.repo);
228
+ requireNonEmpty("username", input.username);
229
+ if (!(GITHUB_ACCESS_STATUSES as readonly string[]).includes(input.status)) {
230
+ throw new BadRequestError(
231
+ `status must be one of: ${GITHUB_ACCESS_STATUSES.join(", ")}`,
232
+ );
233
+ }
234
+ const data = {
235
+ canPush: input.canPush,
236
+ level: input.level ?? null,
237
+ checkedAt: this.clock.now(),
238
+ status: input.status,
239
+ attempts: input.attempts ?? 0,
240
+ nextAttemptAt: input.nextAttemptAt ?? null,
241
+ lastError: input.lastError ?? null,
242
+ };
243
+ return this.prisma.gitHubRepoAccess.upsert({
244
+ where: {
245
+ accountId_org_repo_username: {
246
+ accountId: input.accountId,
247
+ org: input.org,
248
+ repo: input.repo,
249
+ username: input.username,
250
+ },
251
+ },
252
+ create: {
253
+ accountId: input.accountId,
254
+ org: input.org,
255
+ repo: input.repo,
256
+ username: input.username,
257
+ ...data,
258
+ },
259
+ update: data,
260
+ });
261
+ }
262
+
263
+ /**
264
+ * Repos in `query.repos` that still need an access check: no row yet, an ok
265
+ * row older than maxAgeMs, or an error row whose nextAttemptAt has passed.
266
+ * Terminal rows are never returned.
267
+ */
268
+ async findMissingOrExpiredAccess(query: AccessQuery): Promise<string[]> {
269
+ requireNonEmpty("accountId", query.accountId);
270
+ requireNonEmpty("org", query.org);
271
+ requireNonEmpty("username", query.username);
272
+ validatePositiveMs("maxAgeMs", query.maxAgeMs);
273
+ if (query.repos.length === 0) return [];
274
+ const now = this.clock.now();
275
+ const rows = await this.prisma.gitHubRepoAccess.findMany({
276
+ where: {
277
+ accountId: query.accountId,
278
+ org: query.org,
279
+ username: query.username,
280
+ repo: { in: query.repos },
281
+ },
282
+ });
283
+ const staleBefore = now.getTime() - query.maxAgeMs;
284
+ const settled = new Set<string>();
285
+ for (const row of rows) {
286
+ const due =
287
+ row.status === "ok"
288
+ ? row.checkedAt.getTime() < staleBefore
289
+ : row.status === "error"
290
+ ? row.nextAttemptAt === null || row.nextAttemptAt <= now
291
+ : false;
292
+ if (!due) settled.add(row.repo);
293
+ }
294
+ return query.repos.filter((r) => !settled.has(r));
295
+ }
296
+ }
@@ -0,0 +1,66 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { PrismaClient } from "../prisma/client/client.ts";
3
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
4
+
5
+ // Validation runs before any DB call, so a throwing proxy proves none happens.
6
+ const noDb = new Proxy(
7
+ {},
8
+ {
9
+ get() {
10
+ throw new Error("db touched");
11
+ },
12
+ },
13
+ ) as unknown as PrismaClient;
14
+ const svc = new GitHubRepoCacheService(noDb);
15
+ const key = {
16
+ accountId: "a",
17
+ appKind: "lookup" as const,
18
+ appRef: "1",
19
+ org: "o",
20
+ };
21
+
22
+ describe("GitHubRepoCacheService argument validation", () => {
23
+ it("rejects a bad appKind", async () => {
24
+ await expect(
25
+ svc.upsertSnapshot({ ...key, appKind: "bogus" as never }),
26
+ ).rejects.toThrow("appKind");
27
+ });
28
+ it("rejects empty key parts", async () => {
29
+ await expect(svc.getSnapshot({ ...key, org: " " })).rejects.toThrow("org");
30
+ await expect(svc.getSnapshot({ ...key, accountId: "" })).rejects.toThrow(
31
+ "accountId",
32
+ );
33
+ });
34
+ it("rejects a non-positive lease ttl and empty holder", async () => {
35
+ await expect(svc.acquireLease("s", "h", 0)).rejects.toThrow("ttlMs");
36
+ await expect(svc.acquireLease("s", "", 10)).rejects.toThrow("holder");
37
+ });
38
+ it("rejects an empty repo fullName", async () => {
39
+ await expect(
40
+ svc.upsertRepos("s", [{ githubId: 1, fullName: "" }]),
41
+ ).rejects.toThrow("fullName");
42
+ });
43
+ it("rejects a bad access status", async () => {
44
+ await expect(
45
+ svc.upsertAccess({
46
+ accountId: "a",
47
+ org: "o",
48
+ repo: "r",
49
+ username: "u",
50
+ canPush: true,
51
+ status: "nope" as never,
52
+ }),
53
+ ).rejects.toThrow("status");
54
+ });
55
+ it("rejects a non-positive maxAgeMs", async () => {
56
+ await expect(
57
+ svc.findMissingOrExpiredAccess({
58
+ accountId: "a",
59
+ org: "o",
60
+ username: "u",
61
+ repos: ["r"],
62
+ maxAgeMs: -1,
63
+ }),
64
+ ).rejects.toThrow("maxAgeMs");
65
+ });
66
+ });
@@ -0,0 +1,167 @@
1
+ /**
2
+ * admin/src/member-id-backfill.integration.test.ts (ACM-1.2)
3
+ * Backfill over a seeded DB: matched, unmapped and overridden rows.
4
+ *
5
+ * Fixture emails mirror the shapes the live tables hold: lowercase matches,
6
+ * mixed-case/whitespace variants of a member email, a departed user with no
7
+ * member, and a renamed address that needs a hand-matched override. They were
8
+ * NOT read from the live database (no access from the build environment);
9
+ * ACM-1.3 (HITL dry-run on prod) is where observed values get reconciled.
10
+ *
11
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
15
+ import type { PrismaClient } from "../prisma/client/client.ts";
16
+ import { runMemberIdBackfill } from "./member-id-backfill.ts";
17
+ import { createAdminPrismaClient } from "./prisma-client.ts";
18
+
19
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
21
+
22
+ describeOrSkip("memberId backfill (integration)", () => {
23
+ let prisma: PrismaClient;
24
+ let aliceId: string;
25
+ let carolId: string;
26
+
27
+ async function seedRows(email: string, n = 1) {
28
+ const agent = await prisma.agent.upsert({
29
+ where: { id: "bf-agent" },
30
+ update: {},
31
+ create: { id: "bf-agent", name: "bf-agent" },
32
+ });
33
+ await prisma.userNotificationPrefs.create({ data: { userEmail: email } });
34
+ for (let i = 0; i < n; i++) {
35
+ await prisma.chatThreadWatch.create({
36
+ data: {
37
+ userEmail: email,
38
+ threadId: `t-${email}-${i}`,
39
+ agentId: agent.id,
40
+ },
41
+ });
42
+ }
43
+ await prisma.pushSubscription.create({
44
+ data: {
45
+ userEmail: email,
46
+ endpoint: `ep-${email}`,
47
+ p256dh: "p",
48
+ auth: "a",
49
+ },
50
+ });
51
+ await prisma.agentMember.create({ data: { agentId: agent.id, email } });
52
+ }
53
+
54
+ beforeEach(async () => {
55
+ prisma = createAdminPrismaClient(TEST_DB as string);
56
+ await prisma.userNotificationPrefs.deleteMany();
57
+ await prisma.chatThreadWatch.deleteMany();
58
+ await prisma.pushSubscription.deleteMany();
59
+ await prisma.agentMember.deleteMany();
60
+ await prisma.accountMember.deleteMany();
61
+ await prisma.agent.deleteMany();
62
+ await prisma.account.deleteMany();
63
+ const account = await prisma.account.create({ data: { name: "Acme" } });
64
+ aliceId = (
65
+ await prisma.accountMember.create({
66
+ data: { accountId: account.id, email: "alice@acme.com", role: "owner" },
67
+ })
68
+ ).id;
69
+ carolId = (
70
+ await prisma.accountMember.create({
71
+ data: {
72
+ accountId: account.id,
73
+ email: "carol@acme.com",
74
+ role: "member",
75
+ },
76
+ })
77
+ ).id;
78
+ await seedRows("alice@acme.com", 2); // matched
79
+ await seedRows("Alice@Acme.com "); // matched after normalization
80
+ await seedRows("gone@old.com", 3); // unmapped
81
+ await seedRows("carol.old@acme.com"); // overridden -> carol
82
+ });
83
+
84
+ afterEach(async () => {
85
+ await prisma.$disconnect();
86
+ });
87
+
88
+ const memberIds = async () => ({
89
+ prefs: await prisma.userNotificationPrefs.findMany({
90
+ orderBy: { userEmail: "asc" },
91
+ }),
92
+ watches: await prisma.chatThreadWatch.findMany(),
93
+ });
94
+
95
+ it("dry run changes nothing and reports unmapped emails with per-table counts", async () => {
96
+ const report = await runMemberIdBackfill(prisma, { dryRun: true });
97
+ expect(report.unmapped).toEqual([
98
+ {
99
+ email: "carol.old@acme.com",
100
+ counts: {
101
+ UserNotificationPrefs: 1,
102
+ ChatThreadWatch: 1,
103
+ PushSubscription: 1,
104
+ AgentMember: 1,
105
+ },
106
+ },
107
+ {
108
+ email: "gone@old.com",
109
+ counts: {
110
+ UserNotificationPrefs: 1,
111
+ ChatThreadWatch: 3,
112
+ PushSubscription: 1,
113
+ AgentMember: 1,
114
+ },
115
+ },
116
+ ]);
117
+ const { prefs, watches } = await memberIds();
118
+ expect(prefs.every((p) => p.memberId === null)).toBe(true);
119
+ expect(watches.every((w) => w.memberId === null)).toBe(true);
120
+ });
121
+
122
+ it("apply maps matched rows, leaves unmapped null, and is idempotent", async () => {
123
+ const first = await runMemberIdBackfill(prisma, { dryRun: false });
124
+ expect(first.mapped.ChatThreadWatch).toBe(3); // alice x2 + variant
125
+ const prefs = await prisma.userNotificationPrefs.findMany();
126
+ const idFor = (e: string) => prefs.find((p) => p.userEmail === e)?.memberId;
127
+ expect(idFor("alice@acme.com")).toBe(aliceId);
128
+ expect(idFor("Alice@Acme.com ")).toBe(aliceId);
129
+ expect(idFor("gone@old.com")).toBeNull();
130
+ expect(idFor("carol.old@acme.com")).toBeNull();
131
+
132
+ const second = await runMemberIdBackfill(prisma, { dryRun: false });
133
+ expect(Object.values(second.mapped).every((n) => n === 0)).toBe(true);
134
+ expect(second.unmapped).toEqual(first.unmapped);
135
+ });
136
+
137
+ it("overrides take precedence over the automatic match and apply is idempotent", async () => {
138
+ const overrides = new Map([
139
+ ["carol.old@acme.com", carolId],
140
+ ["alice@acme.com", carolId], // beats the automatic alice match
141
+ ]);
142
+ await runMemberIdBackfill(prisma, { dryRun: false });
143
+ await runMemberIdBackfill(prisma, { dryRun: false, overrides });
144
+ const again = await runMemberIdBackfill(prisma, {
145
+ dryRun: false,
146
+ overrides,
147
+ });
148
+ expect(Object.values(again.mapped).every((n) => n === 0)).toBe(true);
149
+
150
+ const prefs = await prisma.userNotificationPrefs.findMany();
151
+ const idFor = (e: string) => prefs.find((p) => p.userEmail === e)?.memberId;
152
+ expect(idFor("carol.old@acme.com")).toBe(carolId);
153
+ expect(idFor("alice@acme.com")).toBe(carolId);
154
+ // overrides are keyed on the normalized email, so the variant follows
155
+ expect(idFor("Alice@Acme.com ")).toBe(carolId);
156
+ expect(again.unmapped.map((u) => u.email)).toEqual(["gone@old.com"]);
157
+ });
158
+
159
+ it("rejects an override naming an unknown member id", async () => {
160
+ await expect(
161
+ runMemberIdBackfill(prisma, {
162
+ dryRun: true,
163
+ overrides: new Map([["x@y.z", "nope"]]),
164
+ }),
165
+ ).rejects.toThrow(/unknown member id/);
166
+ });
167
+ });
@@ -0,0 +1,180 @@
1
+ /**
2
+ * admin/src/member-id-backfill.ts
3
+ * ACM-1.2: maps the email-keyed per-user rows (UserNotificationPrefs,
4
+ * ChatThreadWatch, PushSubscription, AgentMember) to AccountMember.id.
5
+ *
6
+ * - Match order: overrides (email -> member id) first, then the automatic
7
+ * match on the normalized email against AccountMember.email.
8
+ * - Dry run writes nothing and reports every distinct email with no match,
9
+ * with its row count per table.
10
+ * - Apply sets memberId on matched rows (only where it differs from the
11
+ * target, so a re-run is a no-op) and leaves unmapped rows null.
12
+ */
13
+
14
+ import type { PrismaClient } from "../prisma/client/client.ts";
15
+ import { normalizeEmail } from "./account-email.ts";
16
+
17
+ export const BACKFILL_TABLES = [
18
+ "UserNotificationPrefs",
19
+ "ChatThreadWatch",
20
+ "PushSubscription",
21
+ "AgentMember",
22
+ ] as const;
23
+ export type BackfillTable = (typeof BACKFILL_TABLES)[number];
24
+
25
+ export interface UnmappedEmail {
26
+ email: string;
27
+ /** Row counts per table (only tables with at least one such row). */
28
+ counts: Partial<Record<BackfillTable, number>>;
29
+ }
30
+
31
+ export interface MemberIdBackfillReport {
32
+ dryRun: boolean;
33
+ /** Rows set (apply) or that would be set (dry run), per table. */
34
+ mapped: Record<BackfillTable, number>;
35
+ unmapped: UnmappedEmail[];
36
+ }
37
+
38
+ /** Parses an overrides file body: a JSON object of email -> AccountMember.id. */
39
+ export function parseOverrides(json: string): Map<string, string> {
40
+ const raw: unknown = JSON.parse(json);
41
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
42
+ throw new Error("overrides must be a JSON object of email -> member id");
43
+ }
44
+ const out = new Map<string, string>();
45
+ for (const [email, id] of Object.entries(raw)) {
46
+ if (typeof id !== "string" || id === "") {
47
+ throw new Error(`override for ${email} must be a non-empty member id`);
48
+ }
49
+ out.set(normalizeEmail(email), id);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ interface TableAccess {
55
+ distinct(): Promise<{ email: string; count: number }[]>;
56
+ /** Sets memberId on rows keyed by this exact email value that don't already have it. */
57
+ assign(email: string, memberId: string): Promise<number>;
58
+ }
59
+
60
+ function tableAccess(prisma: PrismaClient): Record<BackfillTable, TableAccess> {
61
+ const notId = (memberId: string) => ({
62
+ OR: [{ memberId: null }, { memberId: { not: memberId } }],
63
+ });
64
+ return {
65
+ UserNotificationPrefs: {
66
+ distinct: async () =>
67
+ (
68
+ await prisma.userNotificationPrefs.groupBy({
69
+ by: ["userEmail"],
70
+ _count: { _all: true },
71
+ })
72
+ ).map((g) => ({ email: g.userEmail, count: g._count._all })),
73
+ assign: async (email, memberId) =>
74
+ (
75
+ await prisma.userNotificationPrefs.updateMany({
76
+ where: { userEmail: email, ...notId(memberId) },
77
+ data: { memberId },
78
+ })
79
+ ).count,
80
+ },
81
+ ChatThreadWatch: {
82
+ distinct: async () =>
83
+ (
84
+ await prisma.chatThreadWatch.groupBy({
85
+ by: ["userEmail"],
86
+ _count: { _all: true },
87
+ })
88
+ ).map((g) => ({ email: g.userEmail, count: g._count._all })),
89
+ assign: async (email, memberId) =>
90
+ (
91
+ await prisma.chatThreadWatch.updateMany({
92
+ where: { userEmail: email, ...notId(memberId) },
93
+ data: { memberId },
94
+ })
95
+ ).count,
96
+ },
97
+ PushSubscription: {
98
+ distinct: async () =>
99
+ (
100
+ await prisma.pushSubscription.groupBy({
101
+ by: ["userEmail"],
102
+ _count: { _all: true },
103
+ })
104
+ ).map((g) => ({ email: g.userEmail, count: g._count._all })),
105
+ assign: async (email, memberId) =>
106
+ (
107
+ await prisma.pushSubscription.updateMany({
108
+ where: { userEmail: email, ...notId(memberId) },
109
+ data: { memberId },
110
+ })
111
+ ).count,
112
+ },
113
+ AgentMember: {
114
+ distinct: async () =>
115
+ (
116
+ await prisma.agentMember.groupBy({
117
+ by: ["email"],
118
+ _count: { _all: true },
119
+ })
120
+ ).map((g) => ({ email: g.email, count: g._count._all })),
121
+ assign: async (email, memberId) =>
122
+ (
123
+ await prisma.agentMember.updateMany({
124
+ where: { email, ...notId(memberId) },
125
+ data: { memberId },
126
+ })
127
+ ).count,
128
+ },
129
+ };
130
+ }
131
+
132
+ export async function runMemberIdBackfill(
133
+ prisma: PrismaClient,
134
+ opts: { dryRun: boolean; overrides?: Map<string, string> },
135
+ ): Promise<MemberIdBackfillReport> {
136
+ const overrides = opts.overrides ?? new Map<string, string>();
137
+
138
+ const members = await prisma.accountMember.findMany({
139
+ select: { id: true, email: true },
140
+ });
141
+ const byEmail = new Map(members.map((m) => [normalizeEmail(m.email), m.id]));
142
+ const memberIds = new Set(members.map((m) => m.id));
143
+ for (const [email, id] of overrides) {
144
+ if (!memberIds.has(id)) {
145
+ throw new Error(`override for ${email} names unknown member id ${id}`);
146
+ }
147
+ }
148
+
149
+ const tables = tableAccess(prisma);
150
+ const mapped = Object.fromEntries(
151
+ BACKFILL_TABLES.map((t) => [t, 0]),
152
+ ) as Record<BackfillTable, number>;
153
+ const unmapped = new Map<string, UnmappedEmail>();
154
+
155
+ for (const table of BACKFILL_TABLES) {
156
+ for (const { email, count } of await tables[table].distinct()) {
157
+ const key = normalizeEmail(email);
158
+ const memberId = overrides.get(key) ?? byEmail.get(key);
159
+ if (!memberId) {
160
+ const entry = unmapped.get(key) ?? { email: key, counts: {} };
161
+ entry.counts[table] = (entry.counts[table] ?? 0) + count;
162
+ unmapped.set(key, entry);
163
+ continue;
164
+ }
165
+ if (opts.dryRun) {
166
+ mapped[table] += count;
167
+ } else {
168
+ mapped[table] += await tables[table].assign(email, memberId);
169
+ }
170
+ }
171
+ }
172
+
173
+ return {
174
+ dryRun: opts.dryRun,
175
+ mapped,
176
+ unmapped: [...unmapped.values()].sort((a, b) =>
177
+ a.email.localeCompare(b.email),
178
+ ),
179
+ };
180
+ }