@app-vitals/agent-admin 1.107.1 → 1.107.3

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 (54) hide show
  1. package/e2e/real/seed.ts +0 -1
  2. package/package.json +2 -2
  3. package/prisma/client/internal/class.ts +4 -4
  4. package/prisma/client/internal/prismaNamespace.ts +1 -5
  5. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  6. package/prisma/client/models/AgentMember.ts +26 -61
  7. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  8. package/prisma/client/models/PushSubscription.ts +15 -43
  9. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  10. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  11. package/prisma/schema/schema.prisma +11 -15
  12. package/src/account-member-removal.integration.test.ts +31 -44
  13. package/src/account-members.ts +4 -6
  14. package/src/account-onboarding.ts +2 -5
  15. package/src/account-onboarding.unit.test.ts +71 -0
  16. package/src/accounts-api.smoke.test.ts +0 -11
  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 +3 -3
  20. package/src/admin-ui-accounts.smoke.test.ts +6 -14
  21. package/src/admin-ui-agent-members.smoke.test.ts +29 -1
  22. package/src/admin-ui.fixtures.ts +1 -1
  23. package/src/admin-ui.smoke.test.ts +18 -18
  24. package/src/admin-ui.ts +20 -12
  25. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  26. package/src/agent-deletion.integration.test.ts +1 -1
  27. package/src/agent-members.integration.test.ts +15 -11
  28. package/src/agent-members.ts +28 -18
  29. package/src/agents-api.integration.test.ts +2 -2
  30. package/src/agents-api.smoke.test.ts +5 -5
  31. package/src/agents.integration.test.ts +1 -2
  32. package/src/api.smoke.test.ts +1 -1
  33. package/src/chat-credential-config.unit.test.ts +30 -0
  34. package/src/chat.smoke.test.ts +68 -14
  35. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  36. package/src/ensure-account-member.integration.test.ts +17 -232
  37. package/src/ensure-account-member.ts +0 -5
  38. package/src/github-enterprise-client.unit.test.ts +62 -2
  39. package/src/member-rows.ts +24 -0
  40. package/src/member-rows.unit.test.ts +48 -0
  41. package/src/principals-api.integration.test.ts +3 -2
  42. package/src/push-service.integration.test.ts +8 -13
  43. package/src/push-service.ts +28 -39
  44. package/src/push-service.unit.test.ts +8 -8
  45. package/src/reconcile-open-work.integration.test.ts +237 -0
  46. package/src/slack-provisioning.integration.test.ts +1 -1
  47. package/src/{member-id-test-support.ts → test-support/member-id-test-support.ts} +2 -2
  48. package/src/user-notification-prefs.integration.test.ts +6 -17
  49. package/src/user-notification-prefs.ts +12 -18
  50. package/scripts/backfill-member-id.ts +0 -50
  51. package/src/member-id-backfill.integration.test.ts +0 -167
  52. package/src/member-id-backfill.ts +0 -253
  53. package/src/member-id-backfill.unit.test.ts +0 -12
  54. package/src/member-id-stamp.ts +0 -68
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
- import { resetMemberIdFixture } from "./member-id-test-support.ts";
11
+ import { resetMemberIdFixture } from "./test-support/member-id-test-support.ts";
12
12
  import { createAdminPrismaClient } from "./prisma-client.ts";
13
13
  import { PushService } from "./push-service.ts";
14
14
 
@@ -64,20 +64,16 @@ describeOrSkip("PushService by memberId (integration)", () => {
64
64
  expect(rows[0]?.memberId).toBe(aliceId);
65
65
  });
66
66
 
