@app-vitals/agent-admin 1.106.0 → 1.106.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.106.0",
3
+ "version": "1.106.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.106.0",
47
+ "@app-vitals/agent-lib": "1.106.2",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * admin/scripts/backfill-member-id.ts (ACM-1.2)
3
3
  *
4
- * DATABASE_URL_SHIPWRIGHT_ADMIN=... bun admin/scripts/backfill-member-id.ts [--dry-run] [--overrides overrides.json] [--report report.json]
4
+ * DATABASE_URL_SHIPWRIGHT_ADMIN=... bun admin/scripts/backfill-member-id.ts [--dry-run | --verify] [--overrides overrides.json] [--report report.json]
5
5
  *
6
6
  * overrides.json: { "alice@old.com": "<AccountMember.id>" }. Overrides win over
7
- * the automatic email match. --dry-run changes nothing.
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).
8
10
  */
9
11
 
10
12
  import { readFileSync, writeFileSync } from "node:fs";
@@ -12,11 +14,12 @@ import { parseFlags } from "@app-vitals/agent-lib/cli-flags";
12
14
  import {
13
15
  parseOverrides,
14
16
  runMemberIdBackfill,
17
+ verifyMemberIds,
15
18
  } from "../src/member-id-backfill.ts";
16
19
  import { createAdminPrismaClient } from "../src/prisma-client.ts";
17
20
 
18
21
  const flags = parseFlags(process.argv.slice(2), ["--overrides", "--report"], {
19
- booleans: ["--dry-run"],
22
+ booleans: ["--dry-run", "--verify"],
20
23
  });
21
24
  const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
