@app-vitals/agent-admin 1.105.0 → 1.106.1

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.105.0",
3
+ "version": "1.106.1",
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.105.0",
47
+ "@app-vitals/agent-lib": "1.106.1",
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
  }
@@ -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 { 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,9 +61,17 @@ 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
 
64
77
  async remove(accountId: string, email: string): Promise<void> {
@@ -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),
@@ -0,0 +1,202 @@
1
+ /**
2
+ * admin/src/admin-ui-agent-members.smoke.test.ts
3
+ * POST /admin/agents/:id/members ensures an AccountMember first (ensureAccountMember):
4
+ * success, and the two failures (no account can be chosen, caller may not create).
5
+ * In-memory doubles; the real ensure rules run against a fake client.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ makeMockDeps,
12
+ makeSessionCookie,
13
+ } from "./admin-ui.fixtures.ts";
14
+ import { createAdminUIApp } from "./admin-ui.ts";
15
+ import type { CallerScope } from "./caller-scope.ts";
16
+ import {
17
+ ensureAccountMember,
18
+ type MemberCreator,
19
+ } from "./ensure-account-member.ts";
20
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
21
+
22
+ interface Record {
23
+ id: string;
24
+ accountId: string;
25
+ email: string;
26
+ role: string;
27
+ }
28
+
29
+ function setup(opts: {
30
+ agentAccountId: string | null;
31
+ accountIds: string[];
32
+ records?: Record[];
33
+ scope?: CallerScope;
34
+ }) {
35
+ const records = [...(opts.records ?? [])];
36
+ const added: string[] = [];
37
+ const writes: string[] = [];
38
+ const client = {
39
+ accountMember: {
40
+ findUnique: async ({ where }: { where: { email: string } }) =>
41
+ records.find((r) => r.email === where.email) ?? null,
42
+ upsert: async ({
43
+ create,
44
+ }: {
45
+ create: { accountId: string; email: string; role: string };
46
+ }) => {
47
+ writes.push(create.email);
48
+ const row = { id: `m-${records.length}`, ...create };
49
+ records.push(row);
50
+ return row;
51
+ },
52
+ },
53
+ account: {
54
+ findMany: async () => opts.accountIds.map((id) => ({ id })),
55
+ },
56
+ agentMember: { updateMany: async () => ({ count: 0 }) },
57
+ chatThreadWatch: { updateMany: async () => ({ count: 0 }) },
58
+ pushSubscription: { updateMany: async () => ({ count: 0 }) },
59
+ userNotificationPrefs: { updateMany: async () => ({ count: 0 }) },
60
+ } as unknown as PrismaTransactionClient;
61
+
62
+ const base = makeMockDeps();
63
+ const deps = makeMockDeps({
64
+ selfServe: { enabled: true, defaultMaxAgents: 2, contactEmail: "x@y.z" },
65
+ ...(opts.scope
66
+ ? { callerScopeResolver: async () => opts.scope as CallerScope }
67
+ : {}),
68
+ agentService: {
69
+ ...base.agentService,
70
+ getDetail: async (id: string) => {
71
+ const detail = await base.agentService.getDetail(id);
72
+ return detail && { ...detail, accountId: opts.agentAccountId };
73
+ },
74
+ },
75
+ agentMemberService: {
76
+ ...base.agentMemberService,
77
+ add: async (agentId: string, email: string) => {
78
+ added.push(email);
79
+ return {
80
+ id: "am1",
81
+ agentId,
82
+ email,
83
+ memberId: null,
84
+ createdAt: new Date(),
85
+ };
86
+ },
87
+ },
88
+ ensureAccountMember: (input: {
89
+ email: string;
90
+ agentAccountId: string | null;
91
+ creator?: MemberCreator;
92
+ }) => ensureAccountMember(client, input),
93
+ });
94
+ return { app: createAdminUIApp(deps), records, added, writes };
95
+ }
96
+
97
+ async function post(
98
+ app: ReturnType<typeof setup>["app"],
99
+ admin: boolean,
100
+ email: string,
101
+ ) {
102
+ const cookie = await makeSessionCookie(
103
+ undefined,
104
+ "sub",
105
+ admin ? "admin@example.com" : "member@example.com",
106
+ admin,
107
+ );
108
+ return app.request(`/admin/agents/${AGENT_ID}/members`, {
109
+ method: "POST",
110
+ body: new URLSearchParams({ email }).toString(),
111
+ headers: {
112
+ "Content-Type": "application/x-www-form-urlencoded",
113
+ Cookie: `admin_session=${cookie}`,
114
+ },
115
+ });
116
+ }
117
+
118
+ const OK_PATH = `/admin/agents/${AGENT_ID}/access`;
119
+
120
+ describe("POST /admin/agents/:id/members ensures an account member", () => {
121
+ it("creates the record under the agent's account and adds the member", async () => {
122
+ const { app, records, added } = setup({
123
+ agentAccountId: "acct-1",
124
+ accountIds: ["acct-1", "acct-2"],
125
+ });
126
+ const res = await post(app, true, "New@Example.com");
127
+ expect(res.headers.get("Location")).toBe(OK_PATH);
128
+ expect(records).toMatchObject([
129
+ { email: "new@example.com", accountId: "acct-1", role: "member" },
130
+ ]);
131
+ expect(added).toEqual(["new@example.com"]);
132
+ });
133
+
134
+ it("reuses an existing record without touching it", async () => {
135
+ const existing = {
136
+ id: "m0",
137
+ accountId: "acct-2",
138
+ email: "e@example.com",
139
+ role: "owner",
140
+ };
141
+ const { app, records, writes, added } = setup({
142
+ agentAccountId: "acct-1",
143
+ accountIds: ["acct-1", "acct-2"],
144
+ records: [existing],
145
+ });
146
+ const res = await post(app, true, "e@example.com");
147
+ expect(res.headers.get("Location")).toBe(OK_PATH);
148
+ expect(records).toEqual([existing]);
149
+ expect(writes).toEqual([]);
150
+ expect(added).toEqual(["e@example.com"]);
151
+ });
152
+
153
+ it("shows a clear message and writes nothing when no account can be chosen", async () => {
154
+ const { app, records, added } = setup({
155
+ agentAccountId: null,
156
+ accountIds: ["a", "b"],
157
+ });
158
+ const res = await post(app, true, "n@example.com");
159
+ const location = res.headers.get("Location") ?? "";
160
+ expect(location.startsWith(`${OK_PATH}?error=`)).toBe(true);
161
+ expect(decodeURIComponent(location)).toContain("more than one account");
162
+ expect(records).toEqual([]);
163
+ expect(added).toEqual([]);
164
+ });
165
+
166
+ it("denies a member-role caller creating a record: message, nothing written", async () => {
167
+ const { app, records, added } = setup({
168
+ agentAccountId: "acct-1",
169
+ accountIds: ["acct-1"],
170
+ scope: {
171
+ kind: "scoped",
172
+ accountId: "acct-1",
173
+ agentIds: [AGENT_ID],
174
+ role: "member",
175
+ },
176
+ });
177
+ const res = await post(app, false, "n@example.com");
178
+ const location = res.headers.get("Location") ?? "";
179
+ expect(location.startsWith(`${OK_PATH}?error=`)).toBe(true);
180
+ expect(decodeURIComponent(location)).toContain(
181
+ "platform admin or an owner",
182
+ );
183
+ expect(records).toEqual([]);
184
+ expect(added).toEqual([]);
185
+ });
186
+
187
+ it("lets an owner of the agent's account create the record", async () => {
188
+ const { app, records } = setup({
189
+ agentAccountId: "acct-1",
190
+ accountIds: ["acct-1"],
191
+ scope: {
192
+ kind: "scoped",
193
+ accountId: "acct-1",
194
+ agentIds: [AGENT_ID],
195
+ role: "owner",
196
+ },
197
+ });
198
+ const res = await post(app, false, "n@example.com");
199
+ expect(res.headers.get("Location")).toBe(OK_PATH);
200
+ expect(records).toHaveLength(1);
201
+ });
202
+ });
package/src/admin-ui.ts CHANGED
@@ -138,6 +138,11 @@ import {
138
138
  scopeIncludesAgent,
139
139
  type ViewerRole,
140
140
  } from "./caller-scope.ts";
141
+ import {
142
+ creatorFromScope,
143
+ type EnsureAccountMemberResult,
144
+ type MemberCreator,
145
+ } from "./ensure-account-member.ts";
141
146
  import { ForbiddenError, UnprocessableEntityError } from "./errors.ts";
142
147
  import type { GithubAppsState } from "./github-apps-state.ts";
143
148
  import {
@@ -530,6 +535,16 @@ export interface AdminUIDeps {
530
535
  ) => Response | Promise<Response>;
531
536
  /** Best-effort operator push on auto-created accounts (SSP-3.3). */
532
537
  accountCreatedNotifier?: AccountCreatedNotifier;
538
+ /**
539
+ * Ensures an email has an AccountMember before it is added to an agent
540
+ * (ensureAccountMember). Absent → the add route skips the step and an email
541
+ * without a record is saved with a null memberId, the pre-fix behavior.
542
+ */
543
+ ensureAccountMember?: (input: {
544
+ email: string;
545
+ agentAccountId: string | null;
546
+ creator?: MemberCreator;
547
+ }) => Promise<EnsureAccountMemberResult>;
533
548
  /**
534
549
  * Account page + nav services (SSP-3.2). Used only when selfServe.enabled;
535
550
  * absent → no /admin/account routes content, no nav entry, no quota notice.
@@ -966,6 +981,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
966
981
  accountService,
967
982
  accountOnboarding,
968
983
  accountCreatedNotifier,
984
+ ensureAccountMember,
969
985
  accountServices,
970
986
  githubEnterpriseApi,
971
987
  templateService,
@@ -1884,6 +1900,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1884
1900
  ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1885
1901
  // PAI-1.2: owner is the authenticated session user, never form data.
1886
1902
  ownerEmail: c.var.userEmail,
1903
+ memberCreator: c.var.isAdmin
1904
+ ? { platformAdmin: true, ownerOfAccountId: null }
1905
+ : creatorFromScope(await callerScopeResolver(c.var.userEmail, false)),
1887
1906
  },
1888
1907
  );
1889
1908
  if (!result.ok) {
@@ -4469,6 +4488,23 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4469
4488
  return c.redirect(agentSectionPath(agentId, "access"), 302);
4470
4489
  }
4471
4490
  if (email) {
4491
+ if (ensureAccountMember) {
4492
+ const agent = await agentService.getDetail(agentId);
4493
+ const creator = c.var.isAdmin
4494
+ ? { platformAdmin: true, ownerOfAccountId: null }
4495
+ : creatorFromScope(await callerScopeResolver(c.var.userEmail, false));
4496
+ const ensured = await ensureAccountMember({
4497
+ email,
4498
+ agentAccountId: agent?.accountId ?? null,
4499
+ creator,
4500
+ });
4501
+ if (!ensured.ok) {
4502
+ return c.redirect(
4503
+ agentSectionPath(agentId, "access", { error: ensured.message }),
4504
+ 302,
4505
+ );
4506
+ }
4507
+ }
4472
4508
  try {
4473
4509
  await agentMemberService.add(agentId, email);
4474
4510
  } catch {
package/src/agents-api.ts CHANGED
@@ -102,6 +102,10 @@ import {
102
102
  type CronRunTranscriptDeps,
103
103
  registerCronRunTranscriptRoutes,
104
104
  } from "./cron-run-transcripts.ts";
105
+ import {
106
+ creatorFromScope,
107
+ type MemberCreator,
108
+ } from "./ensure-account-member.ts";
105
109
  import {
106
110
  ApiError,
107
111
  BadGatewayError,
@@ -2720,12 +2724,21 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2720
2724
  // agents in THEIR account only: accountId comes from the resolved scope —
2721
2725
  // never the body — and the type is forced to the self-serve specialty.
2722
2726
  let accountId: string | undefined;
2727
+ let memberCreator: MemberCreator = {
2728
+ platformAdmin: true,
2729
+ ownerOfAccountId: null,
2730
+ };
2723
2731
  if (c.get("isAdmin") !== true) {
2724
2732
  const email = c.get("callerEmail");
2725
- const callerAccountId =
2733
+ const callerScope =
2726
2734
  email === undefined
2735
+ ? undefined
2736
+ : await callerScopeResolver(email, false);
2737
+ if (callerScope) memberCreator = creatorFromScope(callerScope);
2738
+ const callerAccountId =
2739
+ callerScope === undefined
2727
2740
  ? null
2728
- : createAccountIdFromScope(await callerScopeResolver(email, false));
2741
+ : createAccountIdFromScope(callerScope);
2729
2742
  if (callerAccountId === null) {
2730
2743
  throw new ForbiddenError(
2731
2744
  "Owner or admin access required to create agent",
@@ -2783,6 +2796,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2783
2796
  restrictSlackToMembersRaw: body.restrictSlackToMembersRaw,
2784
2797
  claudeCodeOauthToken: body.claudeCodeOauthToken,
2785
2798
  anthropicApiKey: body.anthropicApiKey,
2799
+ memberCreator,
2786
2800
  ...(body.templateDetached ? { templateDetached: true } : {}),
2787
2801
  ...(body.env ? { env: body.env } : {}),
2788
2802
  },
@@ -2797,6 +2811,11 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2797
2811
  ACCOUNT_CREATE_ERROR_MESSAGES[result.errorCode],
2798
2812
  );
2799
2813
  }
2814
+ if (result.errorCode === "member_not_permitted") {
2815
+ throw new ForbiddenError(
2816
+ result.errorMessage ?? "Not permitted to add this member.",
2817
+ );
2818
+ }
2800
2819
  if (result.errorCode === ANTHROPIC_CREDENTIALS_BLOCKED_CODE) {
2801
2820
  throw new AnthropicCredentialsBlockedError([
2802
2821
  ...(body.claudeCodeOauthToken ? ["CLAUDE_CODE_OAUTH_TOKEN"] : []),
@@ -181,6 +181,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
181
181
  }
182
182
 
183
183
  it("happy path: creates the Agent row, seeds manifest tools/plugins, and attaches repos/allowlists/members — matching today's form-handler end state", async () => {
184
+ await prisma.account.create({ data: { name: "Only" } });
184
185
  const result = await createAgent(
185
186
  deps(),
186
187
  baseInput({
@@ -189,6 +190,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
189
190
  patchAuthorAllowlistRaw: "patcher1",
190
191
  memberEmailsRaw: "dev@example.com",
191
192
  restrictSlackToMembersRaw: "true",
193
+ memberCreator: { platformAdmin: true, ownerOfAccountId: null },
192
194
  }),
193
195
  );
194
196
 
@@ -224,6 +226,52 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
224
226
  where: { agentId: result.agent.id },
225
227
  });
226
228
  expect(members.map((m) => m.email)).toEqual(["dev@example.com"]);
229
+ // The email got an AccountMember (the only Account), so the row is listed.
230
+ const record = await prisma.accountMember.findUniqueOrThrow({
231
+ where: { email: "dev@example.com" },
232
+ });
233
+ expect(record.role).toBe("member");
234
+ expect(members[0]?.memberId).toBe(record.id);
235
+ });
236
+
237
+ it("a member email that cannot get an account member fails with a message and writes nothing", async () => {
238
+ await prisma.account.create({ data: { name: "Other" } });
239
+ const result = await createAgent(
240
+ deps(),
241
+ baseInput({
242
+ memberEmailsRaw: "first@example.com\nsecond@example.com",
243
+ // A member-role caller: may reuse records but not create them.
244
+ memberCreator: { platformAdmin: false, ownerOfAccountId: null },
245
+ }),
246
+ );
247
+ expect(result.ok).toBe(false);
248
+ if (result.ok) throw new Error("expected failure");
249
+ expect(result.errorCode).toBe("member_not_permitted");
250
+ expect(result.errorMessage).toContain("first@example.com");
251
+ expect(await prisma.agent.findMany()).toEqual([]);
252
+ expect(await prisma.agentMember.findMany()).toEqual([]);
253
+ expect(await prisma.accountMember.findMany()).toEqual([]);
254
+ });
255
+
256
+ it("with several accounts and none on the agent, creation fails and rolls back records made for earlier emails", async () => {
257
+ const acct = await prisma.account.create({ data: { name: "A" } });
258
+ await prisma.accountMember.create({
259
+ data: { accountId: acct.id, email: "known@example.com", role: "owner" },
260
+ });
261
+ await prisma.account.create({ data: { name: "B" } });
262
+ const result = await createAgent(
263
+ deps(),
264
+ baseInput({
265
+ memberEmailsRaw: "known@example.com\nnew@example.com",
266
+ memberCreator: { platformAdmin: true, ownerOfAccountId: null },
267
+ }),
268
+ );
269
+ expect(result.ok).toBe(false);
270
+ if (result.ok) throw new Error("expected failure");
271
+ expect(result.errorCode).toBe("member_account_unresolved");
272
+ expect(await prisma.agent.findMany()).toEqual([]);
273
+ expect(await prisma.agentMember.findMany()).toEqual([]);
274
+ expect(await prisma.accountMember.count()).toBe(1);
227
275
  });
228
276
 
229
277
  it("a failure at the tool-seeding step leaves ZERO Agent row behind in the real database (single-transaction rollback)", async () => {