1. Start Here (Cloud & COSS)
AI-Agent-First Documentation
Raw .md/SKILL.md
Prompt your Agent: "Help me set up apps/open-api locally, seed a tenant database, and execute parameterized ANSI SQL queries and record CUD operations."

Open Valstorm API (apps/open-api)

Greenfield PostgreSQL-Powered Core Engine for Open Valstorm

Open Valstorm API is a greenfield backend built with Python 3.13, uv, and PostgreSQL 16. It introduces a dedicated logical database-per-tenant architecture with an automated DDL compiler and native SQL query execution, completely eliminating application-layer Python joins and legacy regex SQL transpiling.


1. Architectural Highlights

Dedicated Database-Per-Tenant Isolation

  • Zero Cross-Tenant Leaks: Every customer organization operates inside an isolated PostgreSQL database (CREATE DATABASE org_xyz). Cross-database queries are physically prohibited by the PostgreSQL engine.
  • Central Directory DB (valstorm_directory): Coordinates global authentication, organization routing, and the marketplace catalog (app).
  • Universal Support User Pattern: Every provisioned tenant database automatically attaches an attributable Support User (support@...), enabling platform administrators to assist customers, run scheduled workflows, and debug without requesting user passwords.
  • $O(1)$ Instant Custom Fields: Adding custom fields compiles to native PostgreSQL DDL (ALTER TABLE ... ADD COLUMN ...), executing as an instantaneous metadata-only change in PostgreSQL 11+.
  • Native ANSI SQL Optimizer: Relational joins (JOIN ... ON ...) are executed directly by the PostgreSQL query planner with AST sanitization via sqlglot.

2. Tech Stack

ComponentTechnologyDescription
RuntimePython 3.13High-performance async runtime
Package ManageruvSub-second virtual environment & dependency management
Web FrameworkFastAPI (ASGI)REST API & OpenAPI documentation
Database DriverasyncpgNative async PostgreSQL binary protocol driver
Relational StorePostgreSQL 16Dedicated database-per-tenant architecture
Cache & Pub/SubValkey 7.2High-throughput in-memory token & session caching
SQL EnginesqlglotAST parser, validator, and LIMIT injector

3. Quickstart Guide

Step 1: Start the Local Infrastructure

From the repository root, start PostgreSQL and Valkey:

bash
docker compose -f docker-compose.open.yaml up -d
  • PostgreSQL Port: localhost:5432 (Database: valstorm_directory, User: valstorm, Password: valstorm_password)
  • Valkey/Redis Port: localhost:6379

Step 2: Install Python Dependencies via uv

bash
cd apps/open-api
uv sync

Step 3: Run the Core Seeder

Initialize the central Directory DB and provision the Admin Org and Client Workspace.

bash
uv run python app/seed.py --interactive

Option B: CLI Flags (Ideal for CI/CD & Automation)

Note for macOS (zsh) / bash users: Always wrap passwords containing ! or $ in single quotes ('...') rather than double quotes ("..."). In zsh, !" inside double quotes triggers history expansion and leaves the quote unclosed (dquote>).

bash
uv run python app/seed.py \
  --admin-org-name 'Apex Aerospace HQ' \
  --admin-email '[email protected]' \
  --admin-password 'AdminSecret123!' \
  --support-email '[email protected]' \
  --support-password 'SupportSecret123!' \
  --client-org-name 'Cyberdyne Systems' \
  --client-user-name 'Miles Dyson' \
  --client-email '[email protected]' \
  --client-password 'ClientSecret123!'

Option C: Default Valstorm Development Seed

bash
uv run python app/seed.py

Step 4: Start the API Server

bash
uv run uvicorn app.main:app --port 8010 --reload

The API will be available at http://localhost:8010. Interactive Swagger documentation is available at http://localhost:8010/docs.


4. The 33 Foundational Base App Tables

The Base App (app_0Ik4pJ5P60Bk7x1u) automatically seeds these 33 foundational schemas and tables into each tenant database:

