@app-vitals/agent-admin 1.74.0 → 1.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@app-vitals/agent-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.75.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/app-vitals/agent.git",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@anthropic-ai/sdk": "0.137.0",
|
|
46
|
-
"@app-vitals/agent-lib": "1.
|
|
46
|
+
"@app-vitals/agent-lib": "1.75.0",
|
|
47
47
|
"@hono/zod-openapi": "^1.0.0",
|
|
48
48
|
"@prisma/adapter-pg": "^7.10.0",
|
|
49
49
|
"@prisma/client": "^7.10.0",
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/scripts/backfill-member-id.ts (ACM-1.2)
|
|
3
|
+
*
|
|
4
|
+
* DATABASE_URL_SHIPWRIGHT_ADMIN=... bun admin/scripts/backfill-member-id.ts [--dry-run] [--overrides overrides.json] [--report report.json]
|
|
5
|
+
*
|
|
6
|
+
* overrides.json: { "alice@old.com": "<AccountMember.id>" }. Overrides win over
|
|
7
|
+
* the automatic email match. --dry-run changes nothing.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { parseFlags } from "@app-vitals/agent-lib/cli-flags";
|
|
12
|
+
import {
|
|
13
|
+
parseOverrides,
|
|
14
|
+
runMemberIdBackfill,
|
|
15
|
+
} from "../src/member-id-backfill.ts";
|
|
16
|
+
import { createAdminPrismaClient } from "../src/prisma-client.ts";
|
|
17
|
+
|
|
18
|
+
const flags = parseFlags(process.argv.slice(2), ["--overrides", "--report"], {
|
|
19
|
+
booleans: ["--dry-run"],
|
|
20
|
+
});
|
|
21
|
+
const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
|
|
22
|
+
if (!url) {
|
|
23
|
+
console.error("DATABASE_URL_SHIPWRIGHT_ADMIN is required");
|
|
24
|
+
process.exit(2);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const prisma = createAdminPrismaClient(url);
|
|
28
|
+
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);
|
|
39
|
+
} finally {
|
|
40
|
+
await prisma.$disconnect();
|
|
41
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/member-id-backfill.integration.test.ts (ACM-1.2)
|
|
3
|
+
* Backfill over a seeded DB: matched, unmapped and overridden rows.
|
|
4
|
+
*
|
|
5
|
+
* Fixture emails mirror the shapes the live tables hold: lowercase matches,
|
|
6
|
+
* mixed-case/whitespace variants of a member email, a departed user with no
|
|
7
|
+
* member, and a renamed address that needs a hand-matched override. They were
|
|
8
|
+
* NOT read from the live database (no access from the build environment);
|
|
9
|
+
* ACM-1.3 (HITL dry-run on prod) is where observed values get reconciled.
|
|
10
|
+
*
|
|
11
|
+
* Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
15
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
16
|
+
import { runMemberIdBackfill } from "./member-id-backfill.ts";
|
|
17
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
18
|
+
|
|
19
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
20
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
21
|
+
|
|
22
|
+
describeOrSkip("memberId backfill (integration)", () => {
|
|
23
|
+
let prisma: PrismaClient;
|
|
24
|
+
let aliceId: string;
|
|
25
|
+
let carolId: string;
|
|
26
|
+
|
|
27
|
+
async function seedRows(email: string, n = 1) {
|
|
28
|
+
const agent = await prisma.agent.upsert({
|
|
29
|
+
where: { id: "bf-agent" },
|
|
30
|
+
update: {},
|
|
31
|
+
create: { id: "bf-agent", name: "bf-agent" },
|
|
32
|
+
});
|
|
33
|
+
await prisma.userNotificationPrefs.create({ data: { userEmail: email } });
|
|
34
|
+
for (let i = 0; i < n; i++) {
|
|
35
|
+
await prisma.chatThreadWatch.create({
|
|
36
|
+
data: {
|
|
37
|
+
userEmail: email,
|
|
38
|
+
threadId: `t-${email}-${i}`,
|
|
39
|
+
agentId: agent.id,
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
await prisma.pushSubscription.create({
|
|
44
|
+
data: {
|
|
45
|
+
userEmail: email,
|
|
46
|
+
endpoint: `ep-${email}`,
|
|
47
|
+
p256dh: "p",
|
|
48
|
+
auth: "a",
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
await prisma.agentMember.create({ data: { agentId: agent.id, email } });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
beforeEach(async () => {
|
|
55
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
56
|
+
await prisma.userNotificationPrefs.deleteMany();
|
|
57
|
+
await prisma.chatThreadWatch.deleteMany();
|
|
58
|
+
await prisma.pushSubscription.deleteMany();
|
|
59
|
+
await prisma.agentMember.deleteMany();
|
|
60
|
+
await prisma.accountMember.deleteMany();
|
|
61
|
+
await prisma.agent.deleteMany();
|
|
62
|
+
await prisma.account.deleteMany();
|
|
63
|
+
const account = await prisma.account.create({ data: { name: "Acme" } });
|
|
64
|
+
aliceId = (
|
|
65
|
+
await prisma.accountMember.create({
|
|
66
|
+
data: { accountId: account.id, email: "alice@acme.com", role: "owner" },
|
|
67
|
+
})
|
|
68
|
+
).id;
|
|
69
|
+
carolId = (
|
|
70
|
+
await prisma.accountMember.create({
|
|
71
|
+
data: {
|
|
72
|
+
accountId: account.id,
|
|
73
|
+
email: "carol@acme.com",
|
|
74
|
+
role: "member",
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
).id;
|
|
78
|
+
await seedRows("alice@acme.com", 2); // matched
|
|
79
|
+
await seedRows("Alice@Acme.com "); // matched after normalization
|
|
80
|
+
await seedRows("gone@old.com", 3); // unmapped
|
|
81
|
+
await seedRows("carol.old@acme.com"); // overridden -> carol
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
afterEach(async () => {
|
|
85
|
+
await prisma.$disconnect();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const memberIds = async () => ({
|
|
89
|
+
prefs: await prisma.userNotificationPrefs.findMany({
|
|
90
|
+
orderBy: { userEmail: "asc" },
|
|
91
|
+
}),
|
|
92
|
+
watches: await prisma.chatThreadWatch.findMany(),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("dry run changes nothing and reports unmapped emails with per-table counts", async () => {
|
|
96
|
+
const report = await runMemberIdBackfill(prisma, { dryRun: true });
|
|
97
|
+
expect(report.unmapped).toEqual([
|
|
98
|
+
{
|
|
99
|
+
email: "carol.old@acme.com",
|
|
100
|
+
counts: {
|
|
101
|
+
UserNotificationPrefs: 1,
|
|
102
|
+
ChatThreadWatch: 1,
|
|
103
|
+
PushSubscription: 1,
|
|
104
|
+
AgentMember: 1,
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
email: "gone@old.com",
|
|
109
|
+
counts: {
|
|
110
|
+
UserNotificationPrefs: 1,
|
|
111
|
+
ChatThreadWatch: 3,
|
|
112
|
+
PushSubscription: 1,
|
|
113
|
+
AgentMember: 1,
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
]);
|
|
117
|
+
const { prefs, watches } = await memberIds();
|
|
118
|
+
expect(prefs.every((p) => p.memberId === null)).toBe(true);
|
|
119
|
+
expect(watches.every((w) => w.memberId === null)).toBe(true);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("apply maps matched rows, leaves unmapped null, and is idempotent", async () => {
|
|
123
|
+
const first = await runMemberIdBackfill(prisma, { dryRun: false });
|
|
124
|
+
expect(first.mapped.ChatThreadWatch).toBe(3); // alice x2 + variant
|
|
125
|
+
const prefs = await prisma.userNotificationPrefs.findMany();
|
|
126
|
+
const idFor = (e: string) => prefs.find((p) => p.userEmail === e)?.memberId;
|
|
127
|
+
expect(idFor("alice@acme.com")).toBe(aliceId);
|
|
128
|
+
expect(idFor("Alice@Acme.com ")).toBe(aliceId);
|
|
129
|
+
expect(idFor("gone@old.com")).toBeNull();
|
|
130
|
+
expect(idFor("carol.old@acme.com")).toBeNull();
|
|
131
|
+
|
|
132
|
+
const second = await runMemberIdBackfill(prisma, { dryRun: false });
|
|
133
|
+
expect(Object.values(second.mapped).every((n) => n === 0)).toBe(true);
|
|
134
|
+
expect(second.unmapped).toEqual(first.unmapped);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("overrides take precedence over the automatic match and apply is idempotent", async () => {
|
|
138
|
+
const overrides = new Map([
|
|
139
|
+
["carol.old@acme.com", carolId],
|
|
140
|
+
["alice@acme.com", carolId], // beats the automatic alice match
|
|
141
|
+
]);
|
|
142
|
+
await runMemberIdBackfill(prisma, { dryRun: false });
|
|
143
|
+
await runMemberIdBackfill(prisma, { dryRun: false, overrides });
|
|
144
|
+
const again = await runMemberIdBackfill(prisma, {
|
|
145
|
+
dryRun: false,
|
|
146
|
+
overrides,
|
|
147
|
+
});
|
|
148
|
+
expect(Object.values(again.mapped).every((n) => n === 0)).toBe(true);
|
|
149
|
+
|
|
150
|
+
const prefs = await prisma.userNotificationPrefs.findMany();
|
|
151
|
+
const idFor = (e: string) => prefs.find((p) => p.userEmail === e)?.memberId;
|
|
152
|
+
expect(idFor("carol.old@acme.com")).toBe(carolId);
|
|
153
|
+
expect(idFor("alice@acme.com")).toBe(carolId);
|
|
154
|
+
// overrides are keyed on the normalized email, so the variant follows
|
|
155
|
+
expect(idFor("Alice@Acme.com ")).toBe(carolId);
|
|
156
|
+
expect(again.unmapped.map((u) => u.email)).toEqual(["gone@old.com"]);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("rejects an override naming an unknown member id", async () => {
|
|
160
|
+
await expect(
|
|
161
|
+
runMemberIdBackfill(prisma, {
|
|
162
|
+
dryRun: true,
|
|
163
|
+
overrides: new Map([["x@y.z", "nope"]]),
|
|
164
|
+
}),
|
|
165
|
+
).rejects.toThrow(/unknown member id/);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/member-id-backfill.ts
|
|
3
|
+
* ACM-1.2: maps the email-keyed per-user rows (UserNotificationPrefs,
|
|
4
|
+
* ChatThreadWatch, PushSubscription, AgentMember) to AccountMember.id.
|
|
5
|
+
*
|
|
6
|
+
* - Match order: overrides (email -> member id) first, then the automatic
|
|
7
|
+
* match on the normalized email against AccountMember.email.
|
|
8
|
+
* - Dry run writes nothing and reports every distinct email with no match,
|
|
9
|
+
* with its row count per table.
|
|
10
|
+
* - Apply sets memberId on matched rows (only where it differs from the
|
|
11
|
+
* target, so a re-run is a no-op) and leaves unmapped rows null.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
15
|
+
import { normalizeEmail } from "./account-email.ts";
|
|
16
|
+
|
|
17
|
+
export const BACKFILL_TABLES = [
|
|
18
|
+
"UserNotificationPrefs",
|
|
19
|
+
"ChatThreadWatch",
|
|
20
|
+
"PushSubscription",
|
|
21
|
+
"AgentMember",
|
|
22
|
+
] as const;
|
|
23
|
+
export type BackfillTable = (typeof BACKFILL_TABLES)[number];
|
|
24
|
+
|
|
25
|
+
export interface UnmappedEmail {
|
|
26
|
+
email: string;
|
|
27
|
+
/** Row counts per table (only tables with at least one such row). */
|
|
28
|
+
counts: Partial<Record<BackfillTable, number>>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface MemberIdBackfillReport {
|
|
32
|
+
dryRun: boolean;
|
|
33
|
+
/** Rows set (apply) or that would be set (dry run), per table. */
|
|
34
|
+
mapped: Record<BackfillTable, number>;
|
|
35
|
+
unmapped: UnmappedEmail[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Parses an overrides file body: a JSON object of email -> AccountMember.id. */
|
|
39
|
+
export function parseOverrides(json: string): Map<string, string> {
|
|
40
|
+
const raw: unknown = JSON.parse(json);
|
|
41
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
42
|
+
throw new Error("overrides must be a JSON object of email -> member id");
|
|
43
|
+
}
|
|
44
|
+
const out = new Map<string, string>();
|
|
45
|
+
for (const [email, id] of Object.entries(raw)) {
|
|
46
|
+
if (typeof id !== "string" || id === "") {
|
|
47
|
+
throw new Error(`override for ${email} must be a non-empty member id`);
|
|
48
|
+
}
|
|
49
|
+
out.set(normalizeEmail(email), id);
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface TableAccess {
|
|
55
|
+
distinct(): Promise<{ email: string; count: number }[]>;
|
|
56
|
+
/** Sets memberId on rows keyed by this exact email value that don't already have it. */
|
|
57
|
+
assign(email: string, memberId: string): Promise<number>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function tableAccess(prisma: PrismaClient): Record<BackfillTable, TableAccess> {
|
|
61
|
+
const notId = (memberId: string) => ({
|
|
62
|
+
OR: [{ memberId: null }, { memberId: { not: memberId } }],
|
|
63
|
+
});
|
|
64
|
+
return {
|
|
65
|
+
UserNotificationPrefs: {
|
|
66
|
+
distinct: async () =>
|
|
67
|
+
(
|
|
68
|
+
await prisma.userNotificationPrefs.groupBy({
|
|
69
|
+
by: ["userEmail"],
|
|
70
|
+
_count: { _all: true },
|
|
71
|
+
})
|
|
72
|
+
).map((g) => ({ email: g.userEmail, count: g._count._all })),
|
|
73
|
+
assign: async (email, memberId) =>
|
|
74
|
+
(
|
|
75
|
+
await prisma.userNotificationPrefs.updateMany({
|
|
76
|
+
where: { userEmail: email, ...notId(memberId) },
|
|
77
|
+
data: { memberId },
|
|
78
|
+
})
|
|
79
|
+
).count,
|
|
80
|
+
},
|
|
81
|
+
ChatThreadWatch: {
|
|
82
|
+
distinct: async () =>
|
|
83
|
+
(
|
|
84
|
+
await prisma.chatThreadWatch.groupBy({
|
|
85
|
+
by: ["userEmail"],
|
|
86
|
+
_count: { _all: true },
|
|
87
|
+
})
|
|
88
|
+
).map((g) => ({ email: g.userEmail, count: g._count._all })),
|
|
89
|
+
assign: async (email, memberId) =>
|
|
90
|
+
(
|
|
91
|
+
await prisma.chatThreadWatch.updateMany({
|
|
92
|
+
where: { userEmail: email, ...notId(memberId) },
|
|
93
|
+
data: { memberId },
|
|
94
|
+
})
|
|
95
|
+
).count,
|
|
96
|
+
},
|
|
97
|
+
PushSubscription: {
|
|
98
|
+
distinct: async () =>
|
|
99
|
+
(
|
|
100
|
+
await prisma.pushSubscription.groupBy({
|
|
101
|
+
by: ["userEmail"],
|
|
102
|
+
_count: { _all: true },
|
|
103
|
+
})
|
|
104
|
+
).map((g) => ({ email: g.userEmail, count: g._count._all })),
|
|
105
|
+
assign: async (email, memberId) =>
|
|
106
|
+
(
|
|
107
|
+
await prisma.pushSubscription.updateMany({
|
|
108
|
+
where: { userEmail: email, ...notId(memberId) },
|
|
109
|
+
data: { memberId },
|
|
110
|
+
})
|
|
111
|
+
).count,
|
|
112
|
+
},
|
|
113
|
+
AgentMember: {
|
|
114
|
+
distinct: async () =>
|
|
115
|
+
(
|
|
116
|
+
await prisma.agentMember.groupBy({
|
|
117
|
+
by: ["email"],
|
|
118
|
+
_count: { _all: true },
|
|
119
|
+
})
|
|
120
|
+
).map((g) => ({ email: g.email, count: g._count._all })),
|
|
121
|
+
assign: async (email, memberId) =>
|
|
122
|
+
(
|
|
123
|
+
await prisma.agentMember.updateMany({
|
|
124
|
+
where: { email, ...notId(memberId) },
|
|
125
|
+
data: { memberId },
|
|
126
|
+
})
|
|
127
|
+
).count,
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function runMemberIdBackfill(
|
|
133
|
+
prisma: PrismaClient,
|
|
134
|
+
opts: { dryRun: boolean; overrides?: Map<string, string> },
|
|
135
|
+
): Promise<MemberIdBackfillReport> {
|
|
136
|
+
const overrides = opts.overrides ?? new Map<string, string>();
|
|
137
|
+
|
|
138
|
+
const members = await prisma.accountMember.findMany({
|
|
139
|
+
select: { id: true, email: true },
|
|
140
|
+
});
|
|
141
|
+
const byEmail = new Map(members.map((m) => [normalizeEmail(m.email), m.id]));
|
|
142
|
+
const memberIds = new Set(members.map((m) => m.id));
|
|
143
|
+
for (const [email, id] of overrides) {
|
|
144
|
+
if (!memberIds.has(id)) {
|
|
145
|
+
throw new Error(`override for ${email} names unknown member id ${id}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const tables = tableAccess(prisma);
|
|
150
|
+
const mapped = Object.fromEntries(
|
|
151
|
+
BACKFILL_TABLES.map((t) => [t, 0]),
|
|
152
|
+
) as Record<BackfillTable, number>;
|
|
153
|
+
const unmapped = new Map<string, UnmappedEmail>();
|
|
154
|
+
|
|
155
|
+
for (const table of BACKFILL_TABLES) {
|
|
156
|
+
for (const { email, count } of await tables[table].distinct()) {
|
|
157
|
+
const key = normalizeEmail(email);
|
|
158
|
+
const memberId = overrides.get(key) ?? byEmail.get(key);
|
|
159
|
+
if (!memberId) {
|
|
160
|
+
const entry = unmapped.get(key) ?? { email: key, counts: {} };
|
|
161
|
+
entry.counts[table] = (entry.counts[table] ?? 0) + count;
|
|
162
|
+
unmapped.set(key, entry);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (opts.dryRun) {
|
|
166
|
+
mapped[table] += count;
|
|
167
|
+
} else {
|
|
168
|
+
mapped[table] += await tables[table].assign(email, memberId);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
dryRun: opts.dryRun,
|
|
175
|
+
mapped,
|
|
176
|
+
unmapped: [...unmapped.values()].sort((a, b) =>
|
|
177
|
+
a.email.localeCompare(b.email),
|
|
178
|
+
),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import { parseOverrides } from "./member-id-backfill.ts";
|
|
3
|
+
|
|
4
|
+
describe("parseOverrides", () => {
|
|
5
|
+
it("normalizes email keys", () => {
|
|
6
|
+
expect(parseOverrides('{" Bob@X.com ":"m1"}').get("bob@x.com")).toBe("m1");
|
|
7
|
+
});
|
|
8
|
+
it("rejects non-object and non-string values", () => {
|
|
9
|
+
expect(() => parseOverrides("[]")).toThrow();
|
|
10
|
+
expect(() => parseOverrides('{"a@b.c":1}')).toThrow();
|
|
11
|
+
});
|
|
12
|
+
});
|