Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
docs: remove docs/features/ and repoint every reference to it
Jose Ramirez4232c50bf553
diff --git a/README.md b/README.mdindex 6cbb9e8c8..ab58a9950 100644--- a/README.md+++ b/README.md@@ -53,15 +53,12 @@ each pillar links to its depth.- **Workflows** — declarative, multi-workload `WorkflowRecipe`s with alifecycle state machine: risk-based approval, shadow testing, automaticrollback, and multi-step coordinator pods. →- [docs/crds/workflowrecipe.md](docs/crds/workflowrecipe.md),- [docs/features/workflow-recipes.md](docs/features/workflow-recipes.md)+ [docs/crds/workflowrecipe.md](docs/crds/workflowrecipe.md)- **Plugins & registry** — author and publish connectors and recipes to agoverned registry (entries carry trust levels and an `author`); build customcoordinator images with `@clerum/workflow-sdk`; install through a governedflow. →- [packages/workflow-sdk/README.md](packages/workflow-sdk/README.md),- [docs/features/custom-coordinator-images.md](docs/features/custom-coordinator-images.md),- [registry guide](docs/features/control-ui-workflow-recipes-and-registry-guide.md)+ [packages/workflow-sdk/README.md](packages/workflow-sdk/README.md)- **Teams & access** — profiles, teams, roles (admin / inviter / member),invitations, and session → scoped-RPC token brokerage. →[external-rest-api/README.md](external-rest-api/README.md),@@ -69,11 +66,11 @@ each pillar links to its depth.- **Files** — `SharedFileSystem` team workspaces (read-only to agents) and abrokered, audited `GlobalFileSystem` drive. →[gfs-controller/README.md](gfs-controller/README.md),- [docs/features/context-filesystem.md](docs/features/context-filesystem.md)+ [docs/crds/sharedfilesystem.md](docs/crds/sharedfilesystem.md)- **Cost & governance** — token budgets per scope with block/warn decisions(opt-in via `CLERUM_BUDGETS_ENABLED`), usage and LLM-price accounting,`WorkflowRecipePolicy`, and a connector-image allowlist. →- [docs/features/token-budgets.md](docs/features/token-budgets.md)+ [docs/crds/workflowrecipepolicy.md](docs/crds/workflowrecipepolicy.md)- **Config as code** — the entire fleet is eight `clerum.io` CRDs:version-controlled, reviewable, and `kubectl`/GitOps-friendly. →[docs/crds/README.md](docs/crds/README.md)diff --git a/docs/README.md b/docs/README.mdindex 187519e39..4a0592918 100644--- a/docs/README.md+++ b/docs/README.md@@ -52,18 +52,6 @@ Use this index for long-form docs.| [llms.txt](llms.txt) | Machine-readable doc map for coding agents || Service READMEs | One-line map per component in the root [README components list](../README.md#docs-and-components) |-## Feature hubs--| Doc | Description |-| ---------------------------------------------------- | ------------------------------------------------------ |-| [WorkflowRecipes](features/workflow-recipes.md) | Landing page for the recipe CRD + ops + architecture |-| [Token budgets & cost](features/token-budgets.md) | Cap LLM tokens/cost per scope; prices; Cost & Usage UI |-| [Context filesystem](features/context-filesystem.md) | Per-context shared file storage (SharedFileSystem) |--> Other files under `features/` include design-depth writeups (custom-> coordinators, OAuth bridge, registry UI, admin workspace provisioning). Prefer-> the hubs and how-tos above unless you are implementing that subsystem.-## Testing| Doc | Description |diff --git a/docs/architecture/platform-topology.md b/docs/architecture/platform-topology.mdindex a49743d4c..2046abfb9 100644--- a/docs/architecture/platform-topology.md+++ b/docs/architecture/platform-topology.md@@ -1078,6 +1078,5 @@ you to expect:## See Also- [WorkflowRecipe CRD schema](../crds/workflowrecipe.md) — living CRD reference-- [WorkflowRecipes feature hub](../features/workflow-recipes.md) — ops, architecture, authoring entry points- [Non-MCP services](non-mcp-services.md) — namespace splitting and L0–L3 NetworkPolicy layers- Public Recipe Registry — external component; client integration lives in this repodiff --git a/docs/crds/sharedfilesystem.md b/docs/crds/sharedfilesystem.mdindex 2830a5682..4edeb2f5d 100644--- a/docs/crds/sharedfilesystem.md+++ b/docs/crds/sharedfilesystem.md@@ -12,9 +12,6 @@ A **per-team shared workspace**: PVC + file API, mounted **read-only** into`mcp-host` pods for Contexts that reference it. Humans/admins write via theworkspace-files controller; agents do not mutate the mount.-Long-form design notes (may include implementation status):-[features/context-filesystem.md](../features/context-filesystem.md).-## Spec fields (summary)| Field | Description |diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.mdindex 9584f9ffc..db9c3f276 100644--- a/docs/crds/workflowrecipe.md+++ b/docs/crds/workflowrecipe.md@@ -2,7 +2,7 @@**API version:** `clerum.io/v1alpha1`**Kind:** `WorkflowRecipe`-**References:** [Platform Architecture](../architecture/platform-topology.md) | [Feature Hub](../features/workflow-recipes.md) | [Operations Guide](../deploy/workflow-recipes-guide.md) | [Architecture Overview](../architecture/overview.md)+**References:** [Platform Architecture](../architecture/platform-topology.md) | [Operations Guide](../deploy/workflow-recipes-guide.md) | [Architecture Overview](../architecture/overview.md)---@@ -4303,5 +4303,4 @@ This section tracks what has been implemented, validated, and deployed from this## Further Reading-- [Feature hub](../features/workflow-recipes.md) — operator docs, ops, and architecture links- [agents/CLERUM_WORKFLOW_RECIPE_GUIDE.md](../agents/CLERUM_WORKFLOW_RECIPE_GUIDE.md) — deep authoring guidediff --git a/docs/crds/workflowrecipepolicy.md b/docs/crds/workflowrecipepolicy.mdindex b8905f0b4..f9f330832 100644--- a/docs/crds/workflowrecipepolicy.md+++ b/docs/crds/workflowrecipepolicy.md@@ -22,8 +22,7 @@ charts/clerum-crds/crds/workflowrecipepolicy.yaml```Use that schema plus operator logs when authoring policies. Narrative and ops-context: [WorkflowRecipes hub](../features/workflow-recipes.md) and-[workflow-recipes-guide](../deploy/workflow-recipes-guide.md).+context: [workflow-recipes-guide](../deploy/workflow-recipes-guide.md).## Relateddiff --git a/docs/features/admin-desktop-workspace-provisioning.md b/docs/features/admin-desktop-workspace-provisioning.mddeleted file mode 100644index 9579d2d6f..000000000--- a/docs/features/admin-desktop-workspace-provisioning.md+++ /dev/null@@ -1,367 +0,0 @@-# Auto-provision the admin's desktop workspace at first-run setup--**Date:** 2026-06-09-**Status:** Design — awaiting review-**Repo:** clerum-**Base branch:** `origin/feat/multiple-admins` (the only branch where first-run Control-UI setup collects the admin _email_; not yet in `dev`)-**Related:** commit `0c4a95c8d` (feat: add Control UI admin setup and invitations), PR #412 (teamless invitations), PR #300 (desktop initial team-directory load)-------## Problem--A freshly onboarded tenant admin can log into the **Control UI** with their-credentials but the **desktop app is dead** — even though login "succeeds".--There are two **separate** identity systems:--| | Control UI admin | Desktop user |-| ---------- | ------------------------------------------------- | --------------------------------------------- |-| Table | `control_admin_users` (username/email + password) | `users` + `team_members` (email + password) |-| Created by | First-run setup (`POST /admin/auth/setup`) | "Invite desktop member" flow, or Google login |--First-run setup only creates a `control_admin_users` row. It never creates a-desktop `users` identity. For an email to actually use the desktop app, the-tenant's `control-api` needs **all five** of:--1. a `users` row (the desktop identity)-2. a desktop password (`users.password_hash`) — in prod only settable via the- invitation / password-setup flow; direct DB seeding is deliberately- prod-blocked (`scripts/e2e/seed-e2e-data.sh`)-3. a **team** the user administers — without it the desktop app has no team- directory to load, and `POST /external/rpc/token` refuses the team-only- `desktop:view` scope: a team-less caller is denied with- `403 desktop_requires_team` (`TEAM_ONLY_RPC_SCOPES` /- `classifyRpcTokenDenial` in `control-api/src/utils/auth/rpcAuthToken.ts`; the- desktop app requests exactly that scope —- `desktop-app/src/appService.ts` `DESKTOP_VIEW_SCOPES`). The login routes do- issue a session token with `teamId: null`, so a team-less session exists —- it just cannot open the desktop surface.-4. ≥1 **agent grant** (e.g. `chatllm`) at user- or team-level, else the desktop- shows "No agents available"-5. ≥1 **context grant** (e.g. `context1`) at user- or team-level--### Why it breaks today--- **Neither login path creates a team** — `googleLoginData()` and- `passwordLoginData()` both heal accepted-invitation memberships and then fall- back to `membership: { team_id: null, role: 'member', team_name: null }`- (`control-api/src/services/directory/login.ts`). The Control UI tolerates a- null team; the desktop app lands in an empty workspace.-- Invitations can be **teamless** (PR #412), and brand-new teams have **zero**- `team_contexts` / `team_agents` — `createTeamForUser` only inserts the team +- the `admin` `team_members` row.--Net: the onboarded admin is a Control-UI operator with no desktop identity,-team, or grants.-------## Goals--- After the admin completes first-run Control-UI setup, the **same- email + password** logs into the **desktop app** and lands in a ready- workspace (team + working agent + context) with **zero extra steps**.-- Fully **idempotent** — safe to re-run; reuses an existing desktop user/team if- one already exists for the email.-- Onboarding is **never blocked** by desktop-provisioning failure: the Control- UI must stay usable.--## Non-goals--- No change to **MCC**. Its `tenant.adminEmail` stays informational.-- Admins added later via the **admin-invitation** flow are out of scope (their- desktop provisioning is a separate operator-vs-user policy decision — see- Future work).-- No changes to the desktop app or Control UI front-ends (server-side only).- An optional Control-UI success hint is listed under Future work.-------## Approach (chosen: "first-run setup provisions the workspace")--### Decisions locked during brainstorming--1. **One credential** — copy the bcrypt hash produced at setup into- `users.password_hash`, so the same email+password works in both apps- immediately. (`bcryptjs` is used by both `adminAuthService` and `login.ts`,- so the hash is directly compatible.)-2. ~~**Login self-heal backstop**~~ — **not shipped.** The plan was to also make- `passwordLoginData` create a default team + grants on first login. What- shipped instead is invitation-membership healing plus a team-less fallback- (see §3). Setup-time provisioning is therefore the only path that creates a- team.-3. **Config-driven defaults** for the granted agent/context names.-------## Detailed design--### 1. Hook point — `POST /admin/auth/setup`--File: `control-api/src/routes/admin/auth.ts` (on `feat/multiple-admins`).--The handler already validates `email`, `username`, `password`, computes-`passwordHash = await bcrypt.hash(password, 12)`, and calls-`setupInitialAdminCredentials(config.adminBootstrapUsername, email, username, passwordHash)`.--After that call succeeds (the control-admin row is committed), add:--```ts-// best-effort: never block onboarding on desktop provisioning-try {- await provisionAdminDesktopWorkspace({- email,- displayName: username,- passwordHash, // SAME hash → one credential for both apps- agentNames: config.adminDefaultAgentNames,- contextIds: config.adminDefaultContextIds,- seedPassword: seedDesktopPassword, // = req.body?.seedDesktopPassword !== false- })-} catch (err) {- logger.error(- { err, email },- 'admin desktop workspace provisioning failed; control admin still created'- )-}-```--The control-admin row is already committed before this runs, so a failure here-leaves the Control UI fully usable — but note the desktop side is then **not**-repaired at login (see §3): re-provisioning is needed.--### 2. New service — `provisionAdminDesktopWorkspace`--New file: `control-api/src/services/directory/adminProvisioning.ts`.-One `withTransaction`, fully idempotent, reusing existing SQL patterns.--```ts-export async function provisionAdminDesktopWorkspace(input: {- email: string- displayName: string- passwordHash: string- agentNames: string[]- contextIds: string[]- /** When false, skip the users.password_hash write — the desktop password then- * comes only from the invitation flow (MCC-driven installs). Defaults true. */- seedPassword?: boolean-}): Promise<void> {- const email = input.email.trim().toLowerCase()- const name = input.displayName.trim() || null- const teamLabel = input.displayName.trim() || email- return withTransaction(async db => {- // (a) ensure users row (reuse if it already exists for this email)- const existing = await db.query(`SELECT id FROM users WHERE email = $1 LIMIT 1`, [email])- let userId = existing.rows[0]?.id as string | undefined- if (!userId) {- const ins = await db.query(`INSERT INTO users(email, name) VALUES($1, $2) RETURNING id`, [- email,- name,- ])- userId = ins.rows[0].id as string- }-- // ensure a profile row exists (mirrors createAdminUser)- await db.query(- `INSERT INTO profiles(user_id, display_name) VALUES($1, $2)- ON CONFLICT (user_id) DO NOTHING`,- [userId, name]- )-- // (b) set desktop password from the setup hash (one credential), unless- // the caller opted out with seedPassword: false- if (input.seedPassword !== false) {- await db.query(- `UPDATE users SET password_hash = $2, password_set_at = NOW(), updated_at = NOW()- WHERE id = $1`,- [userId, input.passwordHash]- )- }-- // (c) + (d) + (e): default team + grants (shared helper, see §4)- await ensureDefaultTeamAndGrants(db, userId, teamLabel, input.agentNames, input.contextIds)- })-}-```--Idempotency: re-running finds the existing user (no duplicate; `users.email` is-`UNIQUE`), re-sets the same password hash (harmless), and `ensureDefaultTeamAndGrants`-skips team creation when the user already owns a team and PUT-replaces grants-with the same values.--### 3. Login self-heal backstop — `passwordLoginData` (NOT SHIPPED)--File: `control-api/src/services/directory/login.ts`.--The plan was to replace the "no membership → return `team_id: null`" branch with-a self-heal that calls `ensureDefaultTeamAndGrants` on first login. **This was-not built.** No login path calls `ensureDefaultTeamAndGrants`; it is only used by-`provisionAdminDesktopWorkspace` (§2).--What `passwordLoginData` actually does when it finds no active membership:--```ts-let membership = await findFirstActiveMembership(db, user.id)-if ((membership.rowCount ?? 0) === 0) {- await healAcceptedInvitationMemberships(db, user.id, user.email)- await linkAcceptedInvitationsToUser(db, user.id, user.email)- membership = await findFirstActiveMembership(db, user.id)-}-// still none → teamlessMemberMembership() = { team_id: null, role: 'member', team_name: null }-```--`googleLoginData` heals unconditionally before its first membership lookup, then-falls back to a pending-invitation membership, then to the same team-less row.-Consequence: a team-less password user is **not** repaired at login — the-workspace only comes from setup-time provisioning.--### 4. Shared helper — `ensureDefaultTeamAndGrants`--Also in `adminProvisioning.ts`, exported for reuse; in the shipped code only §2-calls it.--```ts-export async function ensureDefaultTeamAndGrants(- db: Tx,- userId: string,- displayName: string,- agentNames: string[],- contextIds: string[]-): Promise<string> {- // find an existing active team this user administers- const owned = await db.query(- `SELECT t.id FROM team_members tm JOIN teams t ON t.id = tm.team_id- WHERE tm.user_id = $1 AND tm.status = 'active' AND tm.role = 'admin'- ORDER BY t.created_at ASC LIMIT 1`,- [userId]- )- let teamId = owned.rows[0]?.id as string | undefined- if (!teamId) {- const t = await db.query(`INSERT INTO teams(name) VALUES($1) RETURNING id`, [- `${displayName} team`,- ])- teamId = t.rows[0].id as string- await db.query(- `INSERT INTO team_members(team_id, user_id, role, status)- VALUES($1, $2, 'admin', 'active')- ON CONFLICT (team_id, user_id) DO UPDATE SET role='admin', status='active', updated_at=NOW()`,- [teamId, userId]- )- }- // grant defaults at BOTH team and user level (full-set replace = idempotent)- for (const a of agentNames) {- await db.query(- `INSERT INTO team_agents(team_id, agent_name) VALUES($1,$2) ON CONFLICT DO NOTHING`,- [teamId, a]- )- await db.query(- `INSERT INTO user_agents(user_id, agent_name) VALUES($1,$2) ON CONFLICT DO NOTHING`,- [userId, a]- )- }- for (const c of contextIds) {- await db.query(- `INSERT INTO team_contexts(team_id, context_id) VALUES($1,$2) ON CONFLICT DO NOTHING`,- [teamId, c]- )- await db.query(- `INSERT INTO user_contexts(user_id, context_id) VALUES($1,$2) ON CONFLICT DO NOTHING`,- [userId, c]- )- }- return teamId-}-```--> Implementation note: the existing `setTeamAgents` / `setUserAgents` /-> `setTeamContexts` / `setUserContexts` (in `agentAccess.ts` / `contextAccess.ts`)-> use the pool, not a passed-in `db`/transaction. To keep everything in one-> transaction we inline the inserts here. If those helpers are refactored to-> accept an optional `db`, prefer reusing them.--### 5. Config additions--File: `control-api/src/config.ts`.--```ts-adminDefaultAgentNames: parseCsvList(process.env.CONTROL_API_ADMIN_DEFAULT_AGENT_NAMES || 'chatllm'),-adminDefaultContextIds: parseCsvList(process.env.CONTROL_API_ADMIN_DEFAULT_CONTEXT_IDS || 'context1'),-```--Defaults `chatllm` / `context1` are the canonical deployed names-(`scripts/bootstrap-cluster.sh`, `scripts/e2e/e2e-prod-lib.sh`,-`docs/crds/context.md`). Per-tenant deploys override via the ConfigMap-(`deploy/.../configmaps/control-api-config.yaml`) if their deployed agent/context-names differ.-------## Data model touched--No schema migration. Writes to existing tables only: `users`-(incl. `password_hash`, `password_set_at`), `profiles`, `teams`,-`team_members`, `team_agents`, `user_agents`, `team_contexts`, `user_contexts`.-------## Edge cases--- **Email already a desktop user** (previously invited): reuse the row; set- password from the setup hash (admin re-claims it); ensure team/grants. No- duplicate (`users.email UNIQUE`).-- **User already owns a team**: reuse it; only top up missing grants.-- **Re-run of setup**: `setupInitialAdminCredentials` is a no-op after the first- admin exists (returns `null`), so provisioning won't re-run from setup.- `provisionAdminDesktopWorkspace` is itself safe to call again.-- **Password drift**: if the admin later changes the Control-UI password via- Settings, the desktop `users.password_hash` is **not** updated. Documented- limitation; see Future work for optional sync.-- **Empty config lists**: if an operator sets the default agent/context env to- empty, a team is still created but with no grants (desktop will show empty- catalog) — `log.warn` when the resolved default lists are empty.-------## Testing--**Unit / integration (control-api, vitest + testcontainers Postgres):**--- `provisionAdminDesktopWorkspace` creates user + password + admin team + grants;- re-run is idempotent (no dup user/team, grants stable). With- `seedPassword: false`, `users.password_hash` is left untouched.-- Reuse path: pre-existing user / pre-existing administered team.-- Setup route: after `POST /admin/auth/setup`, the email can `password-login`- (desktop path) AND `POST /external/rpc/token` returns a token carrying the- provisioned `teamId`.-- Failure isolation: stub provisioning to throw → setup still returns `200`- with an admin token.--**E2E (desktop-app Playwright):** onboard via setup → desktop password-login →-team directory + agents (`chatllm`) + context (`context1`) load; can open the-RPC-backed surface.-------## Rollout--- Server-side only; no migration; no front-end change. Ships with the- `feat/multiple-admins` line.-- Existing tenants: new tenants get the workspace at first-run setup. Because the- login backstop was not shipped (§3), already-existing team-less password users- are **not** repaired at login — they need an invitation or a re-provision.-- Config defaults are safe for current prod (agent `chatllm`, context- `context1`); override per tenant only if their deployed names differ.-------## Future work (out of scope)--- **Admin-invitation desktop provisioning**: optionally give invited- control-admins the same desktop workspace (needs an operator-vs-user policy).-- **Password sync on change**: keep `users.password_hash` in sync when the admin- changes the Control-UI password in Settings (removes the drift caveat).-- **Refactor grant helpers** to accept an optional `db` so- `setTeamAgents`/`setUserAgents`/`setTeamContexts`/`setUserContexts` can be- reused inside a transaction instead of inlining inserts.-- **Control-UI hint**: show "Desktop access ready for `<email>`" on setup- completion.diff --git a/docs/features/context-filesystem.md b/docs/features/context-filesystem.mddeleted file mode 100644index c7663ef1c..000000000--- a/docs/features/context-filesystem.md+++ /dev/null@@ -1,597 +0,0 @@-# SharedFileSystem — shared human-managed files for Contexts--This spec defines a v1 feature that adds a **`SharedFileSystem` CRD** referenced by one or more `Context` CRDs. Each SharedFileSystem is:--- **Readable by all `mcp-host` pods** running under any Context that references it (co-located on the wfc's node; see access modes below).-- **Read-only inside `mcp-host`** (agents cannot mutate files via the mount).-- **Writable by Control-UI admins** through a dedicated per-SharedFileSystem `workspace-files-controller` service. End-user writes through the Desktop App are deferred until intra-team RBAC lands (v2).--A Context can reference **multiple** SharedFileSystems at different mount paths. The same SharedFileSystem can be referenced by **many** Contexts.--> **Status:** proposal / implementation-ready spec (v1).-------## Goals--- Provide a shared, persistent set of files (notes + many docs) to improve agent context.-- Allow the same workspace to be reused across multiple Contexts (e.g., team mission docs accessible to both customer-support and engineering agents) without duplicating data.-- Support multiple `mcp-host` replicas across different nodes (RWX storage) — **deferred**: the shipped default is `ReadWriteOnce` and consumer `mcp-host` pods are co-located with the wfc pod via a required podAffinity (#592).-- Keep the control plane stable by isolating heavy filesystem IO behind a dedicated service.-- Keep agents read-only at the filesystem level (kernel-enforced — defense in depth against bugs or prompt injection that might cause an agent to write).-- Keep the admin experience declarative: operators configure via CRD; Control UI edits CRDs and uploads files.--## Non-goals (v1)--- File version history / rollback.-- Device-bound or machine-bound browsing tokens.-- Agent writes to context files (even with approval).-- Cross-cluster replication.-- Expose workspace to workflow recipes (run in another namespace so it's problematic).-- RBAC within a team (all users on a team have the same permissions for now).-- **Desktop App write client.** Writes go through Control UI only (admin-authenticated). End-user **writes** are deferred until intra-team RBAC lands. (End-user **reads** have since shipped: `external-rest-api` exposes a session-JWT-gated `external-rest-api → control-api → wfc` read passthrough that hard-rejects anything but `GET`/`HEAD` with `405`.)-- **Per-SharedFileSystem auth grants distinct from Context grants.** When end-user writes do land in v2, the auth rule will be transitive (a user can browse a SharedFileSystem if they have access to any Context that references it). Per-SharedFileSystem grants would not actually prevent leakage (an agent in any referencing Context can read & return the same files via chat) — they would only add admin burden.-------## High-level architecture--For each `SharedFileSystem`, the Host Context Controller (HCC) reconciles a bundle of resources in the **`mcp-host` namespace**:--1. **PVC** (one per SharedFileSystem)-2. **Root init container** (in the wfc pod) to pre-create the directory layout and apply permissions-3. **`workspace-files-controller` Deployment + Service** (one pod per SharedFileSystem) that mounts the PVC **read-write**-4. **NetworkPolicy** (per wfc) restricting ingress to `app=control-api` only-5. **mcp-host pods** mount each referenced SharedFileSystem PVC **read-only** at the path declared in `Context.spec.sharedFileSystems[].mountPath`--```-┌────────────────────────────────────────────────────────────────────┐-│ mcp-host namespace │-│ │-│ ┌──────────────────────┐ ┌──────────────────────────────┐ │-│ │ SharedFileSystem A │ │ wfc-A (per-SFS Deployment) │ │-│ │ PVC (RWO) │◄─RW─►│ mounts only SFS A's PVC │ │-│ └──────────────────────┘ │ Service :8086 │ │-│ ▲ │ NetPol: from control-api │ │-│ │ RO └──────────────────────────────┘ │-│ │ │-│ ┌──────────────────────┐ ┌──────────────────────────────┐ │-│ │ SharedFileSystem B │ │ wfc-B (per-SFS Deployment) │ │-│ │ PVC (RWO) │◄─RW─►│ mounts only SFS B's PVC │ │-│ └──────────────────────┘ └──────────────────────────────┘ │-│ ▲ │-│ │ RO │-│ ┌───────┴──────────────┐ │-│ │ mcp-host pod (Host X)│ Host X → Context X → [SFS A, SFS B] │-│ │ /workspace/sfs-a/ │ │-│ │ /workspace/sfs-b/ │ │-│ └──────────────────────┘ │-└────────────────────────────────────────────────────────────────────┘-```--v1 write path (admin only, via Control UI):--```-Control UI (admin JWT) → control-api → workspace-files-controller (per SFS) → SharedFileSystem PVC-```--End-user read path (shipped; the same chain in write mode is still deferred):--```-Desktop App → external-rest-api → control-api → workspace-files-controller (per SFS) → SharedFileSystem PVC-```--Agent read path:--```-LLM → built-in clerum__context_files_* tools (mcp-host) → RO mounts → mountPaths-```--The mount itself is just bytes on disk — the LLM only sees what's surfaced to it as tools. mcp-host registers a small family of built-in `clerum__context_files_*` tools (next to the existing `clerum__generate_*` tools) that present every mounted SharedFileSystem under one virtual unified root. See **Agent read access** below.-------## Architecture rationale--The original design intuition is "just attach a PVC to mcp-host, let it own the IO too." The current design (separate wfc service + per-SharedFileSystem PVC + per-SharedFileSystem wfc Deployment) exists for specific, named reasons that are not obvious from the diagram. They are listed here so future contributors don't optimise away something they shouldn't.--### Why a separate wfc service exists at all (instead of file IO inside mcp-host)--Six load-bearing reasons:--1. **PVC mount mechanics demand a writer pod.** PVCs are accessed via pod mounts; mounts are declared at pod-spec time. The "upload file" request from Control UI has to land somewhere with a RW mount of the PVC. _Some_ pod has to be the writer. The choice is whether that pod is mcp-host (combined writer + LLM) or a dedicated wfc.-2. **mcp-host stays RO** → the kernel returns `EROFS` on any write attempt → defense in depth against prompt injection or buggy code that might accidentally register a write tool. With a combined design, "agents are read-only" is enforced only by code convention. With a separate wfc, the kernel enforces it regardless of what mcp-host code does.-3. **Ingress NetworkPolicy lock.** wfc accepts traffic only from `app=control-api`. mcp-host already accepts traffic from rpc-proxy and other paths — putting upload endpoints in mcp-host would expand its attack surface.-4. **Resource isolation.** A 100 MiB upload doesn't share Node event loop / memory budget with active LLM streaming. The LLM's tail latency is independent of file IO load.-5. **Single-writer consistency model.** All writes to a SharedFileSystem serialise through one pod → no write contention, no need for file locks or optimistic concurrency for "Google Drive–style whole-file replace" semantics. (If wfc ever scales to >1 replica per SFS, this becomes nontrivial — v1 stays at 1 replica.)-6. **Threat-model separation.** wfc's job is bounded: validate JWT, do FS IO. mcp-host's job is unbounded LLM orchestration. Different blast radius if either gets exploited.--### Why one wfc per SharedFileSystem (instead of one shared wfc cluster-wide)--Six additional reasons that justify the per-SFS Deployment topology:--7. **K8s pod-spec immutability for PVCs.** A pod can only mount PVCs declared at pod-spec time. To add a new SharedFileSystem to a shared wfc, you must update its pod spec and roll the pod. Every add/remove restarts the shared wfc → brief write downtime for _every_ SharedFileSystem on the cluster. Per-SharedFileSystem wfc avoids this entirely.-8. **Per-SharedFileSystem NetworkPolicy precision.** With per-wfc, each ingress policy is exactly "control-api → this one wfc serving this one SharedFileSystem." With one shared wfc, the network-level policy is "control-api → all SharedFileSystems"; per-SharedFileSystem enforcement happens in code only.-9. **Per-workspace resource limits / quotas.** A high-traffic shared workspace gets its own cgroup; a quiet one doesn't pay for it. Independent CPU/memory budgets.-10. **Per-workspace blast radius.** A bug in file IO that crashes one wfc affects only that SharedFileSystem. Other workspaces keep accepting writes.-11. **Lifecycle cleanup is clean.** `retainOnDelete: false` on a SharedFileSystem → HCC just deletes the wfc Deployment + Service + NetPol + PVC for that SharedFileSystem. No need to mutate a shared Deployment's volume list to drop one mount.-12. **v2 scaling path.** Eventually you might want to HPA-scale a hot SharedFileSystem's wfc independently (e.g., `team-mission` is read-heavy at 9am stand-up). Per-wfc gives you that knob; shared wfc doesn't.--### Why a separate `SharedFileSystem` CRD (instead of inline `Context.spec.filesystem`)--- **Reuse across Contexts.** Most teams want one canonical workspace (mission, runbooks, customer history) shared across many agents/Contexts. Inline-on-Context forces a copy per Context.-- **K8s-native pattern.** This matches `Pod ↔ PVC`: the workload references storage by name; storage has independent lifecycle.-- **Lifecycle independence.** Deleting a Context doesn't delete the workspace. `retainOnDelete` becomes a property of the SharedFileSystem itself (not buried inside whichever Context happened to define it inline).-- **Future "bring your own".** A SharedFileSystem CRD opens the door to future modes: pre-existing PVC, externally-provisioned NFS export, GCS bucket pointer. Inline `spec.filesystem` boxes you into "controller manages it from scratch."--### Why Control-UI-only writes in v1 (no Desktop App write client)--- **Avoid building per-end-user authz before intra-team RBAC exists.** Without RBAC, every team member would have full read+write+delete access to every SharedFileSystem any of their Contexts touches. That's a foot-gun — easier to leave end-user writes off entirely than to ship a hard-to-revoke capability.-- **Control UI is already admin-authenticated.** The token-mint + proxy plumbing on `control-api` is small and can be exercised by the Control UI immediately. The browsing JWT shape we choose now will work unchanged when the Desktop App path is wired up in v2 — only the mint-time AuthZ rule changes.-- **Smaller v1 surface.** No `external-rest-api` route, no per-end-user UI, no team-switch flow. About 30% less code to ship.-------## Cost analysis--Numbers below are us-central1 GKE pricing (April 2026). The only cost delta between this design and a "mcp-host as writer" alternative is the wfc pod itself; PVC storage, init containers, NetworkPolicies, and internal traffic are identical.--### Per-wfc-pod baseline--Realistic for an idle Express + pino + multipart server:--- Requests: `50m CPU` / `64 MiB memory`-- Limits: `200m CPU` / `128 MiB memory`--| GKE pricing model | Cost per wfc pod / month |-| -------------------------------- | ------------------------ |-| GKE Standard, on-demand e2 nodes | ~$1.20 |-| GKE Standard, spot e2 nodes | ~$0.40 |-| GKE Autopilot, on-demand | ~$1.85 |-| GKE Autopilot, spot | ~$1.20 |--### At scale (per-SharedFileSystem wfc, on-demand GKE Standard)--| Active SharedFileSystems | Marginal wfc cost / month | Notes |-| ------------------------ | ------------------------- | ---------------------------------- |-| 1 | ~$1.20 | Fits in node slack |-| 10 | ~$12 | Fits in node slack |-| 50 | ~$60 | Approaches one extra e2-standard-4 |-| 100 | ~$120 | ~1.25 extra e2-standard-4 nodes |-| 500 | ~$600 | ~6 extra nodes |-| 1000 | ~$1200 | ~13 extra nodes |--On the current dev cluster (e2-standard-4 nodes), each wfc pod consumes ~1.25% of one node's CPU. There is headroom for ~80 wfc pods before forcing a node scale-up — so up to ~80 SharedFileSystems, marginal cost is **literally $0** (the pods slot into existing slack).--### Storage--GCS FUSE CSI on GCP overlays (vs Filestore Basic HDD's $200/mo minimum):--- ~$0.02/GiB/mo standard storage-- A typical "team docs" SharedFileSystem at 5 GiB → **~$0.10/mo per SharedFileSystem**-- Plus per-operation costs (Class A ops ~$5/M, Class B ~$0.40/M) — negligible at notes-and-docs scale--### Other line items (negligible)--- Artifact Registry image storage for the wfc image: ~$0.015/mo-- Network egress: $0 (all traffic in-cluster, in-region)-- Image pull bandwidth on first pull per node: $0 (in-region)-- LoadBalancer / public IP: $0 (ClusterIP only)--### Comparison to other costs--- One LLM conversation with Claude Opus on a 50k-token context: ~$0.75. One conversation pays for ~3 wfc pods for a month.-- The original spec's Filestore Basic HDD storage was a $200/mo minimum _per Context_ (because of the 1 TiB floor). Switching to GCS FUSE saves ~$200/mo per SharedFileSystem.-- Cluster baseline (4 nodes, idle): ~$390/mo. A 100-SharedFileSystem wfc fleet adds 30% to compute cost.--### Summary--Below ~80 SharedFileSystems on the current dev cluster, the per-SharedFileSystem wfc design costs **zero real dollars** beyond what's already paid for cluster baseline. Above that, ~$1.20/SharedFileSystem/mo on-demand or ~$0.40 on spot. The financial argument for collapsing to a shared wfc only kicks in past ~500 SharedFileSystems.-------## Kubernetes constraints & invariants--- **PVCs are namespaced.** Pods can only mount PVCs in the same namespace. SharedFileSystem PVCs always live in **`mcp-host`** so wfc + every mcp-host pod can mount them; the SharedFileSystem CRD itself also lives in `mcp-host`.-- **Default access mode is `ReadWriteOnce`** (#592). The wfc Deployment is single-replica (v1) and seeds the PVC via a root **initContainer in the same pod**, and consumer `mcp-host` pods are co-located onto the wfc's node via a required podAffinity — so RWO volumes never need a cross-node Multi-Attach and work on the RWO-only StorageClasses in use (including minikube). **Multi-node readers require RWX semantics and are deferred**: they need an RWX-capable StorageClass (NFS/Filestore/GCS FUSE/EFS/CephFS) and an explicit `spec.accessModes: [ReadWriteMany]`.-- `mcp-host` mounts are **read-only** (`volumeMount.readOnly: true`).-- Each `workspace-files-controller` mount is **read-write** (the only writer for its SharedFileSystem).-- Workflow recipe pods (`sandbox-recipes` namespace) cannot mount SharedFileSystem PVCs by design (cross-namespace mounts are not supported by Kubernetes, and exposing the workspace to recipes is an explicit v1 non-goal).-------## CRD: `SharedFileSystem` (new)--`apiVersion: clerum.io/v1alpha1`, `kind: SharedFileSystem`, **namespaced**, lives in **`mcp-host`**. The CRD itself carries no namespace validation — an instance created elsewhere is accepted by the API server but is simply ignored, because control-api and HCC only ever operate on the configured `mcp-host` namespace.--### `spec`--- **storage**- - `size: string` — e.g. `"20Gi"` (defaulted)- - `storageClassName?: string` — empty means cluster default- - `accessModes?: string[]` — default `["ReadWriteOnce"]`. Set `["ReadWriteMany"]` explicitly (with an RWX-capable StorageClass) to opt into multi-node mounts.- - `annotations?: Record<string,string>` — optional PVC annotations--- **layout**- - `directories: string[]` — relative paths pre-created by the wfc init container (e.g. `["uploads", "agent-output", "notes"]`). Directory paths are validated segment-by-segment and may contain alphanumerics, `_`, `.`, and `-`; absolute paths, `..`, spaces, and shell metacharacters are rejected.--- **posix identity**- - `security?: { runAsUser?: number; runAsGroup?: number; fsGroup?: number }` — applied by the wfc init container; the wfc inherits the same fsGroup so it can write the mounted files.--- **lifecycle**- - `retainOnDelete?: boolean` — default `true`. When `false`, deleting the SharedFileSystem deletes the PVC.--### `status` (written by HCC)--- `phase: "Provisioning" | "Initializing" | "Ready" | "Degraded" | "Failed"`-- `pvcName: string`-- `capacity?: string`-- `storageClassName?: string`-- `serviceName?: string` (the per-SFS wfc Service name)-- `mountedByContexts?: { namespace: string; name: string }[]` — back-reference for ops debuggability-- `conditions?: []` (standard condition list)--> Note: seeding runs as the wfc controller's root **initContainer** (same pod as-> the server), not a standalone Job. The legacy `status.lastInitJob` field is no-> longer written (the CRD keeps it as an optional field for backward compatibility).--### Example--```yaml-apiVersion: clerum.io/v1alpha1-kind: SharedFileSystem-metadata:- name: team-mission- namespace: mcp-host-spec:- size: 5Gi- accessModes: [ReadWriteOnce]- directories: [docs, customer-history, runbooks]- security:- runAsUser: 1000- runAsGroup: 1000- fsGroup: 1000- retainOnDelete: true-```-------## CRD: `Context` additions--A new optional `spec.sharedFileSystems` field references one or more SharedFileSystems. The previous inline `spec.filesystem` field is **not** part of v1.--### `spec.sharedFileSystems`--```yaml-spec:- sharedFileSystems:- - name: team-mission # SharedFileSystem.metadata.name (must exist in mcp-host)- mountPath: /workspace/team-mission- - name: customer-complaints- mountPath: /workspace/customer-complaints-```--Validation (CRD OpenAPI + reconciler):--- Each entry: `{ name: string (required), mountPath: string (required) }`. SharedFileSystem namespace is implicitly `mcp-host` in v1; field reserved for forward compat if cross-namespace ever lands.-- Mount paths within a single Context must be unique (CRD OpenAPI validates uniqueness on `mountPath`).-- A SharedFileSystem name that doesn't resolve to an existing CRD instance puts the Context's filesystem status into `Degraded` with a clear condition; mcp-host pods don't get the missing mount but otherwise come up normally.--### `status.sharedFileSystems` (per-Context view, written by HCC)--For each referenced SharedFileSystem:--- `name: string`-- `mountPath: string`-- `phase: "Resolving" | "Mounted" | "MissingTarget" | "Failed"`-- `pvcName?: string`--This is a per-Context snapshot of how the references resolved; the source of truth for the SharedFileSystem itself is `SharedFileSystem.status`.-------## Controller responsibilities (HCC)--### Per-SharedFileSystem reconciliation--For each `SharedFileSystem`:--1. Create/patch the per-SharedFileSystem PVC in `mcp-host` (name: `sfs-<sfsHash>-files`).-2. The wfc pod's root init container seeds the PVC (mounts it RW; creates `directories`; applies sentinel-guarded `chown`/`chmod` per `security`).-3. Create/patch the per-SharedFileSystem `workspace-files-controller` Deployment (`wfc-<sfsHash>`, one replica) and Service (ClusterIP `:8086`).-4. Create/patch the per-SharedFileSystem ingress NetworkPolicy (allow `:8086` from `control-plane / app=control-api`) and egress NetworkPolicy (DNS only).-5. Update `status.phase` (`Provisioning → Initializing → Ready`).-6. On SharedFileSystem deletion: respect `retainOnDelete`. When `false`, delete Deployment, Service, NetworkPolicies, then PVC last.--Generated resources intentionally do not use Kubernetes `ownerReferences`; HCC-cleans them up through `reconcileDelete()` and stable labels. If HCC misses a-delete event while down, clean up the generated resources with:--```bash-kubectl delete deploy,svc,job,netpol \- -l clerum.io/managed-by=host-context-controller,clerum.io/sharedfilesystem=<name> \- -n mcp-host-```--### Per-Context reconciliation--For each `Context` with a non-empty `spec.sharedFileSystems`:--1. Resolve each ref → SharedFileSystem CRD instance. Mark missing refs in `status.sharedFileSystems[].phase = MissingTarget`.-2. Patch the mcp-host Deployment (existing host reconciler) to add `volumes[]` + `volumeMounts[]` (RO) for each resolved SharedFileSystem PVC at the requested `mountPath`.-3. Inject the env var `CLERUM_CONTEXT_FILES_MOUNTS` (JSON) into the mcp-host container so the built-in tools can register against the correct mounts. See **Agent read access** below.-4. Update `status.sharedFileSystems[].phase = Mounted` once the rollout completes.--### Reconciliation properties--- **Idempotent** per object (SharedFileSystem or Context).-- Debounced 5s; retries on failure with exponential backoff up to 1 min.-- Adding/removing a SharedFileSystem does NOT affect other SharedFileSystems' wfc pods (each wfc is isolated).-- Adding/removing a SharedFileSystem from `Context.spec.sharedFileSystems` rolls only the per-Host mcp-host Deployment.-------## `workspace-files-controller` service responsibilities--Each per-SharedFileSystem wfc serves IO for exactly one SharedFileSystem. The wfc knows its identity from env (`WSF_SHARED_FILESYSTEM_NAME`). JWT validation must check the token's `sharedFileSystem` claim matches the wfc's identity (otherwise `403 forbidden`).--- **Token verification**: validate browsing JWT (see Auth section). Reject tokens whose `sharedFileSystem` claim doesn't match this wfc.-- **Path safety**:- - reject `..` traversal and absolute paths outside the mount root- - deny unsafe symlinks-- **Streaming IO**: list, stat, download, upload, replace, delete, rename/move, mkdir.- - "Edit" in v1 is whole-file replace (Google Drive–style): the client uploads a new version that overwrites the existing file. No partial/range writes, no in-place patching.-- **Observability**: latency, bytes, failures, audit fields including `sharedFileSystem`, `subject` (admin user id from JWT), `op`, `path`.--Network posture:--- Cluster-internal Service (`wfc-<sfsHash>.mcp-host.svc:8086`).-- Restrict ingress to only `app=control-api` via NetworkPolicy (defense in depth).-------## Agent read access (mcp-host built-in tools)--The RO mounts on `mcp-host` are dead bytes unless the LLM has a way to discover and read them. v1 surfaces all SharedFileSystems through a small family of built-in tools registered in `StepMcpRouter` next to the existing `clerum__generate_*` tools — no MCP server, no network hop, just direct filesystem reads from the mounts.--### Tools--All tools are read-only. They present every mounted SharedFileSystem under one **virtual unified root** with the SharedFileSystem `name` as the top-level directory. The mcp-host reader rejects `..`, NUL/control characters, backslashes, symlinks, non-regular files, and paths that resolve outside the SharedFileSystem mount root.--| Tool | Purpose | Key params |-| ---------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------- |-| `clerum__context_files_list` | List entries. At root (`/` or empty) returns the list of available SharedFileSystems. | `path?` (default ".") |-| `clerum__context_files_read` | Return file contents as UTF-8 text. Files larger than the configured read cap are rejected. | `path` (e.g. `team-mission/mission.md`) |--### Discovery and surfacing--- The tools are registered when mcp-host starts with `CLERUM_CONTEXT_FILES_MOUNTS` set to a JSON array describing the mounted SharedFileSystems and their on-disk paths (the host reconciler writes this env var alongside the volumeMounts when `Context.spec.sharedFileSystems` is non-empty):-- ```json- [- {- "name": "team-mission",- "namespace": "mcp-host",- "mountPath": "/workspace/team-mission",- "pvcName": "sfs-team-mission-files"- },- {- "name": "customer-complaints",- "namespace": "mcp-host",- "mountPath": "/workspace/customer-complaints",- "pvcName": "sfs-customer-complaints-files"- }- ]- ```--- mcp-host appends a one-line system-prompt postfix when these tools are registered: _"You have shared filesystems available: `<comma-separated names>`. Use `clerum__context_files_list` to discover files (start at `/` to see workspaces) and `clerum__context_files_read` to read them."_-- With the shipped RWO default, writers and readers share one node and one mount, so writes are visible to readers immediately. If RWX is ever opted into, visibility is bounded by that StorageClass's cache coherency (Filestore: typically a few seconds; GCS FUSE: tunable via mount opts) — a delay that is good-enough for the "notes + docs" workload.--### Limits--- `CLERUM_CONTEXT_FILES_MAX_READ_BYTES` — default `10 MiB` per `read` call. Larger files are rejected before reading.-- `CLERUM_CONTEXT_FILES_MAX_LIST_ENTRIES` — default `1000` per directory listing.--### Files--- `mcp-host/src/workflow/contextFiles.ts` — implementation-- Registered in `mcp-host/src/workflow/internalTools.ts` and dispatched from `stepRouter.ts` exactly like `clerum__generate_*`--### Non-goals (v1)--- Write tools (`clerum__context_files_write`, `_delete`, etc.). The mounts are RO; humans write through the Control UI.-- Auto-loading the entire file index into the system prompt. May land in v2 if LLMs underuse `list`.-------## Auth & authorization (v1)--### v1: Control-UI-only writes--In v1 the only client of the workspace-files-controller is the **Control UI**, authenticated via the existing admin session.--- Control UI logs in with the existing admin auth flow (`/api/v1/admin/auth/login`). The session token grants admin role.-- When the operator opens the workspace browser for SharedFileSystem `S`, the Control UI calls `POST /api/v1/admin/shared-filesystems/:name/token` on `control-api`. control-api verifies the caller has admin role, then mints a browsing JWT scoped to `S`.-- Control UI then calls the proxy endpoints under `/api/v1/admin/shared-filesystems/:name/proxy/*`, which forward to `wfc-<sfsHash>.mcp-host.svc:8086`.--### End-user access--The end-user **read** path has shipped: `external-rest-api` exposes `GET /api/v1/me/contexts/:contextId/shared-filesystems` and `GET /api/v1/me/contexts/:contextId/shared-filesystems/:sfsName/proxy/*` — session-JWT-gated, forwarding to `control-api`'s `/external/contexts/:id/shared-filesystems` router. The router rejects any method other than `GET`/`HEAD` with `405`, so end-user **writes** remain deferred until intra-team RBAC lands.--When end-user writes do land, `control-api`'s token-mint endpoint adds a non-admin AuthZ branch using a transitive rule: a user can mint a browsing JWT for SharedFileSystem `S` if **any** of these are true (OR logic) for **any Context `C` that has `S` in `spec.sharedFileSystems`**, evaluated under the currently selected team:- 1. Team has direct access to `C`, OR- 2. User has direct access to `C`, OR- 3. User has access to an agent/Host that has access to `C`, OR- 4. Team has access to an agent/Host that has access to `C`.--The browsing JWT shape below is forward-compatible — v2 just changes which subjects can be issued tokens, not what tokens look like.--> **Why transitive auth (in v2):** any user who can chat with an agent under `C` can ask the agent to list and read the entire mounted SharedFileSystem via the built-in tools. Per-SharedFileSystem grants on the browsing endpoint would not actually prevent leakage — they would only add admin burden. The data-classification decision is made at the moment an operator references a SharedFileSystem from a Context.->-> **Operational guidance:** treat `Context.spec.sharedFileSystems` references as data-classification grants. Do NOT reference a SharedFileSystem from a Context whose audience shouldn't see those files.--### Browsing JWT — exact claim shape (used in both v1 and v2)--```json-{- "iss": "control-api",- "aud": "workspace-files-controller",- "sub": "<userId>",- "sharedFileSystem": "<name>",- "sharedFileSystemNamespace": "mcp-host",- "scopes": ["files:read", "files:write"],- "iat": 1730000000,- "exp": 1730000300-}-```--- **TTL:** 300 s (5 min). Caller renews on demand by calling the mint endpoint again — no refresh-token flow.-- **Scopes:** exactly two exist — `files:read` and `files:write`. Delete is gated by `files:write`; there is no separate delete scope.-- **Signing:** RS256, using the RPC keypair (`CONTROL_API_RPC_JWT_PRIVATE_KEY` on `control-api`, `WSF_JWT_PUBLIC_KEY` on `workspace-files-controller`). This is a different keypair from the session JWT (`CONTROL_API_SESSION_JWT_PRIVATE_KEY`); audience separation keeps RPC tokens out of the wfc and vice versa.-- **wfc verification:** check `iss`, `aud`, signature, expiry, and that the token's `sharedFileSystem` / `sharedFileSystemNamespace` claims match this wfc's `WSF_SHARED_FILESYSTEM_NAME` / `WSF_SHARED_FILESYSTEM_NAMESPACE`. Reject session JWTs (different `aud`).-- **Forward-compat:** the mint endpoint issues the full scope set by default; a caller may pass an optional narrower `scopes` array (anything outside the two known scopes → `400 invalid_wfc_browsing_scopes`). Per-operation gating happens server-side once intra-team RBAC lands.-- **Audit:** `control-api` logs the admin user id at mint time; the JWT itself doesn't carry additional context.-------## Implementation--### Repository layout--| Path | Purpose | v1? |-| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |-| `workspace-files-controller/` | New TS/Node service. Mirrors the `mcp-host` package layout (Express + pino + vitest). Single image; one Deployment per SharedFileSystem. | yes |-| `host-context-controller/src/sharedFileSystemReconciler.ts` | New HCC reconciler watching `SharedFileSystem` CRDs. | yes |-| `host-context-controller/src/k8s/sharedFileSystemFactory.ts` | Pure builders for PVC, Deployment (+ seeding init container), Service, NetworkPolicies. | yes |-| `control-api/src/routes/admin/sharedFilesystems.ts` | Admin token-mint endpoint + thin proxy to per-SFS wfc. | yes |-| `control-ui/app/shared-filesystems/` | Workspace picker, file tree, viewer, upload/replace/delete dialogs. | yes |-| `mcp-host/src/workflow/contextFiles.ts` | Built-in `clerum__context_files_*` tools (list/read) with virtual unified root over multiple RO mounts. | yes |-| `external-rest-api/src/routes/contextSharedFilesystems.ts` | Session-JWT-gated read passthrough to `control-api` (GET/HEAD only; writes still deferred). | shipped |-| `desktop-app/ui/src/features/workspace/` | End-user UI (file tree, viewer, upload/replace/delete). | **v2 — deferred** |--### HTTP API: `workspace-files-controller`--Listens on `:8086`. All routes except `/healthz` and `/readyz` require a valid browsing JWT in `Authorization: Bearer <token>` whose `sharedFileSystem` claim matches the wfc's identity. The SharedFileSystem identity comes from the JWT, NOT from URL path.--| Method | Path | Body / Query | Purpose |-| -------- | ------------------------------- | ------------------------- | ------------------------------------------------------------------------------------ |-| `GET` | `/v1/files?path=<rel>` | — | List directory entries (name, kind, size, mtime). |-| `GET` | `/v1/files/stat?path=<rel>` | — | File metadata. |-| `GET` | `/v1/files/download?path=<rel>` | — | Stream file contents (`Content-Disposition: attachment`). |-| `POST` | `/v1/files/upload` | multipart `file` + `path` | Create new file. `409` if exists. |-| `PUT` | `/v1/files/replace` | multipart `file` + `path` | Whole-file replace (Google Drive–style). `404` if missing. |-| `POST` | `/v1/files/mkdir` | `{path}` | Create directory (and parents). |-| `POST` | `/v1/files/move` | `{from, to}` | Rename or move within the workspace. |-| `DELETE` | `/v1/files?path=<rel>` | — | Delete file or empty directory. Recursive delete is `?recursive=true` and is logged. |-| `GET` | `/healthz` | — | Liveness. |-| `GET` | `/readyz` | — | Reports PVC mounted + writable. |--**Response envelope:** `{ok: true, data: ...}` on success, `{ok: false, error: {code, message}}` on failure. Error codes: `path_invalid`, `not_found`, `already_exists`, `not_a_directory`, `not_empty`, `payload_too_large`, `forbidden`, `unauthorized`.--**Limits (v1, configurable via env):**--- `WSF_MAX_UPLOAD_BYTES` — default `100 MiB` per file.-- `WSF_MAX_LIST_ENTRIES` — default `5000` per directory listing.-- `WSF_MAX_PATH_DEPTH` — default `32`.--### `control-api` endpoints (new, admin-only in v1)--All under `/api/v1/admin/shared-filesystems/:name/*`. Admin session-JWT auth handled by upstream middleware.--| Method | Path | Purpose |-| ------ | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `GET` | `/api/v1/admin/shared-filesystems` | List SharedFileSystems (proxies the K8s CRD list). |-| `GET` | `/api/v1/admin/shared-filesystems/:name` | Get one SharedFileSystem (CRD + status). |-| `POST` | `/api/v1/admin/shared-filesystems/:name/token` | Mint browsing JWT for this SharedFileSystem. Returns `{token, expiresInSeconds, serviceUrl, audience}`. v1: requires admin role. v2: also accepts non-admin via the transitive rule. |-| `*` | `/api/v1/admin/shared-filesystems/:name/proxy/*` | Thin reverse proxy to `wfc-<sfsHash>.mcp-host.svc:8086`. Does **not** forward the caller's `Authorization`: it mints a fresh browsing JWT bound to this SharedFileSystem and sends that upstream, so the browser never sees a wfc token and the wfc never sees an admin token. Request body is forwarded unchanged. |--The proxy approach keeps the per-SFS wfc reachable only from `control-plane`, simplifying NetworkPolicy. Control UI always traverses `Control UI → control-api → workspace-files-controller`.--### HCC reconciler — `sharedFileSystemReconciler`--**For each `SharedFileSystem`:**--1. **PVC** in `mcp-host`. Name: `sfs-<sfsHash>-files`. Apply size, accessModes, storageClassName, annotations from spec. Single-replica wfc; RWO is safe because seeding co-locates in the controller's root initContainer (same pod ⇒ same node ⇒ same mount).-2. **Seeding init container** in the wfc Deployment pod (image `busybox:1.36`, root, minimal caps). Runs `mkdir -p` + a sentinel-guarded `chown -R`/`chmod` per `spec.security`; the kubelet runs it to completion before the serving container starts (same pod => same node => same RWO mount).-3. **Deployment** `wfc-<sfsHash>` (one replica) running `workspace-files-controller`. Mounts PVC RW. SecurityContext from `spec.security`. Env: `WSF_MOUNT_PATH`, `WSF_SHARED_FILESYSTEM_NAME`, `WSF_SHARED_FILESYSTEM_NAMESPACE`, `WSF_JWT_PUBLIC_KEY` (from `mcp-host-config`), `WSF_MAX_*` limits.-4. **Service** `wfc-<sfsHash>` ClusterIP `:8086`.-5. **NetworkPolicy** `wfc-<sfsHash>-ingress` (allow `:8086` from `control-plane / app=control-api`) + `wfc-<sfsHash>-egress` (DNS only).-6. **Status reconciliation**: write `status.{phase, pvcName, capacity, storageClassName, serviceName, conditions, mountedByContexts}`. Phase transitions: `Provisioning → Initializing → Ready` (or `Failed`/`Degraded`).--**For each `Context`:** the existing host reconciler resolves `spec.sharedFileSystems[*].name` to PVCs and patches the per-Host mcp-host Deployment with RO mounts at the requested `mountPath`. It also writes `CLERUM_CONTEXT_FILES_MOUNTS` JSON env so the built-in tools register correctly.--Reconciliation is **per-object idempotent**, debounced 5s, retries on failure with exponential backoff up to 1 min.--### NetworkPolicies--| Name | Namespace | Effect |-| ---------------------------- | --------------- | ------------------------------------------------------------------------------------- |-| `wfc-<sfsHash>-ingress` | `mcp-host` | Allow `:8086` from `control-plane` / `app=control-api`. Deny everything else. |-| `wfc-<sfsHash>-egress` | `mcp-host` | Allow DNS to `kube-system`. Nothing else. |-| `control-api → wfc` (egress) | `control-plane` | Allow `:8086` to `mcp-host` namespace, pod selector `app=workspace-files-controller`. |-| `mcp-host RO mounts` | `mcp-host` | No new policy needed — mounts are purely volume-level. |--All three per-SFS policies are runtime-managed by HCC. The `control-api → wfc` egress policy lives in `deploy/base/control-plane/networkpolicies.yaml` (control-api egress is namespace-scoped, not per-SFS).--### Storage classes per environment--| Overlay | Class | Notes |-| ---------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |-| `minikube` | `standard` (RWO) | RWX is hard locally; v1 runs at `replicas: 1` with RWO — safe because the initContainer co-locates seeding in the controller pod (no Multi-Attach). |-| `gcp-prod` / `gcp-dev` | RWO block storage | RWO is the shipped default (#592); no RWX StorageClass is enabled on any cluster today. A GCS FUSE CSI class (RWX semantics, ~$0.02/GiB/mo vs Filestore Basic HDD's ~$200/mo minimum) is the deferred escalation path. |--### Path safety (server-side, mandatory)--All paths arriving from clients are normalised and validated before any FS call:--1. Reject any path containing `..`, NUL, or backslash.-2. `path.posix.normalize` then `path.posix.resolve(mountRoot, rel)`; reject if the resolved path doesn't have `mountRoot` as prefix.-3. Reject symlinks: when listing/streaming, `lstat` first; if `isSymbolicLink()` return `path_invalid`.-4. Enforce `WSF_MAX_PATH_DEPTH`.--### Lifecycle--- **SharedFileSystem create**: full reconcile; status moves through `Provisioning → Initializing → Ready`.-- **Context references**: a Context referencing a SharedFileSystem that doesn't yet exist gets `MissingTarget` status; once the SharedFileSystem appears, the next Context reconcile mounts it RO into the mcp-host pod (rolls the per-Host Deployment).-- **SharedFileSystem delete**: respect `spec.retainOnDelete`. Default `true` for v1. When `false`, HCC deletes Deployment, Service, NetworkPolicies, then PVC last.-- **Context delete**: patches the mcp-host Deployment to drop those volumes/volumeMounts. SharedFileSystem PVCs are unaffected (lifecycle independent of any single Context).--### Phased rollout--| Phase | Scope |-| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| **P1** | New `SharedFileSystem` CRD + `Context.spec.sharedFileSystems`. HCC reconciler creating PVC + wfc Deployment (with a seeding init container) per SharedFileSystem; status reaches `Initializing`. No service yet. |-| **P2** | `workspace-files-controller` service: list/stat/download/healthz only. HCC reconciler creates per-SFS Deployment + Service + NetworkPolicies. control-api token-mint + proxy. Read-only Control UI workspace view. |-| **P3** | upload/replace/mkdir/move/delete. Control UI write actions. |-| **P4** | mcp-host RO mount injection (multi-mount via `Context.spec.sharedFileSystems`) + built-in `clerum__context_files_*` tools with virtual unified root. End-to-end with agent reads. |-| **P5** | E2E suite, NetworkPolicy enforcement verification, GCP-dev soak. |--### Test strategy--- **Unit (workspace-files-controller):** path-safety table-driven tests, JWT verification (including SFS-name claim mismatch → 403), error-envelope shape, limit enforcement, symlink rejection.-- **Unit (HCC reconciler):** factory functions for PVC/Job/Deployment/Service/NetworkPolicies; per-Context mount-injection logic; phase transitions; missing-target handling.-- **Unit (mcp-host built-in tools):** path-safety reuse, virtual-root `list("/")` returns SharedFileSystem names, `read("sfs-name/file")` resolves correctly, oversized reads are rejected, and list/read operations refuse unsafe paths and symlinks.-- **Integration (control-api):** admin token-mint (admin role required in v1), proxy passthrough to per-SFS wfc.-- **E2E (`tests/e2e/shared-filesystems/` — planned, not yet written):** create SharedFileSystem; create Context referencing it; wait for `phase=Ready`; upload/replace/list/delete via Control-UI-equivalent HTTP path; verify mcp-host pod sees the file at `mountPath`; verify mcp-host cannot write (EROFS); verify the LLM can list and read via `clerum__context_files_*`. Run on minikube (RWO/single-replica) and GCP-dev (GCS FUSE) profiles.-- **Multi-ref E2E:** create two SharedFileSystems; create one Context referencing both; verify virtual unified root behaviour.-- **Sharing E2E:** create one SharedFileSystem; create two Contexts both referencing it; verify both Contexts' mcp-host pods see the same files.-- **Observability assertions:** Prometheus counters for ops/bytes/errors; pino structured logs include `sharedFileSystem`, `subject`, `op`, `path`, `bytes`, `durationMs`.-------## Operations & failure modes--- **Storage misconfigured / unavailable** (no usable StorageClass, PVC never binds) → `SharedFileSystem.status.phase = Failed` with actionable condition/reason.-- **Seeding init container fails** -> the wfc pod CrashLoops in init; the SFS does not reach `Ready`.-- **wfc unhealthy** → `phase = Degraded` for that SharedFileSystem only. Other SharedFileSystems unaffected. RO mounts on mcp-host remain readable (kernel-level, independent of wfc).-- **Cross-Context exposure (operator-driven)** → if `Context: intern-agent` references `SharedFileSystem: secret-financials`, anyone with intern-agent chat access can ask the agent to read those files. **No auth check prevents this.** Operator discipline on `sharedFileSystems` references is the only mitigation. See "Operational guidance" in Authorization.-- **Missing target** → a Context referencing a non-existent SharedFileSystem starts up without that mount and writes `status.sharedFileSystems[].phase = MissingTarget`. Once the target appears, next reconcile mounts it.-------## Related docs--- **[Context CRD reference](../crds/context.md)** (will be updated to include `spec.sharedFileSystems` once implemented)-- **[SharedFileSystem CRD reference](../crds/sharedfilesystem.md)** (new — created with v1)-- Root [Security model](../../README.md#security-model)-- [SharedFileSystem CRD](../crds/sharedfilesystem.md)diff --git a/docs/features/control-ui-workflow-recipes-and-registry-guide.md b/docs/features/control-ui-workflow-recipes-and-registry-guide.mddeleted file mode 100644index 08a610553..000000000--- a/docs/features/control-ui-workflow-recipes-and-registry-guide.md+++ /dev/null@@ -1,1359 +0,0 @@-# Control UI Workflow Recipes and Registry Guide--This guide explains how WorkflowRecipes and the Registry fit together in Clerum, starting from the operator and product view and moving down into the code paths that create, validate, publish, install, run, and display them.--It is written for the next round of work on `control-ui`, especially the effort to unify the Workflow Recipes and Registry sections. The goal is to make the current behavior clear enough that UI/UX changes can be made deliberately instead of by archaeology.--## 1. Executive Summary--Clerum has two related but currently separate management surfaces:--- **Workflow Recipes** are installed, cluster-resident `WorkflowRecipe` CRDs. They are what actually run. Control UI uses this section to create recipes from JSON, validate them, configure secrets, manage authorized users, inspect status, view workloads, connect background OAuth integrations, and trigger runs.-- **Registry** is a versioned catalog of installable things. It can hold standalone MCP servers and WorkflowRecipe entries. Control UI uses this section to discover, publish, edit metadata, remove catalog versions, and install catalog entries into the cluster.--The two concepts overlap because a registry recipe becomes a live WorkflowRecipe after install. The user thinks "I want a workflow"; the platform currently splits that into:--1. Find or publish a catalog entry in Registry.-2. Install it through `/registry/install`.-3. Land on the live WorkflowRecipe detail page in `/workflow-recipes/sandbox-recipes/<name>`.-4. Configure secrets, integrations, grants, and triggers there.-5. Let Desktop App users run it from Workflows, or open it from Apps if it exposes `spec.ui`.--The core unification opportunity is to treat Registry as an acquisition/install source and Workflow Recipes as the lifecycle/runtime home. A unified UI should make the state transition obvious:--```text-Catalog recipe version- -> install checkpoint- -> live WorkflowRecipe in sandbox-recipes- -> grants/integrations/secrets/status/runs- -> visible in Desktop App Workflows and/or Apps-```--## 2. Conceptual Model--### 2.1 WorkflowRecipe--A `WorkflowRecipe` is a Kubernetes custom resource with:--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: my-workflow- namespace: sandbox-recipes-spec:- workloads: []- steps: []-```--The CRD is the package. It can declare:--- Kubernetes workloads: `deployment`, `statefulset`, `cronjob`, `job`, `daemonset`.-- MCP-facing workloads, identified by a `transport` field.-- Non-MCP runtime workloads such as databases, workers, cron jobs, and webhook handlers.-- Agentic or deterministic workflow steps under `spec.steps`.-- Snippet steps under `step.run`.-- Input schemas under `spec.inputContract`.-- Runtime triggers under `spec.triggers`.-- Output artifacts under `spec.output`.-- Secrets, OAuth clients, webhooks, egress, UI embedding, and policy/security controls.--Important invariant: **WorkflowRecipe CRDs always live in `sandbox-recipes`**. Control API strips or ignores author-provided namespaces on create and update. The reconciler then renders children into the correct namespaces.--### 2.2 Namespace Splitting--The platform routes recipe content by purpose:--| Spec content | Runtime namespace | Why |-|---|---|---|-| `WorkflowRecipe` CRD object | `sandbox-recipes` | Canonical storage and workflow runtime namespace. |-| Workload with `transport` | `mcp-server` | Becomes a managed MCP server child. |-| Workload referenced by `spec.ui.workloadRef` | `sandbox-ui` | Rendered as a sandboxed Desktop App UI. |-| Non-transport workloads | `sandbox-recipes` | Databases, workers, cron jobs, webhook handlers, coordinators. |-| Workflow run coordinators and output PVCs | `sandbox-recipes` | Runtime state stays with the recipe. |--This matters for UI because an installed recipe is not "in" the registry or the MCP server namespace. The live management surface must target `sandbox-recipes`.--### 2.3 Registry Entry--A Registry entry is versioned metadata plus installable content. In Control UI it is represented by `RegistryEntry` in `control-ui/lib/api.ts`.--Key fields:--| Field | Meaning |-|---|---|-| `name`, `version` | Stable catalog identity. |-| `entry_type` | `mcp-server` or `recipe`. |-| `server_mode` | `local` or `remote` for MCP server entries. |-| `recipe_type` | Usually `workflow` or `only-workloads` for recipe entries. |-| `mcp_server_meta` | Image, port, transport, credential schema, remote endpoints, egress summary. |-| `recipe_meta.recipeYaml` | YAML or JSON content used to install a WorkflowRecipe. |-| `trust_level`, `quality_tier`, `origin` | Catalog trust and curation metadata. |-| `downloads`, `installs` | Registry usage counters. |--Registry entries do not run by themselves. Install creates cluster resources and stamps them with catalog metadata:--```yaml-metadata:- labels:- clerum.io/managed-by: control-api- annotations:- clerum.io/catalog-id: <entry-name>- clerum.io/catalog-version: <entry-version>-```--Only `clerum.io/managed-by` is a label. `clerum.io/catalog-id` and `clerum.io/catalog-version` are **annotations**, because org-scoped entry names contain `@` and `/`, which are illegal label values. Installed detection reads the annotations first and falls back to the legacy labels for resources installed before that change. A `kubectl get workflowrecipes -l clerum.io/catalog-id=<entry>` selector will therefore return nothing.--## 3. Current Control UI Surfaces--### 3.1 Workflow Recipes List--Route:--```text-control-ui/app/workflow-recipes/page.tsx-```--Major components:--| File | Role |-|---|---|-| `control-ui/components/RecipesTab.tsx` | Table of live recipes with search, phase, workloads, created date, and row navigation. |-| `control-ui/components/RecipeEditor.tsx` | Create/edit flow for JSON WorkflowRecipe manifests. |-| `control-ui/lib/hooks/useRecipePolling.ts` | Loads recipes, status, and recent runs. |-| `control-ui/lib/workflowRecipeRunState.ts` | Computes user-facing display phase and run button state. |-| `control-ui/app/constants/workflowRecipes.ts` | Holds `DEFAULT_WORKFLOW_RECIPE_NAMESPACE` (`sandbox-recipes`). |--The list is runtime-focused. It reads live recipes from:--```ts-GET /api/v1/admin/recipes-```--Each row opens:--```text-/workflow-recipes/:namespace/:name-```--Note on naming: Control UI already presents this section as **Plugins** in the sidebar, and the Registry section as **Marketplace**. This document uses the code-level names (Workflow Recipes, Registry) for the underlying concepts; the UI labels are called out where you have to click them.--The list currently has an **Install Plugin** button, but that button opens `RecipeEditor`, not the registry. This is one reason the UX feels split: "install" means "paste JSON and create a CRD" here, while "install" in Marketplace means "install a catalog version."--### 3.2 Workflow Recipe Detail--Route:--```text-control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx-```--The detail page is the live operations hub. It loads:--- The recipe CRD.-- Reconciler status.-- Pods and workload status.-- Recent workflow runs.-- Secrets.-- Background OAuth integration status.-- Authorized trigger users.--Tabs include:--| Tab | Purpose |-|---|---|-| Runs | Recent workflow runs, trigger modal, run artifacts. |-| Workloads | Workload reconciliation and pod/container health. |-| Conditions | CRD conditions from the reconciler. |-| Secrets | Recipe-scoped secret management. |-| Integrations | Background OAuth clients from `spec.oauthClients`. |-| Members | Workflow trigger grants for individual users. |-| Teams | Workflow trigger grants for teams. |-| Approval targets | Teams that can be targeted by `step.requiresApproval`. |--This is the page Desktop App behavior depends on indirectly. If a recipe does not declare a user on-demand trigger or has no authorized users, it may be live in Control UI but not practically usable by end users.--### 3.3 Recipe Editor--Component:--```text-control-ui/components/RecipeEditor.tsx-```--The editor is a JSON-first create/update flow. It supports:--- Built-in templates such as MongoDB MCP Stack, Agentic Workflow, PDF reports, snippet workflows, and local-only custom coordinator templates.-- Client validation with `control-ui/lib/recipeValidator.ts`.-- Server validation through `POST /api/v1/admin/recipes/validate`.-- Optional operator default enrichment from `control-ui/lib/recipeDefaults.ts`.-- External egress review from `control-ui/lib/egressModel.ts`.-- Secret detection and pre-deploy secret upsert.-- Per-step human approval gating editor for `step.requiresApproval`.-- Workflow trigger grants through `GrantsPanel`.--The editor is a four-step wizard: **Manifest**, **Review**, **Defaults**, **Access & deploy**. The effective create flow is:--1. Operator pastes JSON or loads a template (Manifest step).-2. Operator clicks **Review manifest**.-3. Client validation checks parse, shape, limits, secret hygiene, template refs, and some security rules; the Review step also shows egress findings.-4. Operator clicks **Apply defaults** and may adjust the operator defaults panel.-5. Operator clicks **Continue to access**.-6. On the Access & deploy step, the editor shows secrets detected from snippet capabilities and workload `envSecret`. Operator may enter values. Values are written as Kubernetes Secrets, not copied into the recipe JSON.-7. Operator selects authorized users.-8. Operator clicks **Deploy plugin** (**Update plugin** when editing an existing recipe).-9. Editor runs server validation.-10. Editor creates or updates the WorkflowRecipe.-11. On create, editor saves workflow grants after the CRD exists.--Server validation is intentionally a submit-time gate because it requires cluster state. For example, agentic recipes that set `spec.contextRef` must also set:--```json-"security": { "allowContextRef": true }-```--and the namespace must have a matching `WorkflowRecipePolicy` that allows context sharing.--### 3.4 Registry Catalog--Component:--```text-control-ui/components/RegistryCatalog.tsx-```--The registry catalog is embedded in the dashboard tab and supports:--- Search.-- Type filtering: all, **Connectors** (`mcp-server`), **Plugins** (`recipe`).-- Category filtering.-- Mode filtering: local, remote, workflow, only-workloads.-- Installed detection.-- Detail navigation.-- Install navigation.-- Edit metadata.-- Remove catalog version.-- Publish new entry.--The catalog makes a single aggregate call:--```ts-GET /api/v1/admin/registry/catalog-```--Control API fans that out server-side to `searchEntries`, `getCategories`, and `getInstalledRegistryState`, and returns `data`, `categories`, and `installed.{catalogKeys,serverNames,recipeKeys}` in one response.--Installed detection differs by entry type:--- MCP servers match either catalog annotations (label fallback) or `metadata.name`.-- Recipes match catalog annotations (label fallback) on live WorkflowRecipe CRDs.--### 3.5 Registry Detail--Route:--```text-control-ui/app/registry/entries/[name]/[version]/page.tsx-```--The detail page shows:--- Trust, quality, category, tags, downloads, installs.-- Install/Edit/Remove actions.-- Description.-- Container images extracted from recipe YAML.-- Source repo URL extracted from `clerum.io/source-repo` annotation.-- Expandable recipe YAML.--For recipe entries, the Install button does **not** route anywhere. `handleInstall()` branches on `entry.entry_type`: for `recipe` it calls `installRecipeFromRegistry(...)` immediately and then pushes straight to `/workflow-recipes/sandbox-recipes/<created-recipe-name>`. Only the `mcp-server` branch pushes to `/registry/install?entry=<entry>&version=<version>`.--The Marketplace catalog card behaves the same way: its recipe Install button calls `handleInstallRecipe` -> `installRecipeFromRegistry` directly, while its MCP-server Install button navigates to `/registry/install`.--So there is no validation/egress preview step for recipe installs from either surface. The `/registry/install` recipe preview described in §3.6 is reachable only through the legacy deep link:--```text-/workflow-recipes?registry=<entry>&version=<version>-```--which `/workflow-recipes` redirects to `/registry/install?entry=<entry>&version=<version>`. A unified UI should decide whether that preview becomes the default path for recipe installs, or is removed.--### 3.6 Registry Install--Route:--```text-control-ui/app/registry/install/page.tsx-```--This route branches by `entry.entry_type`.--For MCP servers, it renders:--```text-control-ui/components/RegistryInstallForm/index.tsx-```--That form collects server name, context, credentials, and warns about external egress.--For recipe entries, it renders `RegistryRecipeInstallPreview` inside the route file. That preview:--- Reads `entry.recipe_meta.recipeYaml`.-- Attempts browser-side validation via `validateRecipe`.-- Runs egress analysis.-- Blocks install on browser-visible validation errors or egress errors.-- Calls `installRecipeFromRegistry`.--Then Control UI navigates to the live recipe detail page:--```text-/workflow-recipes/sandbox-recipes/<created-recipe-name>-```--### 3.7 Publish to Registry--Route:--```text-control-ui/app/registry/publish/page.tsx-```--Component:--```text-control-ui/components/PublishToRegistryForm.tsx-```--This form can publish:--- MCP server entries.-- Recipe entries.--For recipe entries it posts the raw recipe YAML/text in `payload.recipe`. It does not currently provide the full lifecycle affordances the Recipe Editor does, such as secret detection, grants, policy explanations, or rich YAML preview. That is an important product gap if the plan is to make Registry and Recipes feel unified.--## 4. Control API Paths--### 4.1 Live WorkflowRecipe Admin API--Main route:--```text-control-api/src/routes/admin/recipes.ts-```--Client functions:--```text-control-ui/lib/api.ts-```--Important endpoints:--| Method | Route | Purpose |-|---|---|---|-| `GET` | `/api/v1/admin/recipes` | List live WorkflowRecipes. |-| `POST` | `/api/v1/admin/recipes` | Create live WorkflowRecipe. |-| `POST` | `/api/v1/admin/recipes/validate` | Validate without creating. |-| `GET` | `/api/v1/admin/recipes/:name` | Read one recipe. |-| `PUT` | `/api/v1/admin/recipes/:name` | Update recipe spec. |-| `DELETE` | `/api/v1/admin/recipes/:name` | Delete recipe. |-| `POST` | `/api/v1/admin/recipes/:name/retry` | Retry failed reconciliation. |-| `GET` | `/api/v1/admin/recipes/:name/status` | Read status. |-| `GET` | `/api/v1/admin/recipes/:name/pods` | Read rendered pods. |-| `POST` | `/api/v1/admin/recipes/secrets` | Upsert recipe secret. |--Workflow run and grant endpoints:--| Method | Route | Purpose |-|---|---|---|-| `GET` | `/api/v1/admin/workflows/:ns/:name/runs` | List run history. |-| `POST` | `/api/v1/admin/workflows/:ns/:name/trigger` | Trigger a run. |-| `GET` | `/api/v1/admin/workflows/:ns/:name/grants` | List authorized users. |-| `PUT` | `/api/v1/admin/workflows/:ns/:name/grants` | Replace authorized users. |-| `GET` | `/api/v1/admin/workflows/:ns/:name/runs/:runId/artifacts` | List run artifacts. |--The server-side route enforces:--- Recipe names must be RFC1123 labels.-- WorkflowRecipe CRDs are stored in `config.sandboxNamespace`.-- Recipe namespaces are not author-controlled.-- Secret names and keys are validated.-- Platform-managed `wf-*` secrets cannot be used by recipe config.-- Inline sensitive env values are rejected or warned against.-- Template references are checked against declared inputs, computed values, resources, and workload host/port fields.-- Recipe limits are checked through `validateWorkflowRecipeLimits`.-- Agentic `contextRef` requires explicit recipe and policy permission.--### 4.2 Registry Admin API--Main route:--```text-control-api/src/routes/admin/registry.ts-```--Registry client:--```text-control-api/src/services/registryClient.ts-```--Important endpoints:--| Method | Route | Purpose |-|---|---|---|-| `GET` | `/api/v1/admin/registry/catalog` | Catalog plus installed state in one response. Used by `RegistryCatalog.tsx`. |-| `GET` | `/api/v1/admin/registry/entries` | Search catalog. |-| `POST` | `/api/v1/admin/registry/entries` | Publish entry. |-| `GET` | `/api/v1/admin/registry/entries/:name/versions/:version` | Read version. |-| `GET` | `/api/v1/admin/registry/categories` | List categories. |-| `GET` | `/api/v1/admin/registry/entries/:name/versions/:version/credential-schema` | Read install credentials schema. |-| `POST` | `/api/v1/admin/registry/install` | Install MCP server entry. |-| `POST` | `/api/v1/admin/registry/install-recipe` | Install recipe entry. |-| `PUT` | `/api/v1/admin/registry/entries/:name/versions/:version` | Edit version metadata. |-| `DELETE` | `/api/v1/admin/registry/entries/:name/versions/:version` | Remove catalog version. |--`install-recipe` does the important recipe-specific work:--1. Requires `registryEntryName` and `registryEntryVersion`.-2. Fetches the version from registry.-3. Verifies `entry_type === "recipe"`.-4. Extracts `recipe_meta.recipeYaml`.-5. Rejects content over 100 KB.-6. Parses YAML first, JSON second.-7. Generates a recipe name if one was not provided.-8. Uses `parsed.spec` when present, or the parsed object as spec for legacy payloads.-9. Validates recipe limits.-10. Optionally merges `inputValues` into `inputContract.properties[*].default`.-11. Creates the WorkflowRecipe CRD with the `clerum.io/managed-by: control-api` label and the `clerum.io/catalog-id` / `clerum.io/catalog-version` annotations.-12. Reports install back to registry asynchronously.--One difference from direct Recipe Editor creation: `install-recipe` does not currently run the full `validateRecipeBody` path from `admin/recipes.ts`. The browser preview and CRD/admission/reconciler still protect the install, but a unified system should consider whether registry recipe install should reuse the same validation path as direct create.--## 5. Desktop App Visibility--There are two different Desktop App places where recipes can appear.--### 5.1 Workflows Page--Route/component:--```text-desktop-app/ui/src/pages/WorkflowsPage.tsx-desktop-app/ui/src/hooks/domain/useWorkflowController.ts-desktop-app/ui/src/lib/workflows.ts-```--This page lists deployed WorkflowRecipes available to the signed-in user. It shows:--- Name.-- Namespace.-- Status.-- Input form from `spec.inputContract`.-- Trigger button.-- Recent runs and downloadable artifacts.--For the trigger button to be useful, the recipe should declare:--```yaml-spec:- triggers:- onDemand:- allowedActors: [user]-```--If `allowedActors` is absent, Desktop App treats it as triggerable once `onDemand` exists. If `allowedActors` exists and does not contain `user`, the UI disables trigger.--Separate from `spec.triggers`, Control API grants decide which users can see or trigger a workflow. Control UI stores those through the Members/Teams grants panel.--### 5.2 Apps / Sandbox UI Page--Component:--```text-desktop-app/ui/src/pages/SandboxUiPage.tsx-```--This page lists recipes that expose a sandbox UI:--```yaml-spec:- ui:- workloadRef: ui- port: 8080- title: Sales CRM- defaultPath: /-```--When a user opens an app, Desktop App asks the main process to mint a sandbox UI session, mounts a `WebContentsView`, and points it to the platform sandbox UI endpoint. A recipe can therefore appear both:--- In **Workflows**, if it has triggerable workflow steps.-- In **Apps**, if it has `spec.ui`.--The CRM sample is primarily interesting because it is an app-style recipe with a UI, optional integrations, and background jobs. It demonstrates why "workflow recipe" is broader than "LLM workflow."--## 6. Step-by-Step: Create a New WorkflowRecipe--This section describes the practical path for creating new recipes. Use the UI path for day-to-day authoring; use `kubectl` or direct API only for debugging or automation.--### 6.1 Start With the Smallest Valid Shape--For a non-UI, non-agent workload:--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: hello-recipe- namespace: sandbox-recipes-spec:- description: Minimal test workload.- workloads:- - id: web- type: deployment- image: nginxinc/nginx-unprivileged:1.27-alpine- port: 8080- healthCheck:- type: http- path: /- port: 8080- resources:- requests:- cpu: 50m- memory: 64Mi- limits:- cpu: 200m- memory: 128Mi- security:- isolationLevel: minimal-```--Control UI's editor expects JSON today, so convert the YAML to JSON before using **Plugins -> Install Plugin**, or install from Marketplace if the entry is published as YAML.--### 6.2 Add Inputs--Inputs make recipes reusable. They feed template substitutions and Desktop App trigger forms.--```yaml-spec:- inputContract:- properties:- topic:- type: string- default: latest advances in multi-agent systems- description: Research topic-```--In workflow steps, reference them as:--```yaml-instruction: "Research {{inputs.topic}} and produce a concise report."-```--The Desktop App trigger modal/form will prefill defaults from `inputContract`.--### 6.3 Add Workflow Steps--Agentic steps use `instruction`:--```yaml-spec:- agent:- provider: zai- model: glm-4.7- triggers:- onDemand:- allowedActors: [user, autonomous]- steps:- - id: research- instruction: "Research {{inputs.topic}}."- timeoutSeconds: 600- - id: summarize- dependsOn: [research]- instruction: |- Using this research:-- {{research:output}}-- Produce a structured summary.-```--Snippet steps use `run`:--```yaml-steps:- - id: query-postgres- run:- type: snippet- language: typescript- code: |- const rows = await sdk.postgres.query(ref, {- sql: "select now() as now"- });- return rows;- capabilities:- postgres:- workloads: [postgres]- access: readWrite-```--Custom coordinator image recipes can declare `coordinatorImage` and steps without `instruction` or `run`; the custom image owns the execution logic.--### 6.4 Add Workloads--Use workloads for databases, web apps, APIs, workers, MCP servers, and cron jobs.--```yaml-workloads:- - id: postgres- type: statefulset- image: postgres:16-alpine- port: 5432- env:- - name: POSTGRES_DB- value: app- - name: POSTGRES_USER- value: app- - name: PGDATA- value: /var/lib/postgresql/data/pgdata- envSecret:- name: app-db- keys:- - secretKey: password- envVar: POSTGRES_PASSWORD- volumeMounts:- - name: pgdata- mountPath: /var/lib/postgresql/data- volumeClaimTemplates:- - name: pgdata- storageClass: standard- accessMode: ReadWriteOnce- size: 1Gi- security:- runAsUser: 70- runAsGroup: 70- fsGroup: 70-```--Use `dependsOn` when startup ordering matters:--```yaml-- id: api- type: deployment- image: my-org/api:1.0.0- dependsOn: [postgres]-```--Use template references for sibling service discovery. Template refs resolve against workload `host`/`port` fields, `spec.resources[]` data, `inputs.*`, and `computed.*` — a Secret key is **not** addressable this way. Keep the credential in `envSecret` and let the workload assemble the connection string:--```yaml-env:- - name: PGHOST- value: "{{postgres:host}}"- - name: PGPORT- value: "{{postgres:port}}"- - name: PGDATABASE- value: app- - name: PGUSER- value: app-envSecret:- name: app-db- keys:- - secretKey: password- envVar: PGPASSWORD-```--Do not inline a credential into an env value. An env value such as `postgres://app:<password>@host:5432/app` is **rejected** by Control API on both create and validate (rule `workflowInlineSecretEnv`, field `spec.workloads[i].env[j].value`), producing a 422 — it is an error, not a warning. Use `envSecret` or snippet secret capabilities instead.--If the workload really needs a single pre-assembled URL, compose the non-secret part in `spec.computed` and inject the password separately through `envSecret`.--### 6.5 Expose an MCP Server--A workload becomes MCP-facing by declaring `transport`:--```yaml-workloads:- - id: crm-tools- type: deployment- image: my-org/crm-mcp:1.0.0- port: 3000- transport:- type: streamableHttp- path: /mcp-```--That workload will be rendered into `mcp-server`, not `sandbox-recipes`.--If the MCP workload needs to call a database workload, add a binding:--```yaml-bindings:- - from: crm-tools- to: postgres- port: 5432-```--Bindings are important because the default posture is network deny.--### 6.6 Expose a Sandbox UI--A recipe with a UI can show up in Desktop App Apps.--```yaml-workloads:- - id: ui- type: deployment- image: my-org/my-ui:1.0.0- port: 8080- healthCheck:- type: http- path: /- port: 8080-ui:- workloadRef: ui- port: 8080- title: My App- defaultPath: /-```--Rules of thumb from the CRM sample and sandbox UI examples:--- Use non-root images such as `nginxinc/nginx-unprivileged` for static UIs.-- Listen on 8080 unless the platform allowlist says otherwise.-- Keep secrets out of the UI pod. Put secrets in backend workloads in `sandbox-recipes`.-- Use the sandbox UI route as a browser surface, not as a privileged backend.-- If the UI needs backend data, route to an API workload through the platform-supported internal egress/proxy configuration.--### 6.7 Add External Egress--Public internet access is closed by default. Declare explicit egress for workloads that need it.--Exact-host egress:--```yaml-workloads:- - id: web-search- type: deployment- image: ghcr.io/aas-ee/open-web-search:latest- port: 3000- transport:- type: streamableHttp- egressBindings:- - dns: duckduckgo.com- port: 443- protocol: TCP- - dns: html.duckduckgo.com- port: 443- protocol: TCP-```--Public-web egress:--```yaml-egressBindings:- - egressClass: public-web-```--Use public-web sparingly. The UI already treats it as a special review point because it expands the trust boundary, even though private/internal ranges remain blocked.--### 6.8 Add Secrets--For workload environment variables:--```yaml-envSecret:- name: sales-crm-app- keys:- - secretKey: pg-password- envVar: PG_PASSWORD- - secretKey: fireflies-api-key- envVar: FIREFLIES_API_KEY- optional: true-```--For snippet capabilities:--```yaml-run:- capabilities:- secrets:- - alias: pg_password- secretRef:- name: pg-auth- key: password-```--Control UI detects both patterns and offers a secrets panel during create/edit. Filled values are written to Kubernetes Secrets before the recipe is submitted.--Namespace detail:--- Secrets for non-transport workflow workloads go to `sandbox-recipes`.-- Secrets for transport/MCP workloads go to `mcp-server`.-- The editor derives this from whether the workload has `transport`.--### 6.9 Add OAuth Integrations--Background OAuth clients let the platform hold a recipe-owned grant and broker short-lived provider tokens.--Example shape:--```yaml-oauthClients:- - id: google-gmail- provider: google- backgroundAccess: true- clientIdRef:- name: sales-crm-google-oauth- key: client-id- clientSecretRef:- name: sales-crm-google-oauth- key: client-secret- scopes:- - https://www.googleapis.com/auth/gmail.readonly-```--After install, Control UI detail page -> Integrations tab handles connect/disconnect for the recipe. The workload receives broker access, not raw refresh tokens.--### 6.10 Add Webhooks--The CRM sample uses optional webhooks so the recipe can become active before all provider credentials are available.--Pattern:--```yaml-webhooks:- - id: fireflies- workloadRef: api- path: /webhook/fireflies- optional: true- verification:- scheme: hmac-sha256-body- secretRef:- name: sales-crm-fireflies-webhook- key: signing-secret- signatureHeader: X-Hub-Signature-256- signaturePrefix: sha256=- signatureEncoding: hex-```--Optional webhooks can be dormant until their secret exists. This is useful for progressive setup.--### 6.11 Add Human Approval Gates--Per-step approval is expressed on a step:--```yaml-steps:- - id: send-email- instruction: "Draft and send the customer email."- requiresApproval:- target:- userId: <user-id>- message: Approve before sending this email.- timeoutSeconds: 3600-```--Control UI has an approval gating editor inside `RecipeEditor`. It can add or remove this block without manually editing JSON.--### 6.12 Configure Output and Retention--For downloadable run artifacts:--```yaml-output:- name: competitive-intel-report- destination: pvc- format: pdf- storageSize: 256Mi-runRetention:- successfulHistoryLimit: 10- failedHistoryLimit: 10- ttlSecondsAfterFinished: 604800- maxRunDurationSeconds: 3600-```--Desktop App and Control UI can list and download run artifacts from the workflow run endpoints.--### 6.13 Install Through Control UI--Direct recipe authoring path:--1. Open Control UI.-2. Go to **Plugins**.-3. Click **Install Plugin**.-4. Paste JSON.-5. Click **Review manifest**.-6. Resolve errors and review warnings and egress findings.-7. Click **Apply defaults**, adjusting the operator defaults panel if needed.-8. Click **Continue to access**.-9. Fill detected secret values, or leave empty to use existing secrets.-10. Add authorized users in the grants panel.-11. Click **Deploy plugin**.-12. Open the recipe detail page.-13. Check Conditions, Workloads, Secrets, Integrations, Members, Teams, Approval targets, and Runs.--Registry path:--1. Go to **Marketplace**.-2. Filter type to **Plugins**.-3. Open a plugin entry.-4. Review description, images, source repo, trust, and YAML.-5. Click **Install**. The install happens immediately — there is no validation or egress preview step on this path.-6. Control UI navigates to the live recipe detail page.-7. Configure secrets, integrations, and authorized users there.--### 6.14 Verify With kubectl--The live CRD should be in `sandbox-recipes`:--```bash-kubectl --context=clerum-test -n sandbox-recipes get workflowrecipes-kubectl --context=clerum-test -n sandbox-recipes describe workflowrecipe <name>-```--Check non-transport workloads:--```bash-kubectl --context=clerum-test -n sandbox-recipes get pods -l clerum.io/recipe-name=<name>-```--Check transport/MCP children:--```bash-kubectl --context=clerum-test -n mcp-server get pods -l clerum.io/recipe-name=<name>-kubectl --context=clerum-test -n mcp-server get mcpservers-```--Check sandbox UI:--```bash-kubectl --context=clerum-test -n sandbox-ui get pods -l clerum.io/recipe-name=<name>-```--## 7. Step-by-Step: Publish a WorkflowRecipe to Registry--Publishing creates a catalog entry. It does not install the recipe.--### 7.1 Prepare the Recipe YAML--Use YAML for registry entries. Keep:--- `apiVersion: clerum.io/v1alpha1`-- `kind: WorkflowRecipe`-- `metadata.name`-- `metadata.namespace: sandbox-recipes` for readability, even though install enforces placement.-- `metadata.annotations.clerum.io/source-repo` when useful, because Registry detail extracts it for a Source repo button.-- `metadata.labels.clerum.io/catalog-version` if the recipe repo tracks its own version.-- A clear `spec.description`.--### 7.2 Ensure Images Are Pullable--Registry detail extracts `image:` values from recipe YAML and links known registries. Before publishing:--- Push every image tag referenced by the YAML.-- Prefer immutable version tags over `latest`.-- Confirm public/private pull settings match the target cluster.-- If local-only, mark it clearly and do not publish as a general installable recipe.--### 7.3 Publish From Control UI--1. Open Control UI.-2. Go to **Marketplace**.-3. Click **+ Publish to Marketplace**.-4. Select **Plugin** as the entry type.-5. Fill common metadata:- - Name: RFC1123-compatible.- - Version: semantic or project version.- - Author.- - Description.- - Category.- - Origin.- - Tags.-6. Paste the recipe YAML.-7. Submit.-8. Return to Marketplace and verify the entry appears.-9. Open the entry detail and inspect images and YAML.-10. Install it into a test cluster from Marketplace before sharing it.--### 7.4 Registry Install Naming--If a registry recipe install does not specify `recipeName`, Control API generates one from entry name and version:--```text-recipe-<slug>-v<version>-<hash8>-```--This avoids collisions between versions, but it can produce names that are less human-friendly than the recipe's own `metadata.name`.--For a polished UX, the install flow should probably expose a "Recipe name" field for recipe entries, similar to the MCP server install form.--### 7.5 Updating a Published Recipe--Recommended version flow:--1. Change code.-2. Build and push new image tags.-3. Update `recipe.yaml` image tags.-4. Bump recipe/catalog version.-5. Publish a new registry version.-6. Install into a test cluster.-7. Verify status, pods, app UI, workflow trigger, and artifacts.-8. Deprecate or remove older catalog versions only when appropriate.--The current UI supports metadata edit and removal, but not a rich "upgrade installed recipe to new catalog version" experience. The backend has registry upgrade-style routes later in `control-api/src/routes/admin/registry.ts`; they are a natural area to inspect before designing upgrade UX.--## 8. CRM Sample Deep Dive--> The CRM sample (`sales-crm`) is maintained **outside this repository** and is not part of the `evenfire-ai/evenfire` tree. The paths and files below are not checkable in this repo; treat this section as a described reference architecture, not as files you can open here.--The sample is a plugin-style recipe with:--| Part | Purpose |-|---|---|-| Recipe manifest | Authoritative WorkflowRecipe (YAML, with a JSON form for the editor). |-| API image | Fastify API, database migrations, webhook handlers, cron jobs. |-| UI image | Preact/nginx sandbox UI. |--### 8.1 What the CRM Recipe Demonstrates--The CRM sample is a useful reference because it combines many recipe capabilities:--- A Postgres StatefulSet.-- An API deployment in `sandbox-recipes`.-- CronJob workloads for follow-up and inbox polling.-- A static/preact UI deployment in `sandbox-ui`.-- Optional third-party credentials.-- Optional dormant webhooks.-- Background OAuth for Gmail.-- Provider egress.-- Progressive enablement: the recipe can become active with only a Postgres password, then integrations can be enabled later by adding secrets.-- Desktop App Apps visibility through `spec.ui`.--### 8.2 Image Split--The sample uses two main images:--| Image | Namespace | Role |-|---|---|---|-| `docker.io/apavia/sales-crm-api:...` | `sandbox-recipes` | Fastify API, migrations, provider calls, webhooks, cron logic. |-| `docker.io/apavia/sales-crm-ui:...` | `sandbox-ui` | Static Preact UI served by nginx-unprivileged. |--The UI holds no secrets. It talks to backend routes. This is the right pattern for sandbox UI recipes.--### 8.3 Required Secret--The recipe is designed to need only one key at install time:--```bash-kubectl create secret generic sales-crm-app \- -n sandbox-recipes \- --from-literal=pg-password="$(openssl rand -hex 16)"-```--That password is used by both the DB and API/follow-up jobs. Without it, the core app cannot start.--### 8.4 Optional Secrets--Optional keys include:--- `anthropic-api-key`-- `openai-base-url`-- `openai-api-key`-- `openai-model`-- `fireflies-api-key`-- `whatsapp-phone-number-id`-- `whatsapp-access-token`--The recipe marks optional integration keys as `optional: true` so the workload can start without them. The app code must fail closed when optional credentials are absent.--### 8.5 Background OAuth--The CRM sample uses a recipe-owned Google OAuth client for Gmail ingestion:--1. Operator creates a Google OAuth Web Application client.-2. Operator creates `sales-crm-google-oauth` with `client-id` and `client-secret`.-3. Operator opens Control UI recipe detail -> Integrations.-4. Operator clicks **Connect for the recipe**.-5. Control API stores the grant server-side.-6. Runtime workloads use the OAuth broker to request short-lived tokens.--This is different from putting refresh tokens in Kubernetes Secrets. The recipe references client credentials; the platform owns user/provider grants.--### 8.6 Webhooks--The CRM sample shows how to use optional webhooks:--- Fireflies webhook can remain dormant until its signing secret exists.-- Telegram and WhatsApp style webhooks can use provider-specific verification.-- The gateway handles verification before traffic reaches the workload.--This pattern is very important for install UX. A recipe can be "installed and mostly usable" before every external provider is configured.--### 8.7 Desktop App Surfacing--The CRM appears in Desktop App Apps because it declares `spec.ui`. It is not primarily a Workflows page item unless it also declares triggerable workflow steps.--This distinction should be clear in a unified UI:--- "This recipe installs an app" when `spec.ui` exists.-- "This recipe installs runnable workflow triggers" when `spec.triggers.onDemand` and `spec.steps` exist.-- "This recipe installs MCP tools" when workloads have `transport`.-- "This recipe installs support infrastructure" when it has only non-transport workloads.--## 9. Validation and Security Rules to Understand--### 9.1 Client Validation--Client validator:--```text-control-ui/lib/recipeValidator.ts-```--It checks:--- Valid JSON.-- `apiVersion`.-- `kind`.-- `metadata.name`.-- Step count and per-step limits.-- Duplicate step IDs.-- Step shape: `instruction` or `run`, not both.-- Snippet run shape.-- Workload type.-- Secret name/key shape.-- Inline sensitive env values.-- PVC size limits.-- Capabilities allowlist.-- Egress binding count limits through `egressModel`.-- Template reference sanity for many common cases.--The UI currently validates JSON, not YAML, in the direct Recipe Editor. Registry install can parse YAML server-side and attempts browser validation only when `validateRecipe` can parse it.--### 9.2 Server Validation--Server validation:--```text-POST /api/v1/admin/recipes/validate-control-api/src/routes/admin/recipes.ts-```--It repeats structural checks and adds cluster-aware policy checks. This is the validation path users see when clicking Deploy in Recipe Editor.--### 9.3 Admission and Reconciler Validation--Even if UI or Control API misses something, the CRD schema, admission policy, and WRC reconciler remain enforcement layers. Treat UI validation as an ergonomic preflight, not the sole security boundary.--### 9.4 Egress Review--Egress analysis is intentionally prominent in both direct Recipe Editor and Registry install. The platform is default-deny; external access should be visible before deployment.--Current UI messages distinguish:--- No egress declarations.-- Exact-host egress.-- Public-web egress.-- Blocking egress errors.--### 9.5 Grants Are Product-Critical--A recipe can deploy successfully with no authorized users. In that case:--- Admins can see it in Control UI.-- Desktop App users will not be able to trigger it.--The editor warns on create when no users are selected. A unified install flow should preserve or strengthen this warning, especially for registry installs, which currently land on detail after install but do not force a grant decision first.--## 10. UX Unification Opportunities--### 10.1 Rename Actions by Intent--A first rename already shipped: the sections are now **Plugins** and **Marketplace** in the sidebar, and the entry types are **Plugin** and **Connector**.--Remaining ambiguity is on the verb, not the noun:--- Plugins -> **Install Plugin** means "create from JSON template/editor."-- Marketplace -> **Install** means "install catalog entry."--Better labels:--| Current | Suggested |-|---|---|-| Install Plugin in Plugins | Create plugin |-| Marketplace Install | Install from catalog |--### 10.2 Unified Recipe Home--A unified page could have one "Recipes" top-level section with tabs or segmented views:--- Installed-- Catalog-- Draft/Create--Installed should remain runtime-first. Catalog should be acquisition-first. Detail pages can cross-link:--- Installed recipe detail shows catalog source/version if labels exist.-- Catalog detail shows installed versions and links to live recipes.--### 10.3 One Install Wizard for Recipe Entries--Registry recipe install should eventually reuse the richer Recipe Editor capabilities:--- Show parsed YAML.-- Show exact install name.-- Show detected capabilities: App, Workflow, MCP tools, webhooks, OAuth, secrets, egress.-- Let operator choose authorized users before install.-- Detect required secrets and offer to create them.-- Show integrations that will require post-install connect.-- Run the same server validation as direct create.-- Land on the live detail page with a clear setup checklist.--### 10.4 Capability Badges--The catalog and installed list could expose badges derived from spec:--| Badge | Detection |-|---|---|-| App | `spec.ui` exists. |-| Workflow | `spec.steps` exists. |-| On-demand | `spec.triggers.onDemand` exists. |-| Scheduled | `spec.triggers.schedule` exists. |-| MCP tools | Any workload has `transport`. |-| OAuth | `spec.oauthClients.length > 0`. |-| Webhooks | `spec.webhooks.length > 0`. |-| Secrets | Workload `envSecret` or snippet secret capabilities exist. |-| Egress | Workload `egressBindings` or UI egress exists. |--These badges would help users understand what a recipe "has" without reading YAML.--### 10.5 Setup Checklist on Detail--After install, the detail page could show a recipe setup checklist:--- Required secrets present.-- Optional secrets missing.-- OAuth clients connected/disconnected.-- Webhooks active/dormant.-- Authorized users selected.-- App visible to Desktop users.-- On-demand trigger enabled.-- Workloads ready.-- Last run status.--This would be especially valuable for CRM-style recipes, where install is only the first step.--## 11. Code Map for Future Work--Use this map when modifying the UI.--### 11.1 Control UI--| Area | Files |-|---|---|-| Workflow list | `control-ui/app/workflow-recipes/page.tsx`, `control-ui/components/RecipesTab.tsx` |-| Workflow detail | `control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx` |-| Recipe create/edit | `control-ui/components/RecipeEditor.tsx` |-| Recipe status | `control-ui/components/RecipeStatusContent/index.tsx` |-| Run modal | `control-ui/components/WorkflowRunModal/index.tsx` |-| Registry catalog | `control-ui/components/RegistryCatalog.tsx` |-| Registry install | `control-ui/app/registry/install/page.tsx`, `control-ui/components/RegistryInstallForm/index.tsx` |-| Registry detail | `control-ui/app/registry/entries/[name]/[version]/page.tsx` |-| Registry publish | `control-ui/app/registry/publish/page.tsx`, `control-ui/components/PublishToRegistryForm.tsx` |-| API client | `control-ui/lib/api.ts` |-| Validation | `control-ui/lib/recipeValidator.ts` |-| Defaults | `control-ui/lib/recipeDefaults.ts` |-| Egress | `control-ui/lib/egressModel.ts`, `control-ui/components/EgressEditor.tsx` |-| Types | `control-ui/lib/recipeTypes.ts` |--Remember the UI agent rules for `control-ui`: reusable types belong in sibling `types.ts`, shared constants belong in `app/constants`, colors and spacing should use global CSS tokens, and shared classes go in `app/globals.css`.--### 11.2 Control API--| Area | Files |-|---|---|-| Live recipe CRUD/validation/secrets/status | `control-api/src/routes/admin/recipes.ts` |-| Registry search/publish/install | `control-api/src/routes/admin/registry.ts` |-| Registry HTTP client | `control-api/src/services/registryClient.ts` |-| Workflow grants | `control-api/src/services/workflows/workflowGrantManagementService.ts` |-| Workflow trigger | `control-api/src/services/workflows/workflowTriggerService.ts` |-| Run artifacts | `control-api/src/services/workflows/workflowRunArtifactService.ts` |-| Run history | `control-api/src/services/workflowRunService.ts` |-| Limits | `control-api/src/services/workflowRecipeLimits.ts` |--### 11.3 Desktop App--| Area | Files |-|---|---|-| Workflows page | `desktop-app/ui/src/pages/WorkflowsPage.tsx` |-| Workflow controller hook | `desktop-app/ui/src/hooks/domain/useWorkflowController.ts` |-| Workflow summary logic | `desktop-app/ui/src/lib/workflows.ts` |-| Sandbox app page | `desktop-app/ui/src/pages/SandboxUiPage.tsx` |--### 11.4 Docs and Examples--| Area | Files |-|---|---|-| Feature hub | `docs/features/workflow-recipes.md` |-| CRD reference | `docs/crds/workflowrecipe.md` |-| Operations guide | `docs/deploy/workflow-recipes-guide.md` |-| Custom coordinator snippet guide | `docs/features/custom-coordinator-snippet-workflow.md` |--The registry service and the CRM sample are maintained outside this repository and have no paths in this tree.--## 12. Practical Checklist for a New Recipe--Use this as the authoring checklist.--1. Define the recipe purpose.-2. Decide which capabilities it has: App, Workflow, MCP tools, OAuth, webhooks, cron, storage, egress.-3. Create the smallest valid `WorkflowRecipe` YAML.-4. Add workloads with explicit resources and health checks.-5. Add `spec.ui` only if it should show in Desktop App Apps.-6. Add `spec.steps` and `spec.triggers.onDemand` only if it should show in Desktop App Workflows.-7. Add `spec.inputContract` for user-provided run inputs.-8. Add `envSecret` and snippet secret capabilities for credentials.-9. Mark truly optional integration secrets as `optional: true`.-10. Add exact-host egress for provider/API calls.-11. Add bindings between workloads that must communicate.-12. Add OAuth clients if the platform should broker provider tokens.-13. Add webhooks with verification and replay settings.-14. Validate locally in Control UI or through `POST /admin/recipes/validate`.-15. Install in a clean test cluster.-16. Verify CRD phase, conditions, pods, secrets, integrations, UI, trigger, runs, and artifacts.-17. Publish to Registry with versioned metadata.-18. Install from Registry into a test cluster.-19. Confirm the `clerum.io/catalog-id` / `clerum.io/catalog-version` annotations and the `clerum.io/managed-by` label are present on the live recipe.-20. Confirm Desktop App visibility for the intended users.--## 13. Known Sharp Edges--- Direct Recipe Editor is JSON-first; registry recipes are usually YAML.-- Registry recipe install preview can fail to parse YAML client-side but still allow server-side YAML install only when there are no parsed blocking findings; the messaging currently calls this a fallback.-- Registry recipe install currently does not ask for authorized users before install.-- Registry publish form does not validate recipe YAML as richly as the Recipe Editor validates JSON.-- Installed detection depends on the catalog annotations (with a legacy label fallback), so direct-created recipes will not show as installed catalog entries.-- `metadata.labels` in author YAML may not survive direct recipe create because Control API owns labels and namespace placement.-- A recipe can be active but not visible in Desktop App Workflows if grants/triggers are missing.-- A recipe can be active but not visible in Desktop App Apps if `spec.ui` is absent.-- Optional credentials only work safely when the application code treats missing env vars as disabled integrations.-- Public-web egress should be treated as a serious review moment in UI.--## 14. Recommended Mental Model--Think of the system as three layers:--1. **Catalog layer**: Registry entries answer "What can I install?"-2. **Runtime layer**: WorkflowRecipes answer "What is running and healthy?"-3. **User layer**: Desktop App answers "What can this user open or trigger?"--Most confusion comes from jumping between those layers without naming the transition. The unification work should make the transition explicit:--```text-Registry entry selected- -> install preview and setup requirements- -> WorkflowRecipe created in sandbox-recipes- -> operator completes secrets/integrations/grants- -> users see Apps or Workflows in Desktop App-```--If the UI can keep that story visible, the underlying technical richness becomes a strength instead of a maze.diff --git a/docs/features/custom-coordinator-images.md b/docs/features/custom-coordinator-images.mddeleted file mode 100644index 3690f0498..000000000--- a/docs/features/custom-coordinator-images.md+++ /dev/null@@ -1,677 +0,0 @@-# Custom Coordinator Images--This guide explains how to build a custom coordinator image for a-`WorkflowRecipe`.--A custom coordinator image is useful when a workflow needs real business logic:-domain calculations, deterministic transformations, file generation, or a-controlled call to MCP tools. The platform still owns scheduling, security,-status, artifacts, and downloads. Your image owns the workflow logic.--If the workflow can fit inside the Clerum-managed TypeScript SDK runtime, start-with [Custom Coordinator Snippet Workflow](./custom-coordinator-snippet-workflow.md).-Use a custom coordinator image when you need a full developer-owned container,-custom dependencies, or image-level runtime behavior.--## The Mental Model--Custom coordinator images follow one product contract:--```text-WorkflowRecipe run- -> custom coordinator image- -> writes files to /output- -> reports artifacts in step output- -> Desktop App / Control UI download artifacts for that exact run-```--The artifact owner is the `WorkflowRecipe` run. It is not ChatLLM, Desktop RPC,-or a host/chat artifact flow.--## Snippet Runtime Or Custom Image--Both options produce the same product outcome: run-scoped workflow artifacts-downloadable from Desktop App and Control UI. The difference is the runtime-boundary.--| Need | Use |-| ------------------------------------------------------------ | -------------------------- |-| Small TypeScript business logic with curated SDK calls | Custom coordinator snippet |-| Platform-owned runtime and stricter SDK surface | Custom coordinator snippet |-| Custom npm/native dependencies or non-standard runtime setup | Custom coordinator image |-| Full coordinator lifecycle implemented in your own image | Custom coordinator image |--Choose the snippet runtime first when it is enough. Choose a custom image when-the code needs to own more than a snippet step can safely expose.--## What You Build--A custom coordinator image is a container that:--1. Starts the Clerum workflow SDK.-2. Reads the mounted workflow config.-3. Executes the recipe steps in dependency order.-4. Runs your business logic for each step.-5. Writes downloadable files under `/output`.-6. Reports step and workflow status back to WRC.-7. Optionally calls the WRC-managed `mcp-host` when the recipe declares MCP- tools for a step.--You do not build a Kubernetes operator, artifact server, token issuer, or-download API. Clerum provides those.--## SDK Base Image--The published `clerum-workflow-base` image is a convenience base for custom-coordinator images. It contains Node.js plus the compiled `@clerum/workflow-sdk`-package under `node_modules/@clerum/workflow-sdk`, and its required runtime-dependency `@clerum/workflow-runtime-core` under-`node_modules/@clerum/workflow-runtime-core`. The SDK re-exports from-runtime-core, so both packages must be present; an image with only-`@clerum/workflow-sdk` fails at `require()` time.--Use it when your coordinator is a Node/TypeScript runtime:--```dockerfile-FROM your-registry.example.com/evenfire/clerum-workflow-base:1.0.0-COPY dist/ ./dist/-CMD ["node", "dist/coordinator.js"]-```--The base-image build compiles the SDK with TypeScript only. It intentionally-does not run test dependency lifecycle scripts inside the Docker builder stage,-because those scripts are not needed for the production SDK files copied into-the final image and can make CI Docker builds flaky. SDK tests still run in the-normal package test jobs before the image build.--## Platform Status--Custom coordinator images are disabled by default:--```text-WRC_ENABLE_CUSTOM_COORDINATOR_IMAGE=false-```--An operator must explicitly enable the feature and configure the allowed image-prefixes before WRC accepts `spec.coordinatorImage`.--## Minimal Recipe--Create the parent `WorkflowRecipe` in `sandbox-recipes` and set-`spec.coordinatorImage`.--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: receivables-risk-review- namespace: sandbox-recipes-spec:- coordinatorImage: ghcr.io/acme/receivables-coordinator:v1.2.3-- inputContract:- type: object- properties:- requestId:- type: string- approvalThreshold:- type: number- default: 1000-- output:- destination: pvc- format: json- storageSize: 128Mi-- steps:- - id: prepare- - id: score-risk- dependsOn: [prepare]- - id: emit- dependsOn: [score-risk]-```--How to read this:--- `metadata.namespace` is always `sandbox-recipes` for `WorkflowRecipe` CRDs.-- `coordinatorImage` is your image. WRC uses it instead of the built-in- coordinator.-- `inputContract` is the product input shape shown to users and passed into the- mounted runtime config.-- `output.destination: pvc` tells Clerum to mount `/output` from a dedicated- workflow output PVC and make workflow artifacts downloadable.-- With a custom coordinator, steps can be id-only. The CRD declares the workflow- shape; your image decides what each step does.-- WRC limits workflow step count with `WRC_MAX_WORKFLOW_STEPS`, default `100`.- The CRD also has a static `100` ceiling for `spec.steps` and step dependencies- because Kubernetes admission schemas cannot read WRC runtime environment- variables.--## Deployable Recipe Shape--A recipe that should be launched by a user needs an on-demand trigger and user-grant, even when the custom image is fully deterministic:--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: custom-risk-review- namespace: sandbox-recipes-spec:- coordinatorImage: ghcr.io/acme/risk-coordinator:v1.2.3-- triggers:- onDemand:- requiresApproval: false- allowedActors: ['user']-- inputContract:- type: object- properties:- requestId:- type: string- customer:- type: string-- output:- destination: pvc- format: multi- storageSize: 128Mi-- runtimeEgress:- http:- allowedHosts:- - api.vendor.example-- steps:- - id: fetch-inputs- - id: score-risk- dependsOn: [fetch-inputs]- - id: emit-artifacts- dependsOn: [score-risk]-```--Use this as the deterministic baseline: no child `mcp-host` is required, and-your image performs the step logic from the mounted config plus declared-context. If the workflow needs MCP broker behavior, add declared transport-workloads, `mcpServers`, `allowedTools`, and `agent` metadata to the step that-needs the broker. WRC then creates the child `mcp-host` and provides the scoped-`MCP_HOST_TOKEN_FILE` only for that broker-backed path.--For manual testing:--- use YAML with `kubectl apply`;-- use JSON if the Control UI editor expects JSON;-- include `triggers.onDemand` when the workflow must be user-triggerable;-- grant the target user access to the recipe before testing from Desktop App;-- use a unique `requestId` per run when comparing downloaded artifacts;-- do not bake API keys, provider keys, or Clerum runtime credentials into the- image or CRD; use the platform's approved secret provisioning path;-- verify deterministic recipes do not create a child `mcp-host`;-- verify broker-backed recipes create a child `mcp-host` and only use declared- `mcpServers` and `allowedTools`.--## Validation Model--Custom coordinator recipes use the same early-validation split as the rest of-WorkflowRecipe:--| Checkpoint | Fails | Examples |-| ----------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Kubernetes CEL | Invalid CRD shape or invalid public egress intent | duplicate step ids, non-public `runtimeEgress.http.allowedHosts`, malformed cron, invalid run/instruction combinations |-| WRC before pods | Policy and semantic checks that need controller context | feature flag disabled, image prefix or digest policy failure, unsupported Linux capability, unknown step dependency, broker-backed step without agent config, undeclared workload/MCP binding |-| Runtime SDK/image | Behavior only the running image can perform | business logic, actual artifact content, custom HTTP client behavior inside the image |--WRC should reject policy or semantic violations before creating the custom-coordinator pod. Runtime failures are reserved for work that only the image can-perform after the declared context has already been accepted.--## Public HTTP Egress--Custom coordinator pods do not get public ingress. They can call WRC and other-declared workflow runtime services through explicit NetworkPolicies.--The model is capability control through declared workflow context. If the-`WorkflowRecipe` declares a non-transport workload, the custom coordinator may-perform the business operation it needs against that declared dependency. WRC-generates egress from the coordinator and ingress to that workload by recipe-label and port. Transport workloads and MCP tools still go through the-WRC-managed `mcp-host` path so `allowedTools` and scoped broker tokens remain-in force. The platform limits which destinations and tokens exist; it does not-try to infer each operation's business intent.--If the image needs direct public HTTP calls, declare the intent on the recipe:--```yaml-spec:- coordinatorImage: ghcr.io/acme/receivables-coordinator:v1.2.3- runtimeEgress:- http:- allowedHosts:- - api.vendor.example-```--The current implementation follows the existing WRC runtime egress pattern. WRC-resolves the declared hostnames to public IPv4 `/32` CIDRs and opens TCP `80/443`-egress for the custom `workflow-coordinator` only to that resolved CIDR set.-Resolution fails closed when a host does not resolve or resolves to private,-metadata, link-local, cluster-local, documentation, benchmarking, multicast, or-reserved ranges. While a workflow run is active, WRC periodically re-resolves-those hosts and patches the NetworkPolicy. If the CIDR set changes, WRC keeps-the previous CIDRs for `WRC_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS` seconds-(default `300`) so DNS rotation does not cut over in-flight runs abruptly. Treat-this as a bounded trust window as well as an availability setting: the previous-public CIDRs remain allowed until the overlap expires.-Kubernetes NetworkPolicy still cannot enforce HTTP hostnames at L7; a shared-egress proxy remains the hardening path for redirect/TLS/method/rate-limit-policy on custom images.--## Image Policy--WRC accepts a custom image only when all policy checks pass:--| Check | Meaning |-| ------------- | ----------------------------------------------------------------------- |-| Feature flag | `WRC_ENABLE_CUSTOM_COORDINATOR_IMAGE=true` must be set by the operator. |-| Allowlist | The image must match `WRC_ALLOWED_COORDINATOR_IMAGE_PREFIXES`. |-| No `:latest` | Mutable `latest` tags are rejected. |-| Digest policy | `WRC_REQUIRE_COORDINATOR_IMAGE_DIGEST` defaults to `true` (and `deploy/base` ships `"true"`), so the image must include a valid `sha256` digest. |--This is a platform control. Your image does not enforce it, but release images-should be built as if the policy will be strict.--Because digest enforcement is on by default, a tag-only `spec.coordinatorImage`-is rejected in the default and base configurations. The tag-only references in-this guide's examples are shown for readability; use a digest-pinned reference such-as `ghcr.io/acme/receivables-coordinator@sha256:<64-hex>` unless an operator has-explicitly set `WRC_REQUIRE_COORDINATOR_IMAGE_DIGEST=false` (the minikube overlay-does this for local E2E fixtures).--## Runtime Environment--WRC starts your container with a small set of environment variables and mounted-files:--| Name | What it is for |-| ---------------------------- | ------------------------------------------------------------------ |-| `CLERUM_WORKFLOW_NAME` | Child run recipe name. Use it for WRC calls. |-| `CLERUM_NAMESPACE` | Runtime namespace, normally `sandbox-recipes`. |-| `CLERUM_WRC_URL` | In-cluster WRC REST base URL. |-| `WRC_TOKEN_FILE` | File containing the current Clerum runtime JWT for WRC routes. |-| `WORKFLOW_CONFIG_PATH` | Mounted workflow config, normally `/etc/workflow/config.json`. |-| `SOUL_MD_PATH` | Mounted `SOUL.md` path, when present. |-| `CLERUM_WORKFLOW_OUTPUT_DIR` | Output directory, normally `/output`. |-| `CLERUM_MCPHOST_URL` | Present only when a step requires broker-backed MCP work. |-| `MCP_HOST_TOKEN_FILE` | File containing the current child `mcp-host` token, when required. |--`WRC_TOKEN_FILE` and `MCP_HOST_TOKEN_FILE` point to Kubernetes Secret volume-files. WRC rotates those files while the pod runs, so coordinators should use-the SDK token provider instead of reading a startup token once and caching it-forever. These are Clerum runtime tokens, not OpenAI, Anthropic, Z.ai, Bailian,-or other provider API keys. Provider secrets are held by platform services and-are not exposed to custom coordinator code.--## Token Handling--Your code can access its own runtime tokens through the SDK because they are-delivered as Kubernetes Secret-backed files. That is expected. The security rule-is narrower:--- Use the token from `WRC_TOKEN_FILE` only to call the allowed WRC SDK/API- routes.-- Use the token from `MCP_HOST_TOKEN_FILE` only through the SDK `mcp-host`- client.-- Do not log either token.-- Do not write either token into `/output`.-- Do not pass either token to MCP tools, model prompts, external services, or- generated artifacts.--If a token appears in an artifact, that artifact is a leak created by the custom-image.--## Pod Constraints--The platform runs custom coordinators with a hardened pod profile:--| Constraint | Impact on your image |-| ------------------------------------------------ | --------------------------------------------------------------------------- |-| Non-root user/group `1000` | Files your image writes must be writable by user `1000`. |-| Read-only root filesystem | Do not write into `/app`, `/usr`, or other image paths. |-| Writable `/tmp` | Put temporary files in `/tmp`. |-| Writable `/output` | Put product artifacts in `/output`. |-| No privilege escalation and dropped capabilities | Do not rely on privileged Linux operations. |-| No service account token dependency | Do not design the image around Kubernetes API access. |-| `restartPolicy: Never` | The image should fail clearly and report failure before exit when possible. |--These are platform controls. You do not need to implement them in your code, but-your image must be compatible with them.--## SDK Lifecycle--Use `@clerum/workflow-sdk`. A coordinator usually follows this lifecycle:--```js-const { WorkflowSDK, emitLog } = require('@clerum/workflow-sdk')--async function main() {- const sdk = await WorkflowSDK.fromEnvironment()- const spec = await sdk.config.getSpec()- const steps = sdk.coordinator.resolveOrder(spec.steps)- const outputs = {}-- try {- sdk.updatePhase('running')- await sdk.status.reportWorkflowStatus('running')-- for (const step of steps) {- await sdk.status.reportStepStatus(step.id, 'running', {- executor: 'custom',- startedAt: new Date().toISOString(),- })-- const output = await runBusinessStep(step, spec, outputs, sdk)- outputs[step.id] = output-- await sdk.status.reportStepStatus(step.id, 'completed', {- executor: 'custom',- output,- completedAt: new Date().toISOString(),- })- }-- await sdk.status.reportWorkflowStatus('completed', {- completedAt: new Date().toISOString(),- })- } catch (err) {- const message = err instanceof Error ? err.message : String(err)- await sdk.status.reportWorkflowStatus('failed', { failureReason: message })- emitLog('error', `Custom coordinator failed: ${message}`)- process.exitCode = 1- } finally {- await sdk.shutdown()- }-}--main().catch(err => {- console.error(err)- process.exit(1)-})-```--`runBusinessStep` is your code. It can calculate, transform, call internal-business libraries, create files, or call `mcp-host` when the recipe declares a-broker-backed step.--## Writing Artifacts--To create a downloadable workflow artifact:--1. Write the file under `/output`.-2. Return artifact metadata from the step output.--Single artifact:--```js-return {- artifact: {- name: 'receivables-risk-result.json',- format: 'json',- path: '/output/receivables-risk-result.json',- sizeBytes: 989,- createdAt: new Date().toISOString(),- },-}-```--Multiple artifacts:--```js-return {- artifacts: [- {- name: 'receivables-risk-result.json',- format: 'json',- path: '/output/receivables-risk-result.json',- sizeBytes: 989,- createdAt: new Date().toISOString(),- },- {- name: 'risk-summary.md',- format: 'md',- path: '/output/risk-summary.md',- sizeBytes: 431,- createdAt: new Date().toISOString(),- },- ],-}-```--Artifact rules enforced by WRC:--| Rule | Why it matters |-| ----------------------------------------------- | ------------------------------------------------ |-| `name` must be a filename only | Prevents path traversal and ambiguous downloads. |-| `path` must be under `/output/` | Keeps downloads bound to workflow output only. |-| `sizeBytes` must be a safe non-negative integer | Prevents invalid metadata. |-| Metadata has length limits | Prevents oversized status payloads. |-| At most 20 artifacts per step update | Keeps status updates bounded. |--Desktop App and Control UI download workflow artifacts by parent recipe plus-`runId`. Do not use `window.clerum.rpc.downloadArtifact` for workflow outputs;-that API is for host/chat artifacts.--Downloaded filenames may be prefixed by the run id in the UI. The artifact name-in `status.artifacts[]` remains the logical workflow artifact name, while the-local filename prefix prevents accidental overwrites when two runs emit-`risk-summary.md` or `custom-sdk-result.json`.--## Status Output Is A Preview--`status.steps[].output` is intentionally bounded. WRC stores it as an operator-preview with truncation metadata, not as a complete report body. If your custom-coordinator creates a full Markdown, PDF, DOCX, XLSX, HTML, JSON, or image-artifact, write it under `/output` and report artifact metadata as shown above.--`{{step-id:output}}` prompt interpolation in the SDK follows the same principle:-it sends a bounded, marked preview of a dependency step's output. Use it for-compact summaries or structured handoff data. Do not use it as the transport for-complete reports; those belong in `/output` artifacts.--## Deterministic Workflows--A deterministic custom coordinator does not need an LLM or `mcp-host`.--Use this style when the workflow can run from inputs plus code:--- scoring;-- classification with fixed rules;-- report generation from provided inputs;-- normalization or validation;-- deterministic file generation.--For deterministic workflows:--- the CRD can have id-only steps;-- no child `mcp-host` should be created;-- artifacts still come from `/output` and `status.artifacts[]`;-- Desktop App and Control UI should still download by the exact `runId`.--## Broker-Backed MCP Workflows--A broker-backed custom coordinator uses a WRC-managed child `mcp-host` for steps-that declare agent/tool requirements.--Example:--```yaml-spec:- coordinatorImage: ghcr.io/acme/receivables-coordinator:v1.2.3-- workloads:- - id: receivables-tools- type: deployment- image: ghcr.io/acme/receivables-mcp:v1.2.3- port: 3000- transport:- type: streamableHttp- path: /mcp- healthCheck:- type: tcp- port: 3001-- steps:- - id: prepare- - id: broker-review- dependsOn: [prepare]- instruction: |- Use receivables-tools to fetch the customer risk snapshot.- Return normalized JSON.- agent:- provider: zai- model: glm-4.7- mcpServers:- - receivables-tools- allowedTools:- include:- - receivables-tools__risk_snapshot- maxIterations: 6- - id: emit- dependsOn: [broker-review]-```--How this works:--- WRC sees that `broker-review` requires broker-backed execution.-- WRC creates the child `mcp-host`.-- Your container receives `CLERUM_MCPHOST_URL` and `MCP_HOST_TOKEN_FILE`.-- Your code requests model injection through WRC for the declared provider/model.-- Your code calls `mcp-host` through the SDK.-- `mcp-host` enforces declared servers and allowed tools.-- MCP SDK tool requests are bounded by the recipe-local `mcp-host` timeout- configuration and by the workflow/custom-coordinator step budget. A streamed- `mcp-host` response must produce a result before the SDK step timeout expires.-- Your code writes final artifacts under `/output`.--SDK sketch:--```js-const { requestModelInjection, renderPrompt } = require('@clerum/workflow-sdk')--async function runBrokerStep(step, spec, outputs, sdk) {- const mcpHost = sdk.requireMcpHost()- const cfg = sdk.config.getConfig()-- await requestModelInjection(cfg.wrcUrl, spec.name, cfg.tokenProvider, {- stepId: step.id,- provider: step.agent.provider,- model: step.agent.model,- })-- const result = await mcpHost.executeAgentStep({- stepId: step.id,- instruction: renderPrompt(step.instruction, {- step,- previousOutputs: outputs,- workflowName: spec.name,- }),- mcpServers: step.mcpServers ?? [],- allowedTools: step.allowedTools ?? {},- maxIterations: step.maxIterations,- timeoutSeconds: step.timeoutSeconds,- })-- if (result.status === 'failed') {- throw new Error(result.error || `mcp-host failed step ${step.id}`)- }-- return result-}-```--## Platform-Enforced Boundaries--The platform already blocks several unsafe or out-of-contract behaviors. They-are documented here so image authors know what not to depend on.--| Boundary | What happens |-| ------------------------- | -------------------------------------------------------------------------------------------------- |-| `/configure-model` | Custom coordinator tokens cannot use this privileged route. Use WRC model injection instead. |-| `/trigger` | Custom coordinator tokens cannot trigger workflows. They can only operate on the current run. |-| Undeclared model/provider | WRC rejects model injection that is not declared by the step/recipe. |-| Undeclared MCP tools | `mcp-host` enforces the declared `mcpServers` and `allowedTools`. |-| Artifact path traversal | WRC rejects unsafe artifact names and paths. |-| Kubernetes API dependency | Custom pods are not meant to use service account tokens, `pods/exec`, or broad cluster API access. |--These controls protect the platform. They do not replace developer hygiene:-your code must still avoid logging tokens, writing secrets into artifacts, or-sending runtime tokens to tools or external systems.--## Image Build Checklist--Recommended Dockerfile shape. `@clerum/workflow-sdk` depends on-`@clerum/workflow-runtime-core` through a `file:` link, so the build context must-be the repository root and runtime-core must be built first and copied into the-final image alongside the SDK:--```Dockerfile-FROM node:24-alpine AS sdk-builder-WORKDIR /app-COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/-COPY packages/workflow-runtime-core/tsconfig.json ./packages/workflow-runtime-core/-COPY packages/workflow-runtime-core/src ./packages/workflow-runtime-core/src-WORKDIR /app/packages/workflow-runtime-core-RUN npm ci --ignore-scripts && npm run build--WORKDIR /app-COPY packages/workflow-sdk/package.json packages/workflow-sdk/package-lock.json ./packages/workflow-sdk/-COPY packages/workflow-sdk/tsconfig.json ./packages/workflow-sdk/-COPY packages/workflow-sdk/src ./packages/workflow-sdk/src-WORKDIR /app/packages/workflow-sdk-RUN npm ci --ignore-scripts && npm run build:docker--FROM node:24-alpine-WORKDIR /app-COPY packages/workflow-runtime-core/package.json ./node_modules/@clerum/workflow-runtime-core/package.json-COPY --from=sdk-builder /app/packages/workflow-runtime-core/dist ./node_modules/@clerum/workflow-runtime-core/dist-COPY packages/workflow-sdk/package.json ./node_modules/@clerum/workflow-sdk/package.json-COPY --from=sdk-builder /app/packages/workflow-sdk/dist ./node_modules/@clerum/workflow-sdk/dist-COPY coordinator.js ./coordinator.js-RUN mkdir -p /output /tmp && chown -R 1000:1000 /app /output /tmp-USER 1000:1000-EXPOSE 8090-CMD ["node", "coordinator.js"]-```--This mirrors `packages/workflow-sdk/Dockerfile.base` and the E2E fixture at-`tests/e2e/fixtures/custom-workflow-coordinator/Dockerfile`. If you extend the-published `clerum-workflow-base` image instead, both packages are already present-and you only need to copy your own build output.--Before release:--- Run as user `1000`, not root.-- Write only to `/tmp` and `/output`.-- Do not bundle provider API keys or static Clerum credentials.-- Pin third-party dependencies.-- Use digest-pinned image references: digest enforcement is on by default, so a- tag-only reference is rejected unless an operator turns it off.-- Keep business logic testable outside Kubernetes.--## Validation Checklist--Before asking an operator to allow your image:--- Unit-test the business logic without Kubernetes.-- Build the image and run it as non-root.-- Apply a `WorkflowRecipe` in `sandbox-recipes`.-- Verify WRC accepts `spec.coordinatorImage`.-- Verify the child run reaches `Succeeded`.-- Verify the coordinator pod uses your image.-- For deterministic workflows, verify no child `mcp-host` pod is created.-- For broker-backed workflows, verify the child `mcp-host` is created and the- custom coordinator uses the declared MCP server/tool.-- Verify `status.artifacts[]` contains the expected artifact metadata.-- Verify Desktop App downloads the artifact for the exact run.-- Verify Control UI downloads the same artifact for the exact run.-- Verify two consecutive runs do not cross-download each other's artifacts.diff --git a/docs/features/custom-coordinator-snippet-runtime.md b/docs/features/custom-coordinator-snippet-runtime.mddeleted file mode 100644index 1c6c0a5c9..000000000--- a/docs/features/custom-coordinator-snippet-runtime.md+++ /dev/null@@ -1,272 +0,0 @@-# Custom Coordinator Snippet Runtime--Custom coordinator snippets run small TypeScript snippets inside a-Clerum-managed runtime image. They are meant for workflow business logic that-needs code but does not need a developer-owned Docker image.--For a developer-facing guide with copyable recipe patterns, see-[Custom Coordinator Snippet Workflow](./custom-coordinator-snippet-workflow.md).-This page is the compact runtime reference for validation, SDK scope, and-operational behavior.--Use snippets when the workflow can be expressed as:--```text-WorkflowRecipe -> platform coordinator -> workflow-snippet-runner -> sdk.* -> /output artifacts-```--Use a custom coordinator image instead when the developer needs custom-dependencies or a runtime that cannot fit the curated SDK.--## Runtime Contract--Snippet steps use `run.type: snippet`:--```yaml-steps:- - id: summarize-receivables- run:- type: snippet- language: typescript- code: |- const rows = await sdk.postgres.query(- { workload: "postgres", database: "clerum" },- { sql: "select customer, amount from receivables where status = $1 limit $2", values: ["open", 100] }- )-- const artifact = await sdk.artifacts.writeMarkdown(- "receivables-summary.md",- `# Open Receivables\n\nRows: ${rows.length}\n`- )-- return { rows, artifact }- capabilities:- postgres:- access: read- workloads: [postgres]-```--Every capability must be declared. The runner resolves capabilities from the-mounted WorkflowRecipe config, not from the coordinator request, so a caller-cannot widen code, endpoints, workloads, or tools at execution time.--Workflow step count is an operator setting: WRC reads-`WRC_MAX_WORKFLOW_STEPS` and defaults it to `100`. The CRD keeps the same-`100` ceiling for `spec.steps` and step dependencies because Kubernetes schemas-cannot read runtime environment variables.--## Validation Model--The snippet runtime intentionally fails as early as the check can be made without-duplicating runtime logic:--| Checkpoint | Fails | Examples |-| --------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Kubernetes CEL | Invalid CRD shape or explicit intent mismatch | duplicate step ids, `run + instruction`, `run + agent`, DB capability missing `access`, wildcard MCP tools, non-public `runtimeEgress.http.allowedHosts`, snippet HTTP hosts not declared in `spec.runtimeEgress.http.allowedHosts`, MCP servers without `allowedTools.include` |-| WRC before pods | Semantic recipe references that require controller context | unknown `dependsOn`, snippet `secretRef` Secret not owned by or shared with the recipe, snippet `secretRef` Secret/key missing from `sandbox-recipes`, Mongo/Postgres workload not declared in `spec.workloads`, MCP server/tool not declared or scoped |-| SDK runtime | Values only known while code runs | actual URL host, HTTPS requirement, HTTP method, redirect target, response size, DB write attempted with `access: read`, unsafe artifact filename |--This keeps admission useful for developer feedback without making the CRD-expensive. WRC semantic failures happen before coordinator or runner pods are-created, so a bad recipe does not wait until the end of a workflow run to fail.--## Available SDK--The snippet receives one argument: `sdk`.--- `sdk.inputs`: resolved workflow inputs.-- `sdk.previousOutputs`: outputs from dependency steps.-- `sdk.http.fetchJson(url, init?)` and `sdk.http.fetchText(url, init?)`:- public HTTP helpers for explicitly declared hosts. Supported methods are- `GET`, `HEAD`, `POST`, and `PUT`.-- `sdk.secrets.get(alias)`: reads declared recipe Secret values by alias.-- `sdk.mongo.find/aggregate/insertOne/insertMany/updateOne/updateMany/deleteOne/deleteMany`:- MongoDB helpers scoped to declared recipe workloads.-- `sdk.postgres.execute/query/queryOne`: PostgreSQL helpers scoped to declared recipe workloads.-- `sdk.mcp.callTool(serverId, toolName, args)`: manual MCP tool calls through the MCP TypeScript SDK, scoped to declared servers and tools.-- `sdk.artifacts.writeJson(name, data)` and `sdk.artifacts.writeMarkdown(name, body)`: writes product artifacts under `/output`.-- `sdk.log.info/warn/error(message, meta)`: structured snippet logs with secret redaction.--The runtime does not expose raw `fetch`, `axios`, `process.env`, `require`,-dynamic `import`, direct filesystem access, sockets, Kubernetes API access, or-arbitrary connection strings.--`sdk.previousOutputs` is runtime state, not CRD syntax. A step sees outputs from-completed dependency steps keyed by `step.id`; the CRD only declares the-dependency with `dependsOn`.--## Capability Rules--HTTP:--```yaml-runtimeEgress:- http:- allowedHosts: [api.example.com]--steps:- - id: call-api- run:- type: snippet- language: typescript- code: |- return await sdk.http.fetchJson("https://api.example.com/report")- capabilities:- http:- allowedHosts: [api.example.com]-```--`spec.runtimeEgress.http.allowedHosts` is the workflow-level public egress-contract shared with custom coordinator images. A snippet step may then declare-the subset it uses through `run.capabilities.http.allowedHosts`; Kubernetes-admission rejects the recipe if the step asks for a host outside the-workflow-level list. WRC resolves the workflow-level hosts to public IPv4 `/32`-CIDRs and opens TCP `80/443` egress for snippet runner pods only to that-resolved CIDR set. Resolution fails closed for unresolved, private, metadata,-link-local, cluster-local, documentation, benchmarking, multicast, or reserved-addresses. While a workflow run is active, WRC periodically re-resolves those-hosts and patches the NetworkPolicy. If the CIDR set changes, WRC keeps the-previous CIDRs for `WRC_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS` seconds (default-`300`) so DNS rotation does not cut over in-flight runs abruptly. That overlap is-also a bounded trust window: the old public CIDRs remain allowed until the window-expires, even if the hostname has already moved. The SDK also enforces the-per-step host allowlist in-process,-requires HTTPS for public hosts, blocks redirects to undeclared hosts, restricts-methods to `GET`, `HEAD`, `POST`, and `PUT`, and limits response size.--Secrets:--```yaml-steps:- - id: call-api- run:- type: snippet- language: typescript- code: |- const key = sdk.secrets.get("api_key")- return { hasKey: Boolean(key) }- capabilities:- secrets:- - alias: api_key- secretRef:- name: public-api-key- key: key-```--Snippet secrets reference Kubernetes Secrets by `secretRef.name/key`. Control UI-can capture these values in password fields and creates or updates the Secret in-`sandbox-recipes` before deploying the WorkflowRecipe; the CRD stores only the-reference, never the value. If you apply YAML directly, create the Kubernetes-Secret yourself first, and label it so the recipe is allowed to read it: either-`clerum.io/shared: "true"` (any recipe may reference it) or-`clerum.io/owner-recipe: <recipeName>` (only that recipe may). An unlabeled-Secret — or one carrying both labels — is denied, and the recipe fails with-`snippet secret "<name>" is not accessible to recipe "<recipe>"`.-Platform-managed runtime Secrets such as coordinator tokens are rejected.--MongoDB/PostgreSQL:--```yaml-workloads:- - id: postgres- type: deployment- image: postgres:16- port: 5432-steps:- - id: query-db- run:- type: snippet- language: typescript- code: |- const ref = { workload: "postgres", database: "clerum" }- await sdk.postgres.execute(ref, {- sql: "insert into receivables(account, amount) values ($1, $2)",- values: ["dao-alpha", 1880]- })- return await sdk.postgres.query(ref, {- sql: "select * from receivables where amount >= $1",- values: [1000],- limit: 10- })- capabilities:- postgres:- access: readWrite- workloads: [postgres]-```--Database helpers can only reach declared workloads in the same WorkflowRecipe.-Within that declared context, the snippet can perform the business operations-it needs. Declare `access: read` for read-only steps and `access: readWrite`-for steps that insert, update, delete, run PostgreSQL DDL, or use MongoDB-`$out`/`$merge`. The runner does not accept arbitrary connection strings,-host/port overrides, or undeclared workload ids. PostgreSQL calls are one-statement per SDK call to avoid bundled follow-on statements; use multiple SDK-calls when a step needs a sequence of operations.--MCP:--```yaml-workloads:- - id: mongo-mcp- type: deployment- image: clerum/mock-mcp-server:test- port: 3000- transport:- type: streamableHttp- path: /mcp-steps:- - id: read-mcp- run:- type: snippet- language: typescript- code: |- return await sdk.mcp.callTool("mongo-mcp", "upsert_receivable", {- account: "dao-alpha",- amount: 1880- })- capabilities:- mcp:- servers: [mongo-mcp]- allowedTools:- include: [mongo-mcp__upsert_receivable]-```--Tool allowlists must be explicit. Wildcards are rejected. If a declared MCP tool-mutates data, that mutation is considered part of the workflow context chosen-by the recipe author; WRC controls access to the declared server/tool rather-than trying to infer each tool's internal side effects.--Manual MCP calls use the MCP TypeScript SDK directly inside the snippet worker.-Operators can tune SDK request bounds with `CLERUM_MCP_TOOL_TIMEOUT_MS` and-`CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS`; the effective call timeout is still-clamped to the remaining snippet step budget. For snippets that do not declare-`timeoutSeconds`, the runner keeps its existing operational fallback timeout,-but declared step budgets are not replaced by that fallback.--## Artifacts--Artifacts become product artifacts when the snippet returns metadata produced by-`sdk.artifacts.*`:--```ts-const artifact = await sdk.artifacts.writeJson("custom-report.json", { ok: true })-return { artifact }-```--Safe artifact names contain only letters, numbers, dot, underscore, and hyphen.-Artifacts are mounted at `/output` and later surfaced through the run-scoped-WorkflowRecipe artifact download flow in Control UI and Desktop App.-Artifacts written through `sdk.artifacts.*` are tracked by the runtime even when-the returned object is nested or named differently; returning-`{ artifacts: [...] }` is still recommended because it makes the step output-easy to inspect.--## Operational Notes--- The feature flag is `WRC_ENABLE_SNIPPET_RUNTIME`; operators enable it per- environment.-- The runner image is `clerum/workflow-snippet-runner`.-- The runner pod has no service account token, runs non-root, uses a read-only- root filesystem, drops Linux capabilities, and receives only declared snippet- secret aliases plus the explicit MCP timeout env allowlist.-- NetworkPolicies are generated from declared snippet capabilities.diff --git a/docs/features/custom-coordinator-snippet-workflow.md b/docs/features/custom-coordinator-snippet-workflow.mddeleted file mode 100644index 8616b9645..000000000--- a/docs/features/custom-coordinator-snippet-workflow.md+++ /dev/null@@ -1,588 +0,0 @@-# Custom Coordinator Snippet Workflow--This guide explains how to write workflow business logic with TypeScript-snippets in the Clerum-managed custom coordinator runtime.--Custom coordinator snippets are for developers who need code inside a-`WorkflowRecipe` but do not need to own a Docker image. Clerum owns the runtime-image, pod hardening, network policies, token delivery, status reporting, and-artifact download path. The developer owns the snippet logic and declares the-context it is allowed to use.--## Mental Model--Custom coordinator snippets follow one product artifact contract:--```text-WorkflowRecipe run- -> platform coordinator- -> workflow-snippet-runner- -> sdk.*- -> /output- -> status.artifacts[]- -> Desktop App / Control UI download artifacts for that exact run-```--The artifact owner is the `WorkflowRecipe` run. It is not ChatLLM, Desktop RPC,-or a host/chat artifact flow.--## When To Use Snippets--Use snippets when the workflow logic fits inside the curated SDK:--- fetch or submit data to declared public HTTP hosts;-- read or write declared MongoDB/PostgreSQL workloads from the same recipe;-- call declared MCP servers/tools directly without an LLM;-- combine snippet steps with separate agentic steps that use `mcp-host`;-- generate JSON or Markdown artifacts from workflow inputs and step outputs.--Use [Custom Coordinator Images](custom-coordinator-images.md) instead when you-need custom dependencies, a long-lived runtime, language/runtime choices beyond-the curated TypeScript SDK, or image-level business code.--| Need | Choose |-| --------------------------------------------------- | -------------------------- |-| Small TypeScript business logic | Custom coordinator snippet |-| Platform-owned runtime and SDK controls | Custom coordinator snippet |-| Custom npm/native dependencies or runtime bootstrap | Custom coordinator image |-| Full coordinator lifecycle owned by developer image | Custom coordinator image |--## Minimal Snippet Step--Snippet steps use `run.type: snippet` and `language: typescript`.--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: receivables-summary- namespace: sandbox-recipes-spec:- inputContract:- type: object- properties:- minAmount:- type: number- default: 1000-- output:- destination: pvc- format: json- storageSize: 128Mi-- resources:- - id: pg-auth- type: secret- data:- password: dev-only-password-- workloads:- - id: postgres- type: deployment- image: postgres:16- port: 5432- env:- - name: POSTGRES_DB- value: clerum- - name: POSTGRES_PASSWORD- value: '{{pg-auth:password}}'-- steps:- - id: build-summary- run:- type: snippet- language: typescript- code: |- const minAmount = sdk.inputs.minAmount ?? 1000- const rows = await sdk.postgres.query(- {- workload: "postgres",- database: "clerum",- user: "postgres",- passwordSecretAlias: "pg_password",- },- {- sql: "select account, amount from receivables where amount >= $1 order by amount desc limit $2",- values: [minAmount, 100],- }- )-- const artifact = await sdk.artifacts.writeMarkdown(- "receivables-summary.md",- `# Receivables Summary\n\nRows: ${rows.length}\n`- )-- return { rows, artifact }- capabilities:- secrets:- - alias: pg_password- secretRef:- name: pg-auth- key: password- postgres:- access: read- workloads: [postgres]-```--How to read this:--- `WorkflowRecipe` CRDs live in `sandbox-recipes`.-- `output.destination: pvc` makes `/output` available for product artifacts on- the parent recipe output PVC, sized by `output.storageSize` unless an existing- `output.claimName` is provided.-- The snippet can query only the declared `postgres` workload.-- The PostgreSQL ref carries the connection identity: `user` defaults to- `postgres` when omitted, and no password is sent unless the ref declares- `passwordSecretAlias`. Declare the alias in `run.capabilities.secrets` so it- resolves.-- `capabilities.postgres.access: read` declares read-only intent for this step.-- The returned artifact metadata is surfaced through run-scoped downloads.--## Deployable Recipe Shape--A recipe that a user can trigger from Desktop App or Control UI needs more than-steps. The usual shape is:--```yaml-apiVersion: clerum.io/v1alpha1-kind: WorkflowRecipe-metadata:- name: api-db-report- namespace: sandbox-recipes-spec:- triggers:- onDemand:- requiresApproval: false- allowedActors: ['user']-- inputContract:- type: object- properties:- requestId:- type: string- customer:- type: string-- output:- destination: pvc- format: multi- storageSize: 128Mi-- runtimeEgress:- http:- allowedHosts: [api.vendor.example]-- resources:- - id: pg-auth- type: secret- data:- password: dev-only-password-- workloads:- - id: mongo- type: deployment- image: mongo:7- port: 27017- - id: postgres- type: deployment- image: postgres:16- port: 5432- env:- - name: POSTGRES_DB- value: clerum- - name: POSTGRES_PASSWORD- value: '{{pg-auth:password}}'-- steps:- - id: fetch-api-to-mongo- run:- type: snippet- language: typescript- code: |- const apiKey = sdk.secrets.get("vendor_api_key")- const payload = await sdk.http.fetchJson("https://api.vendor.example/report", {- method: "GET",- headers: { authorization: `Bearer ${apiKey}` },- })- await sdk.mongo.insertOne(- { workload: "mongo", database: "clerum", collection: "reports" },- { document: { requestId: sdk.inputs.requestId, payload } }- )- return await sdk.artifacts.writeJson("api-to-mongo.json", { requestId: sdk.inputs.requestId })- capabilities:- http:- allowedHosts: [api.vendor.example]- secrets:- - alias: vendor_api_key- secretRef:- name: vendor-api- key: apiKey- mongo:- access: readWrite- workloads: [mongo]-```--Add later steps with `dependsOn` to read from MongoDB, write to PostgreSQL, and-emit the final report. Keep the recipe context explicit: public hosts in-`runtimeEgress`, secret references in `run.capabilities.secrets`, DBs in-`workloads`, and per-step capabilities under `run.capabilities`.--For manual testing:--- use YAML with `kubectl apply`;-- use JSON if the Control UI editor expects JSON;-- include `triggers.onDemand` when the workflow must be user-triggerable;-- grant the target user access to the recipe before testing from Desktop App;-- use a unique `requestId` per run when comparing downloaded artifacts;-- Control UI detects `run.capabilities.secrets[].secretRef`, asks for the- values in password fields, and creates or updates the Kubernetes Secret in- `sandbox-recipes` before deploying;-- if you apply YAML directly, create the Kubernetes Secret in `sandbox-recipes`- first and label it `clerum.io/owner-recipe=<recipeName>` (or- `clerum.io/shared=true`) — unlabeled Secrets are denied, see [Secrets](#secrets);-- never commit real API keys or database passwords to Git.--## SDK Surface--The snippet receives one argument: `sdk`.--| API | Purpose |-| --------------------------------------- | -------------------------------------------------- |-| `sdk.inputs` | Workflow inputs resolved from the `inputContract`. |-| `sdk.previousOutputs` | Outputs from dependency steps. |-| `sdk.http.fetchJson/fetchText` | Public HTTP to declared hosts. |-| `sdk.secrets.get(alias)` | Declared recipe Secret values by alias. |-| `sdk.mongo.*` | MongoDB helpers scoped to declared workloads. |-| `sdk.postgres.*` | PostgreSQL helpers scoped to declared workloads. |-| `sdk.mcp.callTool` | Manual MCP tool calls to declared servers/tools. |-| `sdk.artifacts.writeJson/writeMarkdown` | Writes files under `/output` and returns metadata. |-| `sdk.log.info/warn/error` | Structured logs with secret redaction. |--The runtime does not expose raw `fetch`, `axios`, `process.env`,-`require/import`, direct filesystem access, sockets, Kubernetes API access, or-arbitrary connection strings.--`sdk.previousOutputs` is not a CRD field. It is runtime state built from-completed dependency steps and keyed by `step.id`. Declare dependencies with-`dependsOn` when a step needs another step's output.--## Output Previews And Artifacts--`status.steps[].output` is a bounded status preview. It is useful for compact-summaries, artifact metadata, and operator diagnostics, but it is not the source-of truth for complete reports. Large reports must be written through-`sdk.artifacts.*` so they land under `/output` and are exposed through-run-scoped artifact downloads.--Prompt interpolation with `{{step-id:output}}` is also bounded. When previous-step output is too large, the SDK sends only a marked preview to the model. Do-not depend on prompt interpolation to move a full Markdown/PDF/DOCX/Excel report-between steps; pass compact structured data in step output and write the full-file as an artifact.--## Declared Context Controls Access--The snippet runtime is not meant to guess whether a business operation is good-or bad. It controls whether the snippet can reach the services the recipe author-declared.--That means:--- if a DB workload is declared and the step asks for `access: readWrite`, the- snippet may write to that DB through the SDK;-- if an MCP server/tool is declared, the snippet may call that tool;-- if a public HTTP host is declared, the snippet may call that host with the- allowed HTTP methods;-- if a workload, host, secret, or tool is not declared, the recipe fails early- or the SDK call fails closed.--This keeps the platform secure without making the SDK too restrictive for real-business workflows.--## Public HTTP--Declare public HTTP intent twice:--1. At workflow level, in `spec.runtimeEgress.http.allowedHosts`.-2. At step level, in `run.capabilities.http.allowedHosts`.--```yaml-spec:- runtimeEgress:- http:- allowedHosts:- - api.vendor.example-- steps:- - id: fetch-vendor-data- run:- type: snippet- language: typescript- code: |- return await sdk.http.fetchJson("https://api.vendor.example/report", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ status: "open" }),- })- capabilities:- http:- allowedHosts:- - api.vendor.example-```--Rules:--- supported methods are `GET`, `HEAD`, `POST`, and `PUT`;-- public hosts must use HTTPS;-- IP literals, cluster-local names, `.svc`, `.internal`, and metadata hosts are- rejected;-- redirects to undeclared hosts are rejected;-- response size and timeouts are bounded.--WRC resolves the workflow-level hosts to public IPv4 `/32` CIDRs and opens TCP-`80/443` egress for snippet runner pods only to that resolved CIDR set.-Resolution fails closed for unresolved, private, metadata, link-local,-cluster-local, documentation, benchmarking, multicast, or reserved addresses.-While a workflow run is active, WRC periodically re-resolves those hosts and-patches the NetworkPolicy. If the CIDR set changes, WRC keeps the previous CIDRs-for `WRC_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS` seconds (default `300`) so DNS-rotation does not cut over in-flight runs abruptly. Kubernetes NetworkPolicy-still cannot enforce HTTP hostnames at L7, so a shared egress proxy remains the-hardening path for redirect/TLS/method/rate-limit policy on custom images.--## Secrets--Secrets are declared as Kubernetes `secretRef` values and mapped into a snippet-alias. The WorkflowRecipe carries the reference only.--```yaml-steps:- - id: call-vendor- run:- type: snippet- language: typescript- code: |- const token = sdk.secrets.get("vendor_token")- return await sdk.http.fetchJson("https://api.vendor.example/report", {- method: "GET",- headers: { authorization: `Bearer ${token}` },- })- capabilities:- http:- allowedHosts: [api.vendor.example]- secrets:- - alias: vendor_token- secretRef:- name: vendor-api- key: token-```--Control UI captures the missing `vendor-api/token` value outside the JSON-editor and writes the Kubernetes Secret to `sandbox-recipes` before the final-server-side validation. Direct `kubectl apply` users must create the Secret-first, and the Secret must carry an ownership label or WRC refuses to project-it:--```bash-kubectl --context=clerum-test -n sandbox-recipes create secret generic vendor-api \- --from-literal=token="$VENDOR_TOKEN"--# Grant this recipe access. Use the owner label for a single-recipe Secret:-kubectl --context=clerum-test -n sandbox-recipes label secret vendor-api \- clerum.io/owner-recipe=api-db-report--# ...or the shared label when several recipes must read the same Secret:-# kubectl ... label secret vendor-api clerum.io/shared=true-```--Secret ownership is fail closed. An unlabeled Secret — or one carrying both-labels — is denied, the recipe never reaches `active`, and WRC reports:--```text-snippet secret "vendor-api" is not accessible to recipe "api-db-report" —-it requires clerum.io/shared=true or clerum.io/owner-recipe=api-db-report-```--Set exactly one of `clerum.io/owner-recipe=<recipeName>` or-`clerum.io/shared=true`. This is why Control UI always attaches an ownership-descriptor when it creates the Secret for you, and why Secrets declared as-`spec.resources[].type: secret` need no manual labeling — WRC stamps the owner-label on the Secrets it creates.--Platform runtime tokens and provider API keys are not exposed as snippet-secrets.--## MongoDB And PostgreSQL--Database helpers can only connect to workloads declared by the same-`WorkflowRecipe`. They do not accept arbitrary connection strings or host/port-overrides.--Read-only MongoDB:--```yaml-run:- type: snippet- language: typescript- code: |- return await sdk.mongo.find(- { workload: "mongo", database: "clerum", collection: "receivables" },- { filter: { status: "open" }, limit: 100 }- )- capabilities:- mongo:- access: read- workloads: [mongo]-```--Read-write PostgreSQL:--```yaml-run:- type: snippet- language: typescript- code: |- const ref = {- workload: "postgres",- database: "clerum",- user: "postgres",- passwordSecretAlias: "pg_password",- }- await sdk.postgres.execute(ref, {- sql: "insert into receivables(account, amount) values ($1, $2)",- values: ["dao-alpha", 1880],- })- return await sdk.postgres.query(ref, {- sql: "select account, amount from receivables where account = $1",- values: ["dao-alpha"],- })- capabilities:- secrets:- - alias: pg_password- secretRef:- name: pg-auth- key: password- postgres:- access: readWrite- workloads: [postgres]-```--The PostgreSQL ref takes `user` and `passwordSecretAlias` alongside `workload`-and `database`. `user` defaults to `postgres` when omitted, and the connection-sends no password unless `passwordSecretAlias` names an alias declared in-`run.capabilities.secrets`. Match them to the credentials the declared workload-actually accepts.--Use `access: read` when the step should only read. Use `access: readWrite` when-the step needs inserts, updates, deletes, DDL, or MongoDB write pipelines such-as `$out` or `$merge`.--## Manual MCP Calls--A snippet can call a declared MCP server/tool directly through the SDK. This is-not an LLM flow and does not require a child `mcp-host`.--```yaml-workloads:- - id: mongo-tools- type: deployment- image: ghcr.io/acme/mongo-tools-mcp:v1.0.0- port: 3000- transport:- type: streamableHttp- path: /mcp--steps:- - id: load-risk-data- run:- type: snippet- language: typescript- code: |- return await sdk.mcp.callTool("mongo-tools", "upsert_receivable", {- account: "dao-alpha",- amount: 1880,- })- capabilities:- mcp:- servers: [mongo-tools]- allowedTools:- include:- - mongo-tools__upsert_receivable-```--Tool allowlists must be explicit. Wildcards are rejected.--For hybrid workflows, use snippet steps for deterministic logic and separate-`instruction`/`agent` steps for agentic work. Those agentic steps create the-WRC-managed child `mcp-host`; snippet steps themselves do not call-`/configure-model` or `/trigger`.--## Artifacts--Use artifact helpers instead of writing arbitrary files and guessing metadata.--```ts-const json = await sdk.artifacts.writeJson("risk-result.json", {- requestId: sdk.inputs.requestId,- status: "ready",-})--const summary = await sdk.artifacts.writeMarkdown(- "risk-summary.md",- "# Risk Summary\n\nStatus: ready\n"-)--return { artifacts: [json, summary] }-```--Rules:--- artifact names are filenames only;-- files must stay under `/output`;-- generated metadata becomes `status.artifacts[]`;-- returning `{ artifacts: [...] }` keeps the step output readable, but artifacts- written through `sdk.artifacts.*` are still tracked by the runtime;-- Desktop App and Control UI download by parent recipe plus exact `runId`;-- the UI may prefix local downloaded filenames with the run id to avoid- overwriting artifacts from two runs that use the same artifact names;-- do not use host/chat artifact APIs for workflow outputs.--## Early Failure Model--Snippet workflows fail early where possible:--| Checkpoint | Example failures |-| -------------- | ---------------------------------------------------------------------------------------------------------- |-| Kubernetes CEL | invalid snippet shape, duplicate steps, wildcard MCP tools, HTTP host not declared in `runtimeEgress` |-| WRC preflight | undeclared DB workload, missing `secretRef` Secret/key, Secret not owned by or shared with the recipe, undeclared MCP server/tool |-| SDK runtime | unsupported HTTP method, unsafe redirect, DB write attempted with `access: read`, unsafe artifact filename |--Bad recipes should fail before useful runtime resources are created. Runtime-errors are reserved for values only known when code executes.--## Operational Notes--- Feature flag: `WRC_ENABLE_SNIPPET_RUNTIME`.-- Runtime image: `clerum/workflow-snippet-runner`.-- Step count: `WRC_MAX_WORKFLOW_STEPS`, default `100`; CRD schema also uses a- static `100` ceiling.-- The runner runs non-root, has no service account token, uses a read-only root- filesystem, drops Linux capabilities, and receives only declared snippet- secret aliases.-- NetworkPolicies are generated from declared snippet capabilities.--## Validation Checklist--Before publishing a snippet workflow:--- Apply the `WorkflowRecipe` in `sandbox-recipes`.-- Confirm CEL accepts the declared capabilities.-- Confirm WRC reaches an active parent recipe state.-- Trigger from Desktop App or Control UI as an authorized user.-- Confirm the run creates the expected child workflow.-- Confirm pure snippet workflows do not create a child `mcp-host`.-- Confirm hybrid workflows create `mcp-host` only for agentic steps.-- Confirm declared DB/MCP/HTTP access works.-- Confirm undeclared hosts/workloads/tools fail closed.-- Confirm `status.artifacts[]` includes expected artifacts.-- Confirm Desktop App and Control UI download artifacts for the exact `runId`.diff --git a/docs/features/oauth-sandbox-ui-bridge.md b/docs/features/oauth-sandbox-ui-bridge.mddeleted file mode 100644index 275b23ecb..000000000--- a/docs/features/oauth-sandbox-ui-bridge.md+++ /dev/null@@ -1,259 +0,0 @@-# Deep Research — Third‑Party OAuth Bridging in the Sandbox UI--> Status: research / current-state map + gap analysis.-> Scope: how a sandbox‑UI app ("recipe embed" or backend workload) obtains and-> reuses third‑party OAuth credentials, the IPC/SDK surface that drives it, and-> where the credentials/refresh tokens are stored.--## TL;DR--The feature you described **already exists end‑to‑end** in the codebase. A-recipe embed can connect a third‑party account (Slack, Google, Salesforce,-Microsoft Graph, Notion), the platform stores the **OAuth refresh token-encrypted at rest in control‑api**, and reuses it to mint fresh access tokens on-demand. There are two delivery paths:--- **Path A — user grant (embed/interactive):** the end user clicks *Connect* in- the sandbox‑UI embed; the grant belongs to that user.-- **Path B — service grant (admin/background):** an admin connects the account- "for the recipe"; background workloads fetch tokens through a broker.--One important correction to the original framing ("get the refresh token from-the control UI, bring it to the control API"): **the refresh token never passes-through control‑ui or the embed.** control‑api receives the authorization `code`-directly from the provider redirect, exchanges it for tokens server‑side, and-stores the refresh token encrypted. The UI only *initiates* the flow and later-reads short‑lived **access** tokens. This is the correct, more secure design and-is already what the code does.--The main genuine gap relative to your ask is a **generic "request input from the-user" SDK bridge** — today the embed→host IPC surface only exposes OAuth-completion + session refresh, not an arbitrary "prompt the user for X" channel.-------## 1. Components involved--| Layer | Service / file | Role |-|------|----------------|------|-| Embed (recipe JS) | recipe pod in `sandbox-ui` ns | Renders Connect/Connected UI; talks to host via `window.clerum.*` and same‑origin `fetch` |-| Embed host (IPC) | `desktop-app/src/sandboxUiEmbedPreload.ts`, `sandboxUiDriver.ts`, `main.ts` | Electron `WebContentsView` + `contextBridge`; intercepts `clerum://` deep links |-| Edge proxy | `rpc-proxy/src/routes/sandboxUi.ts` | Reverse‑proxies the embed; fronts OAuth helper endpoints; mints per‑recipe session cookie |-| OAuth core | `control-api/src/oauth/*` | Provider adapters, state signing, token exchange/refresh, encrypted store |-| OAuth routes | `control-api/src/routes/{external/oauthCallback,internal/oauth,recipeOauth,admin/recipeOauth}.ts` | Public callback, embed‑fronted helpers, background broker, admin connect |-| Storage | Postgres `oauth_grants` (migrations `0013`, `0015`) | Encrypted access + refresh tokens |-| Schema | `charts/clerum-crds/crds/workflowrecipe.yaml` → `spec.oauthClients[]` | Declares providers + client‑credential Secret refs |-------## 2. How a recipe declares OAuth (CRD)--`WorkflowRecipe.spec.oauthClients[]` (see CRD + `workflow-recipes/src/types.ts`):--```yaml-spec:- oauthClients:- - id: slack-bot # referenced by the embed and by workloads- provider: slack # enum: salesforce|slack|notion|microsoft-graph|google- clientIdRef: { name: slack-oauth-creds, key: client-id }- clientSecretRef: { name: slack-oauth-creds, key: client-secret }- scopes: [users:read, channels:read]- # backgroundAccess: true # opt-in for Path B (service grant)- ui:- workloadRef: hello- port: 8080-```--CRD CEL invariants (enforced in `workflowrecipe.yaml`):-- **O1/O2** every `oauthClient` must have a consumer — either `spec.ui` (embed,- Path A) or a `workloads[].oauthClientRefs` entry (background, Path B, which- also requires `backgroundAccess: true`).-- **O3** `oauthClients[].id` unique.-- Provider is a closed enum — recipes cannot point OAuth at arbitrary endpoints.--Provider client credentials (`client_id` / `client_secret`) live in an ordinary-K8s Secret in the recipe namespace, referenced by `clientIdRef`/`clientSecretRef`.-Working example: `workflow-recipes/samples/sandbox-ui-oauth-hello.yaml`.-------## 3. Path A — user grant (the interactive sandbox‑UI flow)--End‑to‑end sequence (this is the flow you described):--```-1. Embed renders: <a href="clerum://oauth?clientId=slack-bot">Connect Slack</a>--2. Desktop driver intercepts clerum://oauth?clientId=… (sandboxUiDriver.ts)- → POST rpc-proxy /api/v1/sandbox-ui/:ns/:name/oauth/authorize-url- (userId from the session cookie's `sub`; only oauthClientId in body)- → control-api POST /internal/sandbox-ui/oauth/authorize-url- (requireInternalService('rpc-proxy'); grantKind forced to 'user' [SEC-1])- → buildAuthorizeUrl(): loads recipe+client creds, signs HMAC `state`- ← { authorizeUrl }- → desktop shell.openExternal(authorizeUrl) // real OS browser--3. Provider auth → redirect to- control-api GET /api/v1/oauth-callback/:clientId?code&state- (no cookie/bearer — auth IS the signed state, re-verified;- recipe ns/name recovered from the state, not the URL path)- → handleOAuthCallback(): verify state, exchange code→tokens,- upsert ENCRYPTED grant in oauth_grants (user_id = caller)- ← success HTML that bounces to clerum://oauth-completed?clientId&provider--4. Desktop main.ts `open-url` handler parses clerum://oauth-completed- → driver.dispatchSandboxUiOauthCompleted({ oauthClientId, provider })- → IPC 'clerum:sandbox-ui:oauth-completed' into the embed- → recipe JS window.clerum.onOauthCompleted(cb) re-probes--5. Embed reads the token:- → POST /oauth/token (same-origin, cookie-authed) via rpc-proxy- → control-api POST /internal/sandbox-ui/oauth/token- → getAccessToken(): returns a FRESH access token (refreshing if stale)- ← { accessToken, expiresAt } // refresh token is NEVER returned-```--Disconnect: embed `DELETE /oauth/grant` → control‑api `deleteOAuthGrant` (drops-the local row, idempotent 204; **no provider‑side revocation**).--### The IPC/SDK surface (your "sandbox UI SDK")--`desktop-app/src/sandboxUiEmbedPreload.ts` exposes exactly two methods to-untrusted recipe JS via `contextBridge`:--```ts-window.clerum = {- requestSessionRefresh(): Promise<void>, // recover from a stale cookie- onOauthCompleted(cb): () => void, // subscribe to OAuth completion-}-```--Plus the navigation‑based triggers handled by the driver/main:-- `clerum://oauth?clientId=…` → start Connect-- `clerum://oauth-completed?…` → completion event (host → embed)--Security properties already in place: `contextIsolation: true`,-`nodeIntegration: false`, `sandbox: true`, IPC handlers sender‑pinned by-`webContents.id` and rate‑limited; embed served under CSP `script-src 'self'`-(hence recipes must use external `app.js`, not inline `<script>`).-------## 4. Path B — service grant (admin connect + background workloads)--For workloads that must call a provider **without a user present**:--- **Admin connects** via control‑ui → `control-api POST- /admin/recipes/:name/oauth/:oauthClientId/connect` → same authorize/callback- machinery but `grantKind: 'service'` (state records the initiating admin for- audit). Stored row has `user_id = NULL` (`oauth_grants_service_unique`).-- **Background workload fetches a token** via the broker:- `control-api /api/v1/recipe-oauth/token` (`routes/recipeOauth.ts`), gated by- `requireBrokerToken`. `(recipeNamespace, recipeName)` come **only** from the- broker token's `sub` ([SEC‑3]); just `oauthClientId` is taken from the body.- Returns a fresh access token; refresh token + encryption key never leave- control‑api.--Status check for admin UI: `GET /admin/recipes/:name/oauth/:clientId/status`-returns `{ connected }` without decrypting anything.-------## 5. Refresh‑token storage & reuse (the "guardar el refresh token" requirement)--This is fully implemented in `control-api/src/oauth/`:--- **Table `oauth_grants`** (`store.ts`, migrations `0013`/`0015`) keyed by- `(recipe_namespace, recipe_name, user_id, oauth_client_id)` for user grants and- by `(recipe_namespace, recipe_name, oauth_client_id) WHERE grant_kind='service'`- for service grants.-- **Encryption at rest** (`encryption.ts`): AES‑256‑GCM, 12‑byte random IV,- 16‑byte auth tag, payload `v1.<iv>.<ct>.<tag>`. Key from- `CONTROL_API_OAUTH_ENCRYPTION_KEY` (32‑byte hex). Both access and refresh- tokens are encrypted columns.-- **Reuse / refresh on demand** (`tokenHelper.getAccessToken`): if the stored- access token is within `refreshBufferMs` (default 60s) of expiry and a refresh- token exists, control‑api POSTs the provider's refresh endpoint (per‑provider- adapter), re‑upserts the row (keeping the old refresh token if the provider- doesn't issue a new one), and returns only the new **access** token.-- **Isolation:** the refresh token and the encryption key are confined to- control‑api. rpc‑proxy, the embed, the desktop app, and workloads only ever- see short‑lived access tokens.--Provider adapters (`providers.ts`) encode per‑provider quirks:-Google `access_type=offline&prompt=consent`; Microsoft `offline_access`;-Notion HTTP‑Basic token POST and **no refresh token**; Slack v2 (classic scopes-don't refresh); Salesforce requires explicit scopes.-------## 6. Trust boundaries (summary)--| Hop | Auth | Notes |-|-----|------|-------|-| embed → rpc-proxy | per‑recipe httpOnly session cookie (HS256), `SameSite=Strict`, path‑scoped, ~5 min TTL | `sub` = userId; refreshed ~270s |-| rpc-proxy → control-api internal OAuth | `x-service-token` + bearer, `requireInternalService('rpc-proxy')` | rpc‑proxy is the sole caller; forces `grantKind='user'` |-| provider → control-api callback | signed HMAC `state` (recipe/user/client/grantKind + nonce + 10‑min expiry) | no cookie/bearer |-| workload → control-api broker | mounted broker token, `requireBrokerToken` | recipe identity from `sub` only |-| admin → control-api connect | control‑ui admin JWT | issues `service` grants |-------## 7. Gaps & recommendations--What is **missing or worth hardening** relative to the stated goal:--1. **Generic "request input from user" SDK bridge (your explicit ask).** Today- the embed↔host IPC only does OAuth completion + session refresh, and the- pod‑side plugin‑workload SDK (`mcp-host/src/pluginWorkloadSdk`) exposes only- `prompt-bridge` (LLM) and `client-notifications`. There is **no** generic- "ask the user for a value / approval / secret" round‑trip. If recipes need- interactive input beyond OAuth, design a new `clerum.requestInput(schema)`- IPC method (host‑rendered modal, sender‑pinned + rate‑limited like the- existing handlers) with an SSE/IPC response channel.-2. **Provider set is closed (5 providers).** Adding one is a 3‑site code change- (`control-api/src/oauth/providers.ts`, `workflow-recipes/src/types.ts`, CRD- enum). Acceptable for auditability, but document the checklist.-3. **No provider‑side revocation on Disconnect.** `deleteOAuthGrant` only drops- the local row; the token stays valid at the provider until it expires.- Consider calling provider revoke endpoints where available.-4. **Single static encryption key.** `CONTROL_API_OAUTH_ENCRYPTION_KEY` has no- rotation/versioning or KMS envelope. The payload is already versioned- (`v1.`), so add key‑id support before this scales.-5. **No refresh for Notion / Slack‑classic.** Expiry forces full re‑auth; make- sure embeds surface a clear Reconnect affordance (the sample already does).-6. **Plugin‑workload SDK does not surface OAuth tokens.** Background token- access is the separate broker token path, not the SDK. If desired, unify so a- workload's SDK client can request `service`‑grant access tokens directly.--### Suggested next steps-- If the intent is **only** OAuth bridging: the feature is built — focus on- end‑to‑end verification (`scripts/e2e/e2e-sandbox-ui-oauth.sh`), real provider- apps, and the gaps above (revocation, key rotation).-- If the intent includes a **general plugin↔user input SDK**: that is net‑new;- scope it as item (1) and reuse the existing IPC hardening patterns.-------## 8. Key file index--```-control-api/src/oauth/providers.ts # 5 provider adapters-control-api/src/oauth/store.ts # oauth_grants CRUD (user + service)-control-api/src/oauth/encryption.ts # AES-256-GCM at rest-control-api/src/oauth/state.ts # HMAC signed-state binding-control-api/src/oauth/authorizeUrlHelper.ts # builds provider authorize URL-control-api/src/oauth/tokenHelper.ts # getAccessToken + refresh-on-demand-control-api/src/oauth/callback.ts # token exchange + grant upsert-control-api/src/routes/external/oauthCallback.ts # public /oauth-callback-control-api/src/routes/internal/oauth.ts # embed-fronted helpers (Path A)-control-api/src/routes/recipeOauth.ts # background broker (Path B)-control-api/src/routes/admin/recipeOauth.ts # admin connect (service grants)-rpc-proxy/src/routes/sandboxUi.ts # edge proxy + OAuth bridge-desktop-app/src/sandboxUiEmbedPreload.ts # window.clerum.* IPC surface-desktop-app/src/sandboxUiDriver.ts # clerum://oauth interception-desktop-app/src/main.ts # clerum://oauth-completed handler-charts/clerum-crds/crds/workflowrecipe.yaml # spec.oauthClients[] schema-workflow-recipes/samples/sandbox-ui-oauth-hello.yaml # working demo recipe-scripts/e2e/e2e-sandbox-ui-oauth.sh # e2e gate-```diff --git a/docs/features/token-budgets.md b/docs/features/token-budgets.mddeleted file mode 100644index 651e23b88..000000000--- a/docs/features/token-budgets.md+++ /dev/null@@ -1,270 +0,0 @@-# Token Budgets & Cost Enforcement--Token budgets let an admin cap LLM consumption — either raw **tokens** or-converted **cost** (currency) — over a rolling period, scoped to a slice of-traffic (a user, a team, a provider, a model, an agent, a workflow recipe, or-globally). Before an agent turn runs its LLM call, or before a workflow step-does, evenfire (code name **clerum**) checks the matching budgets and can block-the request once the period's limit is reached.--> **Budgets are a cost-control mechanism, not a security boundary.** The check-> path is **fail-open**: if the flag is off, no budget client is wired, or-> control-api is unreachable, the task is allowed. A denial always means a real-> budget verdict — never a transport error.-------## 1. What it is and why--The feature enforces spend limits on the LLM usage produced by **agent turns**-and **workflow steps**. Each budget targets a scope, carries a per-period limit-in one unit (tokens or cost), and runs in one of two modes: `warn`-(observation only — logs, never denies) or `block` (denies once the limit is-reached). Spend is computed on demand from the usage rollups (`usage_daily` /-`usage_5min`), so there is no materialized counter to drift; the tradeoff is-that rollups lag roughly 1–2 minutes.--## 2. Enabling it--Budget enforcement is gated by a single boolean env var on **mcp-host**:--| Env var | Default | Effect |-| ------------------------- | -------------- | ------------------------------------------------------------------- |-| `CLERUM_BUDGETS_ENABLED` | `false` (OFF) | Gates the whole check path (BudgetClient + SessionProcessor wiring) |--It is **OFF by default.** When off, the agent and workflow budget checks are-no-ops that resolve `{ allowed: true }`-(`mcp-host/src/config.ts:619`, comment at `153–156`).--The **minikube overlay turns it ON explicitly**:--```yaml-# deploy/overlays/minikube/configmaps/mcp-host-config.yaml-CLERUM_BUDGETS_ENABLED: "true"-```--## 3. How it works--### Lifecycle: reserve → execute → release--1. **Check (read-only).** Once per task, mcp-host calls- `POST /api/v1/internal/budgets/check`. control-api's `evaluateBudgetCheck`- loads the enabled budgets (5s in-memory cache), filters them by scope match,- and for each matching budget computes `spent` and- `remaining = limit_amount − spent`. The decision is **most-restrictive-wins**.-2. **Reserve (only in the danger zone).** A reservation is an *ephemeral- anti-race guard*, not a persistent counter. It is taken **only** when a- matching `block` budget is in the danger zone- (`max_task_amount != null && remaining < max_task_amount`). Outside the- danger zone the check is a pure read with no lock or transaction. Inside one- transaction holding `pg_advisory_xact_lock(hashtext(budget_id))`, it sums the- `est_amount` of non-expired reservations as `pending`, computes- `effective_remaining = limit − spent − pending`, and DENIES if that is below- `min_start_amount`; otherwise it inserts a reservation row- (`est_amount = max_task_amount`, `expires_at = NOW() + TTL`, `task_ref`,- `host_ref`) and allows.-3. **Release / settle.** On task terminal, mcp-host calls- `POST /api/v1/internal/budgets/release` (by `task_ref`, scoped to the- caller's `host_ref`) to drop the reservation early — fire-and-forget.- Otherwise the reservation self-expires by TTL. **There is no explicit- "settle actuals into the budget" step:** real spend lands separately via the- usage-event rollups, and the reservation is purely released or expired.--**Reservation TTL** defaults to **300 seconds** (`BUDGET_RESERVATION_TTL_SECONDS`).-Expired reservations stop counting immediately (the pending sum filters-`expires_at > NOW()`) even before the sweep deletes them — this is the-fail-open safety so a stuck task never blocks a budget permanently.--### Exceed behavior: warn vs block--Enforcement is a per-budget column defaulting to `block`.--- **`warn` budgets NEVER deny.** Over the limit, they only log- `budget_would_block` (observation mode).-- **`block` budgets deny** (fail-closed) once the limit is reached.-- A **`block` budget that cannot be evaluated** (spend computation error)- DENIES with reason `budget_eval_error` (anti-bypass). A real exceed sets- reason `budget_exceeded`; losing a danger-zone reservation to a concurrent- task also denies with `budget_exceeded`.-- A **`warn` budget that errors is skipped** entirely — never denies, imposes no- brake.--### Per-task brake (`max_task_amount`)--Distinct from the per-period limit, the check also returns a per-task cap-(`maxTaskTokens` / `maxTaskCost`) = the **MIN of `max_task_amount` across-matching `block` budgets**, by unit. Only `block` budgets impose a brake.--### Agent turns vs workflow steps--Both paths are **fail-open across services**: if control-api is unreachable or-throws, mcp-host's `checkTaskBudget` and the SessionProcessor resolve-`{ allowed: true }`.--- **Agent turns.** SessionProcessor runs `checkTaskBudget` after the lifecycle- transition to `processing` and before the executor. On deny it calls- `onBudgetDenied → AgentStateMachine.handleBudgetDenied`, failing the task via- the canonical failure path. The caller sees:- - error code `BUDGET_EXCEEDED`- - message: *"This period's consumption budget has been reached. Please try- again later."*- - `retryable: false`- - lifecycle status `failed`-- **Workflow steps.** `WorkflowService.runStepBudgetCheck` runs a pre-step check- (`source_kind = 'workflow'`, `context_ref = null`, team/user resolved- server-side, `task_ref = 'wf:{recipe}:{stepId}:{execId}'`). On deny, the step- returns `status = 'failed'` with error string- `budget_exceeded: {reason}`, and the LLM is never called. Same block/warn- semantics; the deny surfaces as a failed step result rather than an agent- task-failure error object.--## 4. Budget scopes--A budget's target is a JSONB `scope` object. Keys are **ANDed**, values within a-key are **ORed**, and an empty scope `{}` matches everything (global). A strict-zod schema rejects any key outside the allowlist (anti-injection); each-dimension maps to a non-empty `string[]`.--The ten allowlisted dimensions:--| Dimension | Targets |-| ----------------- | -------------------------------- |-| `user_id` | a user |-| `team_id` | a team |-| `provider` | an LLM provider |-| `model` | a specific model |-| `llm_secret_name` | a specific LLM credential |-| `host_ref` | an agent (host) |-| `context_ref` | a context |-| `source_kind` | e.g. `workflow` |-| `recipe_name` | a workflow recipe |-| `cron_job_id` | a cron job |--So per-user, per-team, per-provider, per-model, per-agent, per-recipe, per-cron,-and global budgets are all expressible.--## 5. LLM prices — deriving cost from tokens--A budget's **unit is EITHER `tokens` OR `cost`** — not both. `unit = 'cost'`-requires a `currency` (enforced by both zod and a DB CHECK).--- **Tokens budget.** Spend is a raw token count with no price JOIN:- `SUM(input_tokens + output_tokens + cache_read_tokens + cache_write_tokens)`- over the period rollups.-- **Cost budget.** Spend is per-`(provider, model)` token sums multiplied by the- active `llm_model_prices` rates. Unpriced `(provider, model)` pairs count as- **$0** and are surfaced (logged as `budget_unpriced_usage`) but never denied.--**How prices are keyed and stored:**--- Prices are keyed by `(provider, model)`, with **one enabled row per pair**- (partial unique index `idx_llm_model_prices_active … WHERE enabled`).-- Each row carries four per-token-class prices: `input_token_price`,- `output_token_price`, `cache_read_token_price`, `cache_write_token_price`.-- Prices are expressed **per 1,000,000 tokens** (per 1M), stored as `NUMERIC`- for monetary precision. Cost is computed as:-- ```- amount = (input_tokens*input_token_price- + output_tokens*output_token_price- + cache_read_tokens*cache_read_token_price- + cache_write_tokens*cache_write_token_price) / 1e6- ```--- Currency is a per-row `TEXT` column defaulting to `USD`; seeded values are USD- per 1M tokens. Price fields validate as finite numbers `>= 0`; cache prices- default to `0`.--Spend is period-aligned, stitching `usage_daily` (whole past days) and-`usage_5min` (today), with period bounds computed in Postgres via-`date_trunc … AT TIME ZONE`.--**Period & timezone.** A budget has a `period` (`daily` / `weekly` / `monthly`)-and a `timezone` column, but only **`UTC`** is accepted in this version.--## 6. Managing budgets--### Admin API--Both routers are mounted under the admin router at `/api/v1/admin`.--**LLM prices** (`/api/v1/admin/llm-prices`):--| Method + path | Behavior |-| ------------------------------------ | ------------------------------------------------------------------------------- |-| `GET /admin/llm-prices` | List all prices (`{ rows }`) |-| `GET /admin/llm-prices/unpriced` | Distinct `(provider, model)` pairs seen in usage with no active price row |-| `GET /admin/llm-prices/:id` | Fetch one by UUID (404 on non-UUID or missing) |-| `POST /admin/llm-prices` | Create (201; 400 zod; 409 on duplicate active provider/model) |-| `PUT /admin/llm-prices/:id` | Update (409 `price_in_use_by_budget` if disabling/re-keying a pinned price) |-| `DELETE /admin/llm-prices/:id` | Delete (204; 409 `price_in_use_by_budget` if still pinned by a cost budget) |--**Budgets** (`/api/v1/admin/budgets`):--| Method + path | Behavior |-| ---------------------------- | --------------------------------------------------------------------------- |-| `GET /admin/budgets` | List, each with live computed `spent`/`remaining` (`{ rows }`) |-| `GET /admin/budgets/:id` | Fetch one with computed spend (404 on non-UUID or missing) |-| `POST /admin/budgets` | Create (201; 400 `unpriced_models`; 400 `invalid_request`) |-| `PUT /admin/budgets/:id` | Update (200; 400 on unpriced/validation errors) |-| `PATCH /admin/budgets/:id` | Quick `enabled` toggle |-| `DELETE /admin/budgets/:id` | Delete (204) |--### Control UI--The sidebar section is labeled exactly **Cost & Usage** (links to-`/cost/usage`). The surface has three tabs, in order:--1. **Usage** — `/cost/usage`-2. **LLM Prices** — `/cost/llm-prices`-3. **Token Budgets** — `/cost/token-budgets`--On **Token Budgets**, admins can:--- View budgets in a table with columns: Name, Scope, Unit, Period, Spent /- Limit (live progress bar, with an "over" state), Mode (enforcement), Enabled,- Actions.-- Create a budget (**New budget** button), edit (pencil), delete (X), and toggle- enabled/disabled by clicking the badge.-- Search/filter by name, unit, period, and scope text; refresh.--The **budget form** (create/edit) sets:--- **Budget:** Name (required), Unit (Cost / Tokens), Limit amount (> 0), and- Currency (shown and required only when unit is cost, default USD).-- **Period:** Period (Daily / Weekly / Monthly, default monthly) and Timezone- (read-only, pinned to UTC).-- **Thresholds:** Min remaining to start (>= 0, default 0), Max per task- (optional, > 0 or blank), Enforcement (**Warn** default / **Block**), and an- Enabled checkbox (default true).-- **Scope:** pin to Provider, Model (free-text with suggestions), Team, User,- Agent (`host_ref`), Secret (`llm_secret_name`) — dimensions ANDed, values- ORed, empty scope = global.--For cost budgets, the form shows a live **unpriced-model** warning derived from-loaded prices and links to **LLM Prices** to add them; a server-`400 unpriced_models` rejection blocks the save with a banner.--## 7. Gotchas--- **Cost enforcement needs prices.** A cost budget can only enforce against- `(provider, model)` pairs that have an **enabled** price row. Unpriced usage- counts as $0 — it is surfaced/logged but **never denied**, so a cost budget- will silently under-count until you add the missing prices. Creating a cost- budget that pins unpriced models is rejected with `400 unpriced_models`.-- **Spend lags ~1–2 minutes.** There is no live counter; spend is computed from- usage rollups. Bursts of concurrent tasks are guarded only by the danger-zone- reservation, not by real-time accounting.-- **Off by default.** `CLERUM_BUDGETS_ENABLED` is `false` unless set (the- minikube overlay sets it `true`). With it off, all checks pass.-- **Fail-open by design.** A control-api outage never blocks a task. Budgets- control cost; they are not a security boundary.-- **`warn` never denies.** In observation mode a budget only logs- `budget_would_block`; you must set enforcement to `block` for it to stop- traffic.-- **Only UTC.** The timezone column exists but only `UTC` is accepted in this- version.-------License: MPL-2.0diff --git a/docs/features/workflow-recipes.md b/docs/features/workflow-recipes.mddeleted file mode 100644index 1b8920724..000000000--- a/docs/features/workflow-recipes.md+++ /dev/null@@ -1,76 +0,0 @@-# WorkflowRecipes — Feature Hub--WorkflowRecipes are evenfire’s multi-workload CRD: compose Deployments,-StatefulSets, CronJobs, Jobs, and DaemonSets with MCP registration, network-bindings, security overrides, and scoped runtime tokens.--Because the feature spans schema, operator internals, deployment ops, and-security policy, docs live in several places. **This page is the single-starting point.**--> **Naming:** CRD kinds are `WorkflowRecipe` and `WorkflowRecipePolicy`. The-> operator directory is `workflow-recipes/`; the operator is often called Workload-> Recipes Controller (WRC), and it runs as its own process, separate from the-> host-context-controller (HCC). Public product name is **evenfire**; APIs remain-> `clerum.io` — [code names](../concepts/code-names.md).-------## CRD reference--- **[WorkflowRecipe CRD](../crds/workflowrecipe.md)** — schema, validation,- approval semantics, lifecycle, security overrides-- **[WorkflowRecipePolicy CRD](../crds/workflowrecipepolicy.md)** — governance- policy for recipes-- **[Custom coordinator snippet workflow](./custom-coordinator-snippet-workflow.md)** —- snippet business logic with the curated SDK-- **[Custom coordinator images](custom-coordinator-images.md)** — custom- `coordinatorImage`, `/output` artifacts, optional MCP tools-- **[CRD YAML examples](../../charts/clerum-crds/examples/)** — including the- [MongoDB StatefulSet recipe](../../charts/clerum-crds/examples/MONGODB-STATEFULSET-README.md)--## Architecture--- **[Platform topology](../architecture/platform-topology.md)** — namespaces,- HCC/WRC split, deny-all baseline-- **[Non-MCP services](../architecture/non-mcp-services.md)** — namespace- splitting (`transport` → `mcp-server`, else `sandbox-recipes`), L0–L3 policies--## Deployment & operations--- **[WorkflowRecipes operations guide](../deploy/workflow-recipes-guide.md)** —- Control UI/API, RBAC, REST routes, debugging-- **[Minikube deploy guide](../deploy/minikube.md)** — local full stack-- **[Production notes](../deploy/production.md)** — production checklist and- in-repo deploy assets--## Security--- Recipe CRDs and sandbox workloads follow platform namespace rules- (`sandbox-recipes` vs `mcp-server` for transport children)-- NetworkPolicy behavior: static manifests under- `deploy/base/**/networkpolicies*.yaml` plus HCC-managed policies described in- [architecture overview](../architecture/overview.md)-- Root [security model](../../README.md#security-model)--## Operator internals--- **[`workflow-recipes/README.md`](../../workflow-recipes/README.md)** — reconciler- entry, tests, module layout for the standalone WRC operator-- **[host-context-controller README](../../host-context-controller/README.md)** —- the separate HCC operator (McpServer, Host, and NetworkPolicy reconcilers);- WRC and HCC coordinate through the K8s API--## Quick reference--| I want to… | Go to |-| -------------------------------- | -------------------------------------------------------------------------------------- |-| Define a WorkflowRecipe | [CRD reference](../crds/workflowrecipe.md) |-| Write TypeScript snippet logic | [Snippet workflow](./custom-coordinator-snippet-workflow.md) |-| Build a custom coordinator image | [Custom images](custom-coordinator-images.md) |-| See a working YAML example | [MongoDB StatefulSet](../../charts/clerum-crds/examples/MONGODB-STATEFULSET-README.md) |-| Deploy locally | [Minikube](../deploy/minikube.md) |-| Plan production | [Production notes](../deploy/production.md) |-| Understand namespace splitting | [Non-MCP services](../architecture/non-mcp-services.md) |-| Debug a stuck recipe | [Operations guide](../deploy/workflow-recipes-guide.md) |-| Understand HCC/WRC architecture | [Platform topology](../architecture/platform-topology.md) |diff --git a/docs/get-started/learning-path.md b/docs/get-started/learning-path.mdindex fbe524356..f51cae835 100644--- a/docs/get-started/learning-path.md+++ b/docs/get-started/learning-path.md@@ -27,7 +27,7 @@ NetworkPolicies matter.1. [Minikube deploy guide](../deploy/minikube.md)2. [Configure approvals](../how-to/configure-approvals.md)3. [Add an MCP server](../how-to/add-mcp-server.md)-4. [WorkflowRecipes hub](../features/workflow-recipes.md) if you need multi-workload recipes+4. [WorkflowRecipe CRD reference](../crds/workflowrecipe.md) if you need multi-workload recipes**Success looks like:** Control UI up, a Host responding, an approval orconnector path exercised.diff --git a/docs/how-to/add-mcp-server.md b/docs/how-to/add-mcp-server.mdindex 75d211556..d4930dea7 100644--- a/docs/how-to/add-mcp-server.md+++ b/docs/how-to/add-mcp-server.md@@ -101,4 +101,3 @@ See [stdio-bridge README](../../stdio-bridge/README.md) and- [CRD index](../crds/README.md)- [Architecture overview](../architecture/overview.md)-- [WorkflowRecipes](../features/workflow-recipes.md) — multi-workload recipes that may register MCP serversdiff --git a/docs/llms.txt b/docs/llms.txtindex 07e037716..bfe2777b2 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -40,10 +40,6 @@- SharedFileSystem: crds/sharedfilesystem.md- GlobalFileSystem: crds/globalfilesystem.md-## Features--- WorkflowRecipes hub: features/workflow-recipes.md-## Testing & contributing- E2E guide: testing/e2e-guide.mddiff --git a/docs/testing/custom-coordinator-e2e-gates.md b/docs/testing/custom-coordinator-e2e-gates.mdindex 5a25277fd..34761543b 100644--- a/docs/testing/custom-coordinator-e2e-gates.md+++ b/docs/testing/custom-coordinator-e2e-gates.md@@ -1,9 +1,8 @@# Custom Coordinator E2E GatesThis runbook documents the local minikube gates for custom coordinator snippets-and custom coordinator images. It is intentionally separate from the developer-guides under `docs/features/` because these commands validate the local-branch-scoped minikube cluster, not the public developer contract.+and custom coordinator images. It validates the local branch-scoped minikube+cluster, not the public developer contract.Run these gates only after the normal minikube pre-gate sync has rebuilt andloaded the current worktree images, CRDs, manifests, secrets, and config.