@app-vitals/agent-admin 1.108.1 → 1.109.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/Dockerfile +4 -0
- package/account-move.example.json +22 -0
- package/openapi.platform.json +5 -0
- package/package.json +2 -2
- package/src/account-agent-create.ts +18 -9
- package/src/account-agent-create.unit.test.ts +12 -14
- package/src/account-move.integration.test.ts +594 -0
- package/src/account-move.ts +867 -0
- package/src/account-move.unit.test.ts +206 -0
- package/src/admin-local-agent.smoke.test.ts +65 -0
- package/src/admin-ui-account-pages.ts +2 -3
- package/src/admin-ui-account-pages.unit.test.ts +5 -3
- package/src/admin-ui-pages.ts +16 -5
- package/src/admin-ui-pages.unit.test.ts +25 -20
- package/src/admin-ui.smoke.test.ts +6 -7
- package/src/admin-ui.ts +39 -27
- package/src/agents-api.smoke.test.ts +106 -8
- package/src/agents-api.ts +5 -3
- package/src/agents.integration.test.ts +112 -2
- package/src/agents.ts +37 -6
- package/src/github-enterprise-isolation.unit.test.ts +17 -0
- package/src/move-accounts.ts +201 -0
- package/src/openapi-schemas.ts +6 -0
- package/src/self-serve-config.ts +8 -8
- package/src/self-serve-config.unit.test.ts +3 -10
|
@@ -0,0 +1,867 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/account-move.ts
|
|
3
|
+
*
|
|
4
|
+
* multi-account-2.6: moves agents, members and deployment-wide settings
|
|
5
|
+
* between accounts in the admin database, driven by a mapping file kept
|
|
6
|
+
* outside the repo. Members move in place (same AccountMember.id), so every
|
|
7
|
+
* row keyed by the member id (AgentMember, ChatThreadWatch, PushSubscription,
|
|
8
|
+
* UserNotificationPrefs) keeps pointing at them.
|
|
9
|
+
*
|
|
10
|
+
* planMove() reads only. applyMove() re-plans inside one serializable
|
|
11
|
+
* transaction and refuses (MoveRefusedError, nothing written) on any unclear
|
|
12
|
+
* input. Every change it makes is recorded in a receipt; planReverse() and
|
|
13
|
+
* applyReverse() put back exactly the receipt's changes that are still in the
|
|
14
|
+
* state the move left them in.
|
|
15
|
+
*
|
|
16
|
+
* The CLI is move-accounts.ts; the runbook is docs/account-move.md.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
21
|
+
import type { PrismaTransactionClient } from "./prisma-tx.ts";
|
|
22
|
+
|
|
23
|
+
/** Unusable input (bad JSON shape); exit code 2. */
|
|
24
|
+
export class MoveInputError extends Error {}
|
|
25
|
+
|
|
26
|
+
/** Input that is valid but unclear against the database; nothing is written. */
|
|
27
|
+
export class MoveRefusedError extends Error {
|
|
28
|
+
constructor(readonly reasons: string[]) {
|
|
29
|
+
super(`refused: ${reasons.join("; ")}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ─── Mapping ──────────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
export const SETTING_KINDS = [
|
|
36
|
+
"githubLookupApp",
|
|
37
|
+
"githubInstallerApp",
|
|
38
|
+
"slackConfigToken",
|
|
39
|
+
"agentTemplate",
|
|
40
|
+
] as const;
|
|
41
|
+
export type SettingKind = (typeof SETTING_KINDS)[number];
|
|
42
|
+
|
|
43
|
+
const SETTING_LABELS: Record<SettingKind, string> = {
|
|
44
|
+
githubLookupApp: "GitHub lookup app",
|
|
45
|
+
githubInstallerApp: "GitHub installer app",
|
|
46
|
+
slackConfigToken: "Slack config token",
|
|
47
|
+
agentTemplate: "agent template",
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const ROLES = ["owner", "member"] as const;
|
|
51
|
+
export type MemberRole = (typeof ROLES)[number];
|
|
52
|
+
|
|
53
|
+
const ACCOUNT_ID = z
|
|
54
|
+
.string()
|
|
55
|
+
.regex(/^[A-Za-z0-9._-]+$/, "account ids use letters, digits, . _ -");
|
|
56
|
+
|
|
57
|
+
const MappingSchema = z
|
|
58
|
+
.object({
|
|
59
|
+
accounts: z
|
|
60
|
+
.array(
|
|
61
|
+
z
|
|
62
|
+
.object({
|
|
63
|
+
id: ACCOUNT_ID,
|
|
64
|
+
name: z.string().trim().min(1).optional(),
|
|
65
|
+
maxAgents: z.number().int().min(0).optional(),
|
|
66
|
+
agents: z.array(z.string().trim().min(1)).default([]),
|
|
67
|
+
members: z
|
|
68
|
+
.array(
|
|
69
|
+
z
|
|
70
|
+
.object({
|
|
71
|
+
email: z.string().trim().min(1),
|
|
72
|
+
role: z.enum(ROLES).default("member"),
|
|
73
|
+
})
|
|
74
|
+
.strict(),
|
|
75
|
+
)
|
|
76
|
+
.default([]),
|
|
77
|
+
})
|
|
78
|
+
.strict(),
|
|
79
|
+
)
|
|
80
|
+
.default([]),
|
|
81
|
+
settings: z
|
|
82
|
+
.array(
|
|
83
|
+
z
|
|
84
|
+
.object({
|
|
85
|
+
setting: z.enum(SETTING_KINDS),
|
|
86
|
+
specialty: z.string().trim().min(1).nullable().optional(),
|
|
87
|
+
toAccountId: ACCOUNT_ID,
|
|
88
|
+
})
|
|
89
|
+
.strict()
|
|
90
|
+
.refine(
|
|
91
|
+
(s) => s.setting === "agentTemplate" || s.specialty === undefined,
|
|
92
|
+
{ message: "specialty is only for agentTemplate" },
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
.default([]),
|
|
96
|
+
})
|
|
97
|
+
.strict();
|
|
98
|
+
|
|
99
|
+
export type AccountMoveMapping = z.infer<typeof MappingSchema>;
|
|
100
|
+
|
|
101
|
+
function zodMessage(err: z.ZodError): string {
|
|
102
|
+
return err.issues
|
|
103
|
+
.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`)
|
|
104
|
+
.join("; ");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function parseMapping(raw: unknown): AccountMoveMapping {
|
|
108
|
+
const parsed = MappingSchema.safeParse(raw);
|
|
109
|
+
if (!parsed.success) {
|
|
110
|
+
throw new MoveInputError(`invalid mapping: ${zodMessage(parsed.error)}`);
|
|
111
|
+
}
|
|
112
|
+
const m = parsed.data;
|
|
113
|
+
for (const a of m.accounts) {
|
|
114
|
+
for (const mem of a.members) mem.email = mem.email.toLowerCase();
|
|
115
|
+
}
|
|
116
|
+
return m;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ─── Changes, plans and receipts ──────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
interface AccountFields {
|
|
122
|
+
name: string;
|
|
123
|
+
maxAgents: number;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type Change =
|
|
127
|
+
| {
|
|
128
|
+
type: "createAccount";
|
|
129
|
+
accountId: string;
|
|
130
|
+
name: string;
|
|
131
|
+
maxAgents: number;
|
|
132
|
+
}
|
|
133
|
+
| {
|
|
134
|
+
type: "updateAccount";
|
|
135
|
+
accountId: string;
|
|
136
|
+
from: AccountFields;
|
|
137
|
+
to: AccountFields;
|
|
138
|
+
}
|
|
139
|
+
| {
|
|
140
|
+
type: "moveMember";
|
|
141
|
+
memberId: string;
|
|
142
|
+
email: string;
|
|
143
|
+
from: { accountId: string; role: string };
|
|
144
|
+
to: { accountId: string; role: string };
|
|
145
|
+
}
|
|
146
|
+
| {
|
|
147
|
+
type: "moveAgent";
|
|
148
|
+
agentId: string;
|
|
149
|
+
name: string;
|
|
150
|
+
from: string | null;
|
|
151
|
+
to: string | null;
|
|
152
|
+
}
|
|
153
|
+
| {
|
|
154
|
+
type: "moveSetting";
|
|
155
|
+
setting: SettingKind;
|
|
156
|
+
specialty: string | null;
|
|
157
|
+
rowId: string;
|
|
158
|
+
from: string | null;
|
|
159
|
+
to: string | null;
|
|
160
|
+
}
|
|
161
|
+
| { type: "deleteAccount"; accountId: string };
|
|
162
|
+
|
|
163
|
+
export interface MovePlan {
|
|
164
|
+
changes: Change[];
|
|
165
|
+
/** Notes that do not block the move (e.g. an account left with no owner). */
|
|
166
|
+
warnings: string[];
|
|
167
|
+
/** Receipt changes a reverse leaves alone because they changed since. */
|
|
168
|
+
skipped: string[];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export interface MoveReceipt {
|
|
172
|
+
kind: "admin-account-move";
|
|
173
|
+
version: 1;
|
|
174
|
+
appliedAt: string;
|
|
175
|
+
changes: Change[];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const ChangeSchema: z.ZodType<Change> = z.union([
|
|
179
|
+
z.object({
|
|
180
|
+
type: z.literal("createAccount"),
|
|
181
|
+
accountId: z.string(),
|
|
182
|
+
name: z.string(),
|
|
183
|
+
maxAgents: z.number().int(),
|
|
184
|
+
}),
|
|
185
|
+
z.object({
|
|
186
|
+
type: z.literal("updateAccount"),
|
|
187
|
+
accountId: z.string(),
|
|
188
|
+
from: z.object({ name: z.string(), maxAgents: z.number().int() }),
|
|
189
|
+
to: z.object({ name: z.string(), maxAgents: z.number().int() }),
|
|
190
|
+
}),
|
|
191
|
+
z.object({
|
|
192
|
+
type: z.literal("moveMember"),
|
|
193
|
+
memberId: z.string(),
|
|
194
|
+
email: z.string(),
|
|
195
|
+
from: z.object({ accountId: z.string(), role: z.string() }),
|
|
196
|
+
to: z.object({ accountId: z.string(), role: z.string() }),
|
|
197
|
+
}),
|
|
198
|
+
z.object({
|
|
199
|
+
type: z.literal("moveAgent"),
|
|
200
|
+
agentId: z.string(),
|
|
201
|
+
name: z.string(),
|
|
202
|
+
from: z.string().nullable(),
|
|
203
|
+
to: z.string().nullable(),
|
|
204
|
+
}),
|
|
205
|
+
z.object({
|
|
206
|
+
type: z.literal("moveSetting"),
|
|
207
|
+
setting: z.enum(SETTING_KINDS),
|
|
208
|
+
specialty: z.string().nullable(),
|
|
209
|
+
rowId: z.string(),
|
|
210
|
+
from: z.string().nullable(),
|
|
211
|
+
to: z.string().nullable(),
|
|
212
|
+
}),
|
|
213
|
+
z.object({ type: z.literal("deleteAccount"), accountId: z.string() }),
|
|
214
|
+
]);
|
|
215
|
+
|
|
216
|
+
const ReceiptSchema = z.object({
|
|
217
|
+
kind: z.literal("admin-account-move"),
|
|
218
|
+
version: z.literal(1),
|
|
219
|
+
appliedAt: z.string(),
|
|
220
|
+
changes: z.array(ChangeSchema),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
export function parseReceipt(raw: unknown): MoveReceipt {
|
|
224
|
+
const parsed = ReceiptSchema.safeParse(raw);
|
|
225
|
+
if (!parsed.success) {
|
|
226
|
+
throw new MoveInputError(`invalid receipt: ${zodMessage(parsed.error)}`);
|
|
227
|
+
}
|
|
228
|
+
return parsed.data as MoveReceipt;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ─── Settings tables ──────────────────────────────────────────────────────────
|
|
232
|
+
|
|
233
|
+
type Db = PrismaTransactionClient;
|
|
234
|
+
|
|
235
|
+
interface SettingRow {
|
|
236
|
+
id: string;
|
|
237
|
+
accountId: string | null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The setting row for `scope` (null = deployment-wide), if any. */
|
|
241
|
+
async function findSetting(
|
|
242
|
+
db: Db,
|
|
243
|
+
kind: SettingKind,
|
|
244
|
+
specialty: string | null,
|
|
245
|
+
accountId: string | null,
|
|
246
|
+
): Promise<SettingRow | null> {
|
|
247
|
+
const select = { id: true, accountId: true } as const;
|
|
248
|
+
switch (kind) {
|
|
249
|
+
case "githubLookupApp":
|
|
250
|
+
case "githubInstallerApp":
|
|
251
|
+
return db.gitHubEnterpriseApp.findFirst({
|
|
252
|
+
where: {
|
|
253
|
+
accountId,
|
|
254
|
+
role: kind === "githubLookupApp" ? "lookup" : "installer",
|
|
255
|
+
},
|
|
256
|
+
select,
|
|
257
|
+
});
|
|
258
|
+
case "slackConfigToken":
|
|
259
|
+
return db.slackConfigToken.findFirst({ where: { accountId }, select });
|
|
260
|
+
case "agentTemplate":
|
|
261
|
+
return db.agentTemplate.findFirst({
|
|
262
|
+
where: { accountId, specialty },
|
|
263
|
+
select,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function findSettingById(
|
|
269
|
+
db: Db,
|
|
270
|
+
kind: SettingKind,
|
|
271
|
+
id: string,
|
|
272
|
+
): Promise<SettingRow | null> {
|
|
273
|
+
const select = { id: true, accountId: true } as const;
|
|
274
|
+
switch (kind) {
|
|
275
|
+
case "githubLookupApp":
|
|
276
|
+
case "githubInstallerApp":
|
|
277
|
+
return db.gitHubEnterpriseApp.findUnique({ where: { id }, select });
|
|
278
|
+
case "slackConfigToken":
|
|
279
|
+
return db.slackConfigToken.findUnique({ where: { id }, select });
|
|
280
|
+
case "agentTemplate":
|
|
281
|
+
return db.agentTemplate.findUnique({ where: { id }, select });
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function settingLabel(kind: SettingKind, specialty: string | null): string {
|
|
286
|
+
if (kind !== "agentTemplate") return SETTING_LABELS[kind];
|
|
287
|
+
return specialty === null
|
|
288
|
+
? "agent template (any specialty)"
|
|
289
|
+
: `agent template for specialty "${specialty}"`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function scopeLabel(accountId: string | null): string {
|
|
293
|
+
return accountId === null ? "deployment-wide" : `account "${accountId}"`;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ─── Planning a move ──────────────────────────────────────────────────────────
|
|
297
|
+
|
|
298
|
+
export async function planMove(
|
|
299
|
+
db: Db,
|
|
300
|
+
mapping: AccountMoveMapping,
|
|
301
|
+
): Promise<MovePlan> {
|
|
302
|
+
const reasons: string[] = [];
|
|
303
|
+
const warnings: string[] = [];
|
|
304
|
+
const creates: Change[] = [];
|
|
305
|
+
const updates: Change[] = [];
|
|
306
|
+
const memberChanges: Extract<Change, { type: "moveMember" }>[] = [];
|
|
307
|
+
const agentChanges: Extract<Change, { type: "moveAgent" }>[] = [];
|
|
308
|
+
const settingChanges: Change[] = [];
|
|
309
|
+
|
|
310
|
+
// Accounts.
|
|
311
|
+
const accountIds = new Set<string>();
|
|
312
|
+
for (const a of mapping.accounts) {
|
|
313
|
+
if (accountIds.has(a.id)) {
|
|
314
|
+
reasons.push(`account "${a.id}" is listed more than once`);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
accountIds.add(a.id);
|
|
318
|
+
const existing = await db.account.findUnique({ where: { id: a.id } });
|
|
319
|
+
if (!existing) {
|
|
320
|
+
if (a.name === undefined) {
|
|
321
|
+
reasons.push(
|
|
322
|
+
`account "${a.id}" does not exist and has no name; add "name" to create it`,
|
|
323
|
+
);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
creates.push({
|
|
327
|
+
type: "createAccount",
|
|
328
|
+
accountId: a.id,
|
|
329
|
+
name: a.name,
|
|
330
|
+
maxAgents: a.maxAgents ?? 0,
|
|
331
|
+
});
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const to = {
|
|
335
|
+
name: a.name ?? existing.name,
|
|
336
|
+
maxAgents: a.maxAgents ?? existing.maxAgents,
|
|
337
|
+
};
|
|
338
|
+
if (to.name !== existing.name || to.maxAgents !== existing.maxAgents) {
|
|
339
|
+
updates.push({
|
|
340
|
+
type: "updateAccount",
|
|
341
|
+
accountId: a.id,
|
|
342
|
+
from: { name: existing.name, maxAgents: existing.maxAgents },
|
|
343
|
+
to,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Members: each email in at most one account, and it must already exist.
|
|
349
|
+
const memberTargets = new Map<string, string[]>();
|
|
350
|
+
for (const a of mapping.accounts) {
|
|
351
|
+
for (const m of a.members) {
|
|
352
|
+
memberTargets.set(m.email, [...(memberTargets.get(m.email) ?? []), a.id]);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
for (const [email, targets] of memberTargets) {
|
|
356
|
+
if (targets.length > 1) {
|
|
357
|
+
reasons.push(
|
|
358
|
+
`member "${email}" is listed in ${targets.length} accounts (${targets.join(", ")}); a member belongs to one account`,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
for (const a of mapping.accounts) {
|
|
363
|
+
for (const m of a.members) {
|
|
364
|
+
if ((memberTargets.get(m.email) ?? []).length > 1) continue;
|
|
365
|
+
const member = await db.accountMember.findUnique({
|
|
366
|
+
where: { email: m.email },
|
|
367
|
+
});
|
|
368
|
+
if (!member) {
|
|
369
|
+
reasons.push(
|
|
370
|
+
`unknown member "${m.email}"; only existing members move (invite new people instead)`,
|
|
371
|
+
);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (member.accountId !== a.id || member.role !== m.role) {
|
|
375
|
+
memberChanges.push({
|
|
376
|
+
type: "moveMember",
|
|
377
|
+
memberId: member.id,
|
|
378
|
+
email: member.email,
|
|
379
|
+
from: { accountId: member.accountId, role: member.role },
|
|
380
|
+
to: { accountId: a.id, role: m.role },
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Agents: by id, else by unique name; each in at most one account.
|
|
387
|
+
const agentTargets = new Map<
|
|
388
|
+
string,
|
|
389
|
+
{ ref: string; name: string; from: string | null; to: string[] }
|
|
390
|
+
>();
|
|
391
|
+
for (const a of mapping.accounts) {
|
|
392
|
+
for (const ref of a.agents) {
|
|
393
|
+
const found = await db.agent.findMany({
|
|
394
|
+
where: { OR: [{ id: ref }, { name: ref }] },
|
|
395
|
+
select: { id: true, name: true, accountId: true },
|
|
396
|
+
});
|
|
397
|
+
const byId = found.find((x) => x.id === ref);
|
|
398
|
+
const agent = byId ?? (found.length === 1 ? found[0] : undefined);
|
|
399
|
+
if (!agent) {
|
|
400
|
+
reasons.push(
|
|
401
|
+
found.length === 0
|
|
402
|
+
? `unknown agent "${ref}"`
|
|
403
|
+
: `agent "${ref}" matches ${found.length} agents by name; use the agent id`,
|
|
404
|
+
);
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
const entry = agentTargets.get(agent.id) ?? {
|
|
408
|
+
ref,
|
|
409
|
+
name: agent.name,
|
|
410
|
+
from: agent.accountId,
|
|
411
|
+
to: [],
|
|
412
|
+
};
|
|
413
|
+
entry.to.push(a.id);
|
|
414
|
+
agentTargets.set(agent.id, entry);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
for (const [agentId, t] of agentTargets) {
|
|
418
|
+
if (t.to.length > 1) {
|
|
419
|
+
reasons.push(
|
|
420
|
+
`agent "${t.name}" (${agentId}) is listed in ${t.to.length} accounts (${t.to.join(", ")})`,
|
|
421
|
+
);
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const to = t.to[0] as string;
|
|
425
|
+
if (t.from !== to) {
|
|
426
|
+
agentChanges.push({
|
|
427
|
+
type: "moveAgent",
|
|
428
|
+
agentId,
|
|
429
|
+
name: t.name,
|
|
430
|
+
from: t.from,
|
|
431
|
+
to,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Settings: move the deployment-wide row; refuse if the target has its own.
|
|
437
|
+
const settingKeys = new Set<string>();
|
|
438
|
+
for (const s of mapping.settings) {
|
|
439
|
+
const specialty = s.specialty ?? null;
|
|
440
|
+
const label = settingLabel(s.setting, specialty);
|
|
441
|
+
const key = `${s.setting}|${specialty ?? ""}`;
|
|
442
|
+
if (settingKeys.has(key)) {
|
|
443
|
+
reasons.push(`${label} is listed more than once`);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
settingKeys.add(key);
|
|
447
|
+
if (
|
|
448
|
+
!accountIds.has(s.toAccountId) &&
|
|
449
|
+
!(await db.account.findUnique({ where: { id: s.toAccountId } }))
|
|
450
|
+
) {
|
|
451
|
+
reasons.push(
|
|
452
|
+
`account "${s.toAccountId}" does not exist (needed for the ${label}); add it to "accounts"`,
|
|
453
|
+
);
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
const global = await findSetting(db, s.setting, specialty, null);
|
|
457
|
+
const target = await findSetting(db, s.setting, specialty, s.toAccountId);
|
|
458
|
+
if (global && target) {
|
|
459
|
+
reasons.push(
|
|
460
|
+
`account "${s.toAccountId}" already has its own ${label}; remove one of the two before moving the deployment-wide one`,
|
|
461
|
+
);
|
|
462
|
+
} else if (global) {
|
|
463
|
+
settingChanges.push({
|
|
464
|
+
type: "moveSetting",
|
|
465
|
+
setting: s.setting,
|
|
466
|
+
specialty,
|
|
467
|
+
rowId: global.id,
|
|
468
|
+
from: null,
|
|
469
|
+
to: s.toAccountId,
|
|
470
|
+
});
|
|
471
|
+
} else if (!target) {
|
|
472
|
+
reasons.push(`no deployment-wide ${label} to move`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
if (reasons.length > 0) throw new MoveRefusedError(reasons);
|
|
477
|
+
|
|
478
|
+
warnings.push(
|
|
479
|
+
...(await moveWarnings(db, memberChanges, agentChanges, mapping)),
|
|
480
|
+
);
|
|
481
|
+
return {
|
|
482
|
+
changes: [
|
|
483
|
+
...creates,
|
|
484
|
+
...updates,
|
|
485
|
+
...memberChanges,
|
|
486
|
+
...agentChanges,
|
|
487
|
+
...settingChanges,
|
|
488
|
+
],
|
|
489
|
+
warnings,
|
|
490
|
+
skipped: [],
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Non-blocking notes about the state the move leaves behind. */
|
|
495
|
+
async function moveWarnings(
|
|
496
|
+
db: Db,
|
|
497
|
+
members: Extract<Change, { type: "moveMember" }>[],
|
|
498
|
+
agents: Extract<Change, { type: "moveAgent" }>[],
|
|
499
|
+
mapping: AccountMoveMapping,
|
|
500
|
+
): Promise<string[]> {
|
|
501
|
+
const warnings: string[] = [];
|
|
502
|
+
const finalAgentAccount = new Map(agents.map((c) => [c.agentId, c.to]));
|
|
503
|
+
const movedIds = new Set(members.map((c) => c.memberId));
|
|
504
|
+
|
|
505
|
+
// Accounts that lose their last owner.
|
|
506
|
+
const touched = new Set(members.map((c) => c.from.accountId));
|
|
507
|
+
for (const accountId of touched) {
|
|
508
|
+
const owners = await db.accountMember.findMany({
|
|
509
|
+
where: { accountId, role: "owner" },
|
|
510
|
+
select: { id: true },
|
|
511
|
+
});
|
|
512
|
+
const staying = owners.filter((o) => !movedIds.has(o.id)).length;
|
|
513
|
+
const arriving = members.filter(
|
|
514
|
+
(c) => c.to.accountId === accountId && c.to.role === "owner",
|
|
515
|
+
).length;
|
|
516
|
+
if (owners.length > 0 && staying + arriving === 0) {
|
|
517
|
+
warnings.push(`account "${accountId}" is left with no owner`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Agent access a moved member keeps on agents outside their new account.
|
|
522
|
+
for (const c of members) {
|
|
523
|
+
if (c.from.accountId === c.to.accountId) continue;
|
|
524
|
+
const grants = await db.agentMember.findMany({
|
|
525
|
+
where: { memberId: c.memberId },
|
|
526
|
+
select: { agent: { select: { id: true, accountId: true } } },
|
|
527
|
+
});
|
|
528
|
+
const outside = grants.filter((g) => {
|
|
529
|
+
const final = finalAgentAccount.has(g.agent.id)
|
|
530
|
+
? finalAgentAccount.get(g.agent.id)
|
|
531
|
+
: g.agent.accountId;
|
|
532
|
+
return final !== c.to.accountId;
|
|
533
|
+
}).length;
|
|
534
|
+
if (outside > 0) {
|
|
535
|
+
warnings.push(
|
|
536
|
+
`member "${c.email}" keeps access to ${outside} agent(s) outside account "${c.to.accountId}"`,
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// Agent limits only block new agents; say when an account starts over.
|
|
542
|
+
for (const a of mapping.accounts) {
|
|
543
|
+
const max =
|
|
544
|
+
a.maxAgents ??
|
|
545
|
+
(await db.account.findUnique({ where: { id: a.id } }))?.maxAgents ??
|
|
546
|
+
0;
|
|
547
|
+
const existing = await db.agent.findMany({
|
|
548
|
+
where: { accountId: a.id },
|
|
549
|
+
select: { id: true },
|
|
550
|
+
});
|
|
551
|
+
const ids = new Set(existing.map((x) => x.id));
|
|
552
|
+
for (const [id, to] of finalAgentAccount) {
|
|
553
|
+
if (to === a.id) ids.add(id);
|
|
554
|
+
else ids.delete(id);
|
|
555
|
+
}
|
|
556
|
+
if (ids.size > max) {
|
|
557
|
+
warnings.push(
|
|
558
|
+
`account "${a.id}" will have ${ids.size} agents, over its limit of ${max} (the limit only blocks creating more)`,
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return warnings;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ─── Planning a reverse ───────────────────────────────────────────────────────
|
|
566
|
+
|
|
567
|
+
export async function planReverse(
|
|
568
|
+
db: Db,
|
|
569
|
+
receipt: MoveReceipt,
|
|
570
|
+
): Promise<MovePlan> {
|
|
571
|
+
const reasons: string[] = [];
|
|
572
|
+
const skipped: string[] = [];
|
|
573
|
+
const changes: Change[] = [];
|
|
574
|
+
const deletes: Change[] = [];
|
|
575
|
+
|
|
576
|
+
const accountExists = async (id: string | null) =>
|
|
577
|
+
id === null || (await db.account.count({ where: { id } })) > 0;
|
|
578
|
+
|
|
579
|
+
// What leaves each created account during this reverse.
|
|
580
|
+
const leaving = { agents: new Set<string>(), members: new Set<string>() };
|
|
581
|
+
const leavingSettings = new Set<string>();
|
|
582
|
+
|
|
583
|
+
for (const c of [...receipt.changes].reverse()) {
|
|
584
|
+
switch (c.type) {
|
|
585
|
+
case "moveSetting": {
|
|
586
|
+
const label = settingLabel(c.setting, c.specialty);
|
|
587
|
+
const row = await findSettingById(db, c.setting, c.rowId);
|
|
588
|
+
if (!row || row.accountId !== c.to) {
|
|
589
|
+
skipped.push(`${label} ${c.rowId}: no longer in ${scopeLabel(c.to)}`);
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
if (!(await accountExists(c.from))) {
|
|
593
|
+
reasons.push(`${label} ${c.rowId}: account "${c.from}" is gone`);
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
const occupant = await findSetting(db, c.setting, c.specialty, c.from);
|
|
597
|
+
if (occupant && occupant.id !== c.rowId) {
|
|
598
|
+
reasons.push(
|
|
599
|
+
`${label} ${c.rowId}: ${scopeLabel(c.from)} already has another ${label}`,
|
|
600
|
+
);
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
leavingSettings.add(`${c.setting}|${c.rowId}`);
|
|
604
|
+
changes.push({ ...c, from: c.to, to: c.from });
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
case "moveAgent": {
|
|
608
|
+
const agent = await db.agent.findUnique({
|
|
609
|
+
where: { id: c.agentId },
|
|
610
|
+
select: { accountId: true },
|
|
611
|
+
});
|
|
612
|
+
if (!agent || agent.accountId !== c.to) {
|
|
613
|
+
skipped.push(`agent ${c.name} (${c.agentId}): moved again since`);
|
|
614
|
+
break;
|
|
615
|
+
}
|
|
616
|
+
if (!(await accountExists(c.from))) {
|
|
617
|
+
reasons.push(`agent ${c.agentId}: account "${c.from}" is gone`);
|
|
618
|
+
break;
|
|
619
|
+
}
|
|
620
|
+
leaving.agents.add(c.agentId);
|
|
621
|
+
changes.push({ ...c, from: c.to, to: c.from });
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
case "moveMember": {
|
|
625
|
+
const member = await db.accountMember.findUnique({
|
|
626
|
+
where: { id: c.memberId },
|
|
627
|
+
});
|
|
628
|
+
if (
|
|
629
|
+
!member ||
|
|
630
|
+
member.accountId !== c.to.accountId ||
|
|
631
|
+
member.role !== c.to.role
|
|
632
|
+
) {
|
|
633
|
+
skipped.push(`member ${c.email} (${c.memberId}): changed since`);
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
if (!(await accountExists(c.from.accountId))) {
|
|
637
|
+
reasons.push(
|
|
638
|
+
`member ${c.email}: account "${c.from.accountId}" is gone`,
|
|
639
|
+
);
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
leaving.members.add(c.memberId);
|
|
643
|
+
changes.push({ ...c, from: c.to, to: c.from });
|
|
644
|
+
break;
|
|
645
|
+
}
|
|
646
|
+
case "updateAccount": {
|
|
647
|
+
const account = await db.account.findUnique({
|
|
648
|
+
where: { id: c.accountId },
|
|
649
|
+
});
|
|
650
|
+
if (
|
|
651
|
+
!account ||
|
|
652
|
+
account.name !== c.to.name ||
|
|
653
|
+
account.maxAgents !== c.to.maxAgents
|
|
654
|
+
) {
|
|
655
|
+
skipped.push(`account "${c.accountId}" name/limit: changed since`);
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
changes.push({ ...c, from: c.to, to: c.from });
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
case "createAccount": {
|
|
662
|
+
if (!(await accountExists(c.accountId))) {
|
|
663
|
+
skipped.push(`account "${c.accountId}": already deleted`);
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
const remaining = await remainingRows(
|
|
667
|
+
db,
|
|
668
|
+
c.accountId,
|
|
669
|
+
leaving,
|
|
670
|
+
leavingSettings,
|
|
671
|
+
);
|
|
672
|
+
if (remaining.length > 0) {
|
|
673
|
+
skipped.push(
|
|
674
|
+
`kept account "${c.accountId}": it still has ${remaining.join(", ")}`,
|
|
675
|
+
);
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
deletes.push({ type: "deleteAccount", accountId: c.accountId });
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
case "deleteAccount":
|
|
682
|
+
reasons.push("receipt contains a deleteAccount change");
|
|
683
|
+
break;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
if (reasons.length > 0) throw new MoveRefusedError(reasons);
|
|
688
|
+
return { changes: [...changes, ...deletes], warnings: [], skipped };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** Rows that would still belong to `accountId` after the reverse. */
|
|
692
|
+
async function remainingRows(
|
|
693
|
+
db: Db,
|
|
694
|
+
accountId: string,
|
|
695
|
+
leaving: { agents: Set<string>; members: Set<string> },
|
|
696
|
+
leavingSettings: Set<string>,
|
|
697
|
+
): Promise<string[]> {
|
|
698
|
+
const [agents, members, invites, apps, slack, templates] = await Promise.all([
|
|
699
|
+
db.agent.findMany({ where: { accountId }, select: { id: true } }),
|
|
700
|
+
db.accountMember.findMany({ where: { accountId }, select: { id: true } }),
|
|
701
|
+
db.accountInvite.count({ where: { accountId } }),
|
|
702
|
+
db.gitHubEnterpriseApp.findMany({
|
|
703
|
+
where: { accountId },
|
|
704
|
+
select: { id: true, role: true },
|
|
705
|
+
}),
|
|
706
|
+
db.slackConfigToken.findMany({
|
|
707
|
+
where: { accountId },
|
|
708
|
+
select: { id: true },
|
|
709
|
+
}),
|
|
710
|
+
db.agentTemplate.findMany({ where: { accountId }, select: { id: true } }),
|
|
711
|
+
]);
|
|
712
|
+
const out: string[] = [];
|
|
713
|
+
const nAgents = agents.filter((a) => !leaving.agents.has(a.id)).length;
|
|
714
|
+
const nMembers = members.filter((m) => !leaving.members.has(m.id)).length;
|
|
715
|
+
const nSettings =
|
|
716
|
+
apps.filter(
|
|
717
|
+
(a) =>
|
|
718
|
+
!leavingSettings.has(
|
|
719
|
+
`${a.role === "lookup" ? "githubLookupApp" : "githubInstallerApp"}|${a.id}`,
|
|
720
|
+
),
|
|
721
|
+
).length +
|
|
722
|
+
slack.filter((s) => !leavingSettings.has(`slackConfigToken|${s.id}`))
|
|
723
|
+
.length +
|
|
724
|
+
templates.filter((t) => !leavingSettings.has(`agentTemplate|${t.id}`))
|
|
725
|
+
.length;
|
|
726
|
+
if (nAgents > 0) out.push(`${nAgents} agent(s)`);
|
|
727
|
+
if (nMembers > 0) out.push(`${nMembers} member(s)`);
|
|
728
|
+
if (invites > 0) out.push(`${invites} invite(s)`);
|
|
729
|
+
if (nSettings > 0) out.push(`${nSettings} setting(s)`);
|
|
730
|
+
return out;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// ─── Applying ─────────────────────────────────────────────────────────────────
|
|
734
|
+
|
|
735
|
+
async function writeChange(tx: Db, c: Change): Promise<void> {
|
|
736
|
+
switch (c.type) {
|
|
737
|
+
case "createAccount":
|
|
738
|
+
await tx.account.create({
|
|
739
|
+
data: { id: c.accountId, name: c.name, maxAgents: c.maxAgents },
|
|
740
|
+
});
|
|
741
|
+
return;
|
|
742
|
+
case "updateAccount":
|
|
743
|
+
await tx.account.update({ where: { id: c.accountId }, data: c.to });
|
|
744
|
+
return;
|
|
745
|
+
case "moveMember":
|
|
746
|
+
// In place: the id (and every row keyed by it) stays the same.
|
|
747
|
+
await tx.accountMember.update({
|
|
748
|
+
where: { id: c.memberId },
|
|
749
|
+
data: { accountId: c.to.accountId, role: c.to.role },
|
|
750
|
+
});
|
|
751
|
+
return;
|
|
752
|
+
case "moveAgent":
|
|
753
|
+
await tx.agent.update({
|
|
754
|
+
where: { id: c.agentId },
|
|
755
|
+
data: { accountId: c.to },
|
|
756
|
+
});
|
|
757
|
+
return;
|
|
758
|
+
case "moveSetting": {
|
|
759
|
+
const data = { accountId: c.to };
|
|
760
|
+
switch (c.setting) {
|
|
761
|
+
case "githubLookupApp":
|
|
762
|
+
case "githubInstallerApp":
|
|
763
|
+
await tx.gitHubEnterpriseApp.update({
|
|
764
|
+
where: { id: c.rowId },
|
|
765
|
+
data,
|
|
766
|
+
select: { id: true },
|
|
767
|
+
});
|
|
768
|
+
return;
|
|
769
|
+
case "slackConfigToken":
|
|
770
|
+
await tx.slackConfigToken.update({
|
|
771
|
+
where: { id: c.rowId },
|
|
772
|
+
data,
|
|
773
|
+
select: { id: true },
|
|
774
|
+
});
|
|
775
|
+
return;
|
|
776
|
+
case "agentTemplate":
|
|
777
|
+
await tx.agentTemplate.update({
|
|
778
|
+
where: { id: c.rowId },
|
|
779
|
+
data,
|
|
780
|
+
select: { id: true },
|
|
781
|
+
});
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
case "deleteAccount":
|
|
787
|
+
await tx.account.delete({ where: { id: c.accountId } });
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const TX_OPTIONS = {
|
|
793
|
+
isolationLevel: "Serializable",
|
|
794
|
+
maxWait: 10_000,
|
|
795
|
+
timeout: 120_000,
|
|
796
|
+
} as const;
|
|
797
|
+
|
|
798
|
+
export interface ApplyOptions {
|
|
799
|
+
/** Runs inside the transaction after every write, before commit. */
|
|
800
|
+
beforeCommit?: (receipt: MoveReceipt) => void | Promise<void>;
|
|
801
|
+
now?: () => Date;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Re-plans and applies the mapping in one serializable transaction. Throws
|
|
806
|
+
* MoveRefusedError (nothing written) on unclear input. Returns the receipt.
|
|
807
|
+
*/
|
|
808
|
+
export async function applyMove(
|
|
809
|
+
prisma: PrismaClient,
|
|
810
|
+
mapping: AccountMoveMapping,
|
|
811
|
+
opts: ApplyOptions = {},
|
|
812
|
+
): Promise<MoveReceipt & { warnings: string[] }> {
|
|
813
|
+
return prisma.$transaction(async (tx) => {
|
|
814
|
+
const plan = await planMove(tx, mapping);
|
|
815
|
+
for (const c of plan.changes) await writeChange(tx, c);
|
|
816
|
+
const receipt: MoveReceipt = {
|
|
817
|
+
kind: "admin-account-move",
|
|
818
|
+
version: 1,
|
|
819
|
+
appliedAt: (opts.now?.() ?? new Date()).toISOString(),
|
|
820
|
+
changes: plan.changes,
|
|
821
|
+
};
|
|
822
|
+
await opts.beforeCommit?.(receipt);
|
|
823
|
+
return { ...receipt, warnings: plan.warnings };
|
|
824
|
+
}, TX_OPTIONS);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Puts back what `receipt` moved, in one serializable transaction. */
|
|
828
|
+
export async function applyReverse(
|
|
829
|
+
prisma: PrismaClient,
|
|
830
|
+
receipt: MoveReceipt,
|
|
831
|
+
): Promise<MovePlan> {
|
|
832
|
+
return prisma.$transaction(async (tx) => {
|
|
833
|
+
const plan = await planReverse(tx, receipt);
|
|
834
|
+
for (const c of plan.changes) await writeChange(tx, c);
|
|
835
|
+
return plan;
|
|
836
|
+
}, TX_OPTIONS);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// ─── Output ───────────────────────────────────────────────────────────────────
|
|
840
|
+
|
|
841
|
+
function describeChange(c: Change): string {
|
|
842
|
+
switch (c.type) {
|
|
843
|
+
case "createAccount":
|
|
844
|
+
return `create account "${c.accountId}" (name "${c.name}", agent limit ${c.maxAgents})`;
|
|
845
|
+
case "updateAccount":
|
|
846
|
+
return `update account "${c.accountId}": name "${c.from.name}" -> "${c.to.name}", agent limit ${c.from.maxAgents} -> ${c.to.maxAgents}`;
|
|
847
|
+
case "moveMember":
|
|
848
|
+
return `move member ${c.email} (${c.memberId}): ${c.from.accountId}/${c.from.role} -> ${c.to.accountId}/${c.to.role}`;
|
|
849
|
+
case "moveAgent":
|
|
850
|
+
return `move agent ${c.name} (${c.agentId}): ${c.from ?? "(no account)"} -> ${c.to ?? "(no account)"}`;
|
|
851
|
+
case "moveSetting":
|
|
852
|
+
return `move ${settingLabel(c.setting, c.specialty)} (${c.rowId}): ${scopeLabel(c.from)} -> ${scopeLabel(c.to)}`;
|
|
853
|
+
case "deleteAccount":
|
|
854
|
+
return `delete account "${c.accountId}" (created by the move, now empty)`;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
export function formatPlan(
|
|
859
|
+
plan: Pick<MovePlan, "changes" | "warnings" | "skipped">,
|
|
860
|
+
): string {
|
|
861
|
+
const lines: string[] = [];
|
|
862
|
+
if (plan.changes.length === 0) lines.push(" nothing to change");
|
|
863
|
+
for (const c of plan.changes) lines.push(` ${describeChange(c)}`);
|
|
864
|
+
for (const w of plan.warnings) lines.push(` warning: ${w}`);
|
|
865
|
+
for (const s of plan.skipped) lines.push(` skipped: ${s}`);
|
|
866
|
+
return lines.join("\n");
|
|
867
|
+
}
|