@app-vitals/agent-admin 1.108.1 → 1.110.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.
Files changed (49) hide show
  1. package/Dockerfile +4 -0
  2. package/account-move.example.json +22 -0
  3. package/openapi.platform.json +5 -0
  4. package/package.json +2 -2
  5. package/src/account-agent-create.ts +18 -9
  6. package/src/account-agent-create.unit.test.ts +12 -14
  7. package/src/account-move.integration.test.ts +594 -0
  8. package/src/account-move.ts +867 -0
  9. package/src/account-move.unit.test.ts +206 -0
  10. package/src/admin-local-agent.smoke.test.ts +65 -0
  11. package/src/admin-ui-account-pages.ts +2 -3
  12. package/src/admin-ui-account-pages.unit.test.ts +5 -3
  13. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  14. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  15. package/src/admin-ui-github-enterprise.ts +16 -1
  16. package/src/admin-ui-pages.ts +16 -5
  17. package/src/admin-ui-pages.unit.test.ts +25 -20
  18. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  19. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  20. package/src/admin-ui-slack-config-token.ts +51 -9
  21. package/src/admin-ui-templates-pages.ts +7 -1
  22. package/src/admin-ui-templates.smoke.test.ts +31 -5
  23. package/src/admin-ui-templates.ts +43 -8
  24. package/src/admin-ui.smoke.test.ts +6 -7
  25. package/src/admin-ui.ts +39 -27
  26. package/src/agent-templates-api.integration.test.ts +29 -7
  27. package/src/agent-templates.ts +7 -1
  28. package/src/agents-api.smoke.test.ts +106 -8
  29. package/src/agents-api.ts +5 -3
  30. package/src/agents.integration.test.ts +112 -2
  31. package/src/agents.ts +37 -6
  32. package/src/deployment-wide-settings.integration.test.ts +309 -0
  33. package/src/deployment-wide-settings.ts +42 -0
  34. package/src/github-agent-installation-crawler.ts +18 -1
  35. package/src/github-enterprise-api.integration.test.ts +7 -0
  36. package/src/github-enterprise-api.ts +6 -2
  37. package/src/github-enterprise-apps.integration.test.ts +33 -8
  38. package/src/github-enterprise-apps.ts +4 -0
  39. package/src/github-enterprise-isolation.unit.test.ts +17 -0
  40. package/src/github-installation-wiring.ts +34 -5
  41. package/src/github-installation-wiring.unit.test.ts +38 -1
  42. package/src/github-sync-cache.integration.test.ts +9 -2
  43. package/src/installation-repos-service.ts +7 -4
  44. package/src/move-accounts.ts +201 -0
  45. package/src/openapi-schemas.ts +6 -0
  46. package/src/self-serve-config.ts +8 -8
  47. package/src/self-serve-config.unit.test.ts +3 -10
  48. package/src/slack-config-token.integration.test.ts +19 -2
  49. package/src/slack-config-token.ts +6 -1
@@ -8,6 +8,7 @@ import {
8
8
  withLookupSnapshots,
9
9
  } from "./github-installation.fixtures.ts";
10
10
  import {
11
+ accessCache,
11
12
  createGithubInstallationRepos,
12
13
  createGithubSync,
13
14
  } from "./github-installation-wiring.ts";
@@ -15,6 +16,14 @@ import type { GitHubEnterpriseAppMetadata } from "./github-enterprise-apps.ts";
15
16
  import type { InstallationReposPort } from "./installation-repos-service.ts";
16
17
 
17
18
  const noApp = { get: async () => null, getPrivateKey: async () => null };
19
+ // A deployment-wide lookup App exists: its cached access rows apply.
20
+ const withDeploymentLookup = {
21
+ get: async (role: string, accountId?: string | null) =>
22
+ role === "lookup" && !accountId
23
+ ? ({ accountId: null, appId: 1 } as never)
24
+ : null,
25
+ getPrivateKey: async () => null,
26
+ };
18
27
 
