@app-vitals/agent-admin 1.108.0 → 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.
Files changed (55) hide show
  1. package/Dockerfile +4 -0
  2. package/account-move.example.json +22 -0
  3. package/e2e/real/admin-access.real.e2e.ts +77 -68
  4. package/e2e/real/agent-management.real.e2e.ts +165 -143
  5. package/e2e/real/owner-access.real.e2e.ts +228 -212
  6. package/openapi.platform.json +11 -6
  7. package/package.json +2 -2
  8. package/src/account-agent-create.ts +18 -9
  9. package/src/account-agent-create.unit.test.ts +12 -14
  10. package/src/account-created-notifier.ts +1 -1
  11. package/src/account-move.integration.test.ts +594 -0
  12. package/src/account-move.ts +867 -0
  13. package/src/account-move.unit.test.ts +206 -0
  14. package/src/account-onboarding.integration.test.ts +69 -0
  15. package/src/account-onboarding.ts +29 -3
  16. package/src/account-trial-expiry-sweeper.ts +1 -1
  17. package/src/accounts-api.integration.test.ts +5 -2
  18. package/src/accounts-api.smoke.test.ts +21 -5
  19. package/src/accounts-api.ts +12 -15
  20. package/src/admin-boot-config.ts +2 -0
  21. package/src/admin-boot-config.unit.test.ts +27 -0
  22. package/src/admin-boot.ts +11 -10
  23. package/src/admin-local-agent.smoke.test.ts +65 -0
  24. package/src/admin-ui-account-pages.ts +2 -3
  25. package/src/admin-ui-account-pages.unit.test.ts +5 -3
  26. package/src/admin-ui-account.smoke.test.ts +7 -3
  27. package/src/admin-ui-account.ts +10 -15
  28. package/src/admin-ui-accounts.smoke.test.ts +4 -4
  29. package/src/admin-ui-accounts.ts +7 -11
  30. package/src/admin-ui-pages.ts +16 -5
  31. package/src/admin-ui-pages.unit.test.ts +25 -20
  32. package/src/admin-ui-settings-nav-context.smoke.test.ts +24 -0
  33. package/src/admin-ui-settings.smoke.test.ts +17 -1
  34. package/src/admin-ui.smoke.test.ts +167 -2
  35. package/src/admin-ui.ts +75 -50
  36. package/src/agent-management-access.integration.test.ts +18 -6
  37. package/src/agent-manifest.ts +2 -1
  38. package/src/agent-provisioner.integration.test.ts +10 -10
  39. package/src/agent-provisioner.ts +10 -1
  40. package/src/agent-provisioner.unit.test.ts +110 -36
  41. package/src/agent-templates-api.integration.test.ts +23 -5
  42. package/src/agent-templates-api.ts +11 -8
  43. package/src/agents-api.smoke.test.ts +106 -8
  44. package/src/agents-api.ts +5 -3
  45. package/src/agents.integration.test.ts +112 -2
  46. package/src/agents.ts +37 -6
  47. package/src/caller-scope.integration.test.ts +8 -6
  48. package/src/caller-scope.ts +32 -26
  49. package/src/caller-scope.unit.test.ts +15 -11
  50. package/src/github-enterprise-isolation.unit.test.ts +17 -0
  51. package/src/move-accounts.ts +201 -0
  52. package/src/openapi-schemas.ts +6 -0
  53. package/src/platform-routes.ts +2 -2
  54. package/src/self-serve-config.ts +8 -8
  55. package/src/self-serve-config.unit.test.ts +3 -10
@@ -2,6 +2,7 @@ import { describe, expect, it } from "bun:test";
2
2
  import {
3
3
  type CallerScope,
4
4
  type CallerScopeDeps,
5
+ createCallerScopeResolver,
5
6
  resolveCallerScope,
6
7
  resolveMemberRepoScope,
7
8
  resolveViewerRole,
@@ -120,16 +121,19 @@ describe("resolveCallerScope", () => {
120
121
  });
121
122
  });
122
123
 