22
25
  if (!url) {
@@ -26,16 +29,22 @@ if (!url) {
26
29
 
27
30
  const prisma = createAdminPrismaClient(url);
28
31
  try {
29
- const overrides = flags["--overrides"]
30
- ? parseOverrides(readFileSync(flags["--overrides"], "utf8"))
31
- : undefined;
32
- const report = await runMemberIdBackfill(prisma, {
33
- dryRun: flags["--dry-run"],
34
- overrides,
35
- });
36
- const body = JSON.stringify(report, null, 2);
37
- if (flags["--report"]) writeFileSync(flags["--report"], `${body}\n`);
38
- console.log(body);
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
+ }
39
48
  } finally {
40
49
  await prisma.$disconnect();
41
50
  }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * admin/src/account-member-removal.integration.test.ts
3
+ * AccountMemberService.remove deletes the removed person's access and
4
+ * notification rows (AgentMember, ChatThreadWatch, PushSubscription,
5
+ * UserNotificationPrefs), atomically with the removal. Real Postgres.
6
+ *
7
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import {
13
+ AccountMemberNotFoundError,
14
+ AccountMemberService,
15
+ LastOwnerError,
16
+ } from "./account-members.ts";
17
+ import { AgentMemberService } from "./agent-members.ts";
18
+ import { createAdminPrismaClient } from "./prisma-client.ts";
19
+
20
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
21
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
22
+
23
+ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
24
+ let prisma: PrismaClient;
25
+ let service: AccountMemberService;
26
+ let acme: string;
27
+ let agentId: string;
28
+
29
+ async function seedRows(email: string, memberId: string | null) {
30
+ await prisma.agentMember.create({ data: { agentId, email, memberId } });
31
+ await prisma.chatThreadWatch.create({
32
+ data: { userEmail: email, threadId: `t-${email}`, agentId, memberId },
33
+ });
34
+ await prisma.pushSubscription.create({
35
+ data: {
36
+ userEmail: email,
37
+ endpoint: `ep-${email}`,
38
+ p256dh: "p",
39
+ auth: "a",
40
+ memberId,
41
+ },
42
+ });
43
+ await prisma.userNotificationPrefs.create({
44
+ data: { userEmail: email, memberId },
45
+ });
46
+ }
47
+
48
+ async function rowCounts(email: string) {
49
+ return Promise.all([
50
+ prisma.agentMember.count({ where: { email } }),
51
+ prisma.chatThreadWatch.count({ where: { userEmail: email } }),
52
+ prisma.pushSubscription.count({ where: { userEmail: email } }),
53
+ prisma.userNotificationPrefs.count({ where: { userEmail: email } }),
54
+ ]);
55
+ }
56
+
57
+ async function addMember(email: string, role: "owner" | "member") {
58
+ return prisma.accountMember.create({
59
+ data: { accountId: acme, email, role },
60
+ });
61
+ }
62
+
63
+ beforeEach(async () => {
64
+ prisma = createAdminPrismaClient(TEST_DB as string);
65
+ service = new AccountMemberService(prisma);
66
+ await prisma.userNotificationPrefs.deleteMany();
67
+ await prisma.chatThreadWatch.deleteMany();
68
+ await prisma.pushSubscription.deleteMany();
69
+ await prisma.agentMember.deleteMany();
70
+ await prisma.accountInvite.deleteMany();
71
+ await prisma.accountMember.deleteMany();
72
+ await prisma.agent.deleteMany();
73
+ await prisma.account.deleteMany();
74
+ acme = (await prisma.account.create({ data: { name: "Acme" } })).id;
75
+ agentId = (
76
+ await prisma.agent.create({
77
+ data: { id: "rm-agent", name: "rm-agent", accountId: acme },
78
+ })
79
+ ).id;
80
+ await addMember("owner@acme.com", "owner");
81
+ });
82
+
83
+ afterEach(async () => {
84
+ await prisma.$disconnect();
85
+ });
86
+
87
+ it("deletes the person's rows by memberId and by email where memberId is null, and no one else's", async () => {
88
+ const bob = await addMember("bob@acme.com", "member");
89
+ const carol = await addMember("carol@acme.com", "member");
90
+ await seedRows("bob@acme.com", bob.id);
91
+ await seedRows("carol@acme.com", carol.id);
92
+ await service.remove(acme, "bob@acme.com");
93
+
94
+ expect(await rowCounts("bob@acme.com")).toEqual([0, 0, 0, 0]);
95
+ expect(await rowCounts("carol@acme.com")).toEqual([1, 1, 1, 1]);
96
+ expect(await prisma.accountMember.count({ where: { id: bob.id } })).toBe(0);
97
+ });
98
+
99
+ it("deletes null-memberId rows matched by email (case-insensitive)", async () => {
100
+ await addMember("dee@acme.com", "member");
101
+ await seedRows("Dee@Acme.com", null);
102
+ await service.remove(acme, "dee@acme.com");
103
+ expect(await rowCounts("Dee@Acme.com")).toEqual([0, 0, 0, 0]);
104
+ });
105
+
106
+ it("deletes rows stamped with the member's id even if the stored email differs", async () => {
107
+ const eve = await addMember("eve@acme.com", "member");
108
+ await seedRows("eve-old@acme.com", eve.id);
109
+ await service.remove(acme, "eve@acme.com");
110
+ expect(await rowCounts("eve-old@acme.com")).toEqual([0, 0, 0, 0]);
111
+ });
112
+
113
+ it("deletes nothing when the last owner is refused", async () => {
114
+ const owner = await prisma.accountMember.findUniqueOrThrow({
115
+ where: { email: "owner@acme.com" },
116
+ });
117
+ await seedRows("owner@acme.com", owner.id);
118
+ await expect(service.remove(acme, "owner@acme.com")).rejects.toBeInstanceOf(
119
+ LastOwnerError,
120
+ );
121
+ expect(await rowCounts("owner@acme.com")).toEqual([1, 1, 1, 1]);
122
+ expect(await prisma.accountMember.count()).toBe(1);
123
+ });
124
+
125
+ it("deletes nothing when the member is unknown", async () => {
126
+ await seedRows("ghost@acme.com", null);
127
+ await expect(service.remove(acme, "ghost@acme.com")).rejects.toBeInstanceOf(
128
+ AccountMemberNotFoundError,
129
+ );
130
+ expect(await rowCounts("ghost@acme.com")).toEqual([1, 1, 1, 1]);
131
+ });
132
+
133
+ it("rolls back the removal and the deletes when a step fails partway", async () => {
134
+ const fay = await addMember("fay@acme.com", "member");
135
+ await seedRows("fay@acme.com", fay.id);
136
+ // Fail the final AccountMember delete after the row deletes have run.
137
+ const failing = new Proxy(prisma, {
138
+ get(target, prop, receiver) {
139
+ if (prop !== "$transaction") return Reflect.get(target, prop, receiver);
140
+ return (fn: (tx: unknown) => Promise<unknown>) =>
141
+ target.$transaction(async (tx) =>
142
+ fn(
143
+ new Proxy(tx, {
144
+ get(t, p, r) {
145
+ if (p !== "accountMember") return Reflect.get(t, p, r);
146
+ return new Proxy(t.accountMember, {
147
+ get(m, mp, mr) {
148
+ if (mp === "delete") {
149
+ return async () => {
150
+ throw new Error("boom");
151
+ };
152
+ }
153
+ return Reflect.get(m, mp, mr);
154
+ },
155
+ });
156
+ },
157
+ }),
158
+ ),
159
+ );
160
+ },
161
+ }) as PrismaClient;
162
+
163
+ await expect(
164
+ new AccountMemberService(failing).remove(acme, "fay@acme.com"),
165
+ ).rejects.toThrow("boom");
166
+ expect(await rowCounts("fay@acme.com")).toEqual([1, 1, 1, 1]);
167
+ expect(await prisma.accountMember.count({ where: { id: fay.id } })).toBe(1);
168
+ });
169
+
170
+ it("after re-adding, the person can be added to the same agent again with no earlier settings", async () => {
171
+ const gus = await addMember("gus@acme.com", "member");
172
+ await seedRows("gus@acme.com", gus.id);
173
+ await service.remove(acme, "gus@acme.com");
174
+
175
+ const readded = await service.add(acme, "gus@acme.com");
176
+ expect(readded.id).not.toBe(gus.id);
177
+
178
+ const agentMembers = new AgentMemberService(prisma);
179
+ await agentMembers.add(agentId, "gus@acme.com");
180
+ expect(await agentMembers.exists(agentId, "gus@acme.com")).toBe(true);
181
+ const rows = await prisma.agentMember.findMany({
182
+ where: { email: "gus@acme.com" },
183
+ });
184
+ expect(rows).toHaveLength(1);
185
+ expect(rows[0]?.id).not.toBe(undefined);
186
+ expect(await prisma.chatThreadWatch.count()).toBe(0);
187
+ expect(await prisma.pushSubscription.count()).toBe(0);
188
+ expect(await prisma.userNotificationPrefs.count()).toBe(0);
189
+ });
190
+ });
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { AccountMember, PrismaClient } from "../prisma/client/client.ts";
10
10
  import { normalizeEmail } from "./account-email.ts";
