@app-vitals/agent-admin 1.107.2 → 1.107.4

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.
Files changed (59) hide show
  1. package/e2e/real/agent-management.real.e2e.ts +195 -0
  2. package/e2e/real/seed.ts +0 -1
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -5
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  7. package/prisma/client/models/AgentMember.ts +26 -61
  8. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  9. package/prisma/client/models/PushSubscription.ts +15 -43
  10. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  11. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  12. package/prisma/schema/schema.prisma +11 -15
  13. package/src/account-member-removal.integration.test.ts +31 -44
  14. package/src/account-members.ts +4 -6
  15. package/src/account-onboarding.ts +2 -5
  16. package/src/account-onboarding.unit.test.ts +71 -0
  17. package/src/accounts.ts +1 -3
  18. package/src/admin-dev-login.smoke.test.ts +1 -1
  19. package/src/admin-local-agent.smoke.test.ts +28 -6
  20. package/src/admin-ui-agent-members.smoke.test.ts +31 -7
  21. package/src/admin-ui-pages.ts +23 -1
  22. package/src/admin-ui-pages.unit.test.ts +17 -0
  23. package/src/admin-ui.fixtures.ts +1 -1
  24. package/src/admin-ui.smoke.test.ts +163 -100
  25. package/src/admin-ui.ts +132 -55
  26. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  27. package/src/agent-deletion.integration.test.ts +1 -1
  28. package/src/agent-management-access.integration.test.ts +269 -0
  29. package/src/agent-members.integration.test.ts +14 -10
  30. package/src/agent-members.ts +28 -18
  31. package/src/agents-api.integration.test.ts +2 -2
  32. package/src/agents-api.smoke.test.ts +68 -13
  33. package/src/agents-api.ts +2 -0
  34. package/src/agents.integration.test.ts +1 -2
  35. package/src/api-auth.ts +31 -1
  36. package/src/api-auth.unit.test.ts +106 -6
  37. package/src/api.smoke.test.ts +1 -1
  38. package/src/caller-scope.ts +21 -0
  39. package/src/caller-scope.unit.test.ts +39 -0
  40. package/src/chat.smoke.test.ts +68 -14
  41. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  42. package/src/ensure-account-member.integration.test.ts +17 -232
  43. package/src/ensure-account-member.ts +0 -5
  44. package/src/github-enterprise-client.unit.test.ts +62 -2
  45. package/src/member-rows.ts +24 -0
  46. package/src/member-rows.unit.test.ts +48 -0
  47. package/src/principals-api.integration.test.ts +3 -2
  48. package/src/push-service.integration.test.ts +7 -12
  49. package/src/push-service.ts +28 -39
  50. package/src/push-service.unit.test.ts +8 -8
  51. package/src/slack-provisioning.integration.test.ts +1 -1
  52. package/src/user-notification-prefs.integration.test.ts +5 -16
  53. package/src/user-notification-prefs.ts +12 -18
  54. package/scripts/backfill-member-id.ts +0 -50
  55. package/src/member-id-backfill.integration.test.ts +0 -167
  56. package/src/member-id-backfill.ts +0 -253
  57. package/src/member-id-backfill.unit.test.ts +0 -12
  58. package/src/member-id-stamp.ts +0 -68
  59. package/src/member-id-stamp.unit.test.ts +0 -81
@@ -34,24 +34,19 @@ import {
34
34
  interface PushPrismaLike {
35
35
  chatThreadWatch: {
36
36
  findMany(args: {
37
- where: { threadId: string; memberId: { not: null } };
37
+ where: { threadId: string };
38
38
  select: { memberId: true };
39
- }): Promise<Array<{ memberId: string | null }>>;
39
+ }): Promise<Array<{ memberId: string }>>;
40
40
  upsert(args: {
41
- where: { userEmail_threadId: { userEmail: string; threadId: string } };
42
- create: {
43
- userEmail: string;
44
- threadId: string;
45
- agentId: string;
46
- memberId: string | null;
47
- };
48
- update: { agentId: string; memberId: string | null };
41
+ where: { memberId_threadId: { memberId: string; threadId: string } };
42
+ create: { threadId: string; agentId: string; memberId: string };
43
+ update: { agentId: string };
49
44
  }): Promise<{ id: string }>;
50
45
  };