19
28
  const portWith = (
20
29
  seen: number[],
@@ -88,7 +97,7 @@ describe("createGithubSync", () => {
88
97
  const verified: string[] = [];
89
98
  const svc = createGithubSync({
90
99
  prisma,
91
- appService: noApp,
100
+ appService: withDeploymentLookup,
92
101
  access: accessFor(["acme/api"]),
93
102
  agentEnv: envWith({ GH_APP_ID: "42" }),
94
103
  installationRepos: portWith([]),
@@ -259,3 +268,31 @@ describe("createGithubSync lookup snapshot read", () => {
259
268
  ]);
260
269
  });
261
270
  });
271
+
272
+ describe("accessCache", () => {
273
+ const query = (accountId: string) => ({
274
+ accountId,
275
+ org: "acme",
276
+ username: "dev",
277
+ repos: ["api"],
278
+ });
279
+
280
+ it("ignores stale deployment-key access rows once no deployment-wide lookup App exists", async () => {
281
+ const { prisma } = fakePrisma(
282
+ ["acme/api"],
283
+ freshCache("acme", ["acme/api"], ["acme/api"], new Date()),
284
+ );
285
+ const cache = accessCache({ prisma, appService: noApp });
286
+ expect(await cache.getAccessRows(query("deployment"))).toEqual([]);
287
+ expect((await cache.getAccessRows(query("acct-1"))).length).toBe(1);
288
+ });
289
+
290
+ it("keeps deployment-key rows while the deployment-wide lookup App exists", async () => {
291
+ const { prisma } = fakePrisma(
292
+ ["acme/api"],
293
+ freshCache("acme", ["acme/api"], ["acme/api"], new Date()),
294
+ );
295
+ const cache = accessCache({ prisma, appService: withDeploymentLookup });
296
+ expect((await cache.getAccessRows(query("deployment"))).length).toBe(1);
297
+ });
298
+ });
@@ -29,11 +29,18 @@ const port: InstallationReposPort = {
29
29
  removeRepos: async () => {},
30
30
  };
31
31
 
32
+ // A deployment-wide lookup App exists, so cached rows under the deployment key apply.
33
+ const deploymentLookupApp = {
34
+ get: async () =>
35
+ ({ accountId: null }) as unknown as GitHubEnterpriseAppMetadata,
36
+ getPrivateKey: async () => null,
37
+ };
38
+
32
39
  function preview(cache: ReturnType<typeof freshCache>, now = new Date()) {
33
40
  const { prisma } = fakePrisma(REPOS, cache);
34
41
  const svc = createGithubSync({
35
42
  prisma,
36
- appService: { get: async () => null, getPrivateKey: async () => null },
43
+ appService: deploymentLookupApp,
37
44
  access: accessFor([]), // the live resolver must not be consulted
38
45
  agentEnv: envWith({ GH_APP_ID: "42" }),
39
46
  installationRepos: port,
@@ -118,7 +125,7 @@ describe("installation list access detail", () => {
118
125
  const { prisma } = fakePrisma(REPOS, cache);
119
126
  const svc = createGithubInstallationRepos({
120
127
  prisma,
121
- appService: { get: async () => null, getPrivateKey: async () => null },
128
+ appService: deploymentLookupApp,
122
129
  access: accessFor([]),
123
130
  agentEnv: envWith({ GH_APP_ID: "42" }),
124
131
  installationRepos: port,
@@ -311,7 +311,13 @@ export class InstallationReposService {
311
311
  const snapshots = cache
312
312
  ? await cache.listAgentSnapshots(accountId, String(agent.appId))
313
313
  : [];
314
- const username = agent.githubUsername?.trim();
314
+ const state = this.deps.appsState
315
+ ? await this.deps.appsState(agent.accountId)
316
+ : "both";
317
+ // Without a usable lookup App no access rows apply (they may be left over
318
+ // from a removed deployment-wide App).
319
+ const username =
320
+ state === "lookup_missing" ? undefined : agent.githubUsername?.trim();
315
321
  const orgs: InstallationOrgView[] = [];
316
322
  for (const s of snapshots) {
317
323
  const names = s.repos.map((r) => r.fullName);
@@ -353,9 +359,6 @@ export class InstallationReposService {
353
359
  ...(s.lastTickAt ? { lastTickAt: iso(s.lastTickAt) } : {}),
354
360
  });
355
361
  }
356
- const state = this.deps.appsState
357
- ? await this.deps.appsState(agent.accountId)
358
- : "both";
359
362
  return {
360
363
  status: "ok",
361
364
  appId: agent.appId,
@@ -0,0 +1,201 @@
1
+ /**
2
+ * admin/src/move-accounts.ts
3
+ *
4
+ * multi-account-2.6: admin CLI that creates accounts and moves members,
5
+ * agents and deployment-wide settings between accounts, driven by a mapping
6
+ * file kept outside the repo. Ships in the admin image; the runbook (order
7
+ * with the task-data move, pausing scheduled jobs, recovery) is
8
+ * docs/account-move.md.
9
+ *
10
+ * bun admin/src/move-accounts.ts --mapping FILE # preview (default)
11
+ * bun admin/src/move-accounts.ts --mapping FILE --apply --receipt OUT
12
+ * bun admin/src/move-accounts.ts --reverse RECEIPT # preview the reverse
13
+ * bun admin/src/move-accounts.ts --reverse RECEIPT --apply
14
+ *
15
+ * Reads DATABASE_URL_SHIPWRIGHT_ADMIN. Exit codes: 0 ok, 1 refused (nothing
16
+ * written), 2 usage or input error, 3 unexpected error (rolled back).
17
+ */
18
+
19
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { parseArgs } from "node:util";
21
+ import type { PrismaClient } from "../prisma/client/client.ts";
22
+ import {
23
+ applyMove,
24
+ applyReverse,
25
+ formatPlan,
26
+ MoveInputError,
27
+ MoveRefusedError,
28
+ parseMapping,
29
+ parseReceipt,
30
+ planMove,
31
+ planReverse,
32
+ } from "./account-move.ts";
33
+ import { createAdminPrismaClient } from "./prisma-client.ts";
34
+
35
+ export const USAGE = `Move accounts, members, agents and deployment-wide settings in the admin database.
36
+
37
+ Usage:
38
+ move-accounts --mapping FILE preview (default, writes nothing)
39
+ move-accounts --mapping FILE --apply --receipt OUT apply in one transaction; OUT must not exist
40
+ move-accounts --reverse RECEIPT preview putting back what RECEIPT moved
41
+ move-accounts --reverse RECEIPT --apply put it back
42
+
43
+ Mapping file (keep it outside the repo; see admin/account-move.example.json):
44
+ { "accounts": [ { "id": "example-account", "name": "Example", "maxAgents": 1,
45
+ "agents": ["example-agent"],
46
+ "members": [ { "email": "owner@example.com", "role": "owner" } ] } ],
47
+ "settings": [ { "setting": "slackConfigToken", "toAccountId": "example-account" } ] }
48
+
49
+ Reads DATABASE_URL_SHIPWRIGHT_ADMIN. See docs/account-move.md.
50
+ Exit codes: 0 ok, 1 refused (nothing written), 2 usage or input error.`;
51
+
52
+ export interface CliDeps {
53
+ /** Injected for tests; otherwise built from DATABASE_URL_SHIPWRIGHT_ADMIN. */
54
+ db?: PrismaClient;
55
+ stdout?: (line: string) => void;
56
+ stderr?: (line: string) => void;
57
+ }
58
+
59
+ class UsageError extends Error {}
60
+
61
+ function readJson(path: string): unknown {
62
+ try {
63
+ return JSON.parse(readFileSync(path, "utf8"));
64
+ } catch (err) {
65
+ throw new MoveInputError(
66
+ `cannot read JSON from ${path}: ${(err as Error).message}`,
67
+ );
68
+ }
69
+ }
70
+
71
+ export async function runMoveAccountsCli(
72
+ argv: string[],
73
+ deps: CliDeps = {},
74
+ ): Promise<number> {
75
+ const out = deps.stdout ?? ((s) => console.log(s));
76
+ const err = deps.stderr ?? ((s) => console.error(s));
77
+ let db = deps.db;
78
+ const ownsDb = db === undefined;
79
+ try {
80
+ const { values } = parseArgs({
81
+ args: argv,
82
+ options: {
83
+ mapping: { type: "string" },
84
+ reverse: { type: "string" },
85
+ receipt: { type: "string" },
86
+ apply: { type: "boolean", default: false },
87
+ help: { type: "boolean", short: "h", default: false },
88
+ },
89
+ strict: true,
90
+ allowPositionals: false,
91
+ });
92
+ if (values.help) {
93
+ out(USAGE);
94
+ return 0;
95
+ }
96
+ if ((values.mapping === undefined) === (values.reverse === undefined)) {
97
+ throw new UsageError("give exactly one of --mapping or --reverse");
98
+ }
99
+ if (values.mapping !== undefined && values.apply) {
100
+ if (values.receipt === undefined) {
101
+ throw new UsageError("--apply with --mapping needs --receipt OUT");
102
+ }
103
+ if (existsSync(values.receipt)) {
104
+ throw new UsageError(
105
+ `receipt ${values.receipt} already exists; never overwrite a receipt, pick a new path`,
106
+ );
107
+ }
108
+ }
109
+ if (values.reverse !== undefined && values.receipt !== undefined) {
110
+ throw new UsageError("--receipt is only for --mapping --apply");
111
+ }
112
+ if (values.mapping === undefined && !values.apply && values.receipt) {
113
+ throw new UsageError("--receipt needs --apply");
114
+ }
115
+
116
+ // Parse the input file before touching the database.
117
+ const mapping =
118
+ values.mapping !== undefined
119
+ ? parseMapping(readJson(values.mapping))
120
+ : undefined;
121
+ const receipt =
122
+ values.reverse !== undefined
123
+ ? parseReceipt(readJson(values.reverse))
124
+ : undefined;
125
+
126
+ if (db === undefined) {
127
+ const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
128
+ if (!url) {
129
+ throw new UsageError("DATABASE_URL_SHIPWRIGHT_ADMIN is not set");
130
+ }
131
+ db = createAdminPrismaClient(url);
132
+ }
133
+
134
+ if (mapping !== undefined) {
135
+ if (!values.apply) {
136
+ out("PREVIEW (nothing written; add --apply --receipt OUT to move):");
137
+ out(formatPlan(await planMove(db, mapping)));
138
+ return 0;
139
+ }
140
+ const receiptPath = values.receipt as string;
141
+ const applied = await applyMove(db, mapping, {
142
+ // Written before commit so a committed move always has its receipt.
143
+ beforeCommit: (r) =>
144
+ writeFileSync(receiptPath, `${JSON.stringify(r, null, 2)}\n`, {
145
+ flag: "wx",
146
+ }),
147
+ });
148
+ out(`APPLIED. Receipt: ${receiptPath}`);
149
+ out(
150
+ formatPlan({
151
+ changes: applied.changes,
152
+ warnings: applied.warnings,
153
+ skipped: [],
154
+ }),
155
+ );
156
+ return 0;
157
+ }
158
+
159
+ const r = receipt as NonNullable<typeof receipt>;
160
+ if (!values.apply) {
161
+ out("REVERSE PREVIEW (nothing written; add --apply to move back):");
162
+ out(formatPlan(await planReverse(db, r)));
163
+ return 0;
164
+ }
165
+ out("REVERSED:");
166
+ out(formatPlan(await applyReverse(db, r)));
167
+ return 0;
168
+ } catch (e) {
169
+ if (e instanceof MoveRefusedError) {
170
+ err("REFUSED (nothing written):");
171
+ for (const reason of e.reasons) err(` - ${reason}`);
172
+ return 1;
173
+ }
174
+ if (e instanceof UsageError || e instanceof MoveInputError) {
175
+ err(`error: ${e.message}`);
176
+ err("run with --help for usage");
177
+ return 2;
178
+ }
179
+ if (e instanceof TypeError && "code" in e) {
180
+ // parseArgs: unknown or malformed option.
181
+ err(`error: ${e.message}`);
182
+ return 2;
183
+ }
184
+ throw e;
185
+ } finally {
186
+ if (ownsDb && db !== undefined) await db.$disconnect();
187
+ }
188
+ }
189
+
190
+ if (import.meta.main) {
191
+ runMoveAccountsCli(process.argv.slice(2)).then(
192
+ (code) => process.exit(code),
193
+ (e) => {
194
+ console.error(
195
+ "[move-accounts] failed; the transaction rolls back on any error before commit:",
196
+ e,
197
+ );
198
+ process.exit(3);
199
+ },
200
+ );
201
+ }
@@ -189,6 +189,12 @@ export const CreateAgentBodySchema = z
189
189
  .openapi({ example: "true" }),
190
190
  claudeCodeOauthToken: z.string().optional(),
191
191
  anthropicApiKey: z.string().optional(),
192
+ /**
193
+ * Account for the new agent. Platform admins only: with one account it is
194
+ * used when omitted, with several it must be given. Ignored for account
195
+ * owners, whose agents always go to their own account.
196
+ */
197
+ accountId: z.string().min(1).optional().openapi({ example: "acct_123" }),
192
198
  /**
193
199
  * Explicit env values. They override the agent template per key and are
194
200
  * kept as the agent's own (never overwritten by a template reconcile).
@@ -7,7 +7,11 @@
7
7
  * resolved config as deps.
8
8
  */
9
9
 
10
- export const DEFAULT_SELF_SERVE_CONTACT_EMAIL = "dan@app-vitals.com";
10
+ /**
11
+ * @deprecated The contact address is no longer used; kept as an export so
12
+ * existing consumers keep compiling.
13
+ */
14
+ export const DEFAULT_SELF_SERVE_CONTACT_EMAIL = "";
11
15
 
12
16
  /** Structural env shape — accepts `process.env` or a plain test object. */
13
17
  type SelfServeEnv = Readonly<Record<string, string | undefined>>;
@@ -17,8 +21,8 @@ export interface SelfServeConfig {
17
21
  enabled: boolean;
18
22
  /** Default per-account agent quota (integer >= 0). */
19
23
  defaultMaxAgents: number;
20
- /** Contact address shown when a user needs more quota. */
21
- contactEmail: string;
24
+ /** @deprecated No longer set or read; kept optional for existing consumers. */
25
+ contactEmail?: string;
22
26
  }
23
27
 
24
28
  /**
@@ -44,9 +48,5 @@ export function parseSelfServeConfig(
44
48
  }
45
49
  }
46
50
 
47
- const contactEmail =
48
- env.SHIPWRIGHT_SELF_SERVE_CONTACT_EMAIL?.trim() ||
49
- DEFAULT_SELF_SERVE_CONTACT_EMAIL;
50
-
51
- return { enabled, defaultMaxAgents, contactEmail };
51
+ return { enabled, defaultMaxAgents };
52
52
  }
@@ -20,7 +20,6 @@ describe("parseSelfServeConfig", () => {
20
20
  expect(config).toEqual({
21
21
  enabled: false,
22
22
  defaultMaxAgents: 0,
23
- contactEmail: "dan@app-vitals.com",
24
23
  });
25
24
  expect(warnings).toEqual([]);
26
25
  });
@@ -64,16 +63,10 @@ describe("parseSelfServeConfig", () => {
64
63
  },
65
64
  );
66
65
 
67
- it("uses a custom contact email, trimmed", () => {
66
+ it("no longer reads a contact email", () => {
68
67
  expect(
69
- parse({ SHIPWRIGHT_SELF_SERVE_CONTACT_EMAIL: " ops@example.com " }).config
68
+ parse({ SHIPWRIGHT_SELF_SERVE_CONTACT_EMAIL: "ops@example.com" }).config
70
69
  .contactEmail,
71
- ).toBe("ops@example.com");
72
- });
73
-
74
- it("falls back to the default contact when blank", () => {
75
- expect(
76
- parse({ SHIPWRIGHT_SELF_SERVE_CONTACT_EMAIL: " " }).config.contactEmail,
77
- ).toBe("dan@app-vitals.com");
70
+ ).toBeUndefined();
78
71
  });
79
72
  });
@@ -97,12 +97,27 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
97
97
  await service.clear(acctA); // no-op
98
98
  });
99
99
 
100
+ /** A deployment-wide row that predates the second account. */
101
+ const seedDefault = async () => {
102
+ const row = await prisma.slackConfigToken.create({
103
+ data: {
104
+ accountId: null,
105
+ refreshTokenEncrypted: (
106
+ makeStrictTokenCrypto(KEY) as TokenCrypto
107
+ ).encrypt(REFRESH),
108
+ },
109
+ });
110
+ return row;
111
+ };
112
+
100
113
  it("allows a token with no access token", async () => {
114
+ await prisma.account.deleteMany();
101
115
  const saved = await service.save(null, { refreshToken: REFRESH });
102
116
  expect(saved.accessTokenSet).toBe(false);
103
117
  });
104
118
 
105
119
  it("upserts one row per scope, including two NULL-scope saves", async () => {
120
+ await prisma.account.deleteMany();
106
121
  const first = await service.save(null, { refreshToken: REFRESH });
107
122
  const second = await service.save(null, {
108
123
  refreshToken: "test-refresh-OTHER",
@@ -114,6 +129,8 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
114
129
  await prisma.slackConfigToken.count({ where: { accountId: null } }),
115
130
  ).toBe(1);
116
131
 
132
+ acctA = (await prisma.account.create({ data: { name: "A" } })).id;
133
+ acctB = (await prisma.account.create({ data: { name: "B" } })).id;
117
134
  const a1 = await service.save(acctA, { refreshToken: REFRESH });
118
135
  const a2 = await service.save(acctA, { refreshToken: REFRESH });
119
136
  expect(a2.id).toBe(a1.id);
@@ -145,7 +162,7 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
145
162
 
146
163
  it("resolveForAccount prefers the account row, then default, then null", async () => {
147
164
  expect(await service.resolveForAccount(acctA)).toBeNull();
148
- const def = await service.save(null, { refreshToken: REFRESH });
165
+ const def = await seedDefault();
149
166
  expect((await service.resolveForAccount(acctA))?.id).toBe(def.id);
150
167
  const own = await service.save(acctA, { refreshToken: REFRESH });
151
168
  expect((await service.resolveForAccount(acctA))?.id).toBe(own.id);
@@ -156,7 +173,7 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
156
173
  });
157
174
 
158
175
  it("clears only the targeted scope", async () => {
159
- await service.save(null, { refreshToken: REFRESH });
176
+ await seedDefault();
160
177
  await service.save(acctA, { refreshToken: REFRESH });
161
178
  await service.clear(acctA);
162
179
  expect(await service.get(null)).not.toBeNull();
@@ -19,6 +19,7 @@
19
19
 
20
20
  import type { PrismaClient } from "../prisma/client/client.ts";
21
21
  import { type Clock, SystemClock } from "./clock.ts";
22
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
22
23
  import {
23
24
  BadGatewayError,
24
25
  NotFoundError,
@@ -202,7 +203,8 @@ export class SlackConfigTokenService {
202
203
 
203
204
  /**
204
205
  * Create or replace the token for a scope (accountId null = deployment-wide
205
- * default). Resets lastError; stamps lastRotatedAt.
206
+ * default, refused while there are several accounts). Resets lastError;
207
+ * stamps lastRotatedAt.
206
208
  */
207
209
  async save(
208
210
  accountId: string | null,
@@ -212,6 +214,9 @@ export class SlackConfigTokenService {
212
214
  if (!input.refreshToken) {
213
215
  throw new UnprocessableEntityError("refreshToken is required");
214
216
  }
217
+ if (accountId === null) {
218
+ await assertDeploymentWideAllowed(this.prisma, "the Slack config token");
219
+ }
215
220
  const now = this.clock.now();
216
221
  const data = {
217
222
  refreshTokenEncrypted: this.crypto.encrypt(input.refreshToken),