11
+ import { deleteMemberRows, stampMemberId } from "./member-id-stamp.ts";
11
12
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
12
13
 
13
14
  export type { AccountMember };
@@ -48,6 +49,10 @@ export class AccountMemberService {
48
49
  * Add a member. Throws (unique-constraint violation) if the email already
49
50
  * belongs to any account.
50
51
  *
52
+ * Null memberId rows for the email (AgentMember, ChatThreadWatch,
53
+ * PushSubscription, UserNotificationPrefs) get the new id in the same
54
+ * transaction.
55
+ *
51
56
  * @param client - pass a `tx` from `prisma.$transaction` to participate in it.
52
57
  */
53
58
  async add(
@@ -56,13 +61,27 @@ export class AccountMemberService {
56
61
  role: AccountRole = "member",
57
62
  client: PrismaTransactionClient = this.prisma,
58
63
  ): Promise<AccountMember> {
59
- return client.accountMember.create({
60
- data: { accountId, email: normalizeEmail(email), role },
61
- });
64
+ const normalized = normalizeEmail(email);
65
+ const run = async (tx: PrismaTransactionClient) => {
66
+ const member = await tx.accountMember.create({
67
+ data: { accountId, email: normalized, role },
68
+ });
69
+ await stampMemberId(tx, normalized, member.id);
70
+ return member;
71
+ };
72
+ return "$transaction" in client
73
+ ? (client as PrismaClient).$transaction(run)
74
+ : run(client);
62
75
  }
63
76
 
77
+ /**
78
+ * Remove a member and their access and notification rows (AgentMember,
79
+ * ChatThreadWatch, PushSubscription, UserNotificationPrefs), matched by
80
+ * memberId and by email where memberId is null, in one transaction.
81
+ */
64
82
  async remove(accountId: string, email: string): Promise<void> {
65
83
  await this.guardedChange(accountId, email, async (tx, member) => {
84
+ await deleteMemberRows(tx, member.email, member.id);
66
85
  await tx.accountMember.delete({ where: { id: member.id } });
67
86
  });
68
87
  }
@@ -12,6 +12,7 @@
12
12
 
13
13
  import type { PrismaClient } from "../prisma/client/client.ts";
14
14
  import { normalizeEmail } from "./account-email.ts";
15
+ import { stampMemberId } from "./member-id-stamp.ts";
15
16
 
16
17
  type OnboardingResult =
17
18
  | { kind: "created"; accountId: string }
@@ -73,9 +74,10 @@ export class AccountOnboardingService {
73
74
  data: { acceptedAt: new Date() },
74
75
  });
75
76
  if (claimed.count === 1) {
76
- await tx.accountMember.create({
77
+ const member = await tx.accountMember.create({
77
78
  data: { accountId: invite.accountId, email, role: "member" },
78
79
  });
80
+ await stampMemberId(tx, email, member.id);
79
81
  return { kind: "joined", accountId: invite.accountId };
80
82
  }
81
83
  }
@@ -87,9 +89,10 @@ export class AccountOnboardingService {
87
89
  maxAgents: this.defaultMaxAgents,
88
90
  },
89
91
  });
