@app-vitals/agent-admin 1.101.2 → 1.101.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.101.2",
3
+ "version": "1.101.3",
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.101.2",
47
+ "@app-vitals/agent-lib": "1.101.3",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,99 @@
1
+ /**
2
+ * admin/src/agent-members.integration.test.ts (ACM-4.1)
3
+ * AgentMemberService reads and writes by memberId; email is resolved through
4
+ * the AccountMember lookup. Rows with a null memberId are skipped.
5
+ *
6
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import { AgentMemberService } from "./agent-members.ts";
12
+ import { resetMemberIdFixture } from "./member-id-test-support.ts";
13
+ import { createAdminPrismaClient } from "./prisma-client.ts";
14
+
15
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
16
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
17
+
18
+ describeOrSkip("AgentMemberService by memberId (integration)", () => {
19
+ let prisma: PrismaClient;
20
+ let service: AgentMemberService;
21
+ let aliceId: string;
22
+ let bobId: string;
23
+ let agentId: string;
24
+
25
+ beforeEach(async () => {
26
+ prisma = createAdminPrismaClient(TEST_DB as string);
27
+ const f = await resetMemberIdFixture(prisma);
28
+ aliceId = f.alice.id;
29
+ bobId = f.bob.id;
30
+ agentId = f.agent.id;
31
+ service = new AgentMemberService(prisma);
32
+ });
33
+
34
+ afterEach(async () => {
35
+ await prisma.$disconnect();
36
+ });
37
+
38
+ it("add stamps memberId resolved from the email (case-insensitive)", async () => {
39
+ const row = await service.add(agentId, "alice@acme.com");
40
+ expect(row.memberId).toBe(aliceId);
41
+ const stored = await prisma.agentMember.findUniqueOrThrow({
42
+ where: { id: row.id },
43
+ });
44
+ expect(stored.memberId).toBe(aliceId);
45
+ });
46
+
47
+ it("add inside a transaction resolves memberId through the tx client", async () => {
48
+ await prisma.$transaction(async (tx) => {
49
+ await service.add(agentId, "bob@acme.com", tx);
50
+ });
51
+ const rows = await prisma.agentMember.findMany();
52
+ expect(rows.map((r) => r.memberId)).toEqual([bobId]);
53
+ });
54
+
55
+ it("add for an email with no AccountMember stores a null memberId", async () => {
56
+ const row = await service.add(agentId, "ghost@nowhere.com");
57
+ expect(row.memberId).toBeNull();
58
+ });
59
+
60
+ it("listByEmail and listByMemberId return the member's agents", async () => {
61
+ await service.add(agentId, "alice@acme.com");
62
+ expect((await service.listByEmail("Alice@Acme.com")).length).toBe(1);
63
+ expect((await service.listByMemberId(aliceId)).length).toBe(1);
64
+ expect(await service.listByMemberId(bobId)).toEqual([]);
65
+ });
66
+
67
+ it("exists keys on memberId", async () => {
68
+ await service.add(agentId, "alice@acme.com");
69
+ expect(await service.exists(agentId, "alice@acme.com")).toBe(true);
70
+ expect(await service.exists(agentId, "bob@acme.com")).toBe(false);
71
+ expect(await service.exists(agentId, "ghost@nowhere.com")).toBe(false);
72
+ });
73
+
74
+ it("skips null-memberId rows on every read without crashing", async () => {
75
+ // Legacy row: email only, never backfilled.
76
+ await prisma.agentMember.create({
77
+ data: { agentId, email: "alice@acme.com" },
78
+ });
79
+ expect(await service.listByEmail("alice@acme.com")).toEqual([]);
80
+ expect(await service.exists(agentId, "alice@acme.com")).toBe(false);
81
+ expect(await service.listByAgentId(agentId)).toEqual([]);
82
+ });
83
+
84
+ it("listByAgentId returns rows with the email resolved through the lookup", async () => {
85
+ await service.add(agentId, "alice@acme.com");
86
+ // Stored email drifted from the member's current email.
87
+ await prisma.agentMember.updateMany({ data: { email: "stale@old.com" } });
88
+ const rows = await service.listByAgentId(agentId);
89
+ expect(rows.map((r) => r.email)).toEqual(["alice@acme.com"]);
90
+ });
91
+
92
+ it("remove deletes by row id scoped to the agent", async () => {
93
+ const row = await service.add(agentId, "alice@acme.com");
94
+ await service.remove("other-agent", row.id);
95
+ expect((await service.listByMemberId(aliceId)).length).toBe(1);
96
+ await service.remove(agentId, row.id);
97
+ expect(await service.listByMemberId(aliceId)).toEqual([]);
98
+ });
99
+ });
@@ -2,46 +2,81 @@
2
2
  * agent/src/agent-members.ts
3
3
  * AgentMemberService — authorized human members per agent (access control).
4
4
  *
5
- * Membership rows are keyed by [agentId, email] (unique constraint) — an
6
- * email can be a member of multiple agents, and an agent can have multiple
7
- * member emails.
5
+ * ACM-4.1: reads and writes key on AgentMember.memberId (AccountMember.id).
6
+ * Callers still pass emails; they are resolved to a member id through the
7
+ * AccountMember lookup, and emails handed back are resolved the same way. Rows
8
+ * whose memberId is null (not yet backfilled) are skipped. The [agentId, email]
9
+ * unique constraint stays in place and still guards duplicate adds.
8
10
  */
