@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
package/src/admin-ui.ts CHANGED
@@ -32,7 +32,7 @@ import { sign, verify } from "hono/jwt";
32
32
  import {
33
33
  accountIdFromScope,
34
34
  createAccountIdFromScope,
35
- getSelfServeSpecialty,
35
+ getOwnerAgentSpecialty,
36
36
  } from "./account-agent-create.ts";
37
37
  import type { AccountCreatedNotifier } from "./account-created-notifier.ts";
38
38
  import { fireAccountCreatedNotification } from "./account-created-notifier.ts";
@@ -129,7 +129,11 @@ import type { AgentTemplateService } from "./agent-templates.ts";
129
129
  import type { AgentTokenService } from "./agent-tokens.ts";
130
130
  import type { AgentToolService } from "./agent-tools.ts";
131
131
  import type { AgentService } from "./agents.ts";
132
- import { createAgent, describeRepoNameCollision } from "./agents.ts";
132
+ import {
133
+ ACCOUNT_REQUIRED_MESSAGE,
134
+ createAgent,
135
+ describeRepoNameCollision,
136
+ } from "./agents.ts";
133
137
  import { AnthropicCredentialsBlockedError } from "./anthropic-credential-guard.ts";
134
138
  import {
135
139
  audioContentTypeForFilename,
@@ -176,10 +180,7 @@ import {
176
180
  sanitizeStartUrl,
177
181
  } from "./pwa.ts";
178
182
  import { secretsEqual } from "./secrets-equal.ts";
179
- import {
180
- DEFAULT_SELF_SERVE_CONTACT_EMAIL,
181
- type SelfServeConfig,
182
- } from "./self-serve-config.ts";
183
+ import type { SelfServeConfig } from "./self-serve-config.ts";
183
184
  import {
184
185
  SETUP_RESUME_COOKIE,
185
186
  SETUP_RESUME_TTL_SECONDS,
@@ -494,13 +495,21 @@ export interface AdminUIDeps {
494
495
  appBaseUrl: string;
495
496
  /** Enable the /admin/dev-login route. Hard-blocked in production regardless of this value. */
496
497
  devAuthEnabled?: boolean;
497
- /** Resolved self-serve provisioning config (SSP-1.3). */
498
+ /**
499
+ * Resolved self-serve config (SSP-1.3). `enabled` controls only open signup
500
+ * (an unknown verified Google user creating an account); `contactEmail` is
501
+ * shown on the agent-limit notices.
502
+ */
498
503
  selfServe?: SelfServeConfig;
499
504
  /**
500
- * First-login account provisioning (SSP-3.1). Consulted by the Google
501
- * callback only, and only when selfServe.enabled; absent → no auto-create.
505
+ * First-login account resolution (SSP-3.1), consulted by the Google callback
506
+ * only, for a verified email with no AgentMember rows. Signup on
507
+ * (selfServe.enabled): provisionForEmail (join, existing or create). Signup
508
+ * off: joinForEmail (join or existing, never create); without it the
509
+ * caller gets 403. Absent → 403.
502
510
  */
503
- accountOnboarding?: Pick<AccountOnboardingService, "provisionForEmail">;
511
+ accountOnboarding?: Pick<AccountOnboardingService, "provisionForEmail"> &
512
+ Partial<Pick<AccountOnboardingService, "joinForEmail">>;
504
513
  /**
505
514
  * GHE-1.4: the GHE-1.3 /github-enterprise API app's `request`. Optional
506
515
  * (additive): when absent the Settings page and its nav entry are not
@@ -548,8 +557,9 @@ export interface AdminUIDeps {
548
557
  creator?: MemberCreator;
549
558
  }) => Promise<EnsureAccountMemberResult>;
550
559
  /**
551
- * Account page + nav services (SSP-3.2). Used only when selfServe.enabled;
552
- * absent → no /admin/account routes content, no nav entry, no quota notice.
560
+ * Account page + nav services (SSP-3.2), independent of the self-serve
561
+ * setting; absent → no /admin/account(s) routes, no nav entry, no quota
562
+ * notice and no Account column.
553
563
  */
554
564
  accountServices?: {
555
565
  accounts: Pick<
@@ -1032,7 +1042,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1032
1042
  devAuthEnabled,
1033
1043
  });
1034
1044
 
1035
- const accountNavEnabled = Boolean(selfServe?.enabled && accountServices);
1045
+ const accountNavEnabled = accountServices !== undefined;
1036
1046
 
1037
1047
  const settingsNav = buildSettingsNav({
1038
1048
  githubEnterprise: Boolean(githubEnterpriseApi),
@@ -1064,7 +1074,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1064
1074
  if (user) {
1065
1075
  const role = await resolveNavRole(user.email, user.isAdmin === true);
1066
1076
  nav = filterSettingsNavForRole(settingsNav, role);
1067
- if (accountNavEnabled && accountServices) {
1077
+ if (accountServices) {
1068
1078
  const account = await accountServices.accounts
1069
1079
  .getByMemberEmail(user.email)
1070
1080
  .catch(() => null);
@@ -1186,7 +1196,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1186
1196
  c: Context<AdminUIEnv, any>,
1187
1197
  userInfo: { sub: string; email?: string; email_verified?: boolean },
1188
1198
  returnTo: string | undefined,
1189
- opts: { selfServeSignup?: boolean } = {},
1199
+ opts: { accountSignIn?: boolean } = {},
1190
1200
  ): Promise<Response> {
1191
1201
  if (!userInfo.email) {
1192
1202
  return c.redirect("/admin/login?error=auth_failed", 302);
@@ -1208,21 +1218,26 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1208
1218
  userInfo.email.toLowerCase(),
1209
1219
  );
1210
1220
  if (memberships.length === 0) {
1211
- // Self-serve (SSP-3.1): a verified Google email with no AgentMember
1212
- // rows joins its invited account or gets a new one. Okta and flag-off
1213
- // keep the existing 403.
1214
- const onboarding = accountOnboarding;
1215
- if (!(opts.selfServeSignup && selfServe?.enabled && onboarding)) {
1221
+ // SSP-3.1: a verified Google email with no AgentMember rows signs in
1222
+ // through its account: an existing membership, else a pending invite,
1223
+ // else (signup on only) a new account. Okta keeps the existing 403.
1224
+ const onboarding = opts.accountSignIn ? accountOnboarding : undefined;
1225
+ const resolveAccount =
1226
+ selfServe?.enabled === true
1227
+ ? onboarding?.provisionForEmail.bind(onboarding)
1228
+ : onboarding?.joinForEmail?.bind(onboarding);
1229
+ if (!resolveAccount) {
1216
1230
  return new Response("Forbidden", { status: 403 });
1217
1231
  }
1218
1232
  const email = userInfo.email.toLowerCase();
1219
- let result: Awaited<ReturnType<typeof onboarding.provisionForEmail>>;
1233
+ let result: Awaited<ReturnType<typeof resolveAccount>>;
1220
1234
  try {
1221
- result = await onboarding.provisionForEmail(email);
1235
+ result = await resolveAccount(email);
1222
1236
  } catch (err) {
1223
- console.error("[admin] self-serve account provisioning failed", err);
1237
+ console.error("[admin] account sign-in resolution failed", err);
1224
1238
  return c.redirect("/admin/login?error=server_error", 302);
1225
1239
  }
1240
+ if (!result) return new Response("Forbidden", { status: 403 });
1226
1241
  if (result.kind !== "existing") {
1227
1242
  console.log(
1228
1243
  JSON.stringify({
@@ -1476,7 +1491,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1476
1491
  return c.redirect("/admin/login?error=auth_failed", 302);
1477
1492
  }
1478
1493
 
1479
- return completeLogin(c, userInfo, returnTo, { selfServeSignup: true });
1494
+ return completeLogin(c, userInfo, returnTo, { accountSignIn: true });
1480
1495
  });
1481
1496
 
1482
1497
  app.get("/admin/auth/okta", (c) => {
@@ -1610,20 +1625,18 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1610
1625
  // malformed/tampered query param — render without the panel
1611
1626
  }
1612
1627
  }
1613
- // SSP-3.2: a zero-quota account sees a request-a-trial message and a
1614
- // disabled create button instead of the create CTA.
1615
- let zeroQuotaContactEmail: string | undefined;
1616
- if (accountNavEnabled && accountServices && selfServe) {
1628
+ // SSP-3.2: a zero-quota account sees a limit message and a disabled
1629
+ // create button instead of the create CTA. Platform admins are not limited.
1630
+ let zeroQuota = false;
1631
+ if (accountServices && !c.var.isAdmin) {
1617
1632
  const account = await accountServices.accounts.getByMemberEmail(
1618
1633
  c.var.userEmail,
1619
1634
  );
1620
- if (account && account.maxAgents === 0) {
1621
- zeroQuotaContactEmail = selfServe.contactEmail;
1622
- }
1635
+ zeroQuota = account?.maxAgents === 0;
1623
1636
  }
1624
- // SSP-5.2: admins get an Account column (flag on only).
1637
+ // SSP-5.2: admins get an Account column.
1625
1638
  let accountNames: Map<string, string> | undefined;
1626
- if (c.var.isAdmin && accountNavEnabled && accountServices) {
1639
+ if (c.var.isAdmin && accountServices) {
1627
1640
  accountNames = new Map(
1628
1641
  (await accountServices.accounts.listWithCounts()).map((a) => [
1629
1642
  a.id,
@@ -1637,9 +1650,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1637
1650
  queueActivityLinks: deps.queueActivityLinks,
1638
1651
  successMsg,
1639
1652
  manualSteps,
1640
- zeroQuotaNotice: zeroQuotaContactEmail
1641
- ? renderZeroQuotaNotice(zeroQuotaContactEmail)
1642
- : undefined,
1653
+ zeroQuotaNotice: zeroQuota ? renderZeroQuotaNotice() : undefined,
1643
1654
  }),
1644
1655
  );
1645
1656
  });
@@ -1679,8 +1690,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1679
1690
  "In-cluster provisioning is not enabled on this admin service — create a self-hosted agent instead.",
1680
1691
  provision_failed:
1681
1692
  "Failed to provision the agent's cluster resources — the agent was not created.",
1682
- quota_exceeded: "This account has reached its agent limit.",
1693
+ quota_exceeded:
1694
+ "This account has reached its agent limit. Delete an agent to free a slot.",
1683
1695
  account_inactive: "This account is not active.",
1696
+ account_required: ACCOUNT_REQUIRED_MESSAGE,
1684
1697
  ...deps.agentDetailErrorMessages,
1685
1698
  };
1686
1699
 
@@ -1739,9 +1752,15 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1739
1752
  if (!c.var.isAdmin && accountId === null) {
1740
1753
  return new Response("Forbidden", { status: 403 });
1741
1754
  }
1742
- let selfServeOpts:
1743
- | { remaining: number; max: number; contactEmail: string }
1744
- | undefined;
1755
+ let selfServeOpts: { remaining: number; max: number } | undefined;
1756
+ // Platform admins pick the account when more than one exists.
1757
+ let accountChoices: { id: string; name: string }[] | undefined;
1758
+ if (c.var.isAdmin && accountServices) {
1759
+ const all = await accountServices.accounts.listWithCounts();
1760
+ if (all.length > 1) {
1761
+ accountChoices = all.map((a) => ({ id: a.id, name: a.name }));
1762
+ }
1763
+ }
1745
1764
  if (accountId !== null && accountService) {
1746
1765
  const [account, count] = await Promise.all([
1747
1766
  accountService.getById(accountId),
@@ -1750,8 +1769,6 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1750
1769
  selfServeOpts = {
1751
1770
  remaining: Math.max(0, (account?.maxAgents ?? 0) - count),
1752
1771
  max: account?.maxAgents ?? 0,
1753
- contactEmail:
1754
- selfServe?.contactEmail ?? DEFAULT_SELF_SERVE_CONTACT_EMAIL,
1755
1772
  };
1756
1773
  }
1757
1774
  const rawError = c.req.query("error") ?? undefined;
@@ -1767,6 +1784,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1767
1784
  accountId,
1768
1785
  ),
1769
1786
  ...(selfServeOpts ? { selfServe: selfServeOpts } : {}),
1787
+ ...(accountChoices ? { accountChoices } : {}),
1770
1788
  ...(templateService
1771
1789
  ? {
1772
1790
  template: {
@@ -1791,6 +1809,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1791
1809
  }
1792
1810
  let name: string | undefined;
1793
1811
  let specialty: string | undefined;
1812
+ let chosenAccountId: string | undefined;
1794
1813
  let reposRaw: string | undefined;
1795
1814
  let authorAllowlistRaw: string | undefined;
1796
1815
  let patchAuthorAllowlistRaw: string | undefined;
@@ -1817,6 +1836,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1817
1836
  envRaw = formData.get("env")?.toString();
1818
1837
  name = formData.get("name")?.toString()?.trim();
1819
1838
  specialty = formData.get("type")?.toString()?.trim();
1839
+ chosenAccountId =
1840
+ formData.get("accountId")?.toString()?.trim() || undefined;
1820
1841
  reposRaw = formData.get("repos")?.toString()?.trim();
1821
1842
  authorAllowlistRaw = formData.get("authorAllowlist")?.toString()?.trim();
1822
1843
  patchAuthorAllowlistRaw = formData
@@ -1863,9 +1884,13 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1863
1884
  );
1864
1885
  }
1865
1886
  const connectSlack = connectSlackRaw === "true";
1866
- // SSP-4.2: account users always create self-serve-specialty agents in their own
1867
- // account — any submitted type/accountId is ignored.
1868
- if (accountId !== null) specialty = getSelfServeSpecialty();
1887
+ // Account owners always create the default agent type in their own
1888
+ // account — any submitted type/accountId is ignored. Platform admins
1889
+ // choose the type, and the account when several exist.
1890
+ const targetAccountId = c.var.isAdmin
1891
+ ? chosenAccountId
1892
+ : (accountId ?? undefined);
1893
+ if (accountId !== null) specialty = getOwnerAgentSpecialty();
1869
1894
  // Absent/unrecognized runtime means self-hosted — the historical behavior
1870
1895
  // of this form. createAgent() below re-derives this same value itself
1871
1896
  // (it owns the runtime/provisioning validation); it's recomputed here
@@ -1928,7 +1953,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1928
1953
  restrictSlackToMembersRaw,
1929
1954
  claudeCodeOauthToken,
1930
1955
  anthropicApiKey,
1931
- ...(accountId !== null ? { accountId } : {}),
1956
+ ...(targetAccountId !== undefined
1957
+ ? { accountId: targetAccountId }
1958
+ : {}),
1932
1959
  ...(templateDetachedRaw === "true" ? { templateDetached: true } : {}),
1933
1960
  ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1934
1961
  // PAI-1.2: owner is the authenticated session user, never form data.
@@ -4572,7 +4599,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4572
4599
 
4573
4600
  app.get("/admin/provision", (c) => c.redirect("/admin/agents/new", 302));
4574
4601
 
4575
- // ─── Member management (admin, or any agent-access holder when self-serve is on) ──────────────────────────────────────
4602
+ // ─── Member management (platform admin, or the owner of the agent's account) ───
4576
4603
 
4577
4604
  app.post("/admin/agents/:id/members", requireAuth, async (c) => {
4578
4605
  const agentId = c.req.param("id");
@@ -4663,7 +4690,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4663
4690
  c.var.isAdmin === true,
4664
4691
  );
4665
4692
  let nav = settingsNav;
4666
- if (accountNavEnabled && accountServices) {
4693
+ if (accountServices) {
4667
4694
  const account = await accountServices.accounts
4668
4695
  .getByMemberEmail(c.var.userEmail)
4669
4696
  .catch(() => null);
@@ -4733,14 +4760,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4733
4760
 
4734
4761
  if (accountServices) {
4735
4762
  registerAccountRoutes(app, {
4736
- enabled: accountNavEnabled,
4737
4763
  requireAuth,
4738
4764
  settingsNav,
4739
4765
  ...accountServices,
4740
4766
  html,
4741
4767
  });
4742
4768
  registerAdminAccountsRoutes(app, {
4743
- enabled: accountNavEnabled,
4744
4769
  requireAuth,
4745
4770
  settingsNav,
4746
4771
  ...accountServices,
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * admin/src/agent-management-access.integration.test.ts
3
- * Agent management (JSON API) against a real PostgreSQL DB with self-serve on:
4
- * only platform admins and the owner of the agent's own account may manage an
3
+ * Agent management (JSON API) against a real PostgreSQL DB, with the
4
+ * self-serve setting off and on (it must not change the outcome): only
5
+ * platform admins and the owner of the agent's own account may manage an
5
6
  * agent; a member of the agent (or of its account) and an owner of another
6
7
  * account get 403, while read access is unchanged.
7
8
  *
@@ -145,7 +146,10 @@ const cookieFor = (email: string, isAdmin: boolean) =>
145
146
  "HS256",
146
147
  );
147
148
 
148
- describeOrSkip("agent management access (integration)", () => {
149
+ /** Run with the self-serve setting off and on; the outcome must not differ. */
150
+ const SELF_SERVE = [false, true];
151
+
152
+ describeOrSkip.each(SELF_SERVE)("management, self-serve=%p", (enabled) => {
149
153
  let prisma: PrismaClient;
150
154
  let app: ReturnType<typeof createAdminApp>;
151
155
  let agentId: string;
@@ -180,8 +184,12 @@ describeOrSkip("agent management access (integration)", () => {
180
184
  await prisma.accountMember.deleteMany();
181
185
  await prisma.account.deleteMany();
182
186
 
183
- const one = await prisma.account.create({ data: { name: "Account One" } });
184
- const two = await prisma.account.create({ data: { name: "Account Two" } });
187
+ const one = await prisma.account.create({
188
+ data: { name: "Account One" },
189
+ });
190
+ const two = await prisma.account.create({
191
+ data: { name: "Account Two" },
192
+ });
185
193
  const mk = (accountId: string, email: string, role: string) =>
186
194
  prisma.accountMember.create({ data: { accountId, email, role } });
187
195
  await mk(one.id, "owner-one@example.com", "owner");
@@ -199,12 +207,16 @@ describeOrSkip("agent management access (integration)", () => {
199
207
  const deps = makeDeps(prisma);
200
208
  app = createAdminApp({
201
209
  ...deps,
210
+ selfServe: {
211
+ enabled,
212
+ defaultMaxAgents: 0,
213
+ contactEmail: "ops@example.com",
214
+ },
202
215
  callerScopeResolver: createCallerScopeResolver(
203
216
  callerScopeDepsFromServices({
204
217
  accountService: new AccountService(prisma),
205
218
  agentMemberService: new AgentMemberService(prisma),
206
219
  }),
207
- true,
208
220
  ),
209
221
  });
210
222
  });
@@ -262,7 +262,8 @@ export interface AgentDeploymentOpts {
262
262
  /**
263
263
  * Owning account. When set the pod is a tenant pod: the tenant label is added
264
264
  * to the Deployment and pod template, and a CPU limit is applied. Omit for
265
- * platform agents (manifest unchanged).
265
+ * platform agents (manifest unchanged). The Kubernetes provisioner passes it
266
+ * only when tenant pod restrictions are on (SHIPWRIGHT_SELF_SERVE_ENABLED).
266
267
  */
267
268
  accountId?: string | null;
268
269
  /**
@@ -407,18 +407,18 @@ describeOrSkip("KubernetesAgentProvisioner (integration)", () => {
407
407
  // ─── PVC name template ───────────────────────────────────────────────────────
408
408
 
409
409
  it("provision() uses slug for PVC name when pvcName template is configured", async () => {
410
- const agentId = await createAgent("OkWOW Agent");
410
+ const agentId = await createAgent("Widget Agent");
411
411
  const k8s = emptyClient();
412
412
  const provisioner = new KubernetesAgentProvisioner(k8s, tokens, {
413
413
  ...CONFIG,
414
414
  pvcName: (name) => `acme-agent-${name}-home`,
415
415
  });
416
416
 
417
- await provisioner.provision(agentId, { slug: "okwow" });
417
+ await provisioner.provision(agentId, { slug: "widget" });
418
418
 
419
419
  // PVC must use the slug, not the sanitized agentId.
420
420
  await expect(
421
- k8s.getPvc(NAMESPACE, "acme-agent-okwow-home"),
421
+ k8s.getPvc(NAMESPACE, "acme-agent-widget-home"),
422
422
  ).resolves.toBeDefined();
423
423
  // Default-named PVC must NOT exist.
424
424
  const resourceName = sanitizeAgentName(agentId);
@@ -477,13 +477,13 @@ describeOrSkip("KubernetesAgentProvisioner (integration)", () => {
477
477
 
478
478
  // Agent exists in DB, no k8s Deployment — reconcile should provision it.
479
479
  const result = await provisioner.reconcile([
480
- { id: agentId, slug: "okwow" },
480
+ { id: agentId, slug: "widget" },
481
481
  ]);
482
482
 
483
483
  expect(result.recreated).toEqual([agentId]);
484
484
  // PVC must use the slug passed through reconcile.
485
485
  await expect(
486
- k8s.getPvc(NAMESPACE, "acme-agent-okwow-home"),
486
+ k8s.getPvc(NAMESPACE, "acme-agent-widget-home"),
487
487
  ).resolves.toBeDefined();
488
488
  });
489
489
 
@@ -533,22 +533,22 @@ describeOrSkip("KubernetesAgentProvisioner (integration)", () => {
533
533
  });
534
534
 
535
535
  it("deprovision() deletes the templated PVC name derived from slug", async () => {
536
- const agentId = await createAgent("OkWOW Agent");
536
+ const agentId = await createAgent("Widget Agent");
537
537
  const k8s = emptyClient();
538
538
  const provisioner = new KubernetesAgentProvisioner(k8s, tokens, {
539
539
  ...CONFIG,
540
540
  pvcName: (name) => `acme-agent-${name}-home`,
541
541
  });
542
542
 
543
- await provisioner.provision(agentId, { slug: "okwow" });
543
+ await provisioner.provision(agentId, { slug: "widget" });
544
544
  await expect(
545
- k8s.getPvc(NAMESPACE, "acme-agent-okwow-home"),
545
+ k8s.getPvc(NAMESPACE, "acme-agent-widget-home"),
546
546
  ).resolves.toBeDefined();
547
547
 
548
- await provisioner.deprovision(agentId, { slug: "okwow" });
548
+ await provisioner.deprovision(agentId, { slug: "widget" });
549
549
 
550
550
  await expect(
551
- k8s.getPvc(NAMESPACE, "acme-agent-okwow-home"),
551
+ k8s.getPvc(NAMESPACE, "acme-agent-widget-home"),
552
552
  ).rejects.toThrow();
553
553
  });
554
554
 
@@ -241,6 +241,14 @@ export interface AgentProvisioner {
241
241
  export interface KubernetesAgentProvisionerConfig {
242
242
  /** Additional labels managed on new and existing agent pod templates. */
243
243
  podLabels?: Record<string, string>;
244
+ /**
245
+ * Tenant pod restrictions (SSP-7.1): when true, an agent with an account
246
+ * gets the tenant label (`shipwright.dev/tenant`, selected by the tenant
247
+ * NetworkPolicy) and a CPU limit, on provision and reconcile. Off when
248
+ * unset. Sourced from SHIPWRIGHT_SELF_SERVE_ENABLED in buildProvisioner, so
249
+ * the restrictions apply only on deployments with open signup.
250
+ */
251
+ tenantPodRestrictions?: boolean;
244
252
  /** Namespace the agent resources live in. */
245
253
  namespace: string;
246
254
  /** Agent container image (without tag). */
@@ -982,7 +990,8 @@ export class KubernetesAgentProvisioner implements AgentProvisioner {
982
990
  chatServiceUrl: this.config.chatServiceUrl,
983
991
  claudePolicy: this.config.claudePolicy,
984
992
  anthropicFederation: federation,
985
- accountId,
993
+ // The manifest treats an accountId as a tenant pod (label + CPU limit).
994
+ accountId: this.config.tenantPodRestrictions === true ? accountId : null,
986
995
  ...(this.config.podServiceAccount?.enabled && podServiceAccountName
987
996
  ? { podServiceAccountName }
988
997
  : {}),
@@ -125,7 +125,7 @@ describe("KubernetesAgentProvisioner.provision() — default PVC naming", () =>
125
125
  describe("KubernetesAgentProvisioner.provision() — templated PVC naming", () => {
126
126
  it("creates a PVC named by the template when slug is provided via opts", async () => {
127
127
  const agentId = "cmqalfjcm000m4101iharq28k";
128
- const slug = "okwow";
128
+ const slug = "widget";
129
129
 
130
130
  const config: KubernetesAgentProvisionerConfig = {
131
131
  ...BASE_CONFIG,
@@ -143,7 +143,7 @@ describe("KubernetesAgentProvisioner.provision() — templated PVC naming", () =
143
143
 
144
144
  // PVC must use the slug, not the sanitized agentId
145
145
  await expect(
146
- k8s.getPvc(NAMESPACE, "acme-agent-okwow-home"),
146
+ k8s.getPvc(NAMESPACE, "acme-agent-widget-home"),
147
147
  ).resolves.toBeDefined();
148
148
 
149
149
  // The default name must NOT exist
@@ -155,8 +155,8 @@ describe("KubernetesAgentProvisioner.provision() — templated PVC naming", () =
155
155
 
156
156
  it("Deployment is created alongside the template-derived PVC", async () => {
157
157
  const agentId = "cmqalfjcm000m4101iharq28k";
158
- const slug = "okwow";
159
- const expectedPvcName = "acme-agent-okwow-home";
158
+ const slug = "widget";
159
+ const expectedPvcName = "acme-agent-widget-home";
160
160
 
161
161
  const config: KubernetesAgentProvisionerConfig = {
162
162
  ...BASE_CONFIG,
@@ -973,8 +973,8 @@ describe("KubernetesAgentProvisioner.deprovision() — PVC deletion", () => {
973
973
 
974
974
  it("calls deletePvc with the templated name derived from slug", async () => {
975
975
  const agentId = "cmqalfjcm000m4101iharq28k";
976
- const slug = "okwow";
977
- const expectedPvcName = "acme-agent-okwow-home";
976
+ const slug = "widget";
977
+ const expectedPvcName = "acme-agent-widget-home";
978
978
 
979
979
  const config: KubernetesAgentProvisionerConfig = {
980
980
  ...BASE_CONFIG,
@@ -1172,11 +1172,12 @@ describe("canProvision", () => {
1172
1172
  });
1173
1173
  });
1174
1174
 
1175
- describe("KubernetesAgentProvisioner.reconcile() — tenant drift (SSP-7.1)", () => {
1175
+ describe("KubernetesAgentProvisioner — tenant pod restrictions (SSP-7.1)", () => {
1176
1176
  const agentId = "cmqalfjcm000m4101iharq28k";
1177
1177
  const resourceName = sanitizeAgentName(agentId);
1178
+ const TENANT = "shipwright.dev/tenant";
1178
1179
 
1179
- async function seededWithPlatformManifest() {
1180
+ function build(tenantPodRestrictions?: boolean) {
1180
1181
  const k8s = new RecordedKubernetesClient({
1181
1182
  deployments: {},
1182
1183
  secrets: {},
@@ -1185,43 +1186,116 @@ describe("KubernetesAgentProvisioner.reconcile() — tenant drift (SSP-7.1)", ()
1185
1186
  const provisioner = new KubernetesAgentProvisioner(
1186
1187
  k8s,
1187
1188
  stubTokens() as AgentTokenService,
1188
- BASE_CONFIG,
1189
+ {
1190
+ ...BASE_CONFIG,
1191
+ ...(tenantPodRestrictions === undefined
1192
+ ? {}
1193
+ : { tenantPodRestrictions }),
1194
+ },
1189
1195
  );
1190
- await provisioner.provision(agentId); // created as a platform agent
1191
1196
  return { k8s, provisioner };
1192
1197
  }
1193
1198
 
1194
- it("detects a missing tenant label + CPU limit as drift and patches", async () => {
1195
- const { k8s, provisioner } = await seededWithPlatformManifest();
1196
-
1197
- const result = await provisioner.reconcile([
1198
- { id: agentId, accountId: "acct_1" },
1199
- ]);
1199
+ async function seededWithPlatformManifest(tenantPodRestrictions?: boolean) {
1200
+ const built = build(tenantPodRestrictions);
1201
+ await built.provisioner.provision(agentId); // created as a platform agent
1202
+ return built;
1203
+ }
1200
1204
 
1201
- expect(result.updated).toEqual([agentId]);
1205
+ async function deployment(
1206
+ k8s: RecordedKubernetesClient,
1207
+ ): Promise<Record<string, string | undefined>> {
1202
1208
  const dep = await k8s.getDeployment(NAMESPACE, resourceName);
1203
- expect(dep.spec.template.metadata.labels["shipwright.dev/tenant"]).toBe(
1204
- "true",
1205
- );
1206
- expect(dep.spec.template.spec.containers[0]?.resources?.limits?.cpu).toBe(
1207
- "2",
1208
- );
1209
- });
1209
+ return {
1210
+ podLabel: dep.spec.template.metadata.labels[TENANT],
1211
+ deploymentLabel: dep.metadata.labels?.[TENANT],
1212
+ cpuLimit: dep.spec.template.spec.containers[0]?.resources?.limits?.cpu,
1213
+ };
1214
+ }
1210
1215
 
1211
- it("is a no-op once the tenant Deployment matches", async () => {
1212
- const { provisioner } = await seededWithPlatformManifest();
1213
- await provisioner.reconcile([{ id: agentId, accountId: "acct_1" }]);
1214
- const second = await provisioner.reconcile([
1215
- { id: agentId, accountId: "acct_1" },
1216
- ]);
1217
- expect(second.updated).toEqual([]);
1218
- });
1216
+ describe("restrictions on (self-serve signup enabled)", () => {
1217
+ it("provisions an account agent with the tenant label and a CPU limit", async () => {
1218
+ const { k8s, provisioner } = build(true);
1219
+ await provisioner.provision(agentId, { accountId: "acct_1" });
1220
+ expect(await deployment(k8s)).toEqual({
1221
+ podLabel: "true",
1222
+ deploymentLabel: "true",
1223
+ cpuLimit: "2",
1224
+ });
1225
+ });
1219
1226
 
1220
- it("does not touch platform agents (no accountId)", async () => {
1221
- const { provisioner } = await seededWithPlatformManifest();
1222
- const result = await provisioner.reconcile([{ id: agentId }]);
1223
- expect(result.updated).toEqual([]);
1227
+ it("detects a missing tenant label + CPU limit as drift and patches", async () => {
1228
+ const { k8s, provisioner } = await seededWithPlatformManifest(true);
1229
+
1230
+ const result = await provisioner.reconcile([
1231
+ { id: agentId, accountId: "acct_1" },
1232
+ ]);
1233
+
1234
+ expect(result.updated).toEqual([agentId]);
1235
+ const dep = await deployment(k8s);
1236
+ expect(dep.podLabel).toBe("true");
1237
+ expect(dep.cpuLimit).toBe("2");
1238
+ });
1239
+
1240
+ it("is a no-op once the tenant Deployment matches", async () => {
1241
+ const { provisioner } = await seededWithPlatformManifest(true);
1242
+ await provisioner.reconcile([{ id: agentId, accountId: "acct_1" }]);
1243
+ const second = await provisioner.reconcile([
1244
+ { id: agentId, accountId: "acct_1" },
1245
+ ]);
1246
+ expect(second.updated).toEqual([]);
1247
+ });
1248
+
1249
+ it("does not touch platform agents (no accountId)", async () => {
1250
+ const { provisioner } = await seededWithPlatformManifest(true);
1251
+ const result = await provisioner.reconcile([{ id: agentId }]);
1252
+ expect(result.updated).toEqual([]);
1253
+ });
1224
1254
  });
1255
+
1256
+ const offCases: Array<[string, boolean | undefined]> = [
1257
+ ["restrictions off", false],
1258
+ ["restrictions unset", undefined],
1259
+ ];
1260
+ for (const [label, setting] of offCases) {
1261
+ describe(`${label} (self-serve signup disabled)`, () => {
1262
+ it("provisions an account agent with no tenant label and no CPU limit", async () => {
1263
+ const { k8s, provisioner } = build(setting);
1264
+ await provisioner.provision(agentId, { accountId: "acct_1" });
1265
+ expect(await deployment(k8s)).toEqual({
1266
+ podLabel: undefined,
1267
+ deploymentLabel: undefined,
1268
+ cpuLimit: undefined,
1269
+ });
1270
+ });
1271
+
1272
+ it("reconciling an account agent adds no tenant label and no CPU limit", async () => {
1273
+ const { k8s, provisioner } = await seededWithPlatformManifest(setting);
1274
+ const result = await provisioner.reconcile([
1275
+ { id: agentId, accountId: "acct_1" },
1276
+ ]);
1277
+ expect(result.updated).toEqual([]);
1278
+ expect(await deployment(k8s)).toEqual({
1279
+ podLabel: undefined,
1280
+ deploymentLabel: undefined,
1281
+ cpuLimit: undefined,
1282
+ });
1283
+ });
1284
+
1285
+ it("recreating a missing account agent adds no tenant label and no CPU limit", async () => {
1286
+ const { k8s, provisioner } = build(setting);
1287
+ const result = await provisioner.reconcile([
1288
+ { id: agentId, accountId: "acct_1" },
1289
+ ]);
1290
+ expect(result.recreated).toEqual([agentId]);
1291
+ expect(await deployment(k8s)).toEqual({
1292
+ podLabel: undefined,
1293
+ deploymentLabel: undefined,
1294
+ cpuLimit: undefined,
1295
+ });
1296
+ });
1297
+ });
1298
+ }
1225
1299
  });
1226
1300
 
1227
1301
  // ─── Claude policy drift + reconcile patch ──────────────────────────────────