51
46
  pushSubscription: {
52
47
  findMany(args: { where: { memberId: { in: string[] } } }): Promise<
53
48
  Array<{
54
- memberId: string | null;
49
+ memberId: string;
55
50
  endpoint: string;
56
51
  p256dh: string;
57
52
  auth: string;
@@ -61,25 +56,17 @@ interface PushPrismaLike {
61
56
  upsert(args: {
62
57
  where: { endpoint: string };
63
58
  create: {
64
- userEmail: string;
65
- memberId: string | null;
59
+ memberId: string;
66
60
  endpoint: string;
67
61
  p256dh: string;
68
62
  auth: string;
69
63
  };
70
- update: {
71
- userEmail: string;
72
- memberId: string | null;
73
- p256dh: string;
74
- auth: string;
75
- };
64
+ update: { memberId: string; p256dh: string; auth: string };
76
65
  }): Promise<{ id: string }>;
77
66
  deleteMany(
78
67
  args:
79
68
  | { where: { endpoint: { in: string[] } } }
80
- | {
81
- where: { endpoint: string; memberId?: string; userEmail?: string };
82
- },
69
+ | { where: { endpoint: string; memberId: string } },
83
70
  ): Promise<{ count: number }>;
84
71
  };
85
72
  }
@@ -125,8 +112,8 @@ export class PushService {
125
112
  private readonly lookup: MemberIdLookup;
126
113
 
127
114
  /**
128
- * ACM-4.1: watches and subscriptions are read and written by memberId
129
- * (AccountMember.id); rows with a null memberId are skipped. `lookup`
115
+ * Watches and subscriptions are read and written by memberId
116
+ * (AccountMember.id; ACM-5.1 dropped the email columns). `lookup`
130
117
  * resolves the emails callers still pass; it defaults to a
131
118
  * PrincipalLookupService over `prisma`.
132
119
  */
@@ -145,15 +132,13 @@ export class PushService {
145
132
  return (await this.lookup.findIdByEmail(email))?.id ?? null;
146
133
  }
147
134
 
148
- /** The deduped set of member ids watching a thread (null-memberId rows skipped). */
135
+ /** The deduped set of member ids watching a thread . */
149
136
  private async watchersForThread(threadId: string): Promise<string[]> {
150
137
  const watchers = await this.prisma.chatThreadWatch.findMany({
151
- where: { threadId, memberId: { not: null } },
138
+ where: { threadId },
152
139
  select: { memberId: true },
153
140
  });
154
- return [
155
- ...new Set(watchers.flatMap((w) => (w.memberId ? [w.memberId] : []))),
156
- ];
141
+ return [...new Set(watchers.map((w) => w.memberId))];
157
142
  }
158
143
 
159
144
  /** All push subscriptions belonging to the given member ids. */
@@ -317,10 +302,12 @@ export class PushService {
317
302
  if (!this.prisma.chatThreadWatch) return;
318
303
  try {
319
304
  const memberId = await this.memberIdForEmail(userEmail);
305
+ // No account member record: nothing to key the watch on, so skip.
306
+ if (!memberId) return;
320
307
  await this.prisma.chatThreadWatch.upsert({
321
- where: { userEmail_threadId: { userEmail, threadId } },
322
- create: { userEmail, threadId, agentId, memberId },
323
- update: { agentId, memberId },
308
+ where: { memberId_threadId: { memberId, threadId } },
309
+ create: { memberId, threadId, agentId },
310
+ update: { agentId },
324
311
  });
325
312
  } catch (err) {
326
313
  console.error("[push] watchThread upsert failed:", err);
@@ -349,8 +336,8 @@ export class PushService {
349
336
  if (!memberId) return { ok: false, reason: "no_member" };
350
337
  await this.prisma.pushSubscription.upsert({
351
338
  where: { endpoint },
352
- create: { userEmail, memberId, endpoint, p256dh, auth },
353
- update: { userEmail, memberId, p256dh, auth },
339
+ create: { memberId, endpoint, p256dh, auth },
340
+ update: { memberId, p256dh, auth },
354
341
  });
355
342
  return { ok: true };
356
343
  } catch (err) {
@@ -361,8 +348,8 @@ export class PushService {
361
348
 
362
349
  /**
363
350
  * Deletes a browser push subscription, scoped to both endpoint and
364
- * the owning member (memberId; falls back to userEmail for an email with no member) — this scoping prevents a stale endpoint from pruning another
365
- * user's subscription. Delete failures are best-effort: logged and
351
+ * the owning member (memberId) — this scoping prevents a stale endpoint from
352
+ * pruning another user's subscription. An email with no member is a no-op. Delete failures are best-effort: logged and
366
353
  * swallowed, never surfaced as a distinct outcome.
367
354
  */
368
355
  async unsubscribe(
@@ -373,9 +360,11 @@ export class PushService {
373
360
  return { ok: false, reason: "unavailable" };
374
361
  try {
375
362
  const memberId = await this.memberIdForEmail(userEmail);
376
- await this.prisma.pushSubscription.deleteMany({
377
- where: memberId ? { endpoint, memberId } : { endpoint, userEmail },
378
- });
363
+ if (memberId) {
364
+ await this.prisma.pushSubscription.deleteMany({
365
+ where: { endpoint, memberId },
366
+ });
367
+ }
379
368
  } catch (err) {
380
369
  console.error("[push] unsubscribe delete failed:", err);
381
370
  }
@@ -140,10 +140,13 @@ describe("PushService.notifyThreadReply", () => {
140
140
  expect(deleted).toEqual([]);
141
141
  });
142
142
 
143
- it("skips watchers whose memberId is null without crashing", async () => {
143
+ it("dedupes watchers by memberId", async () => {
144
144
  const prisma = {
145
145
  chatThreadWatch: {
146
- findMany: async () => [{ memberId: null }, { memberId: "a@x.com" }],
146
+ findMany: async () => [
147
+ { memberId: "a@x.com" },
148
+ { memberId: "a@x.com" },
149
+ ],
147
150
  },
148
151
  pushSubscription: {
149
152
  findMany: async ({
@@ -487,7 +490,7 @@ describe("PushService.notifySession", () => {
487
490
  // write-path methods under test below (recordWatch/subscribe/unsubscribe
488
491
  // never touch PushSender).
489
492
  describe("PushService.recordWatch", () => {
490
- it("upserts a ChatThreadWatch row scoped to userEmail+threadId", async () => {
493
+ it("upserts a ChatThreadWatch row scoped to memberId+threadId", async () => {
491
494
  const calls: unknown[] = [];
492
495
  const prisma = {
493
496
  chatThreadWatch: {
@@ -508,15 +511,14 @@ describe("PushService.recordWatch", () => {
508
511
  expect(calls).toEqual([
509
512
  {
510
513
  where: {
511
- userEmail_threadId: { userEmail: "a@x.com", threadId: "thr_1" },
514
+ memberId_threadId: { memberId: "a@x.com", threadId: "thr_1" },
512
515
  },
513
516
  create: {
514
- userEmail: "a@x.com",
515
517
  threadId: "thr_1",
516
518
  agentId: "agt_1",
517
519
  memberId: "a@x.com",
518
520
  },
519
- update: { agentId: "agt_1", memberId: "a@x.com" },
521
+ update: { agentId: "agt_1" },
520
522
  },
521
523
  ]);
522
524
  });
@@ -581,14 +583,12 @@ describe("PushService.subscribe", () => {
581
583
  {
582
584
  where: { endpoint: "https://push/ok" },
583
585
  create: {
584
- userEmail: "a@x.com",
585
586
  memberId: "a@x.com",
586
587
  endpoint: "https://push/ok",
587
588
  p256dh: P256DH,
588
589
  auth: AUTH,
589
590
  },
590
591
  update: {
591
- userEmail: "a@x.com",
592
592
  memberId: "a@x.com",
593
593
  p256dh: P256DH,
594
594
  auth: AUTH,
@@ -220,7 +220,7 @@ function makeMockDeps(
220
220
  id: "m1",
221
221
  agentId,
222
222
  email,
223
- memberId: null,
223
+ memberId: "member-1",
224
224
  createdAt: new Date(),
225
225
  }),
226
226
  remove: async () => {},
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * admin/src/user-notification-prefs.integration.test.ts (ACM-4.1)
3
- * UserNotificationPrefs reads and writes by memberId; the email primary key
4
- * is resolved through the AccountMember lookup. Null-memberId rows are skipped.
3
+ * UserNotificationPrefs reads and writes by memberId; memberId is the primary key;
4
+ * email is resolved through the AccountMember lookup. Rows whose member no longer resolves are skipped.
5
5
  *
6
6
  * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
7
7
  */
@@ -37,12 +37,11 @@ describeOrSkip("UserNotificationPrefsService by memberId (integration)", () => {
37
37
  expect(await service.getByMemberId(aliceId)).toBeNull();
38
38
  });
39
39
 
40
- it("upsert creates the row stamped with memberId and the member's email", async () => {
40
+ it("upsert creates the row keyed on memberId", async () => {
41
41
  const row = await service.upsertByMemberId(aliceId, {
42
42
  reminderHourLocal: 7,
43
43
  });
44
44
  expect(row?.memberId).toBe(aliceId);
45
- expect(row?.userEmail).toBe("alice@acme.com");
46
45
  expect(row?.reminderHourLocal).toBe(7);
47
46
  expect((await service.getByMemberId(aliceId))?.reminderHourLocal).toBe(7);
48
47
  });
@@ -56,26 +55,16 @@ describeOrSkip("UserNotificationPrefsService by memberId (integration)", () => {
56
55
  expect(row?.reminderHourLocal).toBe(7);
57
56
  });
58
57
 
59
- it("upsert adopts an email-only legacy row for the same member", async () => {
60
- await prisma.userNotificationPrefs.create({
61
- data: { userEmail: "alice@acme.com", reminderHourLocal: 5 },
62
- });
63
- const row = await service.upsertByMemberId(aliceId, {});
64
- expect(row?.memberId).toBe(aliceId);
65
- expect(row?.reminderHourLocal).toBe(5);
66
- expect(await prisma.userNotificationPrefs.count()).toBe(1);
67
- });
68
-
69
58
  it("upsert for an unknown member id returns null and writes nothing", async () => {
70
59
  expect(await service.upsertByMemberId("nope", {})).toBeNull();
71
60
  expect(await prisma.userNotificationPrefs.count()).toBe(0);
72
61
  });
73
62
 
74
- it("listAutoFollowers skips null-memberId rows and resolves email via the lookup", async () => {
63
+ it("listAutoFollowers skips unresolvable members and resolves email via the lookup", async () => {
75
64
  await service.upsertByMemberId(aliceId, {});
76
65
  await service.upsertByMemberId(bobId, { autoFollowSessions: false });
77
66
  await prisma.userNotificationPrefs.create({
78
- data: { userEmail: "legacy@old.com" },
67
+ data: { memberId: "gone-member" },
79
68
  });
80
69
  const followers = await service.listAutoFollowers();
81
70
  expect(followers.map((f) => f.email)).toEqual(["alice@acme.com"]);
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * admin/src/user-notification-prefs.ts
3
3
  * UserNotificationPrefsService (ACM-4.1): per-user notification preferences
4
- * read and written by memberId (AccountMember.id). The row's primary key stays
5
- * userEmail for now, so writes resolve the member's email through the
6
- * AccountMember lookup. Rows with a null memberId are skipped on reads.
4
+ * read and written by memberId (AccountMember.id), which is the row's primary
5
+ * key (ACM-5.1 dropped the userEmail column).
7
6
  */
8
7
 
9
8
  import type {
@@ -35,43 +34,38 @@ export class UserNotificationPrefsService {
35
34
 
36
35
  /**
37
36
  * Creates or updates the member's row. Returns null when `memberId` does not
38
- * resolve to a user (no email to key the row on). An email-only legacy row
39
- * for the same member is adopted rather than duplicated.
37
+ * resolve to a user.
40
38
  */
41
39
  async upsertByMemberId(
42
40
  memberId: string,
43
41
  patch: UserNotificationPrefsPatch,
44
42
  ): Promise<UserNotificationPrefs | null> {
45
43
  const { principals } = await this.lookup.resolveMany([memberId]);
46
- const email = principals.find((p) => p.type === "user")?.email;
47
- if (!email) return null;
48
- const existing = await this.getByMemberId(memberId);
44
+ if (!principals.some((p) => p.type === "user")) return null;
49
45
  return this.prisma.userNotificationPrefs.upsert({
50
- where: { userEmail: existing?.userEmail ?? email },
51
- create: { userEmail: email, memberId, ...patch },
52
- update: { memberId, ...patch },
46
+ where: { memberId },
47
+ create: { memberId, ...patch },
48
+ update: patch,
53
49
  });
54
50
  }
55
51
 
56
52
  /**
57
53
  * Members with auto-follow on, each with their email resolved through the
58
- * lookup. Null-memberId rows and members that no longer resolve are skipped.
54
+ * lookup. Members that no longer resolve are skipped.
59
55
  */
60
56
  async listAutoFollowers(): Promise<
61
57
  Array<{ memberId: string; email: string; prefs: UserNotificationPrefs }>
62
58
  > {
63
59
  const rows = await this.prisma.userNotificationPrefs.findMany({
64
- where: { autoFollowSessions: true, memberId: { not: null } },
60
+ where: { autoFollowSessions: true },
65
61
  });
66
62
  const { principals } = await this.lookup.resolveMany(
67
- rows.flatMap((r) => (r.memberId ? [r.memberId] : [])),
63
+ rows.map((r) => r.memberId),
68
64
  );
69
65
  const emails = new Map(principals.map((p) => [p.id, p.email]));
70
66
  return rows.flatMap((prefs) => {
71
- const email = prefs.memberId ? emails.get(prefs.memberId) : null;
72
- return prefs.memberId && email
73
- ? [{ memberId: prefs.memberId, email, prefs }]
74
- : [];
67
+ const email = emails.get(prefs.memberId);
68
+ return email ? [{ memberId: prefs.memberId, email, prefs }] : [];
75
69
  });
76
70
  }
77
71
  }
@@ -1,50 +0,0 @@
1
- /**
2
- * admin/scripts/backfill-member-id.ts (ACM-1.2)
3
- *
4
- * DATABASE_URL_SHIPWRIGHT_ADMIN=... bun admin/scripts/backfill-member-id.ts [--dry-run | --verify] [--overrides overrides.json] [--report report.json]
5
- *
6
- * overrides.json: { "alice@old.com": "<AccountMember.id>" }. Overrides win over
7
- * the automatic email match. --dry-run changes nothing. --verify is a read-only
8
- * check: it reports null and dangling memberId counts and emails per table and
9
- * exits 1 when any exist (0 when clean).
10
- */
11
-
12
- import { readFileSync, writeFileSync } from "node:fs";
13
- import { parseFlags } from "@app-vitals/agent-lib/cli-flags";
14
- import {
15
- parseOverrides,
16
- runMemberIdBackfill,
17
- verifyMemberIds,
18
- } from "../src/member-id-backfill.ts";
19
- import { createAdminPrismaClient } from "../src/prisma-client.ts";
20
-
21
- const flags = parseFlags(process.argv.slice(2), ["--overrides", "--report"], {
22
- booleans: ["--dry-run", "--verify"],
23
- });
24
- const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
25
- if (!url) {
26
- console.error("DATABASE_URL_SHIPWRIGHT_ADMIN is required");
27
- process.exit(2);
28
- }
29
-
30
- const prisma = createAdminPrismaClient(url);
31
- try {
32
- if (flags["--verify"]) {
33
- const verified = await verifyMemberIds(prisma);
34
- console.log(JSON.stringify(verified, null, 2));
35
- if (verified.hasProblems) process.exitCode = 1;
36
- } else {
37
- const overrides = flags["--overrides"]
38
- ? parseOverrides(readFileSync(flags["--overrides"], "utf8"))
39
- : undefined;
40
- const report = await runMemberIdBackfill(prisma, {
41
- dryRun: flags["--dry-run"],
42
- overrides,
43
- });
44
- const body = JSON.stringify(report, null, 2);
45
- if (flags["--report"]) writeFileSync(flags["--report"], `${body}\n`);
46
- console.log(body);
47
- }
48
- } finally {
49
- await prisma.$disconnect();
50
- }
@@ -1,167 +0,0 @@
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
- });