This project uses bd (beads) for issue tracking. Run bd onboard to get started.
bd ready # Find available work
bd show <id> # View issue details
bd update <id> --claim # Claim work atomically
bd close <id> # Complete work
bd sync # Sync with gitALWAYS use non-interactive flags with file operations to avoid hanging on confirmation prompts.
Shell commands like cp, mv, and rm may be aliased to include -i (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input.
Use these forms instead:
# Force overwrite without prompting
cp -f source dest # NOT: cp source dest
mv -f source dest # NOT: mv source dest
rm -f file # NOT: rm file
# For recursive operations
rm -rf directory # NOT: rm -r directory
cp -rf source dest # NOT: cp -r source destOther commands that may prompt:
scp- use-o BatchMode=yesfor non-interactivessh- use-o BatchMode=yesto fail instead of promptingapt-get- use-yflagbrew- useHOMEBREW_NO_AUTO_UPDATE=1env var
This project uses bd (beads) for issue tracking.
Run bd prime for workflow context, or install hooks (bd hooks install) for auto-injection.
Quick reference:
bd ready- Find unblocked workbd create "Title" --type task --priority 2- Create issuebd close <id>- Complete workbd dolt push- Push beads to remote
For full workflow details: bd prime
- Use
bdfor ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists - Run
bd primefor detailed command reference and session close protocol - Use
bd rememberfor persistent knowledge — do NOT use MEMORY.md files
Procella is a self-hosted Pulumi backend written in TypeScript, running on Bun. It implements the Pulumi Service API so that pulumi login, pulumi stack init, pulumi up, etc. work against it. A tRPC web API serves a React dashboard for viewing stacks, updates, and events.
- Bun 1.2 (runtime + package manager + test runner + bundler)
- PostgreSQL 17 (metadata, state)
- Hono v4 (HTTP router for Pulumi CLI protocol)
- tRPC v11 (web dashboard API, mounted on same server)
- Drizzle ORM (type-safe PostgreSQL queries via
Bun.sql) - React 19 + Vite 7 + TailwindCSS v4 (web dashboard SPA)
- Biome (strict linter + formatter for TypeScript)
- Caddy 2 (reverse proxy for production/cluster)
packages/
types/ # Pulumi protocol types (generated via tygo) + domain types + errors
config/ # Zod-validated env config (PROCELLA_*)
db/ # Drizzle schema, connection factory (Bun.sql driver)
crypto/ # AES-256-GCM with HKDF per-stack key derivation
storage/ # Blob storage (local filesystem + S3)
auth/ # Authenticator: dev mode (static token) + Descope (JWT)
stacks/ # Stack service: CRUD, rename, tags (PostgreSQL)
updates/ # Update lifecycle, checkpoints, events, GC worker (PostgreSQL + blob)
api/ # @procella/api — tRPC router definition (stacks.list, updates.list/latest, events.list)
apps/
server/ # @procella/server — Hono HTTP server (CLI routes + tRPC mount + middleware)
ui/ # @procella/ui — React SPA (Vite + Tailwind + tRPC client)
docs/ # @procella/docs — Starlight documentation site
examples/ # Pulumi YAML example programs (7 examples, used by E2E tests)
e2e/ # E2E acceptance tests (89 tests across 9 files)
Dockerfile # bun build --compile → debian-slim
docker-compose.yml # postgres + minio (dev), + procella replicas + caddy (cluster)
Caddyfile # Reverse proxy: /api/* + /trpc/* → server, /* → UI
- Single process — CLI API + tRPC dashboard API share one Hono server on port 9090
- PulumiAccept middleware — version-gated features (delta checkpoints and batch crypto) require
Accept: application/vnd.pulumi+8or newer; legacy/api/*routes may omit it;/trpc/*routes bypass this - Dual auth on tRPC — Same
AuthService.authenticate()as CLI routes, usingAuthorization: token <value> - DevAuthenticator —
Authorization: token <PROCELLA_DEV_AUTH_TOKEN>for dev mode - Transactions — CreateStack, RenameStack, CancelUpdate use Drizzle transactions
- Auto-create — CreateStack auto-creates org + project via INSERT ON CONFLICT DO NOTHING
- Workspace packages — Domain logic in
packages/*, app assembly inapps/*
The sequence the CLI follows during pulumi up:
- CreateUpdate:
POST /api/stacks/{org}/{project}/{stack}/{kind}(kind = update|preview|refresh|destroy)- Auth:
Authorization: token <api-token> - Req:
apitype.UpdateProgramRequest→ Resp:apitype.UpdateProgramResponse(containsupdateID)
- Auth:
- StartUpdate:
POST /api/stacks/{org}/{project}/{stack}/update/{updateID}- Auth:
Authorization: token <api-token> - Req:
apitype.StartUpdateRequest→ Resp:apitype.StartUpdateResponse(contains leasetoken,version,tokenExpiration)
- Auth:
- Execution (all use
Authorization: update-token <lease-token>):PATCH .../checkpoint—PatchUpdateCheckpointRequest(standard)PATCH .../checkpointverbatim—PatchUpdateVerbatimCheckpointRequest(preserves JSON)POST .../events/batch—EngineEventBatchPOST .../renew_lease—RenewUpdateLeaseRequest→RenewUpdateLeaseResponse
- CompleteUpdate:
POST .../complete—CompleteUpdateRequest{status: succeeded|failed|cancelled}
Export: GET /api/stacks/{org}/{project}/{stack}/export returns latest checkpoint as apitype.UntypedDeployment.
GET .../export/{version}returns the final canonical checkpoint of the non-preview update with that stack update version; non-positive-integer versions are rejected with 400.- Empty stacks return valid
UntypedDeploymentwithversion: 3and non-null deployment JSON.
Import: POST /api/stacks/{org}/{project}/{stack}/import — body is apitype.UntypedDeployment, response is apitype.ImportStackResponse{UpdateID}.
- Single-shot operation (no create→start→complete lifecycle).
- CLI polls
GET .../update/{updateID}after import; returnUpdateResults{Status: "succeeded"}. - Cross-stack import requires
--forceflag from CLI.
Encrypt/Decrypt: POST .../encrypt takes apitype.EncryptValueRequest{Plaintext []byte}, returns EncryptValueResponse{Ciphertext []byte}.
POST .../decrypttakesDecryptValueRequest{Ciphertext []byte}, returnsDecryptValueResponse{Plaintext []byte}.Plaintext/Ciphertextare[]byte→ JSON-encoded as base64.- Uses AES-256-GCM with HKDF per-stack key derivation from a master key.
- Dev mode auto-generates deterministic key from
sha256("procella-dev-encryption-key").
Cancel Update: POST /api/stacks/{org}/{project}/{stack}/update/{updateID}/cancel
- Uses regular API token auth (NOT update-token). No request body, no response body.
- Transaction: set status='cancelled', clear lease token, clear stack's active update lock.
- Idempotent: canceling an already-canceled update returns success.
Orphan GC Worker: Background goroutine that cleans up stale updates.
- Scans for: running updates with expired leases, stale not-started/requested updates (>1hr).
- Uses
pg_try_advisory_lock(0x5472617461_4743)for cluster-safe execution — only one instance runs GC at a time. - Runs reconciliation at startup, then every 60s. Lock acquired per-cycle, released after each cycle.
- Wired in
main.go:Start()after server,Stop()before shutdown.
All state lives in PostgreSQL. No in-memory caches, no local-only state.
- Transactions protect critical sections (create stack, rename, cancel update).
- Unique index prevents multiple active updates per stack.
- pg advisory locks ensure only one GC worker runs across the cluster.
- Local blob storage is the only non-clusterable component — use S3 (
PROCELLA_BLOB_BACKEND=s3) for multi-node. - Railway runs 3 replicas — any in-process state (Maps, caches, etc.) is NOT shared across instances. If you need something shared, it goes in PostgreSQL.
- Descope is the auth provider in production. Tokens are managed in HttpOnly cookies (project settings:
sessionTokenResponseMethod/refreshTokenResponseMethod=cookiesininfra/descope.ts) served through a custom auth domain (auth.<stage-domain>, CNAME tocname.descope.com). - Cookie domain is the stage apex (
procella.cloudin prod,pr-N.procella.cloudin previews), so Descope session cookies are first-party cookies sent implicitly on same-origin requests toapp.<stage-domain>. The JWT is never accessible to JS. authenticate(request)inpackages/auth/src/index.tsreadsAuthorization: Bearer <jwt>/Authorization: token <key>, and falls back to any JWT-shaped Descope session cookie when no Authorization header is present. Descope may useDSor dynamic names likeDFN-*; overlapping env-domain cookies are all tried until one verifies against this project.- JWT
issvariants: Descope session cookies may carry bareiss = <projectId>; Bearer JWTs may use the default URL issuer oriss = https://auth.<domain>/<projectId>.DescopeAuthServiceaccepts all three (authBaseUrlin config →PROCELLA_DESCOPE_AUTH_BASE_URL). JWKS stays on the default issuer host. - UI must NOT depend on
getSessionToken()/sessionToken— it is empty in cookie mode. Gate routes onisAuthenticated; derive tenant/roles fromuseSession().claimsviaapps/ui/src/auth/claims.ts.getAuthHeaders()returns{}in cookie mode and the cookie rides along on same-origin requests. EventSourcecannot set custom headers — irrelevant for cookies (sent automatically on same-origin SSE). The ticket-based subscription auth still works as a header-mode fallback.- NEVER invent a separate auth mechanism — the standard
Authorizationheader (CLI, access keys, body-mode projects) plus the DS-cookie fallback cover all cases. - Dev mode uses
Authorization: token <PROCELLA_DEV_AUTH_TOKEN>. The cookie fallback is Descope-only. - CLI uses
Authorization: token <access-key>(long-lived Descope access key, NOT a session JWT).
Current approach: Docker + aws-lambda-adapter extension.
apps/server/src/lambda-bootstrap.tsrunsBun.serve()on port 8080public.ecr.aws/awsguru/aws-lambda-adapterextension proxies Lambda invocations to port 8080 as plain HTTP- SSE/streaming works natively via Bun's
new Response(async function*() { yield ... }) - No
awslambdaglobals needed, no custom runtime loop Dockerfile.lambdabuilds the container image- SST's
streaming: trueprop setsInvokeMode: RESPONSE_STREAMon the Function URL
Migrate function uses provided.al2023 + custom runtime loop (one-shot, no streaming needed).
DO NOT:
- Export
handlerfromlambda-bootstrap.ts— the adapter calls the HTTP server directly - Use
streamHandle()fromhono/aws-lambda— that's for Node.js managed runtimes only - Use
awslambda.streamifyResponse— only available in Node.js managed runtimes
Before adding ANY new stateful thing, ask: "what happens when this runs on 3 replicas simultaneously?"
- In-process Maps, caches, counters → NOT safe. Put it in PostgreSQL.
- Background timers/workers → use
pg_try_advisory_lockso only one replica runs it. - The
pg advisory lockpattern is already used byGCWorker— follow that.
/api/* routes are the Pulumi Service API. Custom endpoints MUST NOT go there.
- All dashboard/UI-only features go through tRPC (
/trpc/*) - The only exceptions are the CLI protocol routes defined in
PulumiRoutes - Adding custom REST endpoints to
/api/*breaks the Pulumi CLI
apps/ui/vite.config.ts proxies /trpc, /api, /healthz to the backend.
- Default port:
9090(production/dev) - Override with
VITE_API_PORTenv var for tests (e.g. Playwright uses18080) - Playwright tests MUST set
VITE_API_PORTto matchPLAYWRIGHT_API_URLport
Playwright runs in Node.js context — NOT Bun. This means:
Bun.spawn,Bun.write,Bun.sleep,SQL from bunare NOT available in test files orglobal-setup.ts- Use
node:child_process.spawn,node:fs/promises.writeFile,setTimeoutinstead - Use
pgnpm package for direct DB access (notbun:sql) import.meta.dirnamemay not work — use__dirnamein CommonJS context- Keep a separate
tsconfig.playwright.jsonwith"module": "CommonJS"for Playwright files
When a new method is added to an interface (e.g. StacksService, UpdatesService), ALL test mock objects implementing that interface must be updated too. CI catches this via tsc --build (project references) even when local typecheck passes.
bun run check # biome lint → typecheck → bun test (320 unit tests)
bun run e2e # E2E acceptance tests (89 tests, requires postgres + pulumi CLI)
bun run check:all # check + e2e| Variable | Default | Description |
|---|---|---|
| PROCELLA_LISTEN_ADDR | :9090 | Server listen address |
| PROCELLA_DATABASE_URL | (required) | PostgreSQL connection string |
| PROCELLA_AUTH_MODE | dev | Auth mode (dev or descope) |
| PROCELLA_DEV_AUTH_TOKEN | (required in dev) | Dev auth token |
| PROCELLA_DEV_USER_LOGIN | dev-user | Dev user login name |
| PROCELLA_DEV_ORG_LOGIN | dev-org | Dev org login name |
| PROCELLA_BLOB_BACKEND | local | Blob storage (local or s3) |
| PROCELLA_BLOB_LOCAL_PATH | ./data/blobs | Local blob path |
| PROCELLA_ENCRYPTION_KEY | (auto in dev) | 64 hex chars (32 bytes) for AES-256 encryption |
You have context-mode MCP tools available. These rules are NOT optional — they protect your context window from flooding. A single unrouted command can dump 56 KB into context and waste the entire session.
Any shell command containing curl or wget will be intercepted and blocked by the context-mode plugin. Do NOT retry.
Instead use:
mcp__context-mode__ctx_fetch_and_index(url, source)to fetch and index web pagesmcp__context-mode__ctx_execute(language: "javascript", code: "const r = await fetch(...)")to run HTTP calls in sandbox
Any shell command containing fetch('http, requests.get(, requests.post(, http.get(, or http.request( will be intercepted and blocked. Do NOT retry with shell.
Instead use:
mcp__context-mode__ctx_execute(language, code)to run HTTP calls in sandbox — only stdout enters context
Do NOT use any direct URL fetching tool. Use the sandbox equivalent. Instead use:
mcp__context-mode__ctx_fetch_and_index(url, source)thenmcp__context-mode__ctx_search(queries)to query the indexed content
Shell is ONLY for: git, mkdir, rm, mv, cd, ls, npm install, pip install, and other short-output commands.
For everything else, use:
mcp__context-mode__ctx_batch_execute(commands, queries)— run multiple commands + search in ONE callmcp__context-mode__ctx_execute(language: "shell", code: "...")— run in sandbox, only stdout enters context
If you are reading a file to edit it → reading is correct (edit needs content in context).
If you are reading to analyze, explore, or summarize → use mcp__context-mode__ctx_execute_file(path, language, code) instead. Only your printed summary enters context.
Search results can flood context. Use mcp__context-mode__ctx_execute(language: "shell", code: "grep ...") to run searches in sandbox. Only your printed summary enters context.
- GATHER:
mcp__context-mode__ctx_batch_execute(commands, queries)— Primary tool. Runs all commands, auto-indexes output, returns search results. ONE call replaces 30+ individual calls. - FOLLOW-UP:
mcp__context-mode__ctx_search(queries: ["q1", "q2", ...])— Query indexed content. Pass ALL questions as array in ONE call. - PROCESSING:
mcp__context-mode__ctx_execute(language, code)|mcp__context-mode__ctx_execute_file(path, language, code)— Sandbox execution. Only stdout enters context. - WEB:
mcp__context-mode__ctx_fetch_and_index(url, source)thenmcp__context-mode__ctx_search(queries)— Fetch, chunk, index, query. Raw HTML never enters context. - INDEX:
mcp__context-mode__ctx_index(content, source)— Store content in FTS5 knowledge base for later search.
- Keep responses under 500 words.
- Write artifacts (code, configs, PRDs) to FILES — never return them as inline text. Return only: file path + 1-line description.
- When indexing content, use descriptive source labels so others can
search(source: "label")later.
| Command | Action |
|---|---|
ctx stats |
Call the stats MCP tool and display the full output verbatim |
ctx doctor |
Call the doctor MCP tool, run the returned shell command, display as checklist |
ctx upgrade |
Call the upgrade MCP tool, run the returned shell command, display as checklist |