diff --git a/README.md b/README.md index ae4193746..5a009de2b 100644 --- a/README.md +++ b/README.md @@ -73,22 +73,17 @@ shape, and the administrator account (`HUB_ADMIN_EMAIL` / `HUB_ADMIN_PASSWORD`, defaulting to alice@example.com / password123 when unset) is seeded so you can sign in immediately. -`bun run dev` only seeds that account — it provisions no bench, catalog, or -workflows. Once the stack is up, run these against it (in another terminal): - -```sh -bun run setup -bun run seed -``` - -`bun run setup` provisions the bench for the administrator account; `bun run -seed` deploys the default workflow set and plants the tenant catalog's model -data, so interactive instances have a model to resolve against. Both read -their configuration from `.env` (see `.env.example`) and are safe to re-run. -`ANTHROPIC_API_KEY` is the one optional line worth setting before you run -`bun run seed` — with it, seeding plants a real credential and the catalog -is actually launchable; without it, everything above still runs, but -inference errors until you set it and re-run `bun run seed`. +`bun run dev` seeds that account and, once the hub is serving, also +provisions and seeds the root tenant itself: publishing the +`corbits-tools` registry, deploying the default workflow set, and +planting the tenant catalog's model data, so interactive instances have +a model to resolve against. This runs automatically on every hub boot +(`apps/hub/src/system-seed.ts`), reads its configuration from `.env` +(see `.env.example`), and is safe to re-run — restarting the hub +re-seeds idempotently. `ANTHROPIC_API_KEY` is the one optional line +worth setting before boot — with it, seeding plants a real credential +and the catalog is actually launchable; without it, everything above +still runs, but inference errors until you set it and restart the hub. Leaving `ANTHROPIC_API_KEY` unset doesn't just apply to the administrator account: anyone who signs up gets a personal bench with no default routines @@ -97,13 +92,13 @@ through picking a provider — Anthropic, OpenAI, Google, OpenRouter, Hugging Face, Groq, or another of the curated providers in [`packages/hub-client/src/catalog-seed-data.ts`](packages/hub-client/src/catalog-seed-data.ts) — and pasting their own key (or, for OpenRouter, completing a PKCE OAuth -connect), which is stored right away — no separate `bun run seed` step, no +connect), which is stored right away — no separate seeding step, no docs to read. A wrong key isn't caught up front; it surfaces the first time it's actually dialed for real inference, through the same in-chat "Fix this connection" flow any credential failure uses. The bench's default agents deploy in the background — "Your workbench is ready — agents will come online shortly," no "Connecting…" wait in the browser. Whichever provider they connect gets its own curated -catalog entry planted the same way `bun run seed` plants Anthropic's; see +catalog entry planted the same way boot-time seeding plants Anthropic's; see [docs/model-seeding.md](docs/model-seeding.md) for how that catalog data is curated and kept up to date. @@ -117,12 +112,11 @@ bun run reset ``` `bun run reset` drops the platform database schema and removes the hub's -and the dev sidecar's on-disk asset directories — everything `bun run setup` -and `bun run seed` created, plus anything provisioned through onboarding. -Nothing is re-seeded: the next `bun run dev` recreates the schema from -scratch and starts you at a fresh sign-up screen. Run `bun run setup && bun -run seed` afterward instead if you want a reprovisioned bench rather than a -blank slate. +and the dev sidecar's on-disk asset directories — everything boot-time +seeding and onboarding created. Nothing is re-seeded until the next `bun +run dev` — that recreates the schema and, once the hub is serving again, +reprovisions and re-seeds the root tenant from scratch, landing you at a +fresh sign-up screen with the administrator's bench ready. It refuses to run against anything but a local `DATABASE_URL` (localhost, 127.0.0.1, or `::1`) — there is no override, since the schema drop is diff --git a/apps/hub/src/config.ts b/apps/hub/src/config.ts index db37b48f5..8e7b8bd78 100644 --- a/apps/hub/src/config.ts +++ b/apps/hub/src/config.ts @@ -268,11 +268,10 @@ const SEED_MODEL_PROVIDER = "anthropic"; const SEED_MODEL = "claude-sonnet-5"; const SEED_MODEL_BASE_URL = "https://api.anthropic.com"; -// Matches `workbench setup`/`workbench seed`'s own defaults -// (packages/cli/src/config.ts) exactly, so a zero-.env-edit local -// checkout that seeds its admin account through `bun run dev` also -// resolves the same operator bench for the env-key auto-plant with no -// extra configuration. +// Matches boot-time seeding's own defaults (`system-seed.ts`) exactly, +// so a zero-.env-edit local checkout that seeds its admin account +// through `bun run dev` also resolves the same operator bench for the +// env-key auto-plant with no extra configuration. const DEFAULT_PLANT_ADMIN_EMAIL = "alice@example.com"; const DEFAULT_PLANT_ADMIN_PASSWORD = "password123"; const DEFAULT_PLANT_ORG_SLUG = "workbench"; diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 3d76f0f1b..1c6ce8c50 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -165,6 +165,7 @@ import { import { generateId } from "@intx/hub-common"; import { ensureDefaultTenant } from "./default-tenant"; +import { runSystemSeed } from "./system-seed"; import { createInMemoryMailboxEventBus, createMailboxDb, @@ -3658,6 +3659,18 @@ if (import.meta.main) { }); const log = getLogger(["hub"]); log.info`Hub serving on port ${port}`; + // CL-7382: replaces `workbench seed`. Runs against the hub's own real + // origin now that it is actually listening — `runSystemSeed`'s + // workflow push needs a reachable origin for `git push`, not just an + // in-process fetch entry point. Never awaited: a slow or still- + // sidecar-less seed must not delay "Hub serving" or hold up shutdown + // wiring below it. + void runSystemSeed({ + baseUrl: config.baseUrl, + orgSlug: config.defaultTenantSlug, + admin: config.envCredentialPlantAdmin, + ...(config.seedModel !== undefined ? { seedModel: config.seedModel } : {}), + }); const SHUTDOWN_DRAIN_MS = 10_000; // In-flight Hono handlers (a request mid-Postgres-transaction, a git // write, anything that has not returned a Response yet) must finish diff --git a/apps/hub/src/system-seed.ts b/apps/hub/src/system-seed.ts new file mode 100644 index 000000000..218fcca77 --- /dev/null +++ b/apps/hub/src/system-seed.ts @@ -0,0 +1,162 @@ +// CL-7382: seeds the root tenant's default workflow set and catalog at +// hub boot — the boot-time replacement for `workbench seed`. Runs +// against the hub's real, already-listening origin (`config.baseUrl`), +// not an in-process `fetch` entry point the way `env-credential-plant.ts` +// runs: `seedTenant`'s workflow push shells out a real `git push` over +// HTTP, so it needs a reachable origin to exist, not just a composed +// app object. +// +// The deploy step needs a connected sidecar; until one dials in, every +// deploy answers 502 and `seedTenant` throws (see +// `scripts/e2e/local-rip.test.ts`'s own `deploySeededWorkflows` retry +// loop, which this mirrors). Boot itself must never block on that or +// fail over it — `bun run dev` starts the hub and sidecar together, but +// they race, and a production boot may reasonably outlive its sidecar's +// own startup. So this polls with a bounded deadline and gives up +// quietly, logged once: every step here is ensure-then-create and every +// workflow push is content-addressed and skips an unchanged tree, so +// the very next boot picks up exactly where this one left off. + +import { reportError } from "@corbits/error-sink"; +import { getLogger } from "@intx/log"; +import { + createHubAPI, + signIn, + seedTenant, + seedCatalog, + ensureDefaultRoutines, + createGitWorkflowPusher, + publishCorbitsToolsRegistry, + DEFAULT_WORKFLOWS, + PLACEHOLDER_CATALOG_API_KEY, + type ApiCall, + type ModelSource, +} from "@workbench/hub-client"; +import { findPersonalTenant } from "@workbench/onboarding"; + +const log = getLogger(["hub", "system-seed"]); + +const DEFAULT_DEADLINE_MS = 60_000; +const DEFAULT_POLL_INTERVAL_MS = 2_000; + +// Matches `workbench seed`'s own default model source (readSeedConfig in +// the now-deleted `packages/cli/src/config.ts`): real anthropic/ +// claude-sonnet-5 when a hub-owned key is configured (`config.seedModel`), +// a placeholder key otherwise so the default workflow set still deploys +// and the catalog is still browsable, just not launchable. +const SEED_MODEL_PROVIDER = "anthropic"; +const SEED_MODEL = "claude-sonnet-5"; +const SEED_MODEL_BASE_URL = "https://api.anthropic.com"; + +function resolvedModel(seedModel: ModelSource | undefined): ModelSource { + return ( + seedModel ?? { + provider: SEED_MODEL_PROVIDER, + model: SEED_MODEL, + baseURL: SEED_MODEL_BASE_URL, + apiKey: PLACEHOLDER_CATALOG_API_KEY, + } + ); +} + +export type SystemSeedDeps = { + baseUrl: string; + orgSlug: string; + admin: { email: string; password: string }; + seedModel?: ModelSource; + deadlineMs?: number; + pollIntervalMs?: number; +}; + +/** + * Seeds the root tenant once: the default workflow set, then the tenant + * catalog (a real credential when a hub-owned seed model is configured, a + * placeholder one otherwise), then the default routine presets. Never + * throws — a failure that persists past the deadline is logged and left + * for the next boot to retry, the same "safe to re-run" property + * `workbench seed` always had. + */ +export async function runSystemSeed(deps: SystemSeedDeps): Promise { + const api: ApiCall = createHubAPI(deps.baseUrl); + const model = resolvedModel(deps.seedModel); + const deadline = Date.now() + (deps.deadlineMs ?? DEFAULT_DEADLINE_MS); + const pollIntervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS; + const pushWorkflow = createGitWorkflowPusher(); + + let lastLoggedReason: string | undefined; + for (;;) { + try { + const session = await signIn(api, deps.admin); + const tenant = await findPersonalTenant( + api, + session.cookies, + deps.orgSlug, + ); + if (tenant === undefined) { + throw new Error( + `root bench "${deps.orgSlug}" is not visible to ${deps.admin.email} yet`, + ); + } + + // `workbench setup` used to publish `corbits-tools` onto the root + // explicitly, before `workbench seed` ran. Every descendant tenant + // inherits the registry from its parent, so this is the one place + // it needs publishing — packing is content-addressed and skips an + // already-present filename, so a re-publish on every boot is cheap. + await publishCorbitsToolsRegistry({ + api, + cookies: session.cookies, + hubUrl: deps.baseUrl, + tenantId: tenant.tenantId, + log: (line) => log.info`${line}`, + }); + + await seedTenant({ + api, + cookies: session.cookies, + hubUrl: deps.baseUrl, + tenant: { + tenantId: tenant.tenantId, + principalId: tenant.principalId, + domain: tenant.tenantDomain, + }, + model, + pushWorkflow, + log: (line) => log.info`${line}`, + workflows: DEFAULT_WORKFLOWS, + }); + + await seedCatalog({ + api, + cookies: session.cookies, + tenantId: tenant.tenantId, + log: (line) => log.info`${line}`, + ...(deps.seedModel !== undefined + ? { apiKey: deps.seedModel.apiKey } + : { placeholderCredential: true }), + }); + + await ensureDefaultRoutines( + api, + session.cookies, + tenant.tenantId, + (line) => log.info`${line}`, + ); + + log.info`root tenant seed complete`; + return; + } catch (cause) { + const reason = cause instanceof Error ? cause.message : String(cause); + if (Date.now() >= deadline) { + reportError(cause, { operation: "system-seed.seedRootTenant" }); + log.error`root tenant seed did not complete before its deadline (last error: ${reason}); the next boot will retry`; + return; + } + if (reason !== lastLoggedReason) { + log.info`root tenant seed not ready yet (${reason}); retrying`; + lastLoggedReason = reason; + } + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } + } +} diff --git a/bun.lock b/bun.lock index 386621b67..98db73ce3 100644 --- a/bun.lock +++ b/bun.lock @@ -489,22 +489,6 @@ "typescript": "catalog:", }, }, - "packages/cli": { - "name": "@workbench/cli", - "version": "0.0.1", - "bin": { - "workbench": "./src/index.ts", - }, - "dependencies": { - "@intx/types": "workspace:*", - "@workbench/hub-client": "workspace:*", - "arktype": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - }, "packages/client-log": { "name": "@corbits/client-log", "version": "0.0.1", @@ -2724,8 +2708,6 @@ "@workbench/access-policy": ["@workbench/access-policy@workspace:packages/access-policy"], - "@workbench/cli": ["@workbench/cli@workspace:packages/cli"], - "@workbench/connections": ["@workbench/connections@workspace:packages/connections"], "@workbench/hub": ["@workbench/hub@workspace:apps/hub"], @@ -3582,16 +3564,6 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "@corbits/artifacts-hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#81049ed", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-81049ed", "sha512-oTE0iFDyQdz0ifG1epo39pwaCaYaw19YcKXwfaZqAEQ56a1g9YIozXwH9CG4NaUTwcJKUeYGuNls6oJsMPisCw=="], - - "@corbits/chat-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/context-menu/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/plugins-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/settings-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3614,10 +3586,6 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="], - "@workbench/hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#81049ed", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-81049ed", "sha512-oTE0iFDyQdz0ifG1epo39pwaCaYaw19YcKXwfaZqAEQ56a1g9YIozXwH9CG4NaUTwcJKUeYGuNls6oJsMPisCw=="], - - "@workbench/web/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "better-call/@better-auth/utils": ["@better-auth/utils@0.5.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="], diff --git a/docs/TENANCY.md b/docs/TENANCY.md index 0e50dfcf1..d5f8dd756 100644 --- a/docs/TENANCY.md +++ b/docs/TENANCY.md @@ -27,8 +27,8 @@ walks the chain on every read. ### Root tenant slug (one deployment fact) The hub ensures a root tenant at boot by slug. That same slug is the -operator bench `workbench setup` / `workbench seed` and the env-key -auto-plant resolve: +operator bench boot-time seeding (`apps/hub/src/system-seed.ts`) and the +env-key auto-plant resolve: 1. `WORKBENCH_DEFAULT_TENANT` if set 2. else `ORG_SLUG` (alias) diff --git a/docs/local-dev.md b/docs/local-dev.md index aeea3acfc..d8fc8adfd 100644 --- a/docs/local-dev.md +++ b/docs/local-dev.md @@ -33,13 +33,13 @@ applies what hasn't already run. A workflow that pins a `@corbits/*` tool package (e.g. **assistant** pinning `@corbits/memory-tools`) resolves that pin from a `package-registry` asset (`CORBITS_TOOLS_REGISTRY`) carrying the package's tarball, built by -`@corbits/tool-registry-publish`. `workbench setup` publishes that tarball -onto the root tenant (descendants inherit it); `workbench seed` does not -pack. After changing a tool package's source, bump its version, then -republish with: +`@corbits/tool-registry-publish`. Boot-time seeding (`apps/hub/src/system-seed.ts`) +publishes that tarball onto the root tenant on every hub boot (descendants +inherit it); the rest of seeding does not pack. After changing a tool +package's source, bump its version, then restart the hub to republish: ```sh -workbench setup +bun run dev ``` This is safe to re-run. Changing a tool package's source requires bumping diff --git a/docs/local-rip.md b/docs/local-rip.md index 0f2541305..ac5db81c5 100644 --- a/docs/local-rip.md +++ b/docs/local-rip.md @@ -36,12 +36,14 @@ bun run dev ``` `bun run reset` drops the schema and every on-disk asset directory -`bun run dev`/`bun run setup`/`bun run seed` created — skip it on a +`bun run dev` and its boot-time seeding created — skip it on a genuinely fresh checkout. `bun run dev` validates `.env`, confirms `DATABASE_URL` is reachable, applies pending migrations, builds the web UI, seeds the administrator account, and starts the hub, one sidecar, and -the web dev server together (see [README.md](../README.md#running-locally) -for exactly what it checks). Leave `ANTHROPIC_API_KEY` unset in `.env` for +the web dev server together — the hub then provisions and seeds the root +tenant itself once it is serving (see +[README.md](../README.md#running-locally) for exactly what it checks). +Leave `ANTHROPIC_API_KEY` unset in `.env` for this walkthrough — the point is proving a bench with no hub-owned seed model gets fully seeded through a person's own connected credential, not through the operator's key. @@ -100,10 +102,11 @@ The **assistant** default workflow pins the `@corbits/memory-tools` tool package (`workflows/assistant/src/index.ts`), and that pin only resolves once a `package-registry`-kind asset named `corbits-tools` carries its tarball (see `apps/hub/src/index.ts`'s `CORBITS_TOOLS_REGISTRY` comment). -`workbench setup` publishes that asset onto the root tenant via -`@corbits/tool-registry-publish` (bundles `@corbits/memory-tools` into a -self-contained tarball and pushes it through the hub's native asset REST -routes). Descendants inherit it; `seedTenant` does not pack. Isolated +Boot-time seeding (`apps/hub/src/system-seed.ts`) publishes that asset onto +the root tenant via `@corbits/tool-registry-publish` (bundles +`@corbits/memory-tools` into a self-contained tarball and pushes it +through the hub's native asset REST routes). Descendants inherit it; +`seedTenant` does not pack. Isolated tests run with no explicit tenant config so the walkthrough's personal bench is itself the root — then the same publish happens once onto that bench, and **echo**, **workbench-digest**, and **assistant** all come up diff --git a/docs/model-seeding.md b/docs/model-seeding.md index 57293435c..3866a81e5 100644 --- a/docs/model-seeding.md +++ b/docs/model-seeding.md @@ -16,7 +16,8 @@ API — never discovered at runtime: - **`packages/hub-client/src/catalog-seed-data.ts` (`CATALOG_SEEDS`)** — one curated seed per supported credential provider: a provider row (its adapter plugin and base URL) and a small hand-picked model set. This is - what `workbench seed` plants for the operator's anthropic key and what + what boot-time seeding (`apps/hub/src/system-seed.ts`) plants for the + operator's anthropic key and what onboarding plants for whichever provider a person connects — including the OpenRouter PKCE connect (see [onboarding-openrouter-connect.md](onboarding-openrouter-connect.md)). @@ -102,8 +103,8 @@ Not as a cutover, for three independent reasons: which providers/models a bench's catalog knows about. Discovery answers a narrower, different question (capability tags for a model workbench already named), and does so via paid, non-CI, human-triggered capture - runs against real provider accounts, not a runtime service the hub or - `workbench seed` could call. + runs against real provider accounts, not a runtime service boot-time + seeding could call. 2. **Not consumable without vendoring.** `@intx/inference-discovery` and `@intx/inference-testing` are published on npm, but only at `0.2.2` — the same pre-folded-model version that is the stated reason every other diff --git a/docs/package-migrations.md b/docs/package-migrations.md index 4332197e4..b71c0ef31 100644 --- a/docs/package-migrations.md +++ b/docs/package-migrations.md @@ -113,7 +113,7 @@ for itself instead (`chat`, `routines`, `insights`, `notify`, key, so nothing about the reference actually required sharing `public`. Schema changes like this are hard cutovers, not data-preserving migrations: pre-GA there is nothing to migrate, and an existing dev database picks up -the new schema by running `workbench reset` rather than by an in-place +the new schema by running `bun run reset` rather than by an in-place `ALTER TABLE ... SET SCHEMA`. ## Which shape to use for a new package diff --git a/docs/seed-reconciliation.md b/docs/seed-reconciliation.md index 023de43d3..ccae3b404 100644 --- a/docs/seed-reconciliation.md +++ b/docs/seed-reconciliation.md @@ -2,7 +2,7 @@ How workbench's automatic seeding converges on the shipped defaults without ever fighting a member. Every seed pass — a hub boot, an -onboarding run, a `workbench seed` — must satisfy four properties: +onboarding run, boot-time seeding — must satisfy four properties: 1. **Idempotent restart** — re-running creates nothing twice. 2. **Content convergence** — a changed shipped default updates the @@ -47,7 +47,7 @@ answers 503 — never a 404, which would read as "no such template". - A member-created artifact sharing a template's title is never touched and never duplicated. -## Default routine presets (onboarding / `workbench seed`) +## Default routine presets (onboarding / boot-time seeding) `ensureDefaultRoutines` (`packages/hub-client/src/default-routines.ts`) plants `DEFAULT_ROUTINE_PRESETS` through `POST /routines` with a @@ -66,7 +66,7 @@ plants `DEFAULT_ROUTINE_PRESETS` through `POST /routines` with a - A routine whose preset no longer ships is deleted only while pristine (`updatedAt` still equals `createdAt`); a member-touched row is kept. -## Default skills (`workbench seed`) +## Default skills (boot-time seeding) `plantDefaultSkills` (`packages/hub-client/src/seed.ts`) plants each `DEFAULT_SKILLS` entry through `POST /api/tenants/:id/skills`, after @@ -79,13 +79,14 @@ first checking `GET /api/tenants/:id/skills/:name`. "already exists" as done, not as a reason to abort the run the hub's own error advice told the operator to re-run. -## Tool registry publish (`workbench setup`, onto the root tenant) +## Tool registry publish (boot-time seeding, onto the root tenant) `publishCorbitsToolsRegistry` (`packages/tool-registry-publish/src/publish.ts`) finds-or-creates the tenant's `corbits-tools` package-registry asset, -then PUTs whatever tarball is missing. `workbench setup` calls this -onto the root tenant so descendants inherit tarballs; `workbench seed` -does not pack. Two properties keep a failed publish from stranding a +then PUTs whatever tarball is missing. Boot-time seeding +(`apps/hub/src/system-seed.ts`) calls this onto the root tenant so +descendants inherit tarballs; the rest of seeding does not pack. Two +properties keep a failed publish from stranding a usable-looking-but-empty asset: - `checkToolPackageFreshness` runs **before** the asset is ever @@ -99,9 +100,9 @@ usable-looking-but-empty asset: a brand-new registry and pushes every package, which is what actually creates the repo's first commit. Repairing a tenant with this history is the same operation as publishing the registry for - the first time: re-run `workbench setup`. + the first time: restart the hub. -## Workflow deployments (`workbench seed`) +## Workflow deployments (boot-time seeding) `ensureDeployment` (`packages/hub-client/src/seed.ts`) treats a workflow's `workflow_run` deployment row as seed-owned state, but the diff --git a/package.json b/package.json index 56af4e10b..c39d9c4af 100644 --- a/package.json +++ b/package.json @@ -23,10 +23,9 @@ "test": "bun test ./scripts/*.test.ts && bun run scripts/run-all.ts test", "test:e2e": "bun test scripts/e2e", "dev": "bun run scripts/dev.ts", - "setup": "bun packages/cli/src/index.ts setup", + "setup": "bun scripts/db-setup.ts", "setup:memory": "bun run scripts/setup-memory.ts", - "seed": "bun packages/cli/src/index.ts seed", - "reset": "bun packages/cli/src/index.ts reset", + "reset": "bun scripts/reset.ts", "check:structural": "bun test scripts/checks/test && bun run check:deletion && bun run check:killdates && bun run check:licenses && bun run check:db-gate && bun run check:no-product-tenancy && bun run check:browser-safe-subpaths && bun run check:web-utilities && bun run check:tailwind-source && bun run check:ui-vocabulary && bun run check:react-ui-drift && bun run check:react-ui-pin && bun run check:tool-package-pins && bun run check:tool-package-freshness && bun run check:hub-git-safety && bun run check:report-error && bun run check:error-envelope && bun run check:routine-target-inference && bun run check:tsconfig-references", "check:deletion": "bun run scripts/checks/deletion.ts", "check:report-error": "bun run scripts/checks/report-error.ts", diff --git a/packages/cli/LICENSE b/packages/cli/LICENSE deleted file mode 100644 index c6487f4fd..000000000 --- a/packages/cli/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - one line to give the library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/cli/README.md b/packages/cli/README.md deleted file mode 100644 index 9647accda..000000000 --- a/packages/cli/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# @workbench/cli - -Curated setup and seed commands that take a fresh checkout to a -provisioned organization with the default workflows deployed and -confirmed. The `workbench` command has three verbs, no generic flags, and -no raw-API escape hatch — the same invocations serve local bootstrap and -hosted provisioning, and every one of them is safe to re-run. - -## Composition over Interchange - -- Tenant creation, authentication, and workflow deployment all go through - `@workbench/hub-client`'s native hub calls — this package only sequences - those calls and reports what happened. -- The tenant-seeding logic itself lives in `@workbench/hub-client`, not - here, so other consumers (the first-login provisioning hook, in - particular) depend on that package directly instead of on the CLI. -- Database initialization is owned by the shared `scripts/db-setup.ts`; - `setup` shells out to it as a child process rather than - re-implementing migrations. - -## Key modules - -- `index.ts` — entry point: parses the verb and dispatches. -- `config.ts` — the one place the CLI reads `process.env`; each verb has - a single arktype schema, and every missing/malformed variable is - reported at once with the exact fix. -- `setup.ts` — `workbench setup`: initializes the database, provisions - the org bench through the hub's native tenant-creation route (or - adopts the boot-ensured root when the operator is already a member), - publishes the platform `corbits-tools` registry onto that root tenant - (descendants inherit it), and reports the role defaults the platform - created. -- `seed.ts` — `workbench seed`: authenticates as the administrator, - resolves the configured bench by slug, and deploys the default - workflow set. It does not pack tarballs. -- `reset.ts` — `workbench reset`: tears down local state (platform - schema and on-disk asset directories) directly, without a hub call. -- `db-setup.ts` — child-process runners for the shared setup/reset - scripts. -- `lib.ts` — the library entry: the env schemas `setup`/`seed` read, for - consumers that don't want the CLI binary. - -## Tests - -``` -cd packages/cli && bun test -``` diff --git a/packages/cli/package.json b/packages/cli/package.json deleted file mode 100644 index fb11aa48b..000000000 --- a/packages/cli/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@workbench/cli", - "private": true, - "description": "Curated setup and seed commands that take a fresh checkout to a provisioned organization with the default workflows deployed and confirmed", - "version": "0.0.1", - "license": "LGPL-2.1-or-later", - "type": "module", - "bin": { - "workbench": "./src/index.ts" - }, - "exports": { - ".": "./src/lib.ts" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "@intx/types": "workspace:*", - "@workbench/hub-client": "workspace:*", - "arktype": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - } -} diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts deleted file mode 100644 index 6f1f8b1b7..000000000 --- a/packages/cli/src/config.ts +++ /dev/null @@ -1,202 +0,0 @@ -// The one place the command-line interface reads the process -// environment. Each verb has a single schema, every missing or -// malformed variable is reported at once, and every report names the -// exact fix. -// -// The identity env (HUB_ADMIN_EMAIL / HUB_ADMIN_PASSWORD) matches -// Interchange's own naming so `scripts/dev.ts`'s account seeding and -// this CLI never disagree about which variables name the -// administrator. ANTHROPIC_API_KEY is the only model-related -// variable, and it is optional: `workbench seed` always deploys the -// default workflow set (using a placeholder key when it is unset) and -// always plants the tenant catalog's model data; only the catalog -// credential — the thing that actually makes a channel or workflow -// launchable — depends on a real key being set. - -import { type } from "arktype"; -import { - CliError, - PLACEHOLDER_CATALOG_API_KEY, - type ModelSource, -} from "@workbench/hub-client"; - -const HTTP_URL = /^https?:\/\/.+$/; - -const SharedEnv = { - "HUB_URL?": type(HTTP_URL).describe( - "the hub origin, e.g. http://localhost:3000", - ), - "BASE_URL?": type(HTTP_URL).describe( - "an http(s) origin, e.g. http://localhost:3000", - ), - "HUB_ADMIN_EMAIL?": type(/^[^@\s]+@[^@\s]+$/).describe( - "the email address for the administrator account, e.g. admin@example.com", - ), - "HUB_ADMIN_PASSWORD?": type("string >= 8").describe( - "the administrator password, at least 8 characters", - ), - "ORG_SLUG?": type(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/).describe( - "alias for WORKBENCH_DEFAULT_TENANT when that is unset — a lowercase-kebab root/operator bench slug, e.g. workbench", - ), - "WORKBENCH_DEFAULT_TENANT?": type( - /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/, - ).describe( - "slug of the root tenant the hub ensures at boot; setup and seed resolve the same slug — ORG_SLUG is an alias when this is unset; default workbench", - ), -} as const; - -const SetupEnv = type({ - ...SharedEnv, - "ORG_NAME?": type("string > 0").describe( - "the bench display name, e.g. Workbench", - ), -}); - -const SeedEnv = type({ - ...SharedEnv, - "ANTHROPIC_API_KEY?": type("string > 0").describe( - "your Anthropic API key; optional, but required for the tenant catalog to be launchable", - ), - "WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS?": type("string").describe( - "set to 1 to also deploy the zero-cost catalog-test workflows (heartbeat); a dev/CI-only opt-in, never set for a real bench", - ), -}); - -const DEFAULT_MODEL_PROVIDER = "anthropic"; -const DEFAULT_MODEL = "claude-sonnet-5"; -const DEFAULT_MODEL_BASE_URL = "https://api.anthropic.com"; - -export type SetupConfig = { - readonly hubUrl: string; - readonly adminEmail: string; - readonly adminDefaulted: boolean; - readonly adminPassword: string; - readonly orgName: string; - readonly orgSlug: string; -}; - -export type { ModelSource }; - -export type SeedConfig = { - readonly hubUrl: string; - readonly adminEmail: string; - readonly adminDefaulted: boolean; - readonly adminPassword: string; - readonly orgSlug: string; - /** Always anthropic/claude-sonnet-5; carries a placeholder key when - * ANTHROPIC_API_KEY is unset, so the default workflow set still - * deploys. */ - readonly modelSource: ModelSource; - readonly anthropicApiKeyConfigured: boolean; - /** - * Opt-in, from WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS: also deploy - * the zero-cost catalog-test workflows (heartbeat) alongside the real - * default set. Unset for a real bench — these exist only to exercise - * the platform, not for a real user. - */ - readonly seedCatalogTestWorkflows: boolean; -}; - -function environmentError(command: string, problems: string[]): CliError { - return new CliError( - `invalid environment for \`workbench ${command}\`:\n ${problems.join("\n ")}`, - "set the variables above (in .env at the repository root, or exported in the environment), then re-run the command", - ); -} - -function resolveHubURL(env: { - HUB_URL?: string; - BASE_URL?: string; -}): string | undefined { - return env.HUB_URL ?? env.BASE_URL; -} - -// Interchange's own dev tooling defaults the admin identity ("unset -// values fall back to the seed defaults") so a fresh clone runs with -// zero .env edits. Real deployments set HUB_ADMIN_EMAIL and -// HUB_ADMIN_PASSWORD; the loud line below is the reminder. -const DEFAULT_ADMIN_EMAIL = "alice@example.com"; -const DEFAULT_ADMIN_PASSWORD = "password123"; - -function adminIdentityFrom(parsed: { - HUB_ADMIN_EMAIL?: string; - HUB_ADMIN_PASSWORD?: string; -}): { adminEmail: string; adminPassword: string; adminDefaulted: boolean } { - return { - adminEmail: parsed.HUB_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL, - adminPassword: parsed.HUB_ADMIN_PASSWORD ?? DEFAULT_ADMIN_PASSWORD, - adminDefaulted: - parsed.HUB_ADMIN_EMAIL === undefined || - parsed.HUB_ADMIN_PASSWORD === undefined, - }; -} - -/** Parse the environment `workbench setup` needs, or fail loudly. */ -export function readSetupConfig( - env: Record, -): SetupConfig { - const parsed = SetupEnv(env); - if (parsed instanceof type.errors) { - throw environmentError("setup", [parsed.summary]); - } - const hubUrl = resolveHubURL(parsed); - if (hubUrl === undefined) { - throw environmentError("setup", [ - "HUB_URL or BASE_URL must name the hub origin, e.g. http://localhost:3000", - ]); - } - const admin = adminIdentityFrom(parsed); - return { - hubUrl, - adminEmail: admin.adminEmail, - adminPassword: admin.adminPassword, - adminDefaulted: admin.adminDefaulted, - orgName: parsed.ORG_NAME ?? "Workbench", - orgSlug: parsed.WORKBENCH_DEFAULT_TENANT ?? parsed.ORG_SLUG ?? "workbench", - }; -} - -/** Parse the environment `workbench seed` needs, or fail loudly. */ -export function readSeedConfig( - env: Record, -): SeedConfig { - const parsed = SeedEnv(env); - if (parsed instanceof type.errors) { - throw environmentError("seed", [parsed.summary]); - } - const hubUrl = resolveHubURL(parsed); - if (hubUrl === undefined) { - throw environmentError("seed", [ - "HUB_URL or BASE_URL must name the hub origin, e.g. http://localhost:3000", - ]); - } - const apiKey = parsed.ANTHROPIC_API_KEY; - const admin = adminIdentityFrom(parsed); - return { - hubUrl, - adminEmail: admin.adminEmail, - adminPassword: admin.adminPassword, - adminDefaulted: admin.adminDefaulted, - orgSlug: parsed.WORKBENCH_DEFAULT_TENANT ?? parsed.ORG_SLUG ?? "workbench", - modelSource: { - provider: DEFAULT_MODEL_PROVIDER, - model: DEFAULT_MODEL, - baseURL: DEFAULT_MODEL_BASE_URL, - apiKey: apiKey ?? PLACEHOLDER_CATALOG_API_KEY, - }, - anthropicApiKeyConfigured: apiKey !== undefined, - seedCatalogTestWorkflows: - parsed.WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS === "1", - }; -} - -/** - * The variable `workbench seed` reads for its model credential. - * `setup` prints this so the one thing the platform cannot provision - * for you is never a surprise; it is optional — seeding still deploys - * the default workflow set and plants the tenant catalog's model data - * without it, but nothing is launchable until it is set. - */ -export const MODEL_CREDENTIAL_VARIABLES = [ - "ANTHROPIC_API_KEY (optional; your Anthropic API key, needed to make the catalog launchable)", -] as const; diff --git a/packages/cli/src/db-setup.ts b/packages/cli/src/db-setup.ts deleted file mode 100644 index c6619ea98..000000000 --- a/packages/cli/src/db-setup.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Database initialization is owned by the shared script at -// scripts/db-setup.ts; the setup verb consumes it as a child process — -// the one surface every runnable script guarantees — so this package -// never re-implements migrations. The script inherits stdio, so its -// own loud failure reporting reaches the operator verbatim. - -import { existsSync } from "node:fs"; -import { join } from "node:path"; -import { CliError } from "@workbench/hub-client"; - -function createScriptRunner( - repoRoot: string, - scriptRelativePath: string, - verb: string, - failureHint: string, -): () => Promise { - return async () => { - const script = join(repoRoot, ...scriptRelativePath.split("/")); - if (!existsSync(script)) { - throw new CliError( - `the ${verb} script is missing: ${script}`, - `restore it from version control (\`git checkout -- ${scriptRelativePath}\`), then re-run: workbench ${verb}`, - ); - } - const child = Bun.spawn(["bun", script], { - cwd: repoRoot, - stdout: "inherit", - stderr: "inherit", - }); - const code = await child.exited; - if (code !== 0) { - throw new CliError( - `${verb} failed: ${scriptRelativePath} exited with code ${code}`, - `${failureHint}, then re-run: workbench ${verb}`, - ); - } - }; -} - -export function createDbSetupRunner(repoRoot: string): () => Promise { - return createScriptRunner( - repoRoot, - "scripts/db-setup.ts", - "setup", - "fix the problem it reported above (is Postgres running and DATABASE_URL correct?)", - ); -} - -export function createResetRunner(repoRoot: string): () => Promise { - return createScriptRunner( - repoRoot, - "scripts/reset.ts", - "reset", - "fix the problem it reported above (is Postgres running, and does DATABASE_URL point at your local database?)", - ); -} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts deleted file mode 100755 index e5aff640a..000000000 --- a/packages/cli/src/index.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Entry point for the `workbench` command: three curated verbs, no -// generic flags, no raw-API escape hatch, and nothing interactive — -// the same invocations serve local bootstrap and hosted provisioning. - -import { resolve } from "node:path"; -import { - createGitWorkflowPusher, - createHubAPI, - isCliError, -} from "@workbench/hub-client"; -import { readSeedConfig, readSetupConfig } from "./config"; -import { createDbSetupRunner, createResetRunner } from "./db-setup"; -import { runReset } from "./reset"; -import { runSeed } from "./seed"; -import { runSetup } from "./setup"; - -const REPO_ROOT = resolve(import.meta.dir, "..", "..", ".."); - -const USAGE = `usage: workbench - -commands: - setup initialize the database, provision the bench, and - report what you still need to supply - seed deploy the default workflow set to the bench and - confirm every deployment answers - reset tear down local state (database schema and on-disk - asset state) so the next \`bun run dev\` starts fresh; - refuses against anything but a local DATABASE_URL - -All three commands read their configuration from the environment (see -.env.example at the repository root) and are safe to re-run. -`; - -function out(line: string): void { - process.stdout.write(`${line}\n`); -} - -function fail(problem: string, fix: string): never { - process.stderr.write(`error: ${problem}\n fix: ${fix}\n`); - process.exit(1); -} - -async function main(argv: string[]): Promise { - const [command, ...rest] = argv; - if (command === undefined || command === "help" || command === "--help") { - process.stdout.write(USAGE); - process.exit(command === undefined ? 1 : 0); - } - if (rest.length > 0) { - fail( - `unexpected argument${rest.length > 1 ? "s" : ""}: ${rest.join(" ")}`, - `\`workbench ${command}\` takes no arguments; configuration comes from the environment`, - ); - } - - switch (command) { - case "setup": { - const config = readSetupConfig(process.env); - await runSetup({ - config, - api: createHubAPI(config.hubUrl), - runDbSetup: createDbSetupRunner(REPO_ROOT), - log: out, - }); - return; - } - case "seed": { - const config = readSeedConfig(process.env); - await runSeed({ - config, - api: createHubAPI(config.hubUrl), - pushWorkflow: createGitWorkflowPusher(), - log: out, - }); - return; - } - case "reset": { - await runReset({ - runReset: createResetRunner(REPO_ROOT), - log: out, - }); - return; - } - default: - fail( - `unknown command: ${command}`, - "run `workbench help` for the list of commands", - ); - } -} - -try { - await main(process.argv.slice(2)); -} catch (error) { - if (isCliError(error)) fail(error.message, error.fix); - throw error; -} diff --git a/packages/cli/src/lib.ts b/packages/cli/src/lib.ts deleted file mode 100644 index 312624127..000000000 --- a/packages/cli/src/lib.ts +++ /dev/null @@ -1,12 +0,0 @@ -// The library entry for `@workbench/cli`: the environment schemas the -// `setup` and `seed` verbs read. The tenant-seeding logic itself lives -// in `@workbench/hub-client`, which any other consumer (the first-login -// provisioning hook, in particular) depends on directly instead of on -// this CLI package. - -export type { ModelSource, SeedConfig, SetupConfig } from "./config"; -export { - MODEL_CREDENTIAL_VARIABLES, - readSeedConfig, - readSetupConfig, -} from "./config"; diff --git a/packages/cli/src/reset.ts b/packages/cli/src/reset.ts deleted file mode 100644 index 8124049cc..000000000 --- a/packages/cli/src/reset.ts +++ /dev/null @@ -1,22 +0,0 @@ -// `workbench reset`: tear down local state — the platform schema and -// the on-disk asset directories `scripts/reset.ts` owns — so the next -// `bun run dev` lands on a virgin onboarding flow. No hub call: unlike -// setup and seed, reset only touches the database and the filesystem -// directly, so it works even when the hub is not running. - -export type ResetDeps = { - runReset: () => Promise; - log: (line: string) => void; -}; - -export async function runReset(deps: ResetDeps): Promise { - deps.log( - "resetting local state (database schema and on-disk asset state)...", - ); - await deps.runReset(); - deps.log(""); - deps.log("reset complete. next: bun run dev"); - deps.log( - " (or: workbench setup && workbench seed, to reprovision without going through onboarding)", - ); -} diff --git a/packages/cli/src/seed.ts b/packages/cli/src/seed.ts deleted file mode 100644 index 8e3337ca2..000000000 --- a/packages/cli/src/seed.ts +++ /dev/null @@ -1,156 +0,0 @@ -// `workbench seed`: authenticate as the administrator, resolve the -// configured bench by slug, and deploy the default workflow set -// through `@workbench/hub-client`'s `seedTenant`. Does not pack -// tarballs — `workbench setup` publishes `corbits-tools` onto the -// root. Safe to re-run; every skipped step says so. - -import { paginatedSchema, PrincipalSummary, TenantResponse } from "@intx/types"; -import { - authenticate, - parseAs, - seedCatalog, - seedTenant, - CATALOG_TEST_WORKFLOWS, - DEFAULT_WORKFLOWS, - type ApiCall, - type DefaultWorkflow, - type WorkflowPusher, -} from "@workbench/hub-client"; -import { CliError } from "@workbench/hub-client"; -import type { SeedConfig } from "./config"; - -export type SeedDeps = { - config: SeedConfig; - api: ApiCall; - pushWorkflow: WorkflowPusher; - log: (line: string) => void; - sleep?: (ms: number) => Promise; - runStartTimeoutMs?: number; - runPollIntervalMs?: number; - /** - * Plant a placeholder catalog credential when ANTHROPIC_API_KEY is - * not set, so the tenant catalog is launchable without a real key. - * Plain `workbench seed` never sets this; the local dev bootstrap and - * the e2e harness do, since they need a launchable channel anchor - * without a real key. - */ - placeholderCredential?: boolean; -}; - -async function resolveTenant( - api: ApiCall, - cookies: string[], - slug: string, -): Promise<{ tenantId: string; principalId: string; domain: string }> { - const principals = await api("GET", "/api/me/principals", undefined, cookies); - const summary = parseAs( - paginatedSchema(PrincipalSummary), - principals.data, - "principals response", - ); - const membership = summary.data.find((p) => p.tenantSlug === slug); - if (!membership) { - throw new CliError( - `bench ${slug} does not exist on the hub (or this account is not a member of it)`, - "provision it first: workbench setup — then re-run: workbench seed", - ); - } - const tenant = await api( - "GET", - `/api/tenants/${membership.tenantId}`, - undefined, - cookies, - ); - if (tenant.status !== 200) { - throw new CliError( - `the hub refused to describe bench ${slug} (status ${tenant.status}): ${JSON.stringify(tenant.data)}`, - "check the hub logs for the underlying failure, then re-run: workbench seed", - ); - } - const row = parseAs(TenantResponse, tenant.data, "tenant response"); - return { - tenantId: membership.tenantId, - principalId: membership.principalId, - domain: row.domain, - }; -} - -/** - * The workflow set a plain `workbench seed` deploys: the real default - * set every tenant gets, plus the zero-cost catalog-test workflows - * only when the caller has explicitly opted in via - * `WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS`. A real bench never sets - * that variable, so it only ever gets `DEFAULT_WORKFLOWS` — the same - * set `provisionPersonalTenantIfNeeded` deploys on first login. - */ -export function resolveSeedWorkflows( - config: Pick, -): readonly DefaultWorkflow[] { - return config.seedCatalogTestWorkflows - ? [...DEFAULT_WORKFLOWS, ...CATALOG_TEST_WORKFLOWS] - : DEFAULT_WORKFLOWS; -} - -export async function runSeed( - deps: SeedDeps, - workflows?: readonly DefaultWorkflow[], -): Promise { - const { config, api, log } = deps; - if (config.adminDefaulted) { - log( - "using default admin alice@example.com — set HUB_ADMIN_EMAIL and HUB_ADMIN_PASSWORD for real deployments", - ); - } - const resolvedWorkflows = workflows ?? resolveSeedWorkflows(config); - if (config.seedCatalogTestWorkflows) { - log( - "WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS=1: also deploying the zero-cost catalog-test workflows (heartbeat)", - ); - } - - const session = await authenticate(api, { - email: config.adminEmail, - password: config.adminPassword, - }); - const cookies = session.cookies; - const tenant = await resolveTenant(api, cookies, config.orgSlug); - log(`seeding bench ${config.orgSlug} (${tenant.tenantId})`); - - const seedArgs: Parameters[0] = { - api, - cookies, - hubUrl: config.hubUrl, - tenant, - model: config.modelSource, - pushWorkflow: deps.pushWorkflow, - log, - workflows: resolvedWorkflows, - }; - if (deps.sleep !== undefined) seedArgs.sleep = deps.sleep; - if (deps.runStartTimeoutMs !== undefined) - seedArgs.runStartTimeoutMs = deps.runStartTimeoutMs; - if (deps.runPollIntervalMs !== undefined) - seedArgs.runPollIntervalMs = deps.runPollIntervalMs; - - await seedTenant(seedArgs); - - if ( - !config.anthropicApiKeyConfigured && - deps.placeholderCredential !== true - ) { - log( - "ANTHROPIC_API_KEY is not set; the tenant catalog is seeded with data only — no credential is planted, so channels and workflows cannot launch until you set it, then either re-run: workbench seed, or set it in the hub's own environment and restart it (the env-key auto-plant, CL-6101, plants it with no other step)", - ); - } - const seedCatalogArgs: Parameters[0] = { - api, - cookies, - tenantId: tenant.tenantId, - log, - }; - if (config.anthropicApiKeyConfigured) - seedCatalogArgs.apiKey = config.modelSource.apiKey; - if (deps.placeholderCredential === true) - seedCatalogArgs.placeholderCredential = true; - await seedCatalog(seedCatalogArgs); -} diff --git a/packages/cli/src/setup.ts b/packages/cli/src/setup.ts deleted file mode 100644 index 0e034b57d..000000000 --- a/packages/cli/src/setup.ts +++ /dev/null @@ -1,178 +0,0 @@ -// `workbench setup`: initialize the database, provision the -// bench through the hub's native tenant-creation route, publish -// the platform `corbits-tools` registry onto that tenant (the -// hub boot's default tenant parents personal benches under it; -// descendants inherit the registry), report the role defaults the -// platform created, and state exactly what the operator must -// still supply. Safe to re-run; every skipped step says so. - -import { - paginatedSchema, - PrincipalSummary, - RoleResponse, - TenantResponse, -} from "@intx/types"; -import { - authenticate, - parseAs, - CliError, - publishCorbitsToolsRegistry, - type ApiCall, - type ToolRegistryPublisher, -} from "@workbench/hub-client"; -import { MODEL_CREDENTIAL_VARIABLES, type SetupConfig } from "./config"; - -export type SetupDeps = { - config: SetupConfig; - api: ApiCall; - /** Runs the shared database-initialization script; throws CliError. */ - runDbSetup: () => Promise; - log: (line: string) => void; - /** - * Publishes `corbits-tools` onto the bench this setup creates. - * Defaults to the real packer; tests pass a double so they never - * bundle a tarball. - */ - publishToolRegistry?: ToolRegistryPublisher; -}; - -async function ensureTenant( - api: ApiCall, - cookies: string[], - args: { name: string; slug: string }, - log: (line: string) => void, -): Promise { - const created = await api( - "POST", - "/api/tenants", - { name: args.name, slug: args.slug }, - cookies, - ); - if (created.status === 201) { - const tenant = parseAs(TenantResponse, created.data, "tenant response"); - log(`created bench ${args.slug} (${tenant.id})`); - return tenant.id; - } - - const principals = await api("GET", "/api/me/principals", undefined, cookies); - const summary = parseAs( - paginatedSchema(PrincipalSummary), - principals.data, - "principals response", - ); - const existing = summary.data.find((p) => p.tenantSlug === args.slug); - if (existing) { - log(`bench ${args.slug} already exists (skipped)`); - return existing.tenantId; - } - - const hubError = - created.status === 403 && - typeof created.data === "object" && - created.data !== null && - "error" in created.data && - typeof created.data.error === "object" && - created.data.error !== null && - "code" in created.data.error && - created.data.error.code === "signup_not_allowed" - ? created.data.error - : undefined; - if (hubError !== undefined && "message" in hubError) { - throw new CliError( - String(hubError.message), - "set ALLOW_UNVERIFIED_EMAILS=1 in .env for local development, then re-run: workbench setup", - ); - } - - throw new CliError( - `the hub rejected creation of bench ${args.slug} with status ${created.status}: ${JSON.stringify(created.data)}`, - "pick a different ORG_SLUG, or check the hub logs for the underlying failure, then re-run: workbench setup", - ); -} - -export async function runSetup(deps: SetupDeps): Promise { - const { config, api, log } = deps; - if (config.adminDefaulted) { - log( - "using default admin alice@example.com — set HUB_ADMIN_EMAIL and HUB_ADMIN_PASSWORD for real deployments", - ); - } - - log("initializing database..."); - await deps.runDbSetup(); - - const session = await authenticate(api, { - email: config.adminEmail, - password: config.adminPassword, - }); - log( - session.signedUp - ? `created administrator ${config.adminEmail}` - : `administrator ${config.adminEmail} already exists (skipped)`, - ); - - const tenantId = await ensureTenant( - api, - session.cookies, - { name: config.orgName, slug: config.orgSlug }, - log, - ); - - const roles = await api( - "GET", - `/api/tenants/${tenantId}/roles?limit=100`, - undefined, - session.cookies, - ); - const roleList = parseAs( - paginatedSchema(RoleResponse), - roles.data, - "roles response", - ).data; - if (roleList.length === 0) { - throw new CliError( - `bench ${config.orgSlug} has zero roles; the platform should have created its role defaults (owner, admin, member) at tenant creation`, - "check the hub logs for the tenant-creation failure, then re-run: workbench setup", - ); - } - log( - `role defaults in place: ${roleList - .map((r) => r.name) - .sort() - .join(", ")}`, - ); - - const publishToolRegistry = - deps.publishToolRegistry ?? publishCorbitsToolsRegistry; - try { - const published = await publishToolRegistry({ - api, - cookies: session.cookies, - hubUrl: config.hubUrl, - tenantId, - log, - }); - if (Array.isArray(published) && published.length === 0) { - log( - `platform corbits-tools registry already on bench ${config.orgSlug} (skipped)`, - ); - } else { - log( - `published the platform corbits-tools registry onto bench ${config.orgSlug} (${tenantId})`, - ); - } - } catch (cause) { - const message = cause instanceof Error ? cause.message : String(cause); - throw new CliError( - `publishing the corbits-tools package-registry asset failed: ${message}`, - "check the hub logs for the underlying failure, then re-run: workbench setup", - { cause }, - ); - } - - log(""); - log("setup complete. next: workbench seed"); - for (const variable of MODEL_CREDENTIAL_VARIABLES) { - log(` ${variable}`); - } -} diff --git a/packages/cli/test/config.test.ts b/packages/cli/test/config.test.ts deleted file mode 100644 index d39e73f14..000000000 --- a/packages/cli/test/config.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { - MODEL_CREDENTIAL_VARIABLES, - readSeedConfig, - readSetupConfig, -} from "../src/config"; -import { CliError } from "@workbench/hub-client"; - -const VALID_SHARED = { - BASE_URL: "http://localhost:3000", - HUB_ADMIN_EMAIL: "admin@example.com", - HUB_ADMIN_PASSWORD: "password123", -}; - -describe("readSetupConfig", () => { - test("defaults the admin identity when the variables are unset", () => { - const config = readSetupConfig({ BASE_URL: "http://localhost:3000" }); - expect(config.adminEmail).toBe("alice@example.com"); - expect(config.adminPassword).toBe("password123"); - }); - - test("reports a malformed admin email with a fix", () => { - let caught: unknown; - try { - readSetupConfig({ - BASE_URL: "http://localhost:3000", - HUB_ADMIN_EMAIL: "not-an-email", - }); - } catch (error) { - caught = error; - } - expect(caught).toBeInstanceOf(CliError); - const error = caught as CliError; - expect(error.message).toContain("HUB_ADMIN_EMAIL"); - expect(error.fix).toContain(".env"); - }); - - test("names the hub URL when neither HUB_URL nor BASE_URL is set", () => { - expect(() => - readSetupConfig({ - HUB_ADMIN_EMAIL: "admin@example.com", - HUB_ADMIN_PASSWORD: "password123", - }), - ).toThrow(/HUB_URL or BASE_URL/); - }); - - test("resolves defaults at the edge and prefers HUB_URL", () => { - const config = readSetupConfig({ - ...VALID_SHARED, - HUB_URL: "http://hub.internal:8080", - }); - expect(config.hubUrl).toBe("http://hub.internal:8080"); - expect(config.orgName).toBe("Workbench"); - expect(config.orgSlug).toBe("workbench"); - }); - - test("falls back to BASE_URL for the hub origin", () => { - expect(readSetupConfig(VALID_SHARED).hubUrl).toBe("http://localhost:3000"); - }); - - test("rejects a malformed bench slug", () => { - expect(() => - readSetupConfig({ ...VALID_SHARED, ORG_SLUG: "Not A Slug" }), - ).toThrow(CliError); - }); - - test("ORG_SLUG sets the bench slug when WORKBENCH_DEFAULT_TENANT is unset", () => { - expect(readSetupConfig({ ...VALID_SHARED, ORG_SLUG: "acme" }).orgSlug).toBe( - "acme", - ); - }); - - test("WORKBENCH_DEFAULT_TENANT wins over ORG_SLUG for the bench slug", () => { - expect( - readSetupConfig({ - ...VALID_SHARED, - WORKBENCH_DEFAULT_TENANT: "root", - ORG_SLUG: "acme", - }).orgSlug, - ).toBe("root"); - }); -}); - -describe("readSeedConfig", () => { - test("ANTHROPIC_API_KEY is optional", () => { - const config = readSeedConfig(VALID_SHARED); - expect(config.anthropicApiKeyConfigured).toBe(false); - expect(config.modelSource).toEqual({ - provider: "anthropic", - model: "claude-sonnet-5", - baseURL: "https://api.anthropic.com", - apiKey: "placeholder-not-a-real-key", - }); - }); - - test("a configured ANTHROPIC_API_KEY is used as the model source's key", () => { - const config = readSeedConfig({ - ...VALID_SHARED, - ANTHROPIC_API_KEY: "sk-ant-test", - }); - expect(config.anthropicApiKeyConfigured).toBe(true); - expect(config.modelSource).toEqual({ - provider: "anthropic", - model: "claude-sonnet-5", - baseURL: "https://api.anthropic.com", - apiKey: "sk-ant-test", - }); - }); - - test("the credential checklist setup prints names ANTHROPIC_API_KEY", () => { - expect(MODEL_CREDENTIAL_VARIABLES.length).toBe(1); - expect(MODEL_CREDENTIAL_VARIABLES[0]).toContain("ANTHROPIC_API_KEY"); - }); - - test("the catalog-test workflow opt-in defaults off", () => { - expect(readSeedConfig(VALID_SHARED).seedCatalogTestWorkflows).toBe(false); - }); - - test("WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS=1 opts into the catalog-test workflows", () => { - const config = readSeedConfig({ - ...VALID_SHARED, - WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS: "1", - }); - expect(config.seedCatalogTestWorkflows).toBe(true); - }); - - test("any other value for WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS stays opted out", () => { - const config = readSeedConfig({ - ...VALID_SHARED, - WORKBENCH_SEED_CATALOG_TEST_WORKFLOWS: "true", - }); - expect(config.seedCatalogTestWorkflows).toBe(false); - }); -}); diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.ts deleted file mode 100644 index 668983f5e..000000000 --- a/packages/cli/test/helpers.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Test doubles for the hub HTTP boundary. Every verb takes its API -// caller as a dependency, so the whole hub collapses to one dispatch -// function per test; an unmatched call fails the test loudly instead -// of vanishing into a stubbed default. - -import type { ApiCall } from "@workbench/hub-client"; - -export type FakeResponse = { status: number; data: unknown }; - -export type FakeHandler = ( - method: string, - path: string, - body: unknown, -) => FakeResponse | undefined; - -export function fakeAPI(handler: FakeHandler): ApiCall { - return async (method, path, body) => { - const response = handler(method, path, body); - if (!response) { - throw new Error(`unexpected hub call: ${method} ${path}`); - } - return { status: response.status, data: response.data, cookies: [] }; - }; -} - -export function collector(): { lines: string[]; log: (line: string) => void } { - const lines: string[] = []; - return { lines, log: (line) => lines.push(line) }; -} - -const TIMESTAMP = "2026-01-01T00:00:00.000Z"; - -export const TENANT_ID = "ten_1"; -export const PRINCIPAL_ID = "prn_1"; -export const ORG_SLUG = "workbench"; -export const TENANT_DOMAIN = "workbench.localhost"; - -export function signUpResponse(): FakeResponse { - return { status: 200, data: { user: { id: "usr_1" } } }; -} - -/** No matching account — authenticate continues to sign-up. */ -export function signInMissing(): FakeResponse { - return { status: 401, data: { error: "invalid credentials" } }; -} - -export function signInResponse(): FakeResponse { - return { status: 200, data: { user: { id: "usr_1" } } }; -} - -export function tenantRow() { - return { - id: TENANT_ID, - name: "Workbench", - slug: ORG_SLUG, - domain: TENANT_DOMAIN, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }; -} - -export function principalsResponse(): FakeResponse { - return { - status: 200, - data: { - data: [ - { - principalId: PRINCIPAL_ID, - tenantId: TENANT_ID, - tenantName: "Workbench", - tenantSlug: ORG_SLUG, - kind: "user", - status: "active", - roles: [{ id: "rol_owner", name: "owner" }], - }, - ], - nextCursor: null, - }, - }; -} - -export function rolesResponse(names: string[]): FakeResponse { - return { - status: 200, - data: { - data: names.map((name, index) => ({ - id: `rol_${index}`, - tenantId: TENANT_ID, - name, - isSystem: true, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - })), - nextCursor: null, - }, - }; -} diff --git a/packages/cli/test/reset.test.ts b/packages/cli/test/reset.test.ts deleted file mode 100644 index c70894abb..000000000 --- a/packages/cli/test/reset.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { runReset } from "../src/reset"; -import { collector } from "./helpers"; - -describe("runReset", () => { - test("runs the reset and reports what to do next", async () => { - const { lines, log } = collector(); - let ran = 0; - await runReset({ - runReset: async () => { - ran += 1; - }, - log, - }); - expect(ran).toBe(1); - const output = lines.join("\n"); - expect(output).toContain("resetting local state"); - expect(output).toContain("reset complete. next: bun run dev"); - expect(output).toContain("workbench setup && workbench seed"); - }); - - test("a failing reset propagates without reporting completion", async () => { - const { lines, log } = collector(); - const failing = async () => { - throw new Error("database unreachable"); - }; - await expect(runReset({ runReset: failing, log })).rejects.toThrow( - "database unreachable", - ); - expect(lines.join("\n")).not.toContain("reset complete"); - }); -}); diff --git a/packages/cli/test/seed.test.ts b/packages/cli/test/seed.test.ts deleted file mode 100644 index 1aa28841d..000000000 --- a/packages/cli/test/seed.test.ts +++ /dev/null @@ -1,532 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { installDisposableHubDataDir } from "../../../test/disposable-hub-data-dir"; -import { CliError } from "@workbench/hub-client"; -import type { SeedConfig } from "../src/config"; -import { resolveSeedWorkflows, runSeed, type SeedDeps } from "../src/seed"; -import { - collector, - fakeAPI, - principalsResponse, - signInMissing, - signUpResponse, - tenantRow, - TENANT_ID, - type FakeHandler, -} from "./helpers"; - -installDisposableHubDataDir(); - -const CONFIG: SeedConfig = { - hubUrl: "http://localhost:3000", - adminDefaulted: false, - adminEmail: "admin@example.com", - adminPassword: "password123", - orgSlug: "workbench", - modelSource: { - provider: "anthropic", - model: "claude-sonnet-5", - baseURL: "https://api.anthropic.com", - apiKey: "placeholder-not-a-real-key", - }, - anthropicApiKeyConfigured: false, - seedCatalogTestWorkflows: false, -}; - -function deps(overrides: Partial & Pick): SeedDeps { - const { log } = collector(); - return { - config: CONFIG, - pushWorkflow: async () => ({ - outcome: "pushed" as const, - commitSha: "a".repeat(40), - }), - log, - ...overrides, - }; -} - -describe("resolveSeedWorkflows", () => { - test("without the opt-in, only the real default workflow set is deployed", () => { - const names = resolveSeedWorkflows({ - seedCatalogTestWorkflows: false, - }).map((w) => w.assetName); - expect(names).toEqual([ - "assistant", - "echo", - "workbench-digest", - "last-30-days-research", - ]); - }); - - test("with the opt-in, the catalog-test workflows are appended", () => { - const names = resolveSeedWorkflows({ - seedCatalogTestWorkflows: true, - }).map((w) => w.assetName); - expect(names).toEqual([ - "assistant", - "echo", - "workbench-digest", - "last-30-days-research", - "heartbeat", - ]); - }); -}); - -describe("runSeed", () => { - test("authenticates, resolves the bench by slug, and starts seeding it", async () => { - const { lines, log } = collector(); - const handler: FakeHandler = (method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "GET" && path === "/api/me/principals") - return principalsResponse(); - if (method === "GET" && path === `/api/tenants/${TENANT_ID}`) - return { status: 200, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/grants?`) - ) - return { status: 200, data: { data: [], nextCursor: null } }; - return undefined; - }; - - // Resolving the bench succeeds and hands off into seedTenant; the - // very next unhandled call (planting the first seed grant) proves - // the handoff happened without re-testing seedTenant's own - // mechanics, which belong to @workbench/hub-client. - expect(runSeed(deps({ api: fakeAPI(handler), log }))).rejects.toThrow( - /unexpected hub call/, - ); - expect(lines.join("\n")).toContain( - `seeding bench workbench (${TENANT_ID})`, - ); - }); - - test("seeds the tenant catalog's inference source after the tenant is seeded", async () => { - const { lines, log } = collector(); - const TIMESTAMP = "2026-01-01T00:00:00.000Z"; - const startedRuns: string[] = []; - const handler: FakeHandler = (method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "GET" && path === "/api/me/principals") - return principalsResponse(); - if (method === "GET" && path === `/api/tenants/${TENANT_ID}`) - return { status: 200, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/grants?`) - ) - return { status: 200, data: { data: [], nextCursor: null } }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/grants`) - return { status: 201, data: {} }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/git-tokens`) - return { status: 201, data: { id: "tok_1", secret: "s3cret" } }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/skills/`) - ) - return { status: 404, data: {} }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/skills`) - return { status: 201, data: {} }; - if ( - method === "GET" && - path === - `/api/tenants/${TENANT_ID}/assets?kind=workflow&inherited=false` - ) - return { status: 200, data: [] }; - if (method === "GET" && path === `/api/tenants/${TENANT_ID}/routines`) - return { status: 200, data: { items: [] } }; - if ( - method === "GET" && - path === - `/api/tenants/${TENANT_ID}/assets?kind=workflow&inherited=false` - ) - return { status: 200, data: [] }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/assets`) - return { - status: 201, - data: { - id: "ast_1", - tenantId: TENANT_ID, - kind: "workflow", - name: "echo", - displayName: null, - creatorPrincipalId: null, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "GET" && - path === `/api/tenants/${TENANT_ID}/workflows/deployments` - ) - return { status: 200, data: [] }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/workflows/deployments` - ) - return { - status: 201, - data: { - id: "dep_1", - tenantId: TENANT_ID, - definitionAssetId: "ast_1", - status: "active", - createdAt: TIMESTAMP, - }, - }; - if ( - method === "GET" && - path === `/api/tenants/${TENANT_ID}/workflows/dep_1/runs` - ) { - return { - status: 200, - data: { runIds: [...startedRuns] }, - }; - } - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/workflows/dep_1/mail` - ) { - const runId = `run_${startedRuns.length + 1}`; - startedRuns.push(runId); - return { - status: 202, - data: { - runId: "dep_1", - address: "ins_dep_1@workbench.localhost", - messageId: ``, - }, - }; - } - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/providers`) - return { - status: 201, - data: { - id: "prv_1", - tenantId: TENANT_ID, - name: "anthropic", - plugin: "anthropic", - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/credentials`) - return { - status: 201, - data: { - id: "cre_1", - tenantId: TENANT_ID, - providerId: "prv_1", - name: "anthropic-default", - type: "api_key", - status: "active", - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/models` - ) - return { - status: 201, - data: { - id: "mdl_1", - tenantId: TENANT_ID, - canonicalName: "claude-sonnet-5", - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/providers` - ) - return { - status: 201, - data: { - id: "cpv_1", - tenantId: TENANT_ID, - name: "anthropic", - plugin: "anthropic", - baseURL: "https://api.anthropic.com", - credentialId: "cre_1", - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/offerings` - ) - return { - status: 201, - data: { - id: "off_1", - tenantId: TENANT_ID, - modelId: "mdl_1", - providerId: "cpv_1", - priority: 0, - deploymentTags: [], - capabilities: [], - quirks: null, - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - return undefined; - }; - - await runSeed( - deps({ - api: fakeAPI(handler), - pushWorkflow: async () => ({ - outcome: "pushed" as const, - commitSha: "a".repeat(40), - }), - log, - sleep: async () => {}, - runStartTimeoutMs: 3, - runPollIntervalMs: 1, - }), - ); - - const output = lines.join("\n"); - expect(output).toContain( - "ANTHROPIC_API_KEY is not set; the tenant catalog is seeded with data only", - ); - expect(output).toContain("created catalog model claude-sonnet-5"); - }); - - test("placeholderCredential opts into a launchable catalog without a real key", async () => { - const { lines, log } = collector(); - const TIMESTAMP = "2026-01-01T00:00:00.000Z"; - const startedRuns: string[] = []; - const handler: FakeHandler = (method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "GET" && path === "/api/me/principals") - return principalsResponse(); - if (method === "GET" && path === `/api/tenants/${TENANT_ID}`) - return { status: 200, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/grants?`) - ) - return { status: 200, data: { data: [], nextCursor: null } }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/grants`) - return { status: 201, data: {} }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/git-tokens`) - return { status: 201, data: { id: "tok_1", secret: "s3cret" } }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/skills/`) - ) - return { status: 404, data: {} }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/skills`) - return { status: 201, data: {} }; - if ( - method === "GET" && - path === - `/api/tenants/${TENANT_ID}/assets?kind=workflow&inherited=false` - ) - return { status: 200, data: [] }; - if (method === "GET" && path === `/api/tenants/${TENANT_ID}/routines`) - return { status: 200, data: { items: [] } }; - if ( - method === "GET" && - path === - `/api/tenants/${TENANT_ID}/assets?kind=workflow&inherited=false` - ) - return { status: 200, data: [] }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/assets`) - return { - status: 201, - data: { - id: "ast_1", - tenantId: TENANT_ID, - kind: "workflow", - name: "echo", - displayName: null, - creatorPrincipalId: null, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "GET" && - path === `/api/tenants/${TENANT_ID}/workflows/deployments` - ) - return { status: 200, data: [] }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/workflows/deployments` - ) - return { - status: 201, - data: { - id: "dep_1", - tenantId: TENANT_ID, - definitionAssetId: "ast_1", - status: "active", - createdAt: TIMESTAMP, - }, - }; - if ( - method === "GET" && - path === `/api/tenants/${TENANT_ID}/workflows/dep_1/runs` - ) { - return { - status: 200, - data: { runIds: [...startedRuns] }, - }; - } - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/workflows/dep_1/mail` - ) { - const runId = `run_${startedRuns.length + 1}`; - startedRuns.push(runId); - return { - status: 202, - data: { - runId: "dep_1", - address: "ins_dep_1@workbench.localhost", - messageId: ``, - }, - }; - } - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/providers`) - return { - status: 201, - data: { - id: "prv_1", - tenantId: TENANT_ID, - name: "anthropic", - plugin: "anthropic", - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if (method === "POST" && path === `/api/tenants/${TENANT_ID}/credentials`) - return { - status: 201, - data: { - id: "cre_1", - tenantId: TENANT_ID, - providerId: "prv_1", - name: "anthropic-default", - type: "api_key", - status: "active", - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/models` - ) - return { - status: 201, - data: { - id: "mdl_1", - tenantId: TENANT_ID, - canonicalName: "claude-sonnet-5", - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/providers` - ) - return { - status: 201, - data: { - id: "cpv_1", - tenantId: TENANT_ID, - name: "anthropic", - plugin: "anthropic", - baseURL: "https://api.anthropic.com", - credentialId: "cre_1", - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - if ( - method === "POST" && - path === `/api/tenants/${TENANT_ID}/catalog/offerings` - ) - return { - status: 201, - data: { - id: "off_1", - tenantId: TENANT_ID, - modelId: "mdl_1", - providerId: "cpv_1", - priority: 0, - deploymentTags: [], - capabilities: [], - quirks: null, - disabled: false, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - }, - }; - return undefined; - }; - - await runSeed( - deps({ - api: fakeAPI(handler), - pushWorkflow: async () => ({ - outcome: "pushed" as const, - commitSha: "a".repeat(40), - }), - log, - sleep: async () => {}, - runStartTimeoutMs: 3, - runPollIntervalMs: 1, - placeholderCredential: true, - }), - ); - - const output = lines.join("\n"); - expect(output).not.toContain("seeded with data only"); - expect(output).toContain("catalog ready: anthropic/claude-sonnet-5"); - }); - - test("a missing bench points at workbench setup", async () => { - const handler: FakeHandler = (method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "GET" && path === "/api/me/principals") - return { status: 200, data: { data: [], nextCursor: null } }; - return undefined; - }; - - let caught: unknown; - try { - await runSeed(deps({ api: fakeAPI(handler) })); - } catch (error) { - caught = error; - } - expect(caught).toBeInstanceOf(CliError); - expect((caught as CliError).fix).toContain("workbench setup"); - }); -}); diff --git a/packages/cli/test/setup.test.ts b/packages/cli/test/setup.test.ts deleted file mode 100644 index d1ce6aad1..000000000 --- a/packages/cli/test/setup.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import type { SetupConfig } from "../src/config"; -import { CliError } from "@workbench/hub-client"; -import { runSetup } from "../src/setup"; -import { - collector, - fakeAPI, - principalsResponse, - rolesResponse, - signInMissing, - signUpResponse, - tenantRow, - TENANT_ID, -} from "./helpers"; - -const CONFIG: SetupConfig = { - hubUrl: "http://localhost:3000", - adminDefaulted: false, - adminEmail: "admin@example.com", - adminPassword: "password123", - orgName: "Workbench", - orgSlug: "workbench", -}; - -const okDbSetup = async () => {}; -const noopPublishToolRegistry = async () => undefined; - -describe("runSetup", () => { - test("fresh run initializes, provisions, and reports what remains", async () => { - const { lines, log } = collector(); - let dbSetupRuns = 0; - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 201, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/roles`) - ) - return rolesResponse(["owner", "admin", "member"]); - return undefined; - }); - - await runSetup({ - config: CONFIG, - api, - runDbSetup: async () => { - dbSetupRuns += 1; - }, - publishToolRegistry: noopPublishToolRegistry, - log, - }); - - expect(dbSetupRuns).toBe(1); - const output = lines.join("\n"); - expect(output).toContain("created administrator admin@example.com"); - expect(output).toContain("created bench workbench"); - expect(output).toContain( - `published the platform corbits-tools registry onto bench workbench (${TENANT_ID})`, - ); - expect(output).toContain("role defaults in place: admin, member, owner"); - expect(output).toContain("ANTHROPIC_API_KEY"); - expect(output).toContain("workbench seed"); - }); - - test("re-run reports skips instead of duplicating", async () => { - const { lines, log } = collector(); - const publishCalls: { tenantId: string }[] = []; - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 409, data: { error: "slug taken" } }; - if (method === "GET" && path === "/api/me/principals") - return principalsResponse(); - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/roles`) - ) - return rolesResponse(["owner", "admin", "member"]); - return undefined; - }); - - await runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: async (args) => { - publishCalls.push({ tenantId: args.tenantId }); - return []; - }, - log, - }); - - expect(publishCalls).toEqual([{ tenantId: TENANT_ID }]); - - const output = lines.join("\n"); - expect(output).toContain( - "administrator admin@example.com already exists (skipped)", - ); - expect(output).toContain("bench workbench already exists (skipped)"); - expect(output).toContain( - "platform corbits-tools registry already on bench workbench (skipped)", - ); - }); - - test("a database initialization failure stops the run before any hub call", async () => { - const { log } = collector(); - const api = fakeAPI(() => { - throw new Error("the hub must not be called when the database fails"); - }); - const failing = async () => { - throw new CliError("database initialization failed", "start Postgres"); - }; - expect( - runSetup({ - config: CONFIG, - api, - runDbSetup: failing, - publishToolRegistry: noopPublishToolRegistry, - log, - }), - ).rejects.toThrow("database initialization failed"); - }); - - test("zero platform roles is an error, never a silent success", async () => { - const { log } = collector(); - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 201, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/roles`) - ) - return rolesResponse([]); - return undefined; - }); - - expect( - runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: noopPublishToolRegistry, - log, - }), - ).rejects.toThrow(/zero roles/); - }); - - test("a wrong password for an existing administrator names the variable to fix", async () => { - const { log } = collector(); - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return { status: 401, data: {} }; - if (method === "POST" && path === "/api/auth/sign-up/email") - return { status: 422, data: {} }; - return undefined; - }); - - let caught: unknown; - try { - await runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: noopPublishToolRegistry, - log, - }); - } catch (error) { - caught = error; - } - expect(caught).toBeInstanceOf(CliError); - expect((caught as CliError).fix).toContain("HUB_ADMIN_PASSWORD"); - }); - - test("an unverified-email signup rejection names the ALLOW_UNVERIFIED_EMAILS fix", async () => { - const { log } = collector(); - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { - status: 403, - data: { - error: { - code: "signup_not_allowed", - message: - "This account's email address isn't verified, and this hub requires verified emails before provisioning.", - }, - }, - }; - if (method === "GET" && path === "/api/me/principals") - return { status: 200, data: { data: [], nextCursor: null } }; - return undefined; - }); - - let caught: unknown; - try { - await runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: noopPublishToolRegistry, - log, - }); - } catch (error) { - caught = error; - } - expect(caught).toBeInstanceOf(CliError); - expect((caught as CliError).message).toContain("isn't verified"); - expect((caught as CliError).fix).toContain("ALLOW_UNVERIFIED_EMAILS=1"); - }); - - test("an unresolvable tenant conflict fails with the failing status", async () => { - const { log } = collector(); - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 409, data: { error: "slug taken" } }; - if (method === "GET" && path === "/api/me/principals") - return { status: 200, data: { data: [], nextCursor: null } }; - return undefined; - }); - - expect( - runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: noopPublishToolRegistry, - log, - }), - ).rejects.toThrow(/status 409/); - }); - - test("publishes corbits-tools onto the created tenant", async () => { - const { log } = collector(); - const calls: { tenantId: string; hubUrl: string }[] = []; - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 201, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/roles`) - ) - return rolesResponse(["owner", "admin", "member"]); - return undefined; - }); - - await runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: async (args) => { - calls.push({ tenantId: args.tenantId, hubUrl: args.hubUrl }); - return [ - { - filename: "memory-tools-0.0.0.tgz", - commit: "c", - integrity: "i", - }, - ]; - }, - log, - }); - - expect(calls).toEqual([{ tenantId: TENANT_ID, hubUrl: CONFIG.hubUrl }]); - }); - - test("a publisher throw is a setup CliError, not a seed error", async () => { - const { log } = collector(); - const api = fakeAPI((method, path) => { - if (method === "POST" && path === "/api/auth/sign-in/email") - return signInMissing(); - if (method === "POST" && path === "/api/auth/sign-up/email") - return signUpResponse(); - if (method === "POST" && path === "/api/tenants") - return { status: 201, data: tenantRow() }; - if ( - method === "GET" && - path.startsWith(`/api/tenants/${TENANT_ID}/roles`) - ) - return rolesResponse(["owner", "admin", "member"]); - return undefined; - }); - - let caught: unknown; - try { - await runSetup({ - config: CONFIG, - api, - runDbSetup: okDbSetup, - publishToolRegistry: async () => { - throw new Error("src/ changed without bumping version"); - }, - log, - }); - } catch (error) { - caught = error; - } - expect(caught).toBeInstanceOf(CliError); - expect((caught as CliError).message).toContain( - "publishing the corbits-tools package-registry asset failed", - ); - expect((caught as CliError).fix).toContain("workbench setup"); - expect((caught as CliError).fix).not.toContain("workbench seed"); - }); -}); diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json deleted file mode 100644 index d7611c122..000000000 --- a/packages/cli/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src", "test"], - "compilerOptions": { - "types": ["bun"], - "noEmit": true - } -} diff --git a/packages/hub-client/src/index.ts b/packages/hub-client/src/index.ts index a5bf68c04..001873ba9 100644 --- a/packages/hub-client/src/index.ts +++ b/packages/hub-client/src/index.ts @@ -62,6 +62,7 @@ export type { WorkbenchHostInferencePreference, } from "./catalog-seed-data"; export { createGitWorkflowPusher } from "./workflow-push"; +export { ensureDefaultRoutines } from "./default-routines"; export { fetchOllamaModelCatalog, ollamaApiRoot, diff --git a/packages/onboarding/src/index.ts b/packages/onboarding/src/index.ts index 997e7d81b..eccc82070 100644 --- a/packages/onboarding/src/index.ts +++ b/packages/onboarding/src/index.ts @@ -3,10 +3,14 @@ export { provisionPersonalTenantIfNeeded, } from "./provision"; export type { ProvisionArgs, ProvisionResult } from "./provision"; -export { completeCredentialSetup } from "./complete-credential"; +export { + completeCredentialSetup, + findPersonalTenant, +} from "./complete-credential"; export type { CompleteCredentialArgs, CompleteCredentialResult, + PersonalTenant, } from "./complete-credential"; export { createConnectStateStore,