CategoryPostgreSQL Tables
Identity & Accessuser, role, permission, user_group, auth_credential
System & Environmentorganization, environment_configuration, app, app_metadata, onboarding
Triggers & Logicapi_trigger, record_trigger, function, schedule_trigger, schedule_trigger_run, schedule_trigger_setting, scheduled_item
UI & Layoutapp_page, dashboard, report, list_filter, template, guide
File Storagefile, related_file
Notificationsnotification, notification_setting, notification_subscriber
Commercial / Billingapp_product, app_product_price, integrated_app
Metadata & Categorizationtag, log

5. API Reference Summary

All routes maintain exact compatibility with the Valstorm frontend (packages/components, apps/workspace, and apps/valstorm-desktop):

Authentication (/auth)

  • POST /auth/register - Create a new user, register an organization, and provision a dedicated database.
  • POST /auth/login - Authenticate with email/password and obtain a JWT bearer token.
  • GET /auth/me - Retrieve authenticated user profile and organization scoping.

Object & Schema DDL (/schema)

  • POST /schema/object - Define a new custom object; compiles and executes CREATE TABLE.
  • POST /schema/field - Add a field to an existing object; compiles and executes ALTER TABLE ... ADD COLUMN.
  • GET /schema/object - Retrieve all registered schemas and property definitions for the tenant.

Record CRUD (/records/c/{object_name})

  • POST /records/c/{object_name} - Batch create records with Base62 ID generation (tick_..., con_...).
  • PUT /records/c/{object_name} - Batch update records by ID.
  • DELETE /records/c/{object_name} - Batch delete records by ID list ({"ids": [...]}).
  • GET /records/c/{object_name} - Paginated list of records (?limit=50&offset=0).

Native SQL Queries (/query)

  • POST /query/sql - Execute parameterized ANSI SQL directly on PostgreSQL:

``json { "query": "SELECT id, name, priority FROM ticket WHERE is_closed = false ORDER BY created_date DESC", "limit": 50 } ``

Tenant Sandboxes (/sandbox)

  • POST /sandbox/create - Provision a dedicated sandbox database (CREATE DATABASE {prod_org}_s_{name}).
  • DELETE /sandbox/delete - Cleanly drop and terminate active connections for a sandbox database.

6. Code Quality, Security & Compliance Audits

The open-api service enforces an automated multi-layer quality and security verification pipeline before any code is approved for deployment.

Code Quality & Linting Checklist (Ruff)

Open Valstorm uses Ruff for high-performance Python 3.13 linting, import sorting (isort), and formatting:

bash
# Check code style, unused imports, and syntax rules
uv run ruff check .

# Automatically apply safe fixes and organize imports
uv run ruff check --fix .

# Verify formatting without mutating files
uv run ruff format --check .

# Format all files to PEP 8 standards
uv run ruff format .

Security & Vulnerability Audits

Run individual security scanners or the unified CI/CD audit script:

bash
# 1. Static Application Security Testing (SAST) via Bandit
uv run bandit -c .bandit.yaml -r app

# 2. Software Supply Chain Vulnerability Scan (SCA) via pip-audit
uv run pip-audit

# 3. Secret Leak Detection via Gitleaks
gitleaks git --log-opts="HEAD~10..HEAD" --verbose

# 4. Dependency License Compliance Audit (0 copyleft/GPL contamination)
uv run pip-licenses --summary

# 5. Full 8-Gate Security & Quality CI/CD Pipeline
./scripting/cicd/security_audit.sh

7. Python Sandbox & AST Security Gatekeeper

Server-side Python functions and record triggers run inside an AST-enforced, asynchronous sandbox (apps/open-api/app/core/sandbox/):

  • Whitelisted Standard Modules: math, datetime, re, orjson, uuid, decimal, random, typing.
  • Performance Enforcement (orjson): Importing the standard json library is actively intercepted by the AST gatekeeper, throwing a SecurityViolationError instructing developers to use orjson for high-throughput serialization.
  • Prohibited Built-ins & Calls: eval(), exec(), open(), compile(), globals(), locals(), vars(), __import__(), breakpoint().
  • Introspection & Escape Armor: Access to dunder attributes (__class__, __subclasses__, __bases__, __mro__, __globals__, __dict__) and dynamic dunder access via getattr/setattr are strictly rejected at parse time.
  • Resource Constraints:
  • Script Execution Timeout: 5.0s maximum wall clock limit (CodeExecutionTimeout / HTTP 408).
  • Trigger Recursion Guard: Maximum depth of 3 nested triggers (TriggerRecursionError / HTTP 400).