123
- it("flag off: account membership contributes nothing", async () => {
124
- expect(await run("both@x.com", false, false)).toEqual({
125
- kind: "scoped",
126
- accountId: null,
127
- agentIds: ["ag-2", "ag-9"],
128
- });
129
- expect(await run("a@x.com", false, false)).toEqual({
124
+ it("the self-serve flag does not change the scope", async () => {
125
+ for (const email of ["a@x.com", "both@x.com", "mem@x.com", "m@x.com"]) {
126
+ expect(await run(email, false, false)).toEqual(await run(email));
127
+ }
128
+ });
129
+
130
+ it("createCallerScopeResolver works without a flag", async () => {
131
+ const resolve = createCallerScopeResolver(deps);
132
+ expect(await resolve("a@x.com", false)).toEqual({
130
133
  kind: "scoped",
131
- accountId: null,
132
- agentIds: [],
134
+ accountId: "acct-a",
135
+ agentIds: ["ag-1", "ag-2"],
136
+ role: "owner",
133
137
  });
134
138
  });
135
139
  });
@@ -209,9 +213,9 @@ describe("resolveViewerRole", () => {
209
213
  describe("resolveCallerScope matrix: role x flag", () => {
210
214
  const cases: Array<[string, boolean, string[], string | null]> = [
211
215
  ["a@x.com", true, ["ag-1", "ag-2"], "acct-a"], // owner, flag on
212
- ["a@x.com", false, [], null], // owner, flag off
216
+ ["a@x.com", false, ["ag-1", "ag-2"], "acct-a"], // owner, flag off
213
217
  ["memboth@x.com", true, ["ag-9"], "acct-a"], // member, flag on
214
- ["memboth@x.com", false, ["ag-9"], null], // member, flag off
218
+ ["memboth@x.com", false, ["ag-9"], "acct-a"], // member, flag off
215
219
  ["none@x.com", true, [], null], // no account
216
220
  ["none@x.com", false, [], null],
217
221
  ];
@@ -18,6 +18,9 @@ const ALLOWED = new Set([
18
18
  "admin/src/github-enterprise-api.ts",
19
19
  "admin/src/admin-boot.ts",
20
20
  "admin/src/github-installation-wiring.ts",
21
+ // multi-account-2.6: the account move tool re-scopes rows (id, accountId,
22
+ // role only); the last test below keeps it away from the key column.
23
+ "admin/src/account-move.ts",
21
24
  ]);
22
25
 
23
26
  function sources(dir: string, out: string[] = []): string[] {
@@ -109,6 +112,20 @@ describe("GitHub Enterprise key isolation", () => {
109
112
  }
110
113
  });
111
114
 
115
+ it("the account move tool never selects or returns the private key", () => {
116
+ const src = readFileSync(join(REPO, "admin/src/account-move.ts"), "utf-8");
117
+ expect(src).not.toMatch(
118
+ /privateKeyEncrypted|getPrivateKey|github-enterprise-apps/,
119
+ );
120
+ // Every query on the table names its columns, so the key is never loaded.
121
+ const calls = src.split("gitHubEnterpriseApp.").slice(1);
122
+ expect(calls.length).toBeGreaterThan(0);
123
+ for (const call of calls) {
124
+ const body = call.slice(0, call.indexOf("})") + 2);
125
+ expect(body).toMatch(/select/);
126
+ }
127
+ });
128
+
112
129
  it("the upload field name is only handled by the pem-upload parser", () => {
113
130
  const handlers = files
114
131
  .map((f) => relative(REPO, f))
@@ -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).
@@ -96,7 +96,7 @@ export function mountPlatformApis(
96
96
  const adminApiApp = createAdminApp(deps.adminApi);
97
97
  mount({ name: "admin", prefix: "/", app: adminApiApp, inSpec: true });
98
98
 
99
- // Platform OpenAPI document — GET /doc, flag-gated (not mounted when off).
99
+ // Platform OpenAPI document — GET /doc (mounted when the host supplies doc deps).
100
100
  if (deps.doc) mountPlatformDoc(root, deps.doc);
101
101
 
102
102
  mount({
@@ -105,7 +105,7 @@ export function mountPlatformApis(
105
105
  app: createAccountsApp(deps.accounts),
106
106
  inSpec: false,
107
107
  specExclusion:
108
- "flag-gated (self-serve signup); never part of the committed platform spec",
108
+ "account administration (admin-only); never part of the committed platform spec",
109
109
  });
110
110
  // The three apps below own disjoint prefixes, so their relative order does
111
111
  // not affect routing; it is fixed to keep the committed spec's key order.
@@ -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
  });