# Open Valstorm Plugin System & Native Dual-Runtime `PlatformContext` Architecture ## 1. Executive Summary Open Valstorm is designed to keep its core (`apps/open-api` in Python and `apps/open-worker` in Go) streamlined, fast, and database-strict on PostgreSQL + Valkey/Redis, while supporting an extensible ecosystem of modular integrations (**Slack, AI, Telnyx, Twilio, Google Workspace, Microsoft 365, DigitalOcean, Azure, Campaigns, Booking**, etc.) packaged under `/plugins/*`. Crucially, Go integrations (like Telnyx, Twilio, Gmail sync, Campaigns, and AI Desktop Sync) **must not** proxy database CUD or schema operations over HTTP through the Python FastAPI server. Instead, both `apps/open-api` (Python) and `apps/open-worker` (Go) implement a **Native `PlatformContext` Data Plane** that communicates directly with PostgreSQL (`asyncpg` in Python, `pgxpool` in Go) and Valkey (`redis`), sharing the exact same Redis schema-invalidation signals, CUD WebSocket broadcast format, and asynchronous trigger queues. --- ## 2. Runtime Order of Operations (Unified Data Plane) Every record mutation (whether initiated from Python `PlatformContext` or Go `pkg/platform`) executes the exact same 6-step order of operations: ```text [1. Ingress] ├── REST / GraphQL / OAuth / AI Chat ────────► open-api (Python) └── High-Speed Webhooks / WS / Asynq / Cron ─► open-worker (Go) │ ▼ [2. Schema & Tenant Resolution (0ms RAM Cache + Redis Invalidation)] • Checks Redis `org:{org_id}:schemas_updated_at` • Loads SchemaDefinition + Postgres column types from local memory cache • Resolves Tenant Postgres connection pool (`db_manager` in Python / `TenantPoolManager` in Go) │ ▼ [3. Record Preparation & Sanitization] • Python: `sanitize_record_for_db` + `format_column_value` • Go: `schema.PrepareRecord` / `schema.PrepareUpdate` • Both: Generate Base62 ID (`prefix_...`), stamp `created_date`/`modified_date` (UTC), stamp `created_by`/`modified_by`, strip lookup dicts to string IDs, format phone objects, hydrate defaults, increment auto-number counters │ ▼ [4. Direct Parameterized PostgreSQL Execution] • Executes `INSERT / UPDATE / DELETE ... RETURNING *` directly against Tenant DB • Native Postgres enforces types (`TIMESTAMPTZ`, `JSONB`, `TEXT[]`) & foreign keys │ ▼ [5. Real-Time WebSocket CUD Broadcast (<0.1ms)] • Publishes `cud_create` / `cud_update` / `cud_delete` envelope to Redis channel `{org_id}` • `open-worker` WebSocket server streams immediately to all connected browsers/desktops │ ▼ [6. Asynchronous Trigger & Workflow Relay (<0.1ms)] • Pushes `valstorm.core.execute_async_trigger` task payload into Redis (`valstorm:queue:default`) • Python `ValstormBackgroundWorker` picks up and runs any tenant custom Python triggers in sandbox ``` --- ## 3. Classification of Existing Modules (`worker-go` & `api`) ### Tier A: Core Engine & Data Plane (Lives in `apps/open-worker` & `apps/open-api` Core) 1. **Multi-Tenant DB Manager (`pkg/tenantdb` in Go / `db_router.py` in Python)**: Manages tenant `pgxpool.Pool` / `asyncpg` pools. 2. **Dynamic Schema & Record Sanitizer (`pkg/schema` in Go / `record_service.py` in Python)**: In-memory `sync.RWMutex` schema cache invalidated by Redis `org:{org_id}:schemas_updated_at`, Base62 ID generation, default value hydration, lookup string extraction, phone normalization, and Postgres column type coercion. 3. **Native `PlatformContext` (`pkg/platform` in Go / `platform_context.py` in Python)**: Unified CUD, SQL query, credential decryption, CUD broadcast, and async trigger relay facade. 4. **WebSocket & CUD Broadcast (`internal/websocket`, `internal/cud`)**: Real-time pub/sub streaming to connected clients. 5. **Dynamic Scheduler (`internal/scheduler`)**: Cron ticker and Python/Asynq task relay. 6. **Fleet App Deployment (`internal/deployment`)**: Concurrent (`errgroup`) multi-tenant schema DDL and app bundle installer. 7. **Telemetry & Logging (`internal/telemetry`)**: High-throughput activity, error, and usage logging. 8. **Core High-Speed Handlers (`internal/inbound`, `internal/vfs`, `internal/webhook`, `internal/notification`, `internal/scraper`)**: Public form/webhook ingestion (`/v1/inbound/submit`), S3 batch purges/cascades, outbound webhook dispatch, and notification routing. ### Tier B: Modular Plugins (Lives in `/plugins/valstorm-plugin-`) Each plugin can contain a `/python` package (FastAPI routers, background tasks, AI tools) and/or a `/go` module (Asynq handlers, high-speed HTTP/WebSocket handlers): 1. **`valstorm-plugin-slack`** (Python): Slack OAuth v2, workspace client, event webhooks, background tasks, AI tools. 2. **`valstorm-plugin-telnyx`** (Python + Go): Number provisioning, Call Control state machine, Deepgram transcription, MMS S3 uploads, SMS webhooks. 3. **`valstorm-plugin-twilio`** (Python + Go): Twilio Conversations state machine, bulk SMS, call ringing/queued alerts. 4. **`valstorm-plugin-ai`** (Python + Go): Agentic chat orchestration, tool bridge, and Go sub-10ms `/v1/ai/chat/{chat_id}/desktop-sync`. 5. **`valstorm-plugin-google`** (Python + Go): Google OAuth, Gmail Pub/Sub delta sync (`pgx.Batch`), Google Calendar sync, and Booking slot engine. 6. **`valstorm-plugin-campaign`** (Python + Go): Bulk email/SMS campaign orchestrator and delivery status tracker. 7. **`valstorm-plugin-m365` / `valstorm-plugin-digitalocean` / `valstorm-plugin-azure`**: Cloud & enterprise integrations. --- ## 4. Phased Implementation Roadmap ### Step 1: Build the Native Go `PlatformContext` in `apps/open-worker` 1. **`apps/open-worker/pkg/id`**: Base62 ID generation and prefix inference matching `open-api`. 2. **`apps/open-worker/pkg/tenantdb`**: Multi-tenant `pgxpool.Pool` manager with thread-safe caching per `orgID`. 3. **`apps/open-worker/pkg/schema`**: Port `apps/worker-go/internal/schema` (`types.go`, `record.go`, `manager.go`) from MongoDB to PostgreSQL (`pgxpool`), including table column type reflection (`information_schema.columns`) and atomic counter increments. 4. **`apps/open-worker/pkg/platform`**: Native Go `PlatformContext` (`ForOrg(orgID, userID)`) providing: - `Records.Create(ctx, apiName, data)` & `Records.CreateBatch(ctx, apiName, records)` - `Records.Update(ctx, apiName, id, data)` - `Records.Delete(ctx, apiName, id)` - `Records.Get(ctx, apiName, id)` & `Records.Query(ctx, apiName, filters, limit)` - Automatic `cud.PublishCUD` broadcast + Redis `valstorm.core.execute_async_trigger` dispatch on mutations. 5. **Comprehensive Go Test Suite**: Unit tests for `pkg/id`, `pkg/schema`, and `pkg/platform` verifying schema hydration, Postgres SQL generation, CUD publishing, and async trigger relay. ### Step 2: Build the Python & Go Plugin Registries + `PlatformContext` Extensions 1. Extend Python `PlatformContext` with `platform.cache`, `platform.credentials`, `platform.tasks`, and `PlatformContext.for_external_account(...)`. 2. Create Python plugin loader (`apps/open-api/app/core/plugins.py`) and Go plugin registry (`apps/open-worker/pkg/plugin/registry.go`) controlled by `VALSTORM_PLUGINS`. 3. Configure `/plugins`, `go.work`, and `docker-compose.open.yaml` volume mounts for live hot-reloading. ### Step 3: Vertical Slice #1 — Pure Python Plugin (`valstorm-plugin-slack`) - Extract `apps/api/app/slack` into `plugins/valstorm-plugin-slack` using pure `PlatformContext`. ### Step 4: Vertical Slice #2 — Hybrid Go + Python Plugins (`valstorm-plugin-telnyx` & `twilio`) - Port Telnyx and Twilio handlers into `plugins/valstorm-plugin-telnyx` and `plugins/valstorm-plugin-twilio` on top of Go `pkg/platform` and Python `PlatformContext`. ### Step 5: Vertical Slice #3 — AI, Google Workspace, Campaigns & Cloud Integrations - Port `ai`, `google` (`gmail` + `calendar` + `booking`), and `campaign` into `/plugins/*`.