9
11
 
10
12
  import type { AgentMember, PrismaClient } from "../prisma/client/client.ts";
13
+ import { normalizeEmail } from "./account-email.ts";
14
+ import { PrincipalLookupService } from "./principal-lookup.ts";
11
15
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
12
16
 
13
17
  export type { AgentMember };
14
18
 
15
19
  export class AgentMemberService {
16
- constructor(private prisma: PrismaClient) {}
20
+ private readonly lookup: PrincipalLookupService;
21
+
22
+ constructor(private prisma: PrismaClient) {
23
+ this.lookup = new PrincipalLookupService(prisma);
24
+ }
25
+
26
+ private async memberIdForEmail(email: string): Promise<string | null> {
27
+ return (await this.lookup.findIdByEmail(email))?.id ?? null;
28
+ }
17
29
 
18
30
  /**
19
- * List all memberships for a given agent.
31
+ * List all memberships for a given agent. Rows with a null memberId, or a
32
+ * memberId that no longer resolves, are skipped; `email` on each returned
33
+ * row is the member's current email from the lookup.
20
34
  */
21
35
  async listByAgentId(agentId: string): Promise<AgentMember[]> {
22
- return this.prisma.agentMember.findMany({ where: { agentId } });
36
+ const rows = await this.prisma.agentMember.findMany({
37
+ where: { agentId, memberId: { not: null } },
38
+ });
39
+ const { principals } = await this.lookup.resolveMany(
40
+ rows.flatMap((r) => (r.memberId ? [r.memberId] : [])),
41
+ );
42
+ const emails = new Map(principals.map((p) => [p.id, p.email]));
43
+ return rows.flatMap((r) => {
44
+ const email = r.memberId ? emails.get(r.memberId) : null;
45
+ return email ? [{ ...r, email }] : [];
46
+ });
47
+ }
48
+
49
+ /** List all memberships for a given AccountMember id. */
50
+ async listByMemberId(memberId: string): Promise<AgentMember[]> {
51
+ return this.prisma.agentMember.findMany({ where: { memberId } });
23
52
  }
24
53
 
25
54
  /**
26
- * List all memberships for a given email, case-sensitive as stored.
27
- * Callers are expected to lowercase the email before calling.
55
+ * List all memberships for the member owning `email` (case-insensitive).
56
+ * Empty when the email has no AccountMember.
28
57
  */
29
58
  async listByEmail(email: string): Promise<AgentMember[]> {
30
- return this.prisma.agentMember.findMany({ where: { email } });
59
+ const memberId = await this.memberIdForEmail(email);
60
+ return memberId ? this.listByMemberId(memberId) : [];
31
61
  }
32
62
 
33
63
  /**
34
- * Returns whether a membership row exists for the given agentId+email pair.
64
+ * Returns whether the member owning `email` has a membership row for the agent.
35
65
  */
36
66
  async exists(agentId: string, email: string): Promise<boolean> {
37
- const membership = await this.prisma.agentMember.findUnique({
38
- where: { agentId_email: { agentId, email } },
67
+ const memberId = await this.memberIdForEmail(email);
68
+ if (!memberId) return false;
69
+ const membership = await this.prisma.agentMember.findFirst({
70
+ where: { agentId, memberId },
71
+ select: { id: true },
39
72
  });
40
73
  return membership !== null;
41
74
  }
42
75
 
43
76
  /**
44
- * Create a membership row for the given agentId and email.
77
+ * Create a membership row for the given agentId and email, stamped with the
78
+ * email's AccountMember id (null when the email has no member yet — such a
79
+ * row is skipped by reads until backfilled).
45
80
  * Throws (unique-constraint violation) if the membership already exists —
46
81
  * callers are expected to catch and handle "already a member" as a no-op.
47
82
  *
@@ -54,7 +89,14 @@ export class AgentMemberService {
54
89
  email: string,
55
90
  client: PrismaTransactionClient = this.prisma,
56
91
  ): Promise<AgentMember> {
57
- return client.agentMember.create({ data: { agentId, email } });
92
+ const normalized = normalizeEmail(email);
93
+ const member = await client.accountMember.findUnique({
94
+ where: { email: normalized },
95
+ select: { id: true },
96
+ });
97
+ return client.agentMember.create({
98
+ data: { agentId, email: normalized, memberId: member?.id ?? null },
99
+ });
58
100
  }
59
101
 
60
102
  /**
@@ -96,6 +96,22 @@ const CODING_TYPE: SpecialtyType = {
96
96
  * specialty. tryGetType() returns undefined (no fallback) for anything
97
97
  * not in the map, mirroring SpecialtyTypes's real contract.
98
98
  */
99
+ // ACM-4.1: AgentMember reads key on memberId, so seeded members need an
100
+ // AccountMember to resolve through.
101
+ async function seedAgentMember(
102
+ prisma: PrismaClient,
103
+ agentId: string,
104
+ email: string,
105
+ ) {
106
+ const account = await prisma.account.create({ data: { name: "Acme" } });
107
+ const member = await prisma.accountMember.create({
108
+ data: { accountId: account.id, email, role: "member" },
109
+ });
110
+ await prisma.agentMember.create({
111
+ data: { agentId, email, memberId: member.id },
112
+ });
113
+ }
114
+
99
115
  function fakeSpecialtyTypes(
100
116
  byType: Record<string, SpecialtyType> = { coding: CODING_TYPE },
101
117
  ): SpecialtyTypeResolver {
@@ -181,6 +197,8 @@ describeOrSkip("admin CRUD API (integration)", () => {
181
197
  await prisma.agentEnv.deleteMany();
182
198
  await prisma.agentMember.deleteMany();
183
199
  await prisma.agent.deleteMany();
200
+ await prisma.accountMember.deleteMany();
201
+ await prisma.account.deleteMany();
184
202
 
185
203
  agentId = await createAgent(prisma);
186
204
  cookie = await makeSessionCookie();
@@ -615,9 +633,7 @@ describeOrSkip("admin CRUD API (integration)", () => {
615
633
  Cookie: `admin_session=${cookie}`,
616
634
  },
617
635
  });
618
- await prisma.agentMember.create({
619
- data: { agentId, email: "member@example.com" },
620
- });
636
+ await seedAgentMember(prisma, agentId, "member@example.com");
621
637
 
622
638
  const secondPatchRes = await app.request(`/agents/${agentId}`, {
623
639
  method: "PATCH",
@@ -745,6 +761,8 @@ describeOrSkip("PATCH /agents/:id podServiceAccountName (integration)", () => {
745
761
  await prisma.agentEnv.deleteMany();
746
762
  await prisma.agentMember.deleteMany();
747
763
  await prisma.agent.deleteMany();
764
+ await prisma.accountMember.deleteMany();
765
+ await prisma.account.deleteMany();
748
766
  agentId = await createAgent(prisma);
749
767
  cookie = await makeSessionCookie();
750
768
  reconciled.length = 0;
@@ -784,9 +802,7 @@ describeOrSkip("PATCH /agents/:id podServiceAccountName (integration)", () => {
784
802
  SESSION_SECRET,
785
803
  "HS256",
786
804
  );
787
- await prisma.agentMember.create({
788
- data: { agentId, email: "member@example.com" },
789
- });
805
+ await seedAgentMember(prisma, agentId, "member@example.com");
790
806
  const res = await patch(
791
807
  appWith(true),
792
808
  { podServiceAccountName: "sa" },
@@ -814,7 +814,12 @@ describe("AgentService.getById", () => {
814
814
  },
815
815
  ],
816
816
  }) as unknown as FakePrisma;
817
- const service = new AgentService(prisma as never);
817
+ // ACM-4.1: AgentMemberService resolves emails through AccountMember and is
818
+ // covered by agent-members.integration.test.ts; here it is a seeded double.
819
+ const service = new AgentService(prisma as never, undefined, {
820
+ listByAgentId: async (agentId: string) =>
821
+ (await prisma.agentMember.findMany({ where: { agentId } })) as never,
822
+ });
818
823
 
819
824
  const result = await service.getById("a1");
820
825
 
@@ -0,0 +1,29 @@
1
+ /**
2
+ * admin/src/member-id-test-support.ts
3
+ * Shared seed helpers for the ACM-4.1 per-table memberId integration tests.
4
+ * Wipes the four per-user tables plus accounts, then seeds one account with
5
+ * two members and one agent.
6
+ */
7
+
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
9
+
10
+ export async function resetMemberIdFixture(prisma: PrismaClient) {
11
+ await prisma.userNotificationPrefs.deleteMany();
12
+ await prisma.chatThreadWatch.deleteMany();
13
+ await prisma.pushSubscription.deleteMany();
14
+ await prisma.agentMember.deleteMany();
15
+ await prisma.accountMember.deleteMany();
16
+ await prisma.agent.deleteMany();
17
+ await prisma.account.deleteMany();
18
+ const account = await prisma.account.create({ data: { name: "Acme" } });
19
+ const alice = await prisma.accountMember.create({
20
+ data: { accountId: account.id, email: "alice@acme.com", role: "owner" },
21
+ });
22
+ const bob = await prisma.accountMember.create({
23
+ data: { accountId: account.id, email: "bob@acme.com", role: "member" },
24
+ });
25
+ const agent = await prisma.agent.create({
26
+ data: { id: "acm41-agent", name: "acm41-agent" },
27
+ });
28
+ return { alice, bob, agent };
29
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * admin/src/push-service.integration.test.ts (ACM-4.1)
3
+ * ChatThreadWatch and PushSubscription reads/writes key on memberId; email is
4
+ * resolved through the AccountMember lookup. Null-memberId rows are skipped.
5
+ *
6
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import { resetMemberIdFixture } from "./member-id-test-support.ts";
12
+ import { createAdminPrismaClient } from "./prisma-client.ts";
13
+ import { PushService } from "./push-service.ts";
14
+
15
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
16
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
17
+
18
+ const P256DH =
19
+ "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
20
+ const AUTH = "BTBZMqHH6r4Tts7J_aSIgg";
21
+
22
+ describeOrSkip("PushService by memberId (integration)", () => {
23
+ let prisma: PrismaClient;
24
+ let service: PushService;
25
+ let pushed: string[];
26
+ let aliceId: string;
27
+ let bobId: string;
28
+ let agentId: string;
29
+
30
+ beforeEach(async () => {
31
+ prisma = createAdminPrismaClient(TEST_DB as string);
32
+ const f = await resetMemberIdFixture(prisma);
33
+ aliceId = f.alice.id;
34
+ bobId = f.bob.id;
35
+ agentId = f.agent.id;
36
+ pushed = [];
37
+ const fetchImpl = (async (url: string) => {
38
+ pushed.push(url);
39
+ return new Response(null, { status: 201 });
40
+ }) as unknown as typeof fetch;
41
+ service = new PushService(
42
+ prisma as never,
43
+ {
44
+ subject: "mailto:a@x.com",
45
+ publicKey:
46
+ "BAl-hYOXgpZwx-qqRoAapu5iSeHrlcJdy89wjv1NyctfsYSyGKCVO97vvlOVR4h61MROU8CZLAxzQEj8vIFsTaI",
47
+ privateKey: "Sl9AT1gAl_yFgHlTToZkarQRWNYHVTAviDf5osjxXN0",
48
+ },
49
+ fetchImpl,
50
+ "title",
51
+ );
52
+ });
53
+
54
+ afterEach(async () => {
55
+ await prisma.$disconnect();
56
+ });
57
+
58
+ describe("ChatThreadWatch", () => {
59
+ it("recordWatch stamps memberId and is idempotent per user+thread", async () => {
60
+ await service.recordWatch("alice@acme.com", agentId, "t1");
61
+ await service.recordWatch("alice@acme.com", agentId, "t1");
62
+ const rows = await prisma.chatThreadWatch.findMany();
63
+ expect(rows.length).toBe(1);
64
+ expect(rows[0]?.memberId).toBe(aliceId);
65
+ });
66
+
67
+ it("recordWatch for an email with no member still stores the row with null memberId", async () => {
68
+ await service.recordWatch("ghost@nowhere.com", agentId, "t1");
69
+ const rows = await prisma.chatThreadWatch.findMany();
70
+ expect(rows.map((r) => r.memberId)).toEqual([null]);
71
+ });
72
+
73
+ it("notifyThreadReply reaches watchers by memberId and skips null-memberId watches", async () => {
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
+ await prisma.pushSubscription.create({
79
+ data: {
80
+ userEmail: "alice@acme.com",
81
+ memberId: aliceId,
82
+ endpoint: "https://push/alice",
83
+ p256dh: P256DH,
84
+ auth: AUTH,
85
+ },
86
+ });
87
+ await prisma.pushSubscription.create({
88
+ data: {
89
+ userEmail: "bob@acme.com",
90
+ memberId: bobId,
91
+ endpoint: "https://push/bob",
92
+ p256dh: P256DH,
93
+ auth: AUTH,
94
+ },
95
+ });
96
+ const res = await service.notifyThreadReply({
97
+ threadId: "t1",
98
+ agentId,
99
+ title: "t",
100
+ preview: "p",
101
+ });
102
+ expect(res.delivered).toBe(1);
103
+ expect(pushed).toEqual(["https://push/alice"]);
104
+ });
105
+ });
106
+
107
+ describe("PushSubscription", () => {
108
+ it("subscribe stamps memberId; re-subscribe by endpoint updates it", async () => {
109
+ expect(
110
+ await service.subscribe("Alice@Acme.com", "https://p/1", P256DH, AUTH),
111
+ ).toEqual({ ok: true });
112
+ let row = await prisma.pushSubscription.findUniqueOrThrow({
113
+ where: { endpoint: "https://p/1" },
114
+ });
115
+ expect(row.memberId).toBe(aliceId);
116
+ await service.subscribe("bob@acme.com", "https://p/1", P256DH, AUTH);
117
+ row = await prisma.pushSubscription.findUniqueOrThrow({
118
+ where: { endpoint: "https://p/1" },
119
+ });
120
+ expect(row.memberId).toBe(bobId);
121
+ });
122
+
123
+ it("sendToUsers resolves emails to members and skips null-memberId subscriptions", async () => {
124
+ await service.subscribe(
125
+ "alice@acme.com",
126
+ "https://p/alice",
127
+ P256DH,
128
+ AUTH,
129
+ );
130
+ await prisma.pushSubscription.create({
131
+ data: {
132
+ userEmail: "bob@acme.com",
133
+ endpoint: "https://p/legacy",
134
+ p256dh: P256DH,
135
+ auth: AUTH,
136
+ },
137
+ });
138
+ const res = await service.sendToUsers(
139
+ ["alice@acme.com", "bob@acme.com", "ghost@nowhere.com"],
140
+ () => "{}",
141
+ );
142
+ expect(res.delivered).toBe(1);
143
+ expect(pushed).toEqual(["https://p/alice"]);
144
+ });
145
+
146
+ it("unsubscribe is scoped to the owning member", async () => {
147
+ await service.subscribe("alice@acme.com", "https://p/1", P256DH, AUTH);
148
+ await service.unsubscribe("bob@acme.com", "https://p/1");
149
+ expect(await prisma.pushSubscription.count()).toBe(1);
150
+ await service.unsubscribe("alice@acme.com", "https://p/1");
151
+ expect(await prisma.pushSubscription.count()).toBe(0);
152
+ });
153
+ });
154
+ });