90
- await tx.accountMember.create({
92
+ const owner = await tx.accountMember.create({
91
93
  data: { accountId: account.id, email, role: "owner" },
92
94
  });
95
+ await stampMemberId(tx, email, owner.id);
93
96
  return { kind: "created", accountId: account.id };
94
97
  }
95
98
  }
package/src/accounts.ts CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  import type { Account, PrismaClient } from "../prisma/client/client.ts";
8
8
  import { normalizeEmail } from "./account-email.ts";
9
+ import { stampMemberId } from "./member-id-stamp.ts";
9
10
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
10
11
 
11
12
  export type { Account };
@@ -48,13 +49,11 @@ export class AccountService {
48
49
  ): Promise<Account> {
49
50
  return this.prisma.$transaction(async (tx) => {
50
51
  const account = await tx.account.create({ data: { name, ...opts } });
51
- await tx.accountMember.create({
52
- data: {
53
- accountId: account.id,
54
- email: normalizeEmail(ownerEmail),
55
- role: "owner",
56
- },
52
+ const email = normalizeEmail(ownerEmail);
53
+ const owner = await tx.accountMember.create({
54
+ data: { accountId: account.id, email, role: "owner" },
57
55
  });
56
+ await stampMemberId(tx, email, owner.id);
58
57
  return account;
59
58
  });
60
59
  }
package/src/admin-boot.ts CHANGED
@@ -47,6 +47,7 @@ import { createAccountCreatedNotifier } from "./account-created-notifier.ts";
47
47
  import { AccountInviteService } from "./account-invites.ts";
48
48
  import { AccountLifecycle } from "./account-lifecycle.ts";
49
49
  import { AccountMemberService } from "./account-members.ts";
50
+ import { ensureAccountMember } from "./ensure-account-member.ts";
50
51
  import { AccountOnboardingService } from "./account-onboarding.ts";
51
52
  import { AccountTrialExpirySweeper } from "./account-trial-expiry-sweeper.ts";
52
53
  import { AccountTrialWarningSweeper } from "./account-trial-warning-sweeper.ts";
@@ -730,6 +731,8 @@ export async function startAdmin(
730
731
  githubEnterpriseApi: (path, init) =>
731
732
  githubEnterpriseApp.request(path, init),
732
733
  agentsApi: (path, init) => adminApiApp.request(path, init),
734
+ ensureAccountMember: (input) =>
735
+ prisma.$transaction((tx) => ensureAccountMember(tx, input)),
733
736
  accountServices: {
734
737
  accounts: new AccountService(prisma),
735
738
  members: new AccountMemberService(prisma),
@@ -32,13 +32,20 @@ interface AccountPageOpts {
32
32
  isAdmin?: boolean;
33
33
  }
34
34
 
35
+ export const REMOVE_MEMBER_CONFIRM =
36
+ "Remove this member? Their agent access and notification settings are removed too.";
37
+
35
38
  function emailForm(
36
39
  action: string,
37
40
  email: string,
38
41
  label: string,
39
42
  danger = false,
43
+ confirmText?: string,
40
44
  ): string {
41
- return `<form method="POST" action="${ACCOUNT_PATH}/${action}" style="display:inline;margin:0">
45
+ const onsubmit = confirmText
46
+ ? ` onsubmit="return confirm('${confirmText}')"`
47
+ : "";
48
+ return `<form method="POST" action="${ACCOUNT_PATH}/${action}"${onsubmit} style="display:inline;margin:0">
42
49
  <input type="hidden" name="email" value="${escapeHtml(email)}" />
43
50
  <button type="submit" class="btn ${danger ? "btn-danger" : "btn-secondary"}" style="font-size:12px;padding:4px 10px">${label}</button>
44
51
  </form>`;
@@ -50,7 +57,13 @@ function renderMemberRow(m: AccountMember, isOwner: boolean): string {
50
57
  m.role === "owner"
51
58
  ? emailForm("members/demote", m.email, "Demote")
52
59
  : emailForm("members/promote", m.email, "Make owner"),
53
- emailForm("members/remove", m.email, "Remove", true),
60
+ emailForm(
61
+ "members/remove",
62
+ m.email,
63
+ "Remove",
64
+ true,
65
+ REMOVE_MEMBER_CONFIRM,
66
+ ),
54
67
  ].join(" ")
55
68
  : "";
56
69
  return `<tr>
@@ -72,6 +72,10 @@ describe("renderAccountPage", () => {
72
72
  expect(html).toContain('action="/admin/account/rename"');
73
73
  });
74
74
 
75
+ test("remove form confirms that access and notification settings are removed", () => {
76
+ expect(render(true)).toContain("notification settings are removed");
77
+ });
78
+
75
79
  test("member sees read-only page", () => {
76
80
  const html = render(false);
77
81
  expect(html).not.toContain('action="/admin/account/');
@@ -7,6 +7,7 @@
7
7
  import type { AccountInvite } from "./account-invites.ts";
8
8
  import type { AccountMember } from "./account-members.ts";
9
9
  import type { AccountWithCounts } from "./accounts.ts";
10
+ import { REMOVE_MEMBER_CONFIRM } from "./admin-ui-account-pages.ts";
10
11
  import { renderAdminPage } from "./admin-ui-layout.ts";
11
12
  import {
12
13
  buildSettingsNav,
@@ -101,14 +102,18 @@ function postForm(
101
102
  fields: Record<string, string>,
102
103
  label: string,
103
104
  danger = false,
105
+ confirmText?: string,
104
106
  ): string {
107
+ const onsubmit = confirmText
108
+ ? ` onsubmit="return confirm('${confirmText}')"`
109
+ : "";
105
110
  const hidden = Object.entries(fields)
106
111
  .map(
107
112
  ([k, v]) =>
108
113
  `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v)}" />`,
109
114
  )
110
115
  .join("");
111
- return `<form method="POST" action="${ADMIN_ACCOUNTS_PATH}/${escapeHtml(accountId)}/${action}" style="display:inline;margin:0">${hidden}
116
+ return `<form method="POST" action="${ADMIN_ACCOUNTS_PATH}/${escapeHtml(accountId)}/${action}"${onsubmit} style="display:inline;margin:0">${hidden}
112
117
  <button type="submit" class="btn ${danger ? "btn-danger" : "btn-secondary"}" style="font-size:12px;padding:4px 10px">${label}</button>
113
118
  </form>`;
114
119
  }
@@ -139,7 +144,14 @@ export function renderAccountDetailPage(opts: AccountDetailPageOpts): string {
139
144
  m.role === "owner"
140
145
  ? postForm(id, "members/demote", { email: m.email }, "Demote")
141
146
  : postForm(id, "members/promote", { email: m.email }, "Make owner"),
142
- postForm(id, "members/remove", { email: m.email }, "Remove", true),
147
+ postForm(
148
+ id,
149
+ "members/remove",
150
+ { email: m.email },
151
+ "Remove",
152
+ true,
153
+ REMOVE_MEMBER_CONFIRM,
154
+ ),
143
155
  ].join(" ")}</td>
144
156
  </tr>`,
145
157
  )
@@ -85,6 +85,7 @@ describe("renderAccountDetailPage", () => {
85
85
 
86
86
  test("edit form, suspend button, agents, members, invites", () => {
87
87
  const html = renderAccountDetailPage(base);
88
+ expect(html).toContain("notification settings are removed");
88
89
  expect(html).toContain('action="/admin/accounts/a1/update"');
89
90
  expect(html).toContain('name="maxAgents"');
90
91
  expect(html).toContain('value="2026-03-05"');