8. Automated Testing & Verification

Run the full automated test suite using pytest:

bash
uv run pytest -v

Test Suite Directory (apps/open-api/tests/)

The test suite consists of 50 integration and unit tests across 19 specialized modules:

Test ModuleCoverage Domain
tests/test_triggers_and_sandbox.pyAST security gatekeeper, orjson enforcement, Before/After record triggers, recursion prevention.
tests/test_platform_context.pyDirect SDK and REST API route parity for records, query, schemas, files/vfs, apps, sandboxes.
tests/test_query_service.pySQL AST validation, SELECT-only enforcement, LIMIT capping, and injection sanitization.
tests/test_query_hydration.pyRelational lookup hydration (hydrate: true/false) and reverse resolution.
tests/test_phase3_security_and_sql.pyObject-Level Security (OLS), Field-Level Security (FLS), Row-Level Security (RLS), and SQL macro rewriting.
tests/test_iteration_a_security_gaps.pyCanonical prefix mapping, schema validation rules, OAuth2 refresh tokens, and OLS/RLS gates.
tests/test_enterprise_licensing.pyMulti-tier enterprise licensing, license activation, and dynamic feature flag toggles.
tests/test_ddl_compiler.pySchema definition to PostgreSQL DDL compilation (CREATE TABLE, ALTER TABLE, DROP COLUMN).
tests/test_schema_sync_reflection.pyDual-system schema synchronization, PostgreSQL drift detection, and prefix utilities.
tests/test_vfs_and_files.pyVirtual File Service (VFS), Knowledge Vault hierarchy, file revisions, and rollback.
tests/test_cud_notifications.pyCUD mutation event publishing, Valkey pub/sub, and WebSocket distribution.
tests/test_graphql.pyDynamic GraphQL schema generation, Strawberry resolvers, and dataloaders.
tests/test_graphql_page_record_errors.pyComplex type handling and field error boundaries in GraphQL execution.
tests/test_app_deployment.pyApplication marketplace installation, bundle deployment, and subscriber tracking.
tests/test_bootstrap_v2.pyFull V2 bootstrap lifecycle and org provisioning.
tests/test_seeder.pyEnd-to-end default core bootstrap seeding (33 foundational Base App tables).
tests/test_generic_seeder.pyCustom non-proprietary org seeding and Universal Support User verification.
tests/test_e2e_seeded_api.pyProduction v1 API contract verification against seeded live tenant data.
tests/test_api_endpoints.pyHealth endpoints, OpenAPI schema generation, and service readiness.

9. Resetting & Wiping Your Local Instance (Fresh Admin & Client Setup)

To completely wipe your local Open Valstorm instance—including the central valstorm_directory database, all isolated per-tenant PostgreSQL databases (org_*), Valkey/Redis cache, and local VFS storage—and bootstrap a fresh Admin and Client workspace from the ground up, follow these steps:

Step 1: Wipe the Databases, Volumes & Local Storage

Because Open Valstorm dynamically creates a dedicated PostgreSQL database for each tenant (org_awmq8vsogmavwkw9, org_dsnpmrjs1zkkdyq2, sandboxes, etc.) inside the open_pgdata Docker volume, tear down the compose stack with -v (remove volumes) from the monorepo root:

bash
# Tear down containers and delete the open_pgdata PostgreSQL volume
docker compose -f docker-compose.open.yaml down -v

# Optional: Remove any local VFS files written to disk during previous test runs
rm -rf apps/open-api/storage

Step 2: Start Fresh PostgreSQL & Valkey Containers

