@app-vitals/agent-admin 1.73.0 → 1.75.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.
Files changed (33) hide show
  1. package/openapi.platform.json +199 -0
  2. package/package.json +2 -2
  3. package/prisma/client/internal/class.ts +4 -4
  4. package/prisma/client/internal/prismaNamespace.ts +4 -0
  5. package/prisma/client/internal/prismaNamespaceBrowser.ts +4 -0
  6. package/prisma/client/models/AgentMember.ts +36 -1
  7. package/prisma/client/models/ChatThreadWatch.ts +29 -1
  8. package/prisma/client/models/PushSubscription.ts +29 -1
  9. package/prisma/client/models/UserNotificationPrefs.ts +29 -1
  10. package/prisma/migrations/20261118000000_add_member_id_columns/migration.sql +14 -0
  11. package/prisma/schema/schema.prisma +5 -0
  12. package/scripts/backfill-member-id.ts +41 -0
  13. package/src/admin-boot.ts +13 -0
  14. package/src/admin-dev-login.smoke.test.ts +1 -0
  15. package/src/admin-local-agent.smoke.test.ts +9 -1
  16. package/src/admin-spec.ts +17 -0
  17. package/src/admin-ui.fixtures.ts +1 -0
  18. package/src/admin-ui.smoke.test.ts +57 -8
  19. package/src/agent-cron-run-stats.smoke.test.ts +1 -0
  20. package/src/agent-members.unit.test.ts +6 -1
  21. package/src/agents-api.smoke.test.ts +5 -0
  22. package/src/api.smoke.test.ts +1 -0
  23. package/src/chat.smoke.test.ts +2 -0
  24. package/src/member-id-backfill.integration.test.ts +167 -0
  25. package/src/member-id-backfill.ts +180 -0
  26. package/src/member-id-backfill.unit.test.ts +12 -0
  27. package/src/openapi-schemas.ts +31 -0
  28. package/src/principal-lookup.ts +67 -0
  29. package/src/principal-lookup.unit.test.ts +104 -0
  30. package/src/principals-api.integration.test.ts +115 -0
  31. package/src/principals-api.ts +142 -0
  32. package/src/principals-api.unit.test.ts +83 -0
  33. package/src/slack-provisioning.integration.test.ts +1 -0
@@ -1302,6 +1302,7 @@ describe("admin UI — authenticated pages", () => {
1302
1302
  id: "m1",
1303
1303
  agentId: AGENT_ID,
1304
1304
  email,
1305
+ memberId: null,
1305
1306
  createdAt: new Date(),
1306
1307
  },
1307
1308
  ]
@@ -1312,6 +1313,7 @@ describe("admin UI — authenticated pages", () => {
1312
1313
  id: "m1",
1313
1314
  agentId: AGENT_ID,
1314
1315
  email: MEMBER_EMAIL,
1316
+ memberId: null,
1315
1317
  createdAt: new Date(),
1316
1318
  }),
1317
1319
  remove: async () => {},