67
- it("recordWatch for an email with no member still stores the row with null memberId", async () => {
67
+ it("recordWatch for an email with no member stores nothing", async () => {
68
68
  await service.recordWatch("ghost@nowhere.com", agentId, "t1");
69
69
  const rows = await prisma.chatThreadWatch.findMany();
70
- expect(rows.map((r) => r.memberId)).toEqual([null]);
70
+ expect(rows).toEqual([]);
71
71
  });
72
72
 
73
- it("notifyThreadReply reaches watchers by memberId and skips null-memberId watches", async () => {
73
+ it("notifyThreadReply reaches watchers by memberId only", async () => {
74
74
  await service.recordWatch("alice@acme.com", agentId, "t1");
75
- await prisma.chatThreadWatch.create({
76
- data: { userEmail: "bob@acme.com", threadId: "t1", agentId },
77
- }); // legacy, memberId null
78
75
  await prisma.pushSubscription.create({
79
76
  data: {
80
- userEmail: "alice@acme.com",
81
77
  memberId: aliceId,
82
78
  endpoint: "https://push/alice",
83
79
  p256dh: P256DH,
@@ -86,7 +82,6 @@ describeOrSkip("PushService by memberId (integration)", () => {
86
82
  });
87
83
  await prisma.pushSubscription.create({
88
84
  data: {
89
- userEmail: "bob@acme.com",
90
85
  memberId: bobId,
91
86
  endpoint: "https://push/bob",
92
87
  p256dh: P256DH,
@@ -132,7 +127,7 @@ describeOrSkip("PushService by memberId (integration)", () => {
132
127
  expect(await prisma.pushSubscription.count()).toBe(0);
133
128
  });
134
129
 
135
- it("sendToUsers resolves emails to members and skips null-memberId subscriptions", async () => {
130
+ it("sendToUsers resolves emails to members and skips emails with no member", async () => {
136
131
  await service.subscribe(
137
132
  "alice@acme.com",
138
133
  "https://p/alice",
@@ -141,14 +136,14 @@ describeOrSkip("PushService by memberId (integration)", () => {
141
136
  );
142
137
  await prisma.pushSubscription.create({
143
138
  data: {
144
- userEmail: "bob@acme.com",
145
- endpoint: "https://p/legacy",
139
+ memberId: bobId,
140
+ endpoint: "https://p/bob",
146
141
  p256dh: P256DH,
147
142
  auth: AUTH,
148
143
  },
149
144
  });
150
145
  const res = await service.sendToUsers(
151
- ["alice@acme.com", "bob@acme.com", "ghost@nowhere.com"],
146
+ ["alice@acme.com", "ghost@nowhere.com"],
152
147
  () => "{}",
153
148
  );
154
149
  expect(res.delivered).toBe(1);
@@ -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,
@@ -0,0 +1,237 @@
1
+ /**
2
+ * admin/src/reconcile-open-work.integration.test.ts
3
+ * T-019: the OpenWorkPort contract driven through the real GithubSyncService
4
+ * repo-removal reconcile, with the real cache and a real GitHubReconcileAudit
5
+ * row in Postgres. Covers the repo-removal path (preview lists, apply blocks
6
+ * per repo with the lost-access reason) and partial-failure behaviour (a port
7
+ * failure becomes a warning, never an error; a failed apply blocks nothing).
8
+ *
9
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
10
+ */
11
+
12
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
15
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
16
+ import { GithubSyncService } from "./github-sync.ts";
17
+ import { PrismaInstallationAudit } from "./installation-ports.ts";
18
+ import { createAdminPrismaClient } from "./prisma-client.ts";
19
+ import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
20
+ import { repoLostAccessBlockReason } from "./repo-removal-open-work.ts";
21
+
22
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
23
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
24
+
25
+ const AGENT_ID = "oow-it-agent";
26
+ const ORG = "oow-eng";
27
+ const APP_ID = 888;
28
+ const KEEP = `${ORG}/keep`;
29
+ const GONE_A = `${ORG}/gone-a`;
30
+ const GONE_B = `${ORG}/gone-b`;
31
+ const ALL = [KEEP, GONE_A, GONE_B];
32
+
33
+ /** In-memory open-work port that records every call; `failOn` repos reject. */
34
+ function recordingPort(failOn: string[] = []) {
35
+ const work: OpenWorkItem[] = ALL.map((repo) => ({
36
+ id: `task-${repo.split("/")[1]}`,
37
+ repo,
38
+ }));
39
+ const blocked: { repos: readonly string[]; reason: string }[] = [];
40
+ const port: OpenWorkPort = {
41
+ listOpenWork: async (_agent, repos) =>
42
+ work.filter((w) => repos.includes(w.repo)),
43
+ blockOpenWork: async (_agent, repos, reason) => {
44
+ if (repos.some((r) => failOn.includes(r))) {
45
+ throw new Error(`store down for ${repos.join(",")}`);
46
+ }
47
+ blocked.push({ repos, reason });
48
+ },
49
+ };
50
+ return { port, blocked };
51
+ }
52
+
53
+ describeOrSkip("reconcile-open-work (integration)", () => {
54
+ let prisma: PrismaClient;
55
+ let cache: GitHubRepoCacheService;
56
+ const checkedAt = new Date(Date.now() - 60_000);
57
+
58
+ const clean = async () => {
59
+ await prisma.gitHubReconcileAudit.deleteMany({
60
+ where: { agentId: AGENT_ID },
61
+ });
62
+ await prisma.gitHubRepoAccess.deleteMany({
63
+ where: { accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY, org: ORG },
64
+ });
65
+ await prisma.gitHubCachedRepo.deleteMany();
66
+ await prisma.gitHubRepoSnapshot.deleteMany();
67
+ };
68
+
69
+ async function seed() {
70
+ const snap = await cache.upsertSnapshot(
71
+ {
72
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
73
+ appKind: "agent" as const,
74
+ appRef: String(APP_ID),
75
+ org: ORG,
76
+ },
77
+ {
78
+ completedAt: checkedAt,
79
+ totalCount: ALL.length,
80
+ repositorySelection: "selected",
81
+ lastError: null,
82
+ },
83
+ );
84
+ await cache.upsertRepos(
85
+ snap.id,
86
+ ALL.map((fullName, i) => ({ githubId: i + 1, fullName })),
87
+ checkedAt,
88
+ );
89
+ for (const full of ALL) {
90
+ const canPush = full === KEEP;
91
+ await prisma.gitHubRepoAccess.create({
92
+ data: {
93
+ accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
94
+ org: ORG,
95
+ repo: full.split("/")[1] as string,
96
+ username: "dev",
97
+ canPush,
98
+ level: canPush ? "write" : "read",
99
+ checkedAt,
100
+ status: "ok",
101
+ },
102
+ });
103
+ }
104
+ }
105
+
106
+ function service(openWork: OpenWorkPort | undefined, removeFails = false) {
107
+ const calls: string[] = [];
108
+ let repos = [...ALL];
109
+ const svc = new GithubSyncService({
110
+ agents: {
111
+ get: async () => ({
112
+ id: AGENT_ID,
113
+ githubUsername: "dev",
114
+ appId: APP_ID,
115
+ repos,
116
+ }),
117
+ setRepos: async (_id, next) => {
118
+ calls.push("setRepos");
119
+ repos = next;
120
+ },
121
+ },
122
+ access: async () => {
123
+ throw new Error("live resolver must not be used");
124
+ },
125
+ cache,
126
+ lookupRepos: async () => [
127
+ { org: ORG, completedAt: checkedAt, repos: ALL },
128
+ ],
129
+ verifyPush: async (_u, repo) => repo === KEEP,
130
+ installation: {
131
+ listInstalled: async () => ({
132
+ status: "found",
133
+ orgs: [{ org: ORG, repos: ALL }],
134
+ }),
135
+ addRepos: async () => {},
136
+ removeRepos: async () => {
137
+ calls.push("removeRepos");
138
+ if (removeFails) throw new Error("installation PATCH failed");
139
+ },
140
+ setRepositorySelection: async () => {},
141
+ },
142
+ audit: new PrismaInstallationAudit(prisma),
143
+ ...(openWork ? { openWork } : {}),
144
+ });
145
+ return { svc, calls };
146
+ }
147
+
148
+ const removeBoth = {
149
+ agentId: AGENT_ID,
150
+ caller: "root",
151
+ appAdds: [],
152
+ appRemoves: [GONE_A, GONE_B],
153
+ agentRemoves: [GONE_A, GONE_B],
154
+ };
155
+
156
+ beforeEach(async () => {
157
+ prisma = createAdminPrismaClient(TEST_DB as string);
158
+ cache = new GitHubRepoCacheService(prisma);
159
+ await clean();
160
+ await seed();
161
+ });
162
+ afterEach(async () => {
163
+ await clean();
164
+ await prisma.$disconnect();
165
+ });
166
+
167
+ it("preview lists the open work on exactly the repos the reconcile would remove", async () => {
168
+ const { port, blocked } = recordingPort();
169
+ const { svc } = service(port);
170
+ const r = await svc.preview(AGENT_ID);
171
+ if (r.status !== "previewed") throw new Error(r.status);
172
+ expect(r.plan.removedRepos.sort()).toEqual([GONE_A, GONE_B]);
173
+ expect(r.openWork.map((w) => w.repo).sort()).toEqual([GONE_A, GONE_B]);
174
+ expect(r.warnings).toEqual([]);
175
+ expect(blocked).toEqual([]); // preview is read-only
176
+ });
177
+
178
+ it("apply blocks each removed repo's work separately with the lost-access reason", async () => {
179
+ const { port, blocked } = recordingPort();
180
+ const { svc, calls } = service(port);
181
+ const r = await svc.apply(removeBoth);
182
+ if (r.status !== "applied") throw new Error(r.status);
183
+ expect(r.warnings).toEqual([]);
184
+ expect(calls).toEqual(["removeRepos", "setRepos"]);
185
+ expect(blocked).toEqual([
186
+ { repos: [GONE_A], reason: repoLostAccessBlockReason(GONE_A) },
187
+ { repos: [GONE_B], reason: repoLostAccessBlockReason(GONE_B) },
188
+ ]);
189
+ const rows = await prisma.gitHubReconcileAudit.findMany({
190
+ where: { agentId: AGENT_ID },
191
+ });
192
+ expect(rows).toHaveLength(1);
193
+ expect(rows[0]?.result).toEqual({ status: "applied" });
194
+ });
195
+
196
+ it("a port failure on one repo is a warning; the other repo is still blocked and the apply still succeeds", async () => {
197
+ const { port, blocked } = recordingPort([GONE_A]);
198
+ const { svc } = service(port);
199
+ const r = await svc.apply(removeBoth);
200
+ if (r.status !== "applied") throw new Error(r.status);
201
+ expect(r.warnings).toEqual([
202
+ `open work for ${GONE_A} was not blocked: store down for ${GONE_A}`,
203
+ ]);
204
+ expect(blocked.map((b) => b.repos)).toEqual([[GONE_B]]);
205
+ const rows = await prisma.gitHubReconcileAudit.findMany({
206
+ where: { agentId: AGENT_ID },
207
+ });
208
+ expect(rows[0]?.result).toEqual({ status: "applied" });
209
+ });
210
+
211
+ it("a failed apply blocks no work and records the failure in the audit row", async () => {
212
+ const { port, blocked } = recordingPort();
213
+ const { svc, calls } = service(port, true);
214
+ const r = await svc.apply(removeBoth);
215
+ if (r.status !== "failed") throw new Error(r.status);
216
+ expect(r.error).toBe("installation PATCH failed");
217
+ expect(calls).toEqual(["removeRepos"]);
218
+ expect(blocked).toEqual([]);
219
+ const rows = await prisma.gitHubReconcileAudit.findMany({
220
+ where: { agentId: AGENT_ID },
221
+ });
222
+ expect(rows[0]?.result).toEqual({
223
+ status: "failed",
224
+ error: "installation PATCH failed",
225
+ });
226
+ });
227
+
228
+ it("without a port the reconcile still applies and reports no open work or warnings", async () => {
229
+ const { svc } = service(undefined);
230
+ const p = await svc.preview(AGENT_ID);
231
+ if (p.status !== "previewed") throw new Error(p.status);
232
+ expect(p.openWork).toEqual([]);
233
+ const r = await svc.apply(removeBoth);
234
+ if (r.status !== "applied") throw new Error(r.status);
235
+ expect(r.warnings).toEqual([]);
236
+ });
237
+ });
@@ -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,11 +1,11 @@
1
1
  /**
2
- * admin/src/member-id-test-support.ts
2
+ * admin/src/test-support/member-id-test-support.ts
3
3
  * Shared seed helpers for the ACM-4.1 per-table memberId integration tests.
4
4
  * Wipes the four per-user tables plus accounts, then seeds one account with
5
5
  * two members and one agent.
6
6
  */
7
7
 
8
- import type { PrismaClient } from "../prisma/client/client.ts";
8
+ import type { PrismaClient } from "../../prisma/client/client.ts";
9
9
 
10
10
  export async function resetMemberIdFixture(prisma: PrismaClient) {
11
11
  await prisma.userNotificationPrefs.deleteMany();
@@ -1,14 +1,14 @@
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
  */
8
8
 
9
9
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
- import { resetMemberIdFixture } from "./member-id-test-support.ts";
11
+ import { resetMemberIdFixture } from "./test-support/member-id-test-support.ts";
12
12
  import { createAdminPrismaClient } from "./prisma-client.ts";
13
13
  import { UserNotificationPrefsService } from "./user-notification-prefs.ts";
14
14
 
@@ -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
  }