Choose whether to run only the database/cache in Docker (with the FastAPI server running on your host via uv) or the entire stack in Docker:

  • Option 1 — Run DB/Cache in Docker & API on Host (Recommended for local dev):

``bash docker compose -f docker-compose.open.yaml up -d open-postgres open-valkey ``

  • Option 2 — Run the Full Stack (Postgres, Valkey, Open-API, Open-Worker) in Docker:

``bash docker compose -f docker-compose.open.yaml up -d ``

Step 3: Seed a Fresh Admin Org, Support User & Client Workspace

Navigate to apps/open-api and run app/seed.py. This initializes valstorm_directory, provisions the dedicated PostgreSQL databases for both the Admin and Client organizations, compiles the foundational Base App tables/schemas, attaches the Universal Support User, and flushes Valkey (FLUSHDB):

bash
cd apps/open-api
uv sync

Choose one of the three seeding modes:

Option A: Default Valstorm Seed (Fastest)

bash
uv run python app/seed.py
RoleEmailPasswordOrganization IDDedicated Postgres DB
Super Admin[email protected]valstorm_admin_passwordorg_AwmQ8vSogMavWkw9org_awmq8vsogmavwkw9
Support User[email protected]valstorm_support_password(Attached to all orgs)(Both Admin & Client DBs)
Client Admin[email protected]valstorm_client_passwordorg_dSnPMRjS1ZkkdYQ2org_dsnpmrjs1zkkdyq2

Option B: Interactive Setup Wizard (Custom Names, Emails & Passwords)

bash
uv run python app/seed.py --interactive

Option C: Custom CLI Flags

bash
uv run python app/seed.py \
  --admin-org-name 'System Administration' \
  --admin-user-name 'Super Admin' \
  --admin-email '[email protected]' \
  --admin-password 'AdminSecret123!' \
  --support-email '[email protected]' \
  --support-password 'SupportSecret123!' \
  --client-org-name 'Test Client Org' \
  --client-user-name 'Client Tester' \
  --client-email '[email protected]' \
  --client-password 'ClientSecret123!'

Step 4: Start the Open API Server

If you selected Option 1 in Step 2 (running the API on your host machine):

bash
cd apps/open-api
uv run uvicorn app.main:app --port 8010 --reload
  • API Base URL: http://localhost:8010
  • Interactive Swagger Docs: http://localhost:8010/docs

Step 5: Migrating Existing MongoDB Tenants to PostgreSQL (1-Click ETL)

To migrate existing Valstorm organizations from MongoDB (apps/api + apps/worker-go) into dedicated Open Valstorm PostgreSQL databases (apps/open-api + apps/open-worker):

bash
# Migrate a single tenant organization (with row-count + checksum verification)
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --org org_dSnPMRjS1ZkkdYQ2 --verify

# Migrate all tenant organizations discovered in MongoDB
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --all-orgs --verify

# Clean re-migration (drops & recreates target tenant databases before loading)
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --all-orgs --flush --verify

What the migration pipeline automatically handles:

  • Global Directory (valstorm_directory): Syncs organization, users, app (filtering deprecated monolithic apps converted to /plugins), and external_account_routing (Twilio, Telnyx, Stripe, OAuth).
  • Schema & Plugin DDL Compilation: Compiles all MongoDB schemas, merges foundational base_app.json + built-in plugin schemas (user_ai_memory, user_asset_affinity, personal_access_token), hydrates picklist/multi-select options from tag, and guarantees zero prefix collisions and SchemaService.get_sync_status() == True.
  • Encrypted Credentials & BYOK: Decrypts legacy AES-256-CBC auth_credential and environment_configuration envelopes (including double-encrypted or Python dict repr payloads) and re-encrypts them as RFC 8259 JSON under the Open Valstorm encryption key.
  • AI Working Memory & VFS Paths: Consolidates user_asset_affinity (uaaf_) records into user_ai_memory.pinned_assets (uaim_) for valstorm-plugin-ai and computes hierarchical vault_paths across vault and file.