@@ -2881,7 +2883,15 @@ describe("admin UI — member access control", () => {
2881
2883
  agentMemberService: {
2882
2884
  listByEmail: async (email: string) =>
2883
2885
  email === MEMBER_EMAIL
2884
- ? [{ id: "m1", agentId: AGENT_ID, email, createdAt: new Date() }]
2886
+ ? [
2887
+ {
2888
+ id: "m1",
2889
+ agentId: AGENT_ID,
2890
+ email,
2891
+ memberId: null,
2892
+ createdAt: new Date(),
2893
+ },
2894
+ ]
2885
2895
  : [],
2886
2896
  exists: async (_agentId: string, email: string) =>
2887
2897
  email === MEMBER_EMAIL,
@@ -2889,6 +2899,7 @@ describe("admin UI — member access control", () => {
2889
2899
  id: "m1",
2890
2900
  agentId: AGENT_ID,
2891
2901
  email: MEMBER_EMAIL,
2902
+ memberId: null,
2892
2903
  createdAt: new Date(),
2893
2904
  }),
2894
2905
  remove: async () => {},
@@ -3031,6 +3042,7 @@ describe("admin UI — member access control", () => {
3031
3042
  id: "m1",
3032
3043
  agentId: AGENT_ID,
3033
3044
  email: MEMBER_EMAIL,
3045
+ memberId: null,
3034
3046
  createdAt: new Date(),
3035
3047
  },
3036
3048
  ]
@@ -3040,6 +3052,7 @@ describe("admin UI — member access control", () => {
3040
3052
  id: "m1",
3041
3053
  agentId: AGENT_ID,
3042
3054
  email: MEMBER_EMAIL,
3055
+ memberId: null,
3043
3056
  createdAt: new Date(),
3044
3057
  }),
3045
3058
  remove: async () => {},
@@ -3186,6 +3199,7 @@ describe("admin UI — member access control", () => {
3186
3199
  id: "m1",
3187
3200
  agentId: AGENT_ID,
3188
3201
  email: MEMBER_EMAIL,
3202
+ memberId: null,
3189
3203
  createdAt: new Date(),
3190
3204
  },
3191
3205
  ]
@@ -3195,6 +3209,7 @@ describe("admin UI — member access control", () => {
3195
3209
  id: "m1",
3196
3210
  agentId: AGENT_ID,
3197
3211
  email: MEMBER_EMAIL,
3212
+ memberId: null,
3198
3213
  createdAt: new Date(),
3199
3214
  }),
3200
3215
  remove: async () => {},
@@ -3668,7 +3683,13 @@ describe("admin UI — member management routes", () => {
3668
3683
  exists: async () => false,
3669
3684
  add: async (agentId: string, email: string) => {
3670
3685
  created = { agentId, email };
3671
- return { id: "m-new", agentId, email, createdAt: new Date() };
3686
+ return {
3687
+ id: "m-new",
3688
+ agentId,
3689
+ email,
3690
+ memberId: null,
3691
+ createdAt: new Date(),
3692
+ };
3672
3693
  },
3673
3694
  remove: async () => {},
3674
3695
  listByAgentId: async () => [],
@@ -3761,6 +3782,7 @@ describe("admin UI — member management routes", () => {
3761
3782
  id: "m1",
3762
3783
  agentId: AGENT_ID,
3763
3784
  email: "member@example.com",
3785
+ memberId: null,
3764
3786
  createdAt: new Date(),
3765
3787
  }),
3766
3788
  remove: async (_agentId: string, memberId: string) => {
@@ -3821,13 +3843,22 @@ describe("admin UI — marketplaces (PMK-1.5)", () => {
3821
3843
  agentMemberService: {
3822
3844
  listByEmail: async (email: string) =>
3823
3845
  email === MEMBER
3824
- ? [{ id: "m1", agentId: AGENT_ID, email, createdAt: new Date() }]
3846
+ ? [
3847
+ {
3848
+ id: "m1",
3849
+ agentId: AGENT_ID,
3850
+ email,
3851
+ memberId: null,
3852
+ createdAt: new Date(),
3853
+ },
3854
+ ]
3825
3855
  : [],
3826
3856
  exists: async (_agentId: string, email: string) => email === MEMBER,
3827
3857
  add: async () => ({
3828
3858
  id: "m1",
3829
3859
  agentId: AGENT_ID,
3830
3860
  email: MEMBER,
3861
+ memberId: null,
3831
3862
  createdAt: new Date(),
3832
3863
  }),
3833
3864
  remove: async () => {},
@@ -4051,7 +4082,15 @@ describe("admin UI — plugin add/remove (PUI-1.2)", () => {
4051
4082
  agentMemberService: {
4052
4083
  listByEmail: async (email: string) =>
4053
4084
  email === MEMBER
4054
- ? [{ id: "m1", agentId: AGENT_ID, email, createdAt: new Date() }]
4085
+ ? [
4086
+ {
4087
+ id: "m1",
4088
+ agentId: AGENT_ID,
4089
+ email,
4090
+ memberId: null,
4091
+ createdAt: new Date(),
4092
+ },
4093
+ ]
4055
4094
  : [],
4056
4095
  exists: async (_a: string, email: string) => email === MEMBER,
4057
4096
  add: async () => ({}) as never,
@@ -6985,6 +7024,7 @@ describe("admin UI — Slack access settings route (restrictSlackToMembers)", ()
6985
7024
  id: "m1",
6986
7025
  agentId: AGENT_ID,
6987
7026
  email: "member@example.com",
7027
+ memberId: null,
6988
7028
  createdAt: new Date("2024-01-01"),
6989
7029
  },
6990
7030
  ],
@@ -7247,6 +7287,7 @@ describe("admin UI — Okta-authenticated access control", () => {
7247
7287
  id: "m1",
7248
7288
  agentId: AGENT_ID,
7249
7289
  email: OKTA_MEMBER_EMAIL,
7290
+ memberId: null,
7250
7291
  createdAt: new Date(),
7251
7292
  },
7252
7293
  ]
@@ -7257,6 +7298,7 @@ describe("admin UI — Okta-authenticated access control", () => {
7257
7298
  id: "m1",
7258
7299
  agentId: AGENT_ID,
7259
7300
  email: OKTA_MEMBER_EMAIL,
7301
+ memberId: null,
7260
7302
  createdAt: new Date(),
7261
7303
  }),
7262
7304
  remove: async () => {},
@@ -7361,7 +7403,15 @@ describe("admin UI — Okta-authenticated access control", () => {
7361
7403
  agentMemberService: {
7362
7404
  listByEmail: async (email: string) =>
7363
7405
  email === OKTA_MEMBER_EMAIL
7364
- ? [{ id: "m1", agentId: AGENT_ID, email, createdAt: new Date() }]
7406
+ ? [
7407
+ {
7408
+ id: "m1",
7409
+ agentId: AGENT_ID,
7410
+ email,
7411
+ memberId: null,
7412
+ createdAt: new Date(),
7413
+ },
7414
+ ]
7365
7415
  : [],
7366
7416
  exists: async (_agentId: string, email: string) =>
7367
7417
  email === OKTA_MEMBER_EMAIL,
@@ -7369,6 +7419,7 @@ describe("admin UI — Okta-authenticated access control", () => {
7369
7419
  id: "m1",
7370
7420
  agentId: AGENT_ID,
7371
7421
  email: OKTA_MEMBER_EMAIL,
7422
+ memberId: null,
7372
7423
  createdAt: new Date(),
7373
7424
  }),
7374
7425
  remove: async () => {},
@@ -7819,9 +7870,7 @@ describe("admin UI — self-serve agent management (SSP-4.3)", () => {
7819
7870
  expect(accessRes.status).toBe(200);
7820
7871
  const html = `${await res.text()}${await accessRes.text()}`;
7821
7872
  expect(html.includes("Danger Zone")).toBe(shown);
7822
- expect(html.includes('<div class="card-title">Slack</div>')).toBe(
7823
- shown,
7824
- );
7873
+ expect(html.includes('<div class="card-title">Slack</div>')).toBe(shown);
7825
7874
  expect(html.includes(`/admin/agents/${AGENT_ID}/members`)).toBe(shown);
7826
7875
  });
7827
7876
  }
@@ -437,6 +437,7 @@ function makeMockDeps(): AdminDeps {
437
437
  id: "member-1",
438
438
  agentId,
439
439
  email,
440
+ memberId: null,
440
441
  createdAt: new Date(),
441
442
  }),
442
443
  listByAgentId: async () => [],
@@ -14,6 +14,7 @@ interface FakeAgentMemberRow {
14
14
  id: string;
15
15
  agentId: string;
16
16
  email: string;
17
+ memberId: string | null;
17
18
  createdAt: Date;
18
19
  }
19
20
 
@@ -64,6 +65,7 @@ function makeFakePrisma(seed: FakeAgentMemberRow[] = []) {
64
65
  id: `member-${nextId++}`,
65
66
  agentId: data.agentId,
66
67
  email: data.email,
68
+ memberId: null,
67
69
  createdAt: new Date("2024-01-01"),
68
70
  };
69
71
  rows.set(row.id, row);
@@ -88,11 +90,14 @@ function makeFakePrisma(seed: FakeAgentMemberRow[] = []) {
88
90
 
89
91
  type FakePrisma = ReturnType<typeof makeFakePrisma>;
90
92
 
91
- function seedRow(overrides: Partial<FakeAgentMemberRow> = {}): FakeAgentMemberRow {
93
+ function seedRow(
94
+ overrides: Partial<FakeAgentMemberRow> = {},
95
+ ): FakeAgentMemberRow {
92
96
  return {
93
97
  id: "member-existing",
94
98
  agentId: "agent-1",
95
99
  email: "person@example.com",
100
+ memberId: null,
96
101
  createdAt: new Date("2024-01-01"),
97
102
  ...overrides,
98
103
  };
@@ -577,6 +577,7 @@ function makeMockDeps(): AdminDeps {
577
577
  id: "member-test-id",
578
578
  agentId,
579
579
  email,
580
+ memberId: null,
580
581
  createdAt: new Date("2024-01-01"),
581
582
  }),
582
583
  // Default: at least one member, so restrictSlackToMembers tests that
@@ -587,6 +588,7 @@ function makeMockDeps(): AdminDeps {
587
588
  id: "member-test-id",
588
589
  agentId,
589
590
  email: "member@example.com",
591
+ memberId: null,
590
592
  createdAt: new Date("2024-01-01"),
591
593
  },
592
594
  ],
@@ -3069,6 +3071,7 @@ describe("admin API — restrictSlackToMembers field", () => {
3069
3071
  id: "member-1",
3070
3072
  agentId: AGENT_ID,
3071
3073
  email: "member@example.com",
3074
+ memberId: null,
3072
3075
  createdAt: new Date("2024-01-01"),
3073
3076
  },
3074
3077
  ],
@@ -5228,6 +5231,7 @@ describe("non-admin session cookie scoping", () => {
5228
5231
  id: "m1",
5229
5232
  agentId: AGENT_ID,
5230
5233
  email,
5234
+ memberId: null,
5231
5235
  createdAt: new Date("2024-01-01"),
5232
5236
  },
5233
5237
  ]
@@ -6221,6 +6225,7 @@ describe("admin API — repo removal blocks open work", () => {
6221
6225
  id: "m1",
6222
6226
  agentId: AGENT_ID,
6223
6227
  email,
6228
+ memberId: null,
6224
6229
  createdAt: new Date("2024-01-01"),
6225
6230
  },
6226
6231
  ]
@@ -1142,6 +1142,7 @@ function buildCombinedApp() {
1142
1142
  id: "member-1",
1143
1143
  agentId,
1144
1144
  email,
1145
+ memberId: null,
1145
1146
  createdAt: new Date(),
1146
1147
  }),
1147
1148
  listByAgentId: async () => [],
@@ -346,6 +346,7 @@ function makeBaseDeps(overrides?: Partial<AdminUIDeps>): AdminUIDeps {
346
346
  id: "m1",
347
347
  agentId,
348
348
  email,
349
+ memberId: null,
349
350
  createdAt: new Date(),
350
351
  }),
351
352
  remove: async () => {},
@@ -1610,6 +1611,7 @@ function makeMemberDeps(
1610
1611
  id: `m-${agentId}`,
1611
1612
  agentId,
1612
1613
  email,
1614
+ memberId: null,
1613
1615
  createdAt: new Date(),
1614
1616
  }))
1615
1617
  : [],
@@ -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
+ }
@@ -0,0 +1,12 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { parseOverrides } from "./member-id-backfill.ts";
3
+
4
+ describe("parseOverrides", () => {
5
+ it("normalizes email keys", () => {
6
+ expect(parseOverrides('{" Bob@X.com ":"m1"}').get("bob@x.com")).toBe("m1");
7
+ });
8
+ it("rejects non-object and non-string values", () => {
9
+ expect(() => parseOverrides("[]")).toThrow();
10
+ expect(() => parseOverrides('{"a@b.c":1}')).toThrow();
11
+ });
12
+ });
@@ -1654,3 +1654,34 @@ export const TemplateItemKeyQuerySchema = z.object({
1654
1654
  kind: TemplateItemKindSchema,
1655
1655
  key: z.string().min(1),
1656
1656
  });
1657
+
1658
+ // ─── Principals (ACM-1.1) ─────────────────────────────────────────────────────
1659
+
1660
+ export const PrincipalSchema = z
1661
+ .object({
1662
+ id: z.string().openapi({ example: "clx1abc" }),
1663
+ type: z.enum(["user", "agent"]),
1664
+ email: z
1665
+ .string()
1666
+ .nullable()
1667
+ .openapi({ description: "null for agents", example: "o@acme.com" }),
1668
+ })
1669
+ .openapi("Principal");
1670
+
1671
+ export const PrincipalLookupBodySchema = z
1672
+ .object({ ids: z.array(z.string().min(1)).max(500) })
1673
+ .openapi("PrincipalLookupBody");
1674
+
1675
+ export const PrincipalLookupResponseSchema = z
1676
+ .object({
1677
+ principals: z.array(PrincipalSchema),
1678
+ notFound: z.array(z.string()),
1679
+ })
1680
+ .openapi("PrincipalLookupResponse");
1681
+
1682
+ export const PrincipalByEmailQuerySchema = z.object({
1683
+ email: z
1684
+ .string()
1685
+ .min(1)
1686
+ .openapi({ param: { name: "email", in: "query" }, example: "o@acme.com" }),
1687
+ });