Compare commits

..
Author SHA1 Message Date
Silvertakana a88d65612b Revise SECURITY.md with support versions and reporting
Updated the security policy to include supported versions and reporting guidelines.
2026-05-10 10:45:04 +12:00
Antigravity AI b6d14dd720 docs(readme): enhance README with standard badges and architecture overview
- docs: added CI, Codecov, NPM, and Discord badges
- docs: added mermaid project architecture diagram
- docs: added key features, structure tree, and prerequisites
- chore: relocated old plan documents to .agents/plans
2026-05-10 10:30:57 +12:00
Antigravity AI 72f485f405 docs(agents): track all remaining agent rules 2026-05-10 10:14:29 +12:00
Antigravity AI 8f82310e3d docs(agents): update gitignore and add coding principles rule 2026-05-10 10:04:15 +12:00
Antigravity AI 3fe9edf6f3 checkout: temporary commit for worktree checkout 2026-05-10 09:51:44 +12:00
Antigravity AI 0156ead243 fix(deployment): resolve stale image issues and legacy migration commands
- Bump version to 2.1.6
- fix: update setup scripts to pull latest image before starting
- fix: set pull_policy to always in self-host compose file
- fix: auto-detect compose container for legacy migration script in setup UI
2026-05-10 01:20:22 +12:00
Antigravity AI 7bd6b32121 refactor: change default legacy DB path to data/wwv.db 2026-05-10 00:41:08 +12:00
Antigravity AI bc10b09788 fix: resolve undefined ID error when migrating settings from legacy SQLite 2026-05-10 00:40:29 +12:00
Antigravity AI 45c41fd2a0 refactor: update setup scripts to download docker-compose.yml and .env.example 2026-05-10 00:34:26 +12:00
Antigravity AI 78fb1dc484 fix(core): update legacy migration script and Dockerfile for Prisma 7 [Patch]
- fix migrate-legacy.mjs to use explicit pg adapter and accept db path arg [Patch]

- copy migrate-legacy.mjs to final docker image [Patch]
2026-05-10 00:06:33 +12:00
Antigravity AI 5fb36069ac fix(core): migrate changes and resolve cors issues [Patch]
- fix marketplace CORS by allowing x-marketplace-ping header [Patch]

- update setup page and docker entrypoint for legacy migrations [Patch]
2026-05-09 23:30:18 +12:00
Silvertakana c4207bd6e1 feat(core): migrate to Prisma 7 and unify PostgreSQL architecture (#56)
* feat(cloud): implement Postgres DB adapter, fix static build crashes, and containerize NextAuth/Stripe integrations

* test(marketplace): fix mocks and assertions for multi-tenant Postgres architecture

* feat: rsa jwt license key verification and state integration

* feat: add internal workspace validation route for Edge Functions

* refactor: clean up hub routes and finalize db proxy/adapter for multi-tenant cloud deploy

* feat(cloud): finalize multi-tenant Prisma extensions and workspace routing

* fix(db): correct Prisma 7 better-sqlite3 adapter initialization [Patch]

- update better-sqlite3 adapter instantiation to use configuration object ({ url }) required by Prisma 7 instead of raw Database instance [Patch]
- fix PrismaClientConstructorValidationError by generating client with adapter support [Patch]

* fix(auth): support dynamic origins for local proxies and multi-tenant subdomains [Patch]

- prioritize forwarded headers and request host over hardcoded envOrigin in getRequestOrigin to support subdomain routing [Patch]
- allow ALLOWED_DEV_ORIGIN in marketplace install redirect checks to fix local network development login flows [Patch]

* fix(marketplace): enable dynamic CORS reflection for marketplace API [Patch]

- remove explicit origin array, replacing with origin header reflection to allow marketplace hosted on any domain or local IP [Patch]

- remove global wildcard CORS headers from next.config.ts to harden security against broader app injection [Patch]

* feat(db): create initial postgresql migration

* refactor(db): update remaining files for postgresql

* feat(db): unify database adapter to PostgreSQL-only [Minor]

- replace SQLite adapter with PostgreSQL PrismaPg [Minor]
- remove better-sqlite3 dependencies [Patch]
- finalize docs and implementation plan [Patch]

* fix: resolve prisma client generation and script execution issues with tsx and type module

* feat(db): port tenant isolation logic to new PostgreSQL adapter

* docs: add rule for transparent and narrated agent actions

* BREAKING CHANGE(core): migrate to PostgreSQL and add auto-migration pipeline [Major]

- unified database adapter to exclusively use PostgreSQL [Major]
- implement auto-migration pipeline to pipe legacy SQLite data to Postgres [Major]
- add sqlite to runner stage to support extraction pipeline [Patch]

* feat(core): migrate to Prisma 7 and unify PostgreSQL architecture [Minor]

- removed legacy Prisma SQLite driver and all Better-Sqlite dependencies [Minor]
- updated schema to utilize purely postgresql providers [Patch]
- modified migration scripts to seamlessly convert local sqlite DBs to PostgreSQL containers using keinos/sqlite3 [Minor]
- updated deployment scripts, Coolify pipelines, and Nginx proxy support [Patch]
- injected Prisma Client Extensions for multi-tenant Row Level Security isolation [Minor]
- stabilized PrismaClient initialization utilizing the official adapter-pg runtime pattern [Patch]
- bumped version to 2.1.0

* fix(core): resolve TypeScript compilation errors for CI [Patch]

- fixed NextResponse.json() 3-arg calls to use 2-arg ResponseInit form [Patch]
- replaced invalid 'developer' TrustTier with 'unverified' in parseWwvManifest and load-unpacked route [Patch]
- removed non-existent pluginManager.hotReload() call in DevModeSubscriber, replaced with disable/reload cycle [Patch]
- updated Stripe API version from '2024-04-10' to '2026-04-22.dahlia' to match installed SDK [Patch]
- excluded local-scripts/ from tsconfig to prevent debug scripts from breaking CI [Patch]

* fix(ci): resolve pnpm version conflict in GitHub Actions [Patch]

- removed explicit version: 9 from pnpm/action-setup@v4 — v4 auto-reads packageManager from package.json [Patch]
- updated build job DATABASE_URL from SQLite to PostgreSQL format [Patch]

* fix(docker): add explicit Prisma generator output path for Docker builds [Patch]

- Prisma 7 changed default output location, causing COPY --from=builder to fail
- added output = '../src/generated/prisma' to generator block for consistency

* fix(prisma): update client import path and resolve CI type errors [Patch]

- updated PrismaClient import in db.ts to point to custom generated output path
- resolved implicit 'any' error in marketplace check-updates route
- verified clean local build with tsc --noEmit

* chore(deps): sync Prisma versions to 7.6.0 [Patch]
2026-05-09 22:44:30 +12:00
Silvertakana 138ea6c721 feat: local Docker HTTPS proxy for Firefox marketplace bridge compatibility (#50)
* feat: implement local docker HTTPS proxy for marketplace bridge

Generates self-signed certs automatically in docker-entrypoint and spins up a native Node HTTPS proxy on port 3001 to resolve Firefox Mixed Content blocks when fetching from local containers via the live marketplace.

* fix(core): fix docker build and marketplace origin parsing [Patch]

- fix pnpm run generate script failure in Dockerfile [Patch]
- implement robust origin parsing for marketplace endpoints [Patch]
2026-05-09 11:02:46 +12:00
Antigravity AI dc10e8ad5c fix(build): downgrade pnpm to v9.15.4 to bypass v10 strict script approvals 2026-05-09 10:13:08 +12:00
Antigravity AI 84f694f93b chore: approve sentry/cli build script to fix docker build 2026-05-09 10:07:22 +12:00
Antigravity AI fa60f845c1 chore: update lockfile for version bump 2026-05-09 09:59:31 +12:00
Antigravity AI 6e3a8ab625 fix(cors): allow permissive CORS and private network access 2026-05-09 09:55:16 +12:00
Antigravity AI 739bffa05b fix: trigger vercel deployment after correcting git email 2026-05-08 14:20:42 +12:00
SilvertakanaandAntigravity AI 9888f11a4b feat(ui): add layer search and right panel deselection persistence (#47)
* feat(ui): add layer search and persist right panel on deselection

* feat(ui): add resizable drag handles to both sidebars

* feat(ui): dynamic toggle button positioning during panel resize

* fix(ui): instantly follow cursor during panel resize without transition delay

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-05-01 22:29:04 +12:00
SilvertakanaandAntigravity AI 7354b414e7 fix: Enlarge panel pull tab trigger areas (#46)
* fix: enlarge panel pull tab trigger areas for better touch targets

* fix: extend trigger area further inward towards panels

* fix(globe): increase mobile pinch zoom sensitivity [Patch]

- decrease _zoomFactor to 5 to make pinch zooming more responsive on touch devices [Patch]
- conditionally allow dev origins in next config [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 23:59:52 +12:00
SilvertakanaandAntigravity AI 196380c0af fix: resolve GlitchTip crashes in core components (#44)
Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 12:43:45 +12:00
SilvertakanaandAntigravity AI 06e919639d docs: comprehensive documentation overhaul and fixes (#42)
* docs(core): comprehensive documentation overhaul

* fix: resolve worktree paths dynamically via git CLI

* refactor(ui): temporarily disable demo ad strip

* fix(ui): redirect header logo and cleanup marketplace routes [Patch]

- make header logo a clickable link to landing page [Patch]

- cleanup marketplace routes and remove builtinPlugins [Patch]

* fix: silently drop malformed legacy built-in plugins from marketplace API validation to prevent console spam

* feat: add Sentry captureMessage for marketplace manifest validation errors to improve observability

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 12:00:58 +12:00
SilvertakanaandAntigravity AI f948f2aaab fix: silently drop legacy plugin manifest and add sentry logging (#41)
* fix: silently drop malformed legacy built-in plugins from marketplace API validation to prevent console spam

* feat: add Sentry captureMessage for marketplace manifest validation errors to improve observability

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 11:52:59 +12:00
SilvertakanaandAntigravity AI a5125dba7b docs: Comprehensive Documentation Overhaul (#39)
* docs(core): comprehensive documentation overhaul

* fix: resolve worktree paths dynamically via git CLI

* refactor(ui): temporarily disable demo ad strip

* fix(ui): redirect header logo and cleanup marketplace routes [Patch]

- make header logo a clickable link to landing page [Patch]

- cleanup marketplace routes and remove builtinPlugins [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-28 23:39:20 +12:00
SilvertakanaandAntigravity AI 21a6c618c8 feat(marketplace): automate default plugin installation (#37)
- Added seedDefaultPlugins pipeline for idempotent initial hydration
- Migrated legacy hard-coded plugins from builtinPlugins.ts to defaultPlugins.ts
- Updated /api/marketplace/load to trigger seeding on fresh installs
- Added support for Antigravity worktrees in local test script
- (Minor version bump for new automated seeding feature)

Co-authored-by: Antigravity AI <[email protected]>
2026-04-23 18:06:06 +12:00
Antigravity AI 48a17bf3ee feat(sdk,docs): add vite static compiler export, overhaul documentation for plugin ecosystem [Minor]
- add wwvStaticCompiler to SDK vite/ subpath export [Minor]
- export createPluginContext and PluginContext type from SDK [Minor]
- update viteGlobals mapping for lucide-react [Patch]
- overhaul all docs/ for decoupled plugin development workflow [Minor]
- update README with new CLI-based plugin creation instructions [Minor]
- fix marketplace load route CORS and error handling [Patch]
- add test coverage for DeclarativePlugin edge cases [Patch]
- bump root to v1.18.0, SDK to v1.5.0
2026-04-23 10:19:17 +12:00
Antigravity AI 2e4c074f77 docs: add repository ecosystem section to readme 2026-04-22 18:17:35 +12:00
Antigravity AI e2108f5049 chore: add multi-repo workspace warnings to local-dev scripts 2026-04-22 18:10:24 +12:00
Antigravity AI b76067c0bb docs: add prerequisites recipe for docker and pnpm installation 2026-04-22 18:03:56 +12:00
Antigravity AI 04e614e1ed docs: add open-core data engine architecture bullet to readme 2026-04-22 17:59:03 +12:00
Antigravity AI 0d14a63246 docs: restore complete README structure and integrate new setup scripts 2026-04-22 17:57:29 +12:00
Antigravity AI 781fe9e790 feat: add local-dev shell and powershell scripts for contributor setup 2026-04-22 17:54:43 +12:00
Antigravity AI f0c2d81e18 fix: replace Here-String with array to fix PowerShell parsing issues 2026-04-22 17:51:18 +12:00
Antigravity AI f86b7d1e94 ci: add docker build and publish workflow to ghcr.io 2026-04-22 17:43:12 +12:00
Antigravity AI 28704e6fe1 feat: add native Windows PowerShell setup script for self-hosting 2026-04-22 17:39:50 +12:00
Antigravity AI 01e291a40e fix: improve docker existence check to catch WSL stub binaries 2026-04-22 17:37:44 +12:00
Antigravity AI 909e150b3d docs: add self-hosting docker compose instructions to readme 2026-04-22 17:34:40 +12:00
Antigravity AI 1fe3a77383 feat: add self-hosting setup scripts 2026-04-22 17:33:54 +12:00
Antigravity AI 998f98851e docs: update architecture docs for dual-repo data engine 2026-04-22 12:46:41 +12:00
Antigravity AI 9c51cdb8a2 feat: add engine split-routing with cloud fallback
When a local data engine is detected at localhost:5001, the frontend
fetches its /manifest to discover available seeders. Plugins with
local seeders route to the local engine; plugins without fall back
to the cloud engine at wss://dataengine.worldwideview.dev/stream.

This enables core contributors to develop with the public engine
while proprietary data sources continue working via the cloud.
2026-04-22 12:46:00 +12:00
Antigravity AI d74ae694a4 feat(cli): implement wwv-cli developer toolkit and finalize plugin bundling architecture
- feat(cli): Update developer workflows and quickstarts to utilize new \@worldwideview/cli\ toolchain externally (Minor)
- refactor(plugins): Standardize remaining internal manifests and loader implementations strictly to dynamic bundled format (Patch)
- docs(core): Revise README and development specs with \
px create-wwv-plugin\ workflows (Patch)
2026-04-19 15:15:04 +12:00
Antigravity AI ec4c89fe51 fix(core): untrack local dev sandbox plugins from git history [Patch]
- Add public/plugins to gitignore
- Untrack pre-compiled dev plugins
- Bump version
2026-04-19 12:45:35 +12:00
Antigravity AI 44e8ff9b70 fix(marketplace): coerce outdated plugin cards to bundle format on install 2026-04-18 23:50:06 +12:00
Antigravity AI cc90d3c2a3 fix(plugins): gracefully align internal plugin IDs with marketplace manifest IDs, update demo environment variables to hyphened identifier 2026-04-18 22:59:53 +12:00
Antigravity AI 0e6268bf72 fix(plugins): implement try/catch for PluginManager polling to prevent silent loading loops and surface errors 2026-04-18 22:37:57 +12:00
Antigravity AI 764af74d14 fix(core): resolve data engine routing and plugin validation errors [Patch]
- update hostGlobals to default to cloud URL and respect explicit engine env vars [Patch]
- fix Next.js CSP headers to allow dynamic CDN bundle loading from unpkg [Patch]
- add strict manifest validation handling and logging to plugin loader [Patch]
2026-04-18 20:58:13 +12:00
Silvertakana 29269c668a Merge pull request #36 from silvertakana/bug/35-fix-plugin-loading-errors
fix: fix plugin loading errors on Coolify and Localhost Dependencies
2026-04-18 18:49:45 +12:00
Antigravity AI c60a0c9d56 fix(core): fix production plugin loading errors [Patch]
- inject engine URL into globalThis for runtime bundle plugins
- update satellite, iranwarlive, gps-jamming to read global reference
- fix military-bases loaded as bundle by SQLite db format override
2026-04-18 18:44:49 +12:00
Silvertakana 05b2dce394 Merge pull request #34 from silvertakana/bug/33-security-hardening
fix: harden endpoints against SSRF, DNS rebinding, open redirects, and error leaks
2026-04-18 16:53:40 +12:00
Antigravity AI 390518be0f fix(security): harden endpoints against SSRF, DNS rebinding, open redirects, and error leaks 2026-04-18 16:45:51 +12:00
Antigravity AI e07bc60672 fix(marketplace): apply demo default config to dynamic plugins [Patch] 2026-04-18 16:11:31 +12:00
Antigravity AI d75618f9aa fix(core): allow marketplace bearer token admin access on demo [Patch] 2026-04-18 15:54:23 +12:00
Silvertakana aa34e1c49d Merge pull request #32 from silvertakana/add-claude-github-actions-1776483677184
Add Claude Code GitHub Workflow
2026-04-18 15:41:48 +12:00
Silvertakana 2f618ce2cf "Update Claude Code Review workflow" 2026-04-18 15:41:21 +12:00
Silvertakana 085f4aa90c "Update Claude PR Assistant workflow" 2026-04-18 15:41:19 +12:00
Silvertakana c1ddb91268 Merge pull request #31 from silvertakana/feature/30-enable-demo-admin-privileges
feat(core): enable admin functionality on demo instance
2026-04-18 15:39:54 +12:00
Antigravity AI b3bc62ad8e feat(core): enable admin functionality on demo instance [Minor]
- allow demo-admin to bypass plugin installation blockers [Minor]

- allow demo-admin to use timeline history playback mode [Minor]
2026-04-18 15:21:01 +12:00
Silvertakana 32a4df4952 Merge pull request #29 from silvertakana/feature/plugin-extraction
feat(plugins): decentralize plugin architecture and marketplace updates
2026-04-18 14:31:46 +12:00
Antigravity AI 3ac36446bf chore(ci): add prisma generate to pipeline [Patch] 2026-04-18 14:04:51 +12:00
Antigravity AI ac95a64115 feat(plugins): implement marketplace updates and fix SDK global injection [Minor]
- add /check-updates mechanism to check with marketplace [Minor]
- inject zustand into WWV_HOST to prevent plugin crashes [Patch]
- fix next.config.ts sentry schema [Patch]
2026-04-18 13:39:46 +12:00
Antigravity AI 1d07698df7 feat(plugins): surface dynamic plugin loading failures to UI toast 2026-04-17 19:43:21 +12:00
Antigravity AI 583622f091 fix(plugins): reject fallback unknown-package manifests in validator 2026-04-17 19:41:35 +12:00
Antigravity AI bfdbd0313d feat(marketplace): add explicit server-side error logging for rejected manifests 2026-04-17 17:03:07 +12:00
Antigravity AI a70f93af0a fix(plugins): allow CDNs for dynamic plugin bundles and add marketplace debug logs 2026-04-17 16:59:15 +12:00
Antigravity AI 26970e6adc build: remove plugin packages from core workspace 2026-04-17 13:41:11 +12:00
Antigravity AI 63bc49949a refactor: decouple frontend from specific plugin logic 2026-04-17 13:04:49 +12:00
Antigravity AI ce45f2d4b6 fix(osm): force IPv4 resolution in proxy to bypass docker IPv6 dropouts 2026-04-16 20:17:37 +12:00
Antigravity AI bec1080cb8 chore(osm): instrument osm proxy error handler for docker debugging 2026-04-16 20:06:37 +12:00
Antigravity AI ed4826484c fix(osm): replace native Next.js fetch with node https client to bypass IPv6 timeout crashes in docker environment 2026-04-16 19:50:37 +12:00
Antigravity AI 77e6bf1d55 fix(ws): normalize engine URL to always include /stream path and wss:// protocol 2026-04-16 19:21:45 +12:00
Antigravity AI fa6413e953 fix(build): sync pnpm-lock.yaml after dependency updates to fix frozen lockfile crash [Patch] 2026-04-16 18:26:43 +12:00
Antigravity AI 53a9931e94 feat(plugins): refactor all plugins to fetch directly from data engine
Updated wildfires, surveillance-satellites, satellite, iranwarlive,
international-sanctions, maritime, military-aviation, gps-jamming,
cyber-attacks, civil-unrest, and earthquakes to bypass Next.js rewrites.
2026-04-16 17:23:20 +12:00
Antigravity AI 055ead345a feat(config): remove legacy REST proxy, point plugins directly at engine
Remove /api/external/ rewrite from next.config.ts.
Update Aviation plugin fetch() to call engine REST API directly
using NEXT_PUBLIC_DEFAULT_ENGINE_URL.
2026-04-16 17:21:22 +12:00
Antigravity AI 89c247e913 feat(ui): update DataBusSubscriber for multi-engine WsClient
Resolve engine URL per-plugin via resolveEngineUrl() before
subscribing. Remove eager wsClient.connect() — connections
are now lazy on first subscription.
2026-04-16 17:20:38 +12:00
Antigravity AI df7df20c46 feat(ws): refactor WsClient to multi-engine connection pool
Supports connecting to multiple Data Engines simultaneously.
Each plugin resolves its own engine URL. Connections are lazily
opened on first subscription and cleaned up after a 30s grace
period when all plugins unsubscribe.
2026-04-16 17:20:11 +12:00
Antigravity AI b738072e05 feat(data): add resolveEngineUrl utility for multi-engine support 2026-04-16 17:19:42 +12:00
Antigravity AI 414ac3b194 feat(sdk): add streamUrl to ServerPluginConfig and DataSourceConfig 2026-04-16 17:19:20 +12:00
Antigravity AI f3b48ac302 refactor(data-engine): extract wwv-data-engine into standalone repo [Minor]
- Bump version to 1.11.0 [Minor]
- Remove wwv-data-engine code, docker-compose and package.json scripts [Patch]
2026-04-16 15:13:59 +12:00
SilvertakanaandAntigravity AI bea39455e6 feat(sanctions,conflict-zones): enable selection and hover intel for sanctioned countries and conflict zones [Minor] (#28)
- Attach _wwvEntity to Resium Entity refs via bindWwvEntity() so InteractionHandler picks them [Minor]
- Build synthetic GeoEntity payloads from static ConflictZone data for conflict-zones plugin [Minor]
- Add sanctions-specific hover fields (country, severity, OFAC count) to EntityInfoCard [Minor]
- Add conflict zone hover intel (escalation score, status, trend) to EntityInfoCard [Minor]
- Bump wwv-plugin-international-sanctions 1.0.0 → 1.1.0 [Minor]
- Bump wwv-plugin-conflict-zones 1.0.0 → 1.1.0 [Minor]
- Bump root 1.9.1 → 1.10.0 [Minor]

Closes #27

Co-authored-by: Antigravity AI <[email protected]>
2026-04-16 15:01:17 +12:00
466 changed files with 15816 additions and 356476 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
# Global Skills Index
All skills below are installed at `C:\Users\silve\.agents\skills\` and are available in every project.
When the user invokes `/skill-name`, read and follow the skill at the path shown.
| Skill | Description | Path |
|---|---|---|
| `adapt` | Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. | `C:\Users\silve\.agents\skills\adapt\SKILL.md` |
| `better-auth-security-best-practices` | Configure rate limiting, manage auth secrets, set up CSRF protection, define trusted origins, secure sessions and cookies, encrypt OAuth tokens, track IP addresses, and implement audit logging for Better Auth. | `C:\Users\silve\.agents\skills\better-auth-security-best-practices\SKILL.md` |
| `brainstorming` | Use before any creative work — creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation. | `C:\Users\silve\.agents\skills\brainstorming\SKILL.md` |
| `ckm-banner-design` | Design banners for social media, ads, website heroes, creative assets, and print. Multiple art direction options. | `C:\Users\silve\.agents\skills\ckm-banner-design\SKILL.md` |
| `ckm-brand` | Brand voice, visual identity, messaging frameworks, asset management, brand consistency. | `C:\Users\silve\.agents\skills\ckm-brand\SKILL.md` |
| `ckm-design` | Comprehensive design skill: brand identity, design tokens, UI styling, logo generation, CIP, HTML presentations, banner design, icon design, social photos. | `C:\Users\silve\.agents\skills\ckm-design\SKILL.md` |
| `ckm-design-system` | Token architecture, component specifications, and slide generation. Three-layer tokens (primitive→semantic→component), CSS variables. | `C:\Users\silve\.agents\skills\ckm-design-system\SKILL.md` |
| `ckm-slides` | Create strategic HTML presentations with Chart.js, design tokens, responsive layouts, copywriting formulas. | `C:\Users\silve\.agents\skills\ckm-slides\SKILL.md` |
| `ckm-ui-styling` | Create beautiful, accessible UIs with shadcn/ui components (Radix UI + Tailwind), Tailwind CSS, canvas-based visual designs. | `C:\Users\silve\.agents\skills\ckm-ui-styling\SKILL.md` |
| `create-agentsmd` | Generate an AGENTS.md file for a repository. | `C:\Users\silve\.agents\skills\create-agentsmd\SKILL.md` |
| `create-proposal` | Generate a customized premium HTML proposal for clients. | `C:\Users\silve\.agents\skills\create-proposal\SKILL.md` |
| `create-readme` | Create a README.md file for the project. | `C:\Users\silve\.agents\skills\create-readme\SKILL.md` |
| `dispatching-parallel-agents` | Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies. | `C:\Users\silve\.agents\skills\dispatching-parallel-agents\SKILL.md` |
| `docker-compose-orchestration` | Container orchestration with Docker Compose for multi-container applications, networking, volumes, and production deployment. | `C:\Users\silve\.agents\skills\docker-compose-orchestration\SKILL.md` |
| `executing-plans` | Use when you have a written implementation plan to execute in a separate session with review checkpoints. | `C:\Users\silve\.agents\skills\executing-plans\SKILL.md` |
| `explain simply` | Explains a task or concept in a straightforward, jargon-free way. Use when the user asks for a simple explanation, or when complex technical topics need to be made accessible. | `C:\Users\silve\.agents\skills\explain-simply\SKILL.md` |
| `find-skills` | Helps discover and install agent skills — use when asking "how do I do X", "find a skill for X", or "is there a skill that can...". | `C:\Users\silve\.agents\skills\find-skills\SKILL.md` |
| `finishing-a-development-branch` | Use when implementation is complete, all tests pass, and you need to decide how to integrate the work. | `C:\Users\silve\.agents\skills\finishing-a-development-branch\SKILL.md` |
| `generate-update-notes` | Generate formatted update notes from recent git commits and track the last processed commit. | `C:\Users\silve\.agents\skills\generate-update-notes\SKILL.md` |
| `multi-stage-dockerfile` | Create optimized multi-stage Dockerfiles for any language or framework. | `C:\Users\silve\.agents\skills\multi-stage-dockerfile\SKILL.md` |
| `n8n-code-javascript` | Write JavaScript code in n8n Code nodes using $input/$json/$node syntax. | `C:\Users\silve\.agents\skills\n8n-code-javascript\SKILL.md` |
| `n8n-expression-syntax` | Validate n8n expression syntax and fix common errors with {{}} syntax. | `C:\Users\silve\.agents\skills\n8n-expression-syntax\SKILL.md` |
| `n8n-mcp-tools-expert` | Expert guide for using n8n-mcp MCP tools effectively. | `C:\Users\silve\.agents\skills\n8n-mcp-tools-expert\SKILL.md` |
| `n8n-node-configuration` | Operation-aware node configuration guidance for n8n. | `C:\Users\silve\.agents\skills\n8n-node-configuration\SKILL.md` |
| `n8n-validation-expert` | Interpret n8n validation errors and guide fixing them. | `C:\Users\silve\.agents\skills\n8n-validation-expert\SKILL.md` |
| `n8n-workflow-patterns` | Proven workflow architectural patterns from real n8n workflows. | `C:\Users\silve\.agents\skills\n8n-workflow-patterns\SKILL.md` |
| `next-best-practices` | Next.js best practices — file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling. | `C:\Users\silve\.agents\skills\next-best-practices\SKILL.md` |
| `next-cache-components` | Next.js 16 Cache Components — PPR, use cache directive, cacheLife, cacheTag, updateTag. | `C:\Users\silve\.agents\skills\next-cache-components\SKILL.md` |
| `next-upgrade` | Upgrade Next.js to the latest version following official migration guides and codemods. | `C:\Users\silve\.agents\skills\next-upgrade\SKILL.md` |
| `nextjs-prisma-standalone` | Use when building Next.js standalone containers with Prisma, or when encountering datasource/dotenv/Prisma 7 schema errors during deployment. | `C:\Users\silve\.agents\skills\nextjs-prisma-standalone\SKILL.md` |
| `nodejs-backend-patterns` | Build production-ready Node.js backend services with Express/Fastify, middleware, error handling, authentication, database integration, and API design. | `C:\Users\silve\.agents\skills\nodejs-backend-patterns\SKILL.md` |
| `pnpm` | Node.js package manager with strict dependency resolution. Use for pnpm commands, configuring workspaces, managing dependencies with catalogs, patches, or overrides. | `C:\Users\silve\.agents\skills\pnpm\SKILL.md` |
| `readme-i18n` | Translate a repository README, make a repo multilingual, localize docs, add a language switcher. | `C:\Users\silve\.agents\skills\readme-i18n\SKILL.md` |
| `receiving-code-review` | Use when receiving code review feedback, before implementing suggestions — requires technical rigor and verification. | `C:\Users\silve\.agents\skills\receiving-code-review\SKILL.md` |
| `refactor` | Surgical code refactoring to improve maintainability without changing behavior. Covers extracting functions, renaming, breaking down god functions, improving type safety. | `C:\Users\silve\.agents\skills\refactor\SKILL.md` |
| `refactoring-ui` | Audit and fix visual hierarchy, spacing, color, and depth in web UIs. | `C:\Users\silve\.agents\skills\refactoring-ui\SKILL.md` |
| `requesting-code-review` | Use when completing tasks, implementing major features, or before merging to verify work meets requirements. | `C:\Users\silve\.agents\skills\requesting-code-review\SKILL.md` |
| `researching-plugins` | Use when evaluating new data sources, researching APIs, or planning a new plugin structure, before writing any implementation code. | `C:\Users\silve\.agents\skills\researching-plugins\SKILL.md` |
| `security-review` | Use when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. | `C:\Users\silve\.agents\skills\security-review\SKILL.md` |
| `seo-audit` | Audit, review, or diagnose SEO issues — technical SEO, meta tags, core web vitals, crawl errors, indexing issues. | `C:\Users\silve\.agents\skills\seo-audit\SKILL.md` |
| `subagent-driven-development` | Use when executing implementation plans with independent tasks in the current session. | `C:\Users\silve\.agents\skills\subagent-driven-development\SKILL.md` |
| `supabase-postgres-best-practices` | Postgres performance optimization and best practices from Supabase. Use when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations. | `C:\Users\silve\.agents\skills\supabase-postgres-best-practices\SKILL.md` |
| `systematic-debugging` | Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes. | `C:\Users\silve\.agents\skills\systematic-debugging\SKILL.md` |
| `test-driven-development` | Use when implementing any feature or bugfix, before writing implementation code. | `C:\Users\silve\.agents\skills\test-driven-development\SKILL.md` |
| `ui-ux-pro-max` | UI/UX design intelligence for web and mobile. 50+ styles, 161 color palettes, 57 font pairings across 10 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, HTML/CSS). | `C:\Users\silve\.agents\skills\ui-ux-pro-max\SKILL.md` |
| `update-context` | Update context documents — sync `.agents/context/` with current project state. | `C:\Users\silve\.agents\skills\update-context\SKILL.md` |
| `using-superpowers` | Use when starting any conversation — establishes how to find and use skills, requires Skill tool invocation before ANY response. | `C:\Users\silve\.agents\skills\using-superpowers\SKILL.md` |
| `vercel-react-best-practices` | React and Next.js performance optimization guidelines from Vercel Engineering. Use when writing, reviewing, or refactoring React/Next.js code. | `C:\Users\silve\.agents\skills\vercel-react-best-practices\SKILL.md` |
| `verification-before-completion` | Use before claiming work is complete — requires running verification commands and confirming output before making any success claims. | `C:\Users\silve\.agents\skills\verification-before-completion\SKILL.md` |
| `web-design-guidelines` | Review UI code for Web Interface Guidelines compliance, accessibility, and UX best practices. | `C:\Users\silve\.agents\skills\web-design-guidelines\SKILL.md` |
| `worldwideview-plugin-creation` | Use when creating a new plugin, adding a new data source, or debugging missing plugin data in the WorldWideView project (Fastify + Next.js + Cesium architecture). | `C:\Users\silve\.agents\skills\worldwideview-plugin-creation\SKILL.md` |
| `writing-plans` | Use when you have a spec or requirements for a multi-step task, before touching code. | `C:\Users\silve\.agents\skills\writing-plans\SKILL.md` |
| `writing-skills` | Use when creating new skills, editing existing skills, or verifying skills work before deployment. | `C:\Users\silve\.agents\skills\writing-skills\SKILL.md` |
@@ -0,0 +1,177 @@
# Decouple Plugin Proxies Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Strip out hardcoded proxy endpoints from the `worldwideview` core repository to enforce a fully decoupled plugin ecosystem, replacing them with direct browser fetching or a universal CORS proxy.
**Architecture:** Remove preferential API routes (`/api/earthquake`, `/api/undersea-cables`, `/api/camera/*`) from the `worldwideview` core app. Promote the existing camera proxy to a universal `/api/proxy` with strict SSRF defenses. Provide direct browser-fetch code for the `wwv-plugin-earthquakes` where CORS permits, and migrate traffic camera fetchers directly into the `wwv-plugin-camera` package to fetch via the universal proxy.
**Tech Stack:** Next.js 16 (App Router), TypeScript, pnpm workspace
---
### Task 1: Promote Universal Proxy in Core Repository
**Files:**
- Create (Move): `src/app/api/proxy/route.ts`
- Delete: `src/app/api/camera/proxy/route.ts`
- [ ] **Step 1: Relocate the proxy route and update logs**
Move the existing camera proxy to act as a system-wide universal proxy.
Run: `mkdir -p src/app/api/proxy`
Run: `mv src/app/api/camera/proxy/route.ts src/app/api/proxy/route.ts`
- [ ] **Step 2: Update the error logging prefix in the new file**
Modify `src/app/api/proxy/route.ts` near line 97:
```json
{
"instruction": "Update the error logging prefix",
"replace_chunks": [
{
"start_line": 96,
"end_line": 98,
"target_content": " } catch (error: any) {\n console.error(\"[CameraProxy] Error fetching target URL:\", error);\n return NextResponse.json(",
"replacement_content": " } catch (error: any) {\n console.error(\"[UniversalProxy] Error fetching target URL:\", error);\n return NextResponse.json("
}
]
}
```
- [ ] **Step 3: Commit the Universal Proxy**
```bash
git add src/app/api/proxy/route.ts src/app/api/camera/proxy/route.ts
git commit -m "refactor: promote camera proxy to universal proxy"
```
### Task 2: Strip Preferential Proxy Routes From Core Application
**Files:**
- Delete: `src/app/api/earthquake/route.ts`
- Delete: `src/app/api/undersea-cables/route.ts`
- Delete: everything in `src/app/api/camera` codebase (`caltrans`, `extract`, `gdot`, `test`, `tfl`, `traffic`)
- [ ] **Step 1: Delete all plugin-specific Next.js API routes**
Run: `rm -rf src/app/api/earthquake`
Run: `rm -rf src/app/api/undersea-cables`
**WAIT**: For `src/app/api/camera`, we must physically copy the fetchers into `worldwideview-plugins` before we delete them.
Run: `cp -r src/app/api/camera/caltrans ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
Run: `cp -r src/app/api/camera/gdot ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
Run: `cp -r src/app/api/camera/tfl ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
Run: `rm -rf src/app/api/camera`
- [ ] **Step 2: Commit the deleted API routes**
```bash
git add src/app/api/earthquake src/app/api/undersea-cables src/app/api/camera
git commit -m "refactor!: strip preferential plugin APIs from core"
```
### Task 3: Migrate Earthquakes and Undersea Cables Plugins
**Files:**
- Modify: `../worldwideview-plugins/packages/wwv-plugin-earthquakes/src/index.ts`
- Modify: `../worldwideview-plugins/packages/wwv-plugin-undersea-cables/src/index.ts`
- [ ] **Step 1: Update Earthquakes plugin to direct browser fetch (Option A)**
In `../worldwideview-plugins/packages/wwv-plugin-earthquakes/src/index.ts`, replace the `/api/earthquake` fetch with the USGS direct URL.
```json
{
"instruction": "Replace the API fetch with direct USGS fetch and remove apiBasePath",
"replace_chunks": [
{
"start_line": 38,
"end_line": 40,
"target_content": " try {\n const res = await globalThis.fetch(`/api/earthquake`);\n if (!res.ok) {",
"replacement_content": " try {\n const res = await globalThis.fetch(`https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson`);\n if (!res.ok) {"
},
{
"start_line": 94,
"end_line": 96,
"target_content": " getServerConfig(): ServerPluginConfig {\n return { apiBasePath: \"/api/earthquake\", pollingIntervalMs: 120000, historyEnabled: false };\n }",
"replacement_content": " getServerConfig(): ServerPluginConfig {\n return { pollingIntervalMs: 120000, historyEnabled: false };\n }"
}
]
}
```
- [ ] **Step 2: Update Undersea Cables plugin to use Universal Proxy (Option B)**
In `../worldwideview-plugins/packages/wwv-plugin-undersea-cables/src/index.ts`:
```json
{
"instruction": "Proxy route to universal proxy",
"replace_chunks": [
{
"start_line": 35,
"end_line": 37,
"target_content": " // Proxy route to bypass CORS for Telegeography submarine cable map API\n const url = \"/api/undersea-cables\";\n ",
"replacement_content": " // Proxy route to bypass CORS for Telegeography submarine cable map API\n const targetUrl = encodeURIComponent(\"https://www.submarinecablemap.com/api/v3/cable/cable-geo.json\");\n const url = `/api/proxy?url=${targetUrl}`;\n "
}
]
}
```
- [ ] **Step 3: Commit the plugin migrations**
```bash
cd ../worldwideview-plugins
git add packages/wwv-plugin-earthquakes/src/index.ts packages/wwv-plugin-undersea-cables/src/index.ts
git commit -m "refactor: transition earthquake and undersea cables to decoupled fetching"
cd ../worldwideview
```
### Task 4: Refactor Camera Plugin to Fetch Natively
**Files:**
- Modify: `../worldwideview-plugins/packages/wwv-plugin-camera/src/index.ts`
- Delete: `caltrans`, `gdot`, `tfl` previously copied components (combine into `trafficFetchers.ts`)
- [ ] **Step 1: Consolidate the camera fetchers**
Create `../worldwideview-plugins/packages/wwv-plugin-camera/src/trafficFetchers.ts`.
Migrate the code from the `caltransFetcher.ts`, `gdotFetcher.ts`, and `tflFetcher.ts` files that we copied in Task 2.
Crucially, when doing `fetch(...)` in these fetchers, if the endpoint doesn't support CORS, wrap it in `/api/proxy?url=${encodeURIComponent(...) }` so the browser can fetch it. Ensure the data models align.
- [ ] **Step 2: Update `wwv-plugin-camera/src/index.ts` to call the fetchers natively**
In `../worldwideview-plugins/packages/wwv-plugin-camera/src/index.ts` function `loadTrafficCameras()`:
```json
{
"instruction": "Replace API fetch with native client-side parallel fetching",
"replace_chunks": [
{
"start_line": 106,
"end_line": 118,
"target_content": " private async loadTrafficCameras(): Promise<void> {\n try {\n const res = await fetch(\"/api/camera/traffic\");\n if (!res.ok) throw new Error(`API returned ${res.status}`);\n const data = await res.json();\n if (data.cameras && Array.isArray(data.cameras)) {\n this.sourceBuckets[\"default\"] = data.cameras.map(\n (f: unknown, i: number) => mapGeoJsonFeature(f, i, \"traffic\"),\n );\n }\n } catch (err) {\n console.warn(\"[CameraPlugin] Traffic cameras API failed:\", err);\n }",
"replacement_content": " private async loadTrafficCameras(): Promise<void> {\n try {\n const { fetchCaltrans, fetchGdot, fetchTfl } = await import(\"./trafficFetchers\");\n const [caltrans, gdot, tfl] = await Promise.allSettled([\n fetchCaltrans(), fetchGdot(), fetchTfl()\n ]);\n \n const cameras = [];\n if (caltrans.status === \"fulfilled\") cameras.push(...caltrans.value);\n if (gdot.status === \"fulfilled\") cameras.push(...gdot.value);\n if (tfl.status === \"fulfilled\") cameras.push(...tfl.value);\n\n if (cameras.length > 0) {\n this.sourceBuckets[\"default\"] = cameras.map(\n (f: unknown, i: number) => mapGeoJsonFeature(f, i, \"traffic\"),\n );\n }\n } catch (err) {\n console.warn(\"[CameraPlugin] Traffic cameras API failed:\", err);\n }"
}
]
}
```
- [ ] **Step 3: Remove the extra node API files from the plugin source tree**
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/caltrans`
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/gdot`
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/tfl`
- [ ] **Step 4: Commit Camera plugin refactoring**
```bash
cd ../worldwideview-plugins
git add packages/wwv-plugin-camera/src
git commit -m "feat: migrate traffic camera fetchers to client-side plugin bundle"
cd ../worldwideview
```
@@ -0,0 +1,118 @@
# Persistent Custom OSM Tags Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Allow users to persistently save custom OSM tags to local storage so they remain available across sessions, and track their usage via Umami analytics.
**Architecture:** We will use `useState` and `useEffect` in the `OSMSidebar` component to sync `customTags` to the browser's `localStorage`. When the user enters a custom tag, we'll store it, render it with a small delete button (so the list doesn't get cluttered over time), and fire an event to `window.umami.track`.
**Tech Stack:** React Hooks, `localStorage`, Umami Analytics
---
### Task 1: Add Custom Tag State and Persistence
**Files:**
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx`
- [ ] **Step 1: Add customTags state and persistence effects**
In `OSMSidebar.tsx`, below the existing `const [activeTags, setActiveTags] = useState<string[]>([]);` line, add:
```tsx
const [customTags, setCustomTags] = useState<string[]>([]);
React.useEffect(() => {
try {
const saved = localStorage.getItem("wwv_osm_custom_tags");
if (saved) setCustomTags(JSON.parse(saved));
} catch {}
}, []);
React.useEffect(() => {
localStorage.setItem("wwv_osm_custom_tags", JSON.stringify(customTags));
}, [customTags]);
```
- [ ] **Step 2: Include customTags in the rendered list**
Replace `const customTagMatch = searchText.includes("=") ? [searchText.trim()] : [];` and `const renderedTags = ...` with:
```tsx
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags, ...customTags]));
```
- [ ] **Step 3: Update Enter key handler to save tags and track**
Inside the `input`'s `onKeyDown` handler:
```tsx
onKeyDown={e => {
if (e.key === "Enter" && searchText.includes("=")) {
const tag = searchText.trim();
if (!activeTags.includes(tag)) {
setActiveTags(prev => [...prev, tag]);
}
if (!customTags.includes(tag)) {
setCustomTags(prev => [...prev, tag]);
try {
(window as any).umami?.track("osm-search-custom-tag", { tag });
} catch {}
}
setSearchText("");
}
}}
```
- [ ] **Step 4: Add a delete button to custom tags**
Inside the `.map(tag => {` block, update the `button` contents to include a delete span if it's a custom tag:
```tsx
<button
key={tag}
style={{
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
color: isActive ? "#fff" : "var(--text-secondary)",
padding: "4px 10px",
borderRadius: "14px",
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
fontSize: "11px",
cursor: "pointer",
transition: "all 0.2s",
display: "flex",
alignItems: "center",
gap: "4px"
}}
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
>
{tag.replace("=", ": ")}
{customTags.includes(tag) && (
<span
onClick={(e) => {
e.stopPropagation();
setCustomTags(prev => prev.filter(t => t !== tag));
setActiveTags(prev => prev.filter(t => t !== tag));
}}
style={{
marginLeft: "2px",
padding: "0 4px",
borderRadius: "50%",
background: "rgba(255,255,255,0.15)",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
×
</span>
)}
</button>
```
- [ ] **Step 5: Commit changes**
```bash
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
git commit -m "feat(osm-search): persist custom tags and track via umami"
```
@@ -0,0 +1,132 @@
# Robust Plugin Linking Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Ensure that when developers link local plugins using `wwv-cli link`, the main engine's database is automatically updated to prioritize the local code instead of accidentally loading the published version from the cloud CDN.
**Architecture:** We will implement a dedicated development API route in the main app (`/api/plugins/dev-link`) that allows the `wwv-cli` to safely push local plugin manifests directly into the `InstalledPlugin` database table without requiring Marketplace authentication. The CLI will be updated to make this request immediately after copying the bundle.
**Tech Stack:** Next.js API Routes, Prisma, Node.js `fetch`
---
### Task 1: Create the Dev-Link API Route
**Files:**
- Create: `c:\dev\worldwideview\src\app\api\plugins\dev-link\route.ts`
- [ ] **Step 1: Write the API Route**
```typescript
import { NextResponse } from "next/server";
import { upsertPlugin } from "@/lib/marketplace/repository";
import { validateManifest } from "@/core/plugins/validateManifest";
import { isPluginInstallEnabled } from "@/core/edition";
export async function POST(request: Request) {
// 1. Security Check: Only allow in development mode or local editions
if (process.env.NODE_ENV !== "development" && !isPluginInstallEnabled) {
return NextResponse.json({ error: "Dev-link is only available in development environments" }, { status: 403 });
}
try {
const body = await request.json();
const { manifest } = body;
if (!manifest || !manifest.id) {
return NextResponse.json({ error: "Invalid payload. 'manifest' with an 'id' is required." }, { status: 400 });
}
// 2. Validate the manifest
const validation = validateManifest(manifest);
if (!validation.valid) {
console.error(`[Dev-Link] Invalid manifest for ${manifest.id}:`, validation.errors);
return NextResponse.json({ error: "Invalid manifest", details: validation.errors }, { status: 400 });
}
// 3. Upsert into database
const config = JSON.stringify(manifest);
const record = await upsertPlugin(manifest.id, manifest.version || "1.0.0", config);
console.log(`[Dev-Link] Successfully synced local plugin config for: ${manifest.id}`);
return NextResponse.json({ success: true, pluginId: record.pluginId });
} catch (err) {
console.error("[Dev-Link] Server Error:", err);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
```
- [ ] **Step 2: Commit API Route**
```bash
git add src/app/api/plugins/dev-link/route.ts
git commit -m "feat(api): add dev-link route to sync local plugin manifests"
```
### Task 2: Update the CLI Link Command
**Files:**
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-cli\src\commands\link.ts`
- [ ] **Step 1: Add the sync request to linkCommand**
Find the `linkCommand` function. Below the `fs.writeFileSync` that writes `plugin.json` (around line 67), add a network request to sync the database.
```typescript
fs.writeFileSync(path.join(finalDestDir, 'plugin.json'), JSON.stringify(manifest, null, 2));
console.log(green(`✅ Proxy manifest injected to WWV instance: ${pluginId}`));
// --- NEW CODE: Sync with database ---
fetch('http://localhost:3000/api/plugins/dev-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ manifest })
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log(green(`✅ Database successfully synced to point to local files.`));
} else {
console.log(red(`⚠️ Warning: Database sync failed: ${data.error}`));
}
})
.catch(err => {
console.log(red(`⚠️ Warning: Could not reach dev server to sync DB. Is localhost:3000 running?`));
});
// --- END NEW CODE ---
```
- [ ] **Step 2: Rebuild the CLI**
```bash
cd packages/wwv-cli
pnpm build
```
- [ ] **Step 3: Commit CLI Update**
```bash
git add packages/wwv-cli/src/commands/link.ts
git commit -m "feat(cli): auto-sync local plugin manifests with engine database during link"
```
### Task 3: Test the Integration
- [ ] **Step 1: Run the Sync Command**
Run the updated sync command in the plugins repo to verify it pushes the manifest properly to the API.
```bash
cd c:\dev\worldwideview-plugins
pnpm run sync:all
```
- [ ] **Step 2: Verify Output**
Expected output in the plugins terminal should include:
`[wwv-plugin-osm-search] ✅ Database successfully synced to point to local files.`
Expected output in the main WorldWideView terminal should include:
`[Dev-Link] Successfully synced local plugin config for: osm-search`
@@ -0,0 +1,105 @@
# Phase 1: Database Adapter Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Modify Prisma schema and client initialization to support both SQLite (local/demo) and PostgreSQL (cloud).
**Architecture:** We use a pre-generation script to swap the Prisma provider based on `NEXT_PUBLIC_WWV_EDITION`. Abstract `src/lib/db.ts` to inject the correct adapter (better-sqlite3 vs pg) based on the edition.
**Tech Stack:** Prisma, PostgreSQL, SQLite.
---
### Task 1: Create Schema Swap Script
**Files:**
- Create: `scripts/prepare-schema.mjs`
- Modify: `package.json`
- [ ] **Step 1: Create a schema swap script**
```javascript
// scripts/prepare-schema.mjs
import fs from 'fs';
import path from 'path';
const schemaPath = path.join(process.cwd(), 'prisma', 'schema.prisma');
let schema = fs.readFileSync(schemaPath, 'utf-8');
if (process.env.NEXT_PUBLIC_WWV_EDITION === 'cloud') {
schema = schema.replace(/provider\s*=\s*"sqlite"/, 'provider = "postgresql"');
console.log("Swapped Prisma provider to PostgreSQL for cloud edition.");
} else {
// Revert back to sqlite just in case it was swapped
schema = schema.replace(/provider\s*=\s*"postgresql"/, 'provider = "sqlite"');
}
fs.writeFileSync(schemaPath, schema);
```
- [ ] **Step 2: Update package.json scripts**
Modify `package.json` to run the prepare script before prisma generate:
```json
"pregenerate": "node scripts/prepare-schema.mjs",
"generate": "prisma generate"
```
### Task 2: Create DB Adapter Factory
**Files:**
- Modify: `src/lib/db.ts`
- Create: `src/core/adapters/db.ts`
- [ ] **Step 1: Create the adapter factory**
```typescript
// src/core/adapters/db.ts
import { isCloud } from "@/core/edition";
import { PrismaClient } from "../../generated/prisma/client";
export function createPrismaClient(): PrismaClient {
if (isCloud) {
// Cloud uses native pg driver or connection pool via standard url
return new PrismaClient({
datasources: {
db: {
url: process.env.DATABASE_URL,
},
},
});
} else {
// Local uses better-sqlite3 adapter (already set up)
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || "file:./data/wwv.db",
});
return new PrismaClient({ adapter });
}
}
```
- [ ] **Step 2: Refactor `src/lib/db.ts`**
```typescript
// src/lib/db.ts
import { PrismaClient } from "../generated/prisma/client";
import { createPrismaClient } from "@/core/adapters/db";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
```
- [ ] **Step 3: Commit**
```bash
git add package.json scripts/ src/lib/ src/core/adapters/
git commit -m "feat: multi-provider database adapter for cloud"
```
@@ -0,0 +1,152 @@
# Phase 2: Tenant System Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement single-container multi-tenancy using PostgreSQL Row-Level Security (RLS) and Next.js middleware to resolve subdomains.
**Architecture:** Middleware extracts the subdomain (e.g., `acme.app.worldwideview.dev`) and sets an `x-tenant-id` header. Prisma extension wraps all queries to `SET LOCAL app.tenant_id = '...'` to enforce RLS in PostgreSQL.
**Tech Stack:** Next.js Middleware, Prisma Client Extensions, PostgreSQL RLS.
---
### Task 1: Database Schema Tenant Column
**Files:**
- Modify: `prisma/schema.prisma`
- [ ] **Step 1: Add tenant columns to models**
Add `tenantId String?` to all relevant models (`InstalledPlugin`, `Favorite`, `Setting`).
For local SQLite, `tenantId` is ignored (null). For cloud, it's enforced via RLS.
```prisma
model InstalledPlugin {
id String @id @default(uuid())
tenantId String? // NULL for local, UUID for cloud
pluginId String
version String
config String @default("{}")
enabled Boolean @default(true)
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([tenantId, pluginId]) // Replaces @@unique([pluginId])
@@map("installed_plugins")
}
model Setting {
id String @id @default(uuid())
tenantId String?
key String
value String
@@unique([tenantId, key])
@@map("settings")
}
```
- [ ] **Step 2: Update primary keys if needed**
Ensure `Setting` uses `id` as `@id` instead of `key` since `key` is no longer globally unique (it's unique per tenant).
- [ ] **Step 3: Commit**
```bash
git add prisma/schema.prisma
git commit -m "feat: add tenantId columns to schema"
```
### Task 2: Subdomain Middleware
**Files:**
- Modify: `src/middleware.ts` (or create if doesn't exist)
- [ ] **Step 1: Create Next.js middleware**
```typescript
// src/middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(req: NextRequest) {
const hostname = req.headers.get("host") || "";
// Extract subdomain if on cloud
if (process.env.NEXT_PUBLIC_WWV_EDITION === "cloud") {
const isApp = hostname.includes(".app.worldwideview.dev");
if (isApp) {
const subdomain = hostname.replace(".app.worldwideview.dev", "");
if (subdomain && subdomain !== "app") {
const res = NextResponse.next();
res.headers.set("x-tenant-subdomain", subdomain);
return res;
}
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico).*)"],
};
```
### Task 3: Prisma RLS Extension
**Files:**
- Modify: `src/core/adapters/db.ts`
- [ ] **Step 1: Wrap Prisma with RLS extension for Cloud**
Modify `createPrismaClient` to wrap the client if in cloud mode:
```typescript
// src/core/adapters/db.ts
import { isCloud } from "@/core/edition";
import { PrismaClient } from "../../generated/prisma/client";
import { headers } from "next/headers";
export function createPrismaClient() {
if (isCloud) {
const client = new PrismaClient({
datasources: { db: { url: process.env.DATABASE_URL } },
});
// Use Prisma Client Extension to inject RLS
return client.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
const headersList = await headers();
const tenantSubdomain = headersList.get("x-tenant-subdomain");
if (tenantSubdomain) {
const [, result] = await client.$transaction([
client.$executeRaw`SELECT set_config('app.tenant_id', ${tenantSubdomain}, TRUE)`,
query(args),
]);
return result;
}
return query(args);
},
},
},
});
} else {
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || "file:./data/wwv.db",
});
return new PrismaClient({ adapter });
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/middleware.ts src/core/adapters/db.ts
git commit -m "feat: multi-tenant middleware and RLS prisma extension"
```
@@ -0,0 +1,117 @@
# Phase 3: Auth Upgrade Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Integrate Supabase Auth for the cloud edition while maintaining the existing Credentials provider for the local edition.
**Architecture:** Use the NextAuth adapter pattern. Modify `src/lib/auth.ts` to dynamically include the Supabase provider and Supabase Adapter if `isCloud` is true.
**Tech Stack:** NextAuth v5, Supabase Auth.
---
### Task 1: Supabase Adapter Integration
**Files:**
- Modify: `src/lib/auth.ts`
- Modify: `package.json`
- [ ] **Step 1: Install Supabase NextAuth Adapter**
Run: `pnpm add @auth/supabase-adapter`
- [ ] **Step 2: Update `src/lib/auth.ts` to branch providers**
```typescript
// src/lib/auth.ts
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { compareSync } from "bcryptjs";
import { timingSafeEqual } from "crypto";
import { prisma } from "@/lib/db";
import { isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
import { authConfig } from "@/lib/auth.config";
import { SupabaseAdapter } from "@auth/supabase-adapter";
// Extract local credentials logic to a helper
const localCredentialsProvider = Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
// ... existing credentials logic ...
return null;
}
});
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
session: { strategy: "jwt" },
adapter: isCloud ? SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
}) : undefined,
providers: isCloud
? [] // If using standard GoTrue via custom logic, or add providers here if using NextAuth OAuth
: [localCredentialsProvider],
callbacks: {
...authConfig.callbacks,
// ... existing callbacks ...
},
});
```
### Task 2: Login Form Cloud Adaptation
**Files:**
- Modify: `src/app/login/page.tsx`
- Modify: `src/app/login/actions.ts`
- [ ] **Step 1: Update Login Form for Cloud Mode**
```typescript
// src/app/login/actions.ts
import { signIn } from "@/lib/auth";
import { isCloud } from "@/core/edition";
import { createClient } from "@supabase/supabase-js";
export async function loginAction(formData: FormData) {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
if (isCloud) {
// Use Supabase GoTrue
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) return { success: false, error: error.message };
return { success: true };
} else {
// Use NextAuth Credentials
try {
await signIn("credentials", {
email,
password,
redirect: false,
});
return { success: true };
} catch (error: any) {
return { success: false, error: "Invalid credentials" };
}
}
}
```
- [ ] **Step 2: Commit**
```bash
git add package.json pnpm-lock.yaml src/lib/auth.ts src/app/login/actions.ts
git commit -m "feat: supabase auth adapter for cloud edition"
```
@@ -0,0 +1,99 @@
# Phase 4: License Keys & Tiers Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement RSA-signed JWT license keys to gate Pro and Enterprise features on both Local and Cloud editions.
**Architecture:** A hardcoded public key verifies the JWT. The JWT payload dictates the tier (`free`, `pro`, `enterprise`) and expiration. The `uiSlice` state provides easy access to the active tier.
**Tech Stack:** `jose` for JWT verification.
---
### Task 1: License Verification Module
**Files:**
- Create: `src/core/license/verifyLicense.ts`
- Create: `src/core/license/tiers.ts`
- [ ] **Step 1: Create Tier Definitions**
```typescript
// src/core/license/tiers.ts
export type LicenseTier = "free" | "pro" | "team" | "enterprise";
export interface TierFeatures {
maxUsers: number;
storageQuotaBytes: number;
historyEnabled: boolean;
snapshotCapture: boolean;
customDomains: boolean;
}
export const TIER_FEATURES: Record<LicenseTier, TierFeatures> = {
free: { maxUsers: 3, storageQuotaBytes: 500 * 1024 * 1024, historyEnabled: false, snapshotCapture: false, customDomains: false },
pro: { maxUsers: 20, storageQuotaBytes: 5 * 1024 * 1024 * 1024, historyEnabled: true, snapshotCapture: true, customDomains: false },
team: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: false },
enterprise: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: true },
};
```
- [ ] **Step 2: Create JWT Verification**
```typescript
// src/core/license/verifyLicense.ts
import * as jose from "jose";
// Public key is safe to hardcode/ship to client
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu... (generate real one)
-----END PUBLIC KEY-----`;
export interface LicensePayload {
tier: "pro" | "team" | "enterprise";
exp: number;
org: string;
}
export async function verifyLicenseKey(token: string): Promise<LicensePayload | null> {
try {
const publicKey = await jose.importSPKI(PUBLIC_KEY_PEM, "RS256");
const { payload } = await jose.jwtVerify(token, publicKey);
return payload as unknown as LicensePayload;
} catch {
return null;
}
}
```
### Task 2: State Integration
**Files:**
- Modify: `src/core/state/configSlice.ts`
- Modify: `src/components/panels/SettingsPanel.tsx`
- [ ] **Step 1: Add license to configSlice**
```typescript
// src/core/state/configSlice.ts
// Add to DataConfig:
export interface DataConfig {
// ... existing ...
licenseKey: string | null;
activeTier: "free" | "pro" | "team" | "enterprise";
}
// Add to initial state:
// licenseKey: null, activeTier: "free"
```
- [ ] **Step 2: Add License input UI**
Add a text input in `SettingsPanel` for users to paste their license key, dispatching an action to verify and save it to the DB and Zustand store.
- [ ] **Step 3: Commit**
```bash
git add src/core/license/ src/core/state/configSlice.ts src/components/panels/
git commit -m "feat: rsa jwt license key verification"
```
@@ -0,0 +1,76 @@
# Phase 5: Cloud Deployment Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Create the Docker Compose configuration and routing layer necessary to run the multi-tenant cloud application.
**Architecture:** Use Traefik or nginx to route wildcard subdomains to the Next.js container. Provide environment variable overrides.
**Tech Stack:** Docker Compose, Traefik.
---
### Task 1: Docker Compose Setup
**Files:**
- Create: `deploy/cloud/docker-compose.yml`
- Create: `deploy/cloud/.env.example`
- [ ] **Step 1: Create compose file**
```yaml
# deploy/cloud/docker-compose.yml
services:
wwv-cloud:
image: ghcr.io/silvertakana/worldwideview:latest
restart: always
environment:
NEXT_PUBLIC_WWV_EDITION: cloud
DATABASE_URL: ${SUPABASE_PG_URL}
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
labels:
- "traefik.enable=true"
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`)"
- "traefik.http.routers.wwv.entrypoints=websecure"
- "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
traefik:
image: traefik:v3.0
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
- "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
- "letsencrypt:/letsencrypt"
volumes:
letsencrypt:
```
- [ ] **Step 2: Create example env file**
```env
# deploy/cloud/.env.example
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
SUPABASE_URL=https://xyz.supabase.co
SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
ACME_EMAIL=[email protected]
```
- [ ] **Step 3: Commit**
```bash
git add deploy/
git commit -m "chore: add cloud deployment compose configuration"
```
@@ -0,0 +1,77 @@
# Phase 6: Stripe Billing Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement Stripe subscriptions for the cloud edition, generating license keys upon payment.
**Architecture:** Use Stripe Checkout Sessions for upgrades. Use Stripe Webhooks to listen for `checkout.session.completed` and `customer.subscription.updated` to update the user's tier in the database and generate their JWT license key.
**Tech Stack:** Stripe Node SDK, Next.js API Routes.
---
### Task 1: Stripe Integration
**Files:**
- Modify: `package.json`
- Create: `src/lib/stripe/client.ts`
- Create: `src/app/api/billing/webhook/route.ts`
- Create: `src/app/api/billing/checkout/route.ts`
- [ ] **Step 1: Install SDK**
Run: `pnpm add stripe`
- [ ] **Step 2: Create Stripe Client**
```typescript
// src/lib/stripe/client.ts
import Stripe from "stripe";
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-04-10",
});
```
- [ ] **Step 3: Create Checkout Route**
```typescript
// src/app/api/billing/checkout/route.ts
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
export async function POST(req: Request) {
const session = await auth();
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
const { priceId } = await req.json();
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
client_reference_id: session.user.id,
});
return NextResponse.json({ url: checkoutSession.url });
}
```
- [ ] **Step 4: Create Webhook Handler**
```typescript
// src/app/api/billing/webhook/route.ts
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
// ... basic webhook payload verification and logging ...
```
- [ ] **Step 5: Commit**
```bash
git add package.json pnpm-lock.yaml src/lib/stripe/ src/app/api/billing/
git commit -m "feat: stripe checkout and webhook integration"
```
@@ -0,0 +1,51 @@
# Cloud Hosting & Plans — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Transform WorldWideView from a local-only SQLite app into a multi-tenant cloud platform with `[user].app.worldwideview.dev` subdomains, PostgreSQL RLS isolation, Supabase Auth, cryptographic license keys, and Stripe billing.
**Architecture:** Single Docker container serves all tenants. nginx wildcard routes `*.app.worldwideview.dev` → Next.js. Middleware reads subdomain → sets `tenant_id` → PostgreSQL RLS scopes all queries. Same codebase, three editions (`local`/`cloud`/`demo`), adapter pattern for DB/auth/storage/tenant.
**Tech Stack:** Next.js 16, Prisma (multi-provider), PostgreSQL + RLS, Supabase Auth, Supabase Storage, RSA-signed JWTs (license keys), Stripe Checkout + Webhooks, nginx wildcard SSL.
---
## Current State Summary
| Component | Status |
|---|---|
| Edition system (`edition.ts`) | ✅ `local`/`cloud`/`demo` flags exist |
| Auth (`src/lib/auth.ts`) | ✅ Credentials provider (bcrypt + SQLite) |
| Database (`src/lib/db.ts`) | ⚠️ Hardcoded to `better-sqlite3` adapter |
| Prisma schema | ⚠️ `provider = "sqlite"` only |
| Tenant isolation | ❌ Not implemented |
| Cloud auth (Supabase) | ❌ Not implemented |
| License keys | ❌ Not implemented |
| Storage adapter | ❌ Not implemented |
| Stripe billing | ❌ Not implemented |
| Cloud deployment repo | ❌ Not created |
---
## Phase Breakdown
Each phase is a self-contained deliverable. Phases 1–3 are foundational. Phases 4–6 add monetization.
| Phase | File | What It Builds | Depends On |
|---|---|---|---|
| 1 | [01-database-adapter.md](./01-database-adapter.md) | Prisma multi-provider (SQLite + PostgreSQL) | Nothing |
| 2 | [02-tenant-system.md](./02-tenant-system.md) | RLS isolation, middleware, tenant context | Phase 1 |
| 3 | [03-auth-upgrade.md](./03-auth-upgrade.md) | Supabase Auth provider for cloud edition | Phase 1 |
| 4 | [04-license-keys.md](./04-license-keys.md) | RSA-signed JWT license keys, tier gating | Phase 1 |
| 5 | [05-cloud-deployment.md](./05-cloud-deployment.md) | `worldwideview-cloud` repo, nginx, Docker Compose | Phases 1–3 |
| 6 | [06-stripe-billing.md](./06-stripe-billing.md) | Stripe Checkout, webhooks, subscription management | Phases 3–4 |
---
## Key Design Decisions
1. **Adapter pattern** — Three thin files (`src/core/adapters/db.ts`, `auth.ts`, `storage.ts`, `tenant.ts`) branch on `edition`. Everything else is edition-unaware.
2. **Prisma multi-provider** — Use a build-time script to swap the provider in `schema.prisma` before generating the client if building for cloud. One schema, two providers.
3. **RLS over application-level filtering** — PostgreSQL physically refuses cross-tenant data. Even bugs can't leak.
4. **License keys are RSA JWTs** — Marketplace signs with private key; app verifies with hardcoded public key. No phone-home required.
5. **Stripe is the only payment processor** — Checkout Sessions for signup, Webhooks for lifecycle events.
@@ -0,0 +1,533 @@
# WorldWideView CLI Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Build `@worldwideview/cli`, a standalone CLI tool that scaffolds, hot-reloads, and packages WWV plugins using the Chrome Extension model, completely decoupled from the main monorepo build pipeline.
**Architecture:** A Node.js CLI built with `commander`. It uses `vite` programmatically to serve and build plugins. For dev mode, it attaches a `ws` WebSocket server to the Vite dev server to broadcast hot-reload events to the running WWV web app, and communicates with `/api/dev/load-unpacked` to inject the plugin. Publishing creates a `.wwvpkg` ZIP archive via `archiver`.
**Tech Stack:** Node.js, TypeScript, Commander, Vite, WebSocket (`ws`), Archiver, Vitest.
---
### Task 1: Initialize Package & CLI Entry Point
**Files:**
- Create: `packages/wwv-cli/package.json`
- Create: `packages/wwv-cli/tsconfig.json`
- Create: `packages/wwv-cli/bin/wwv.js`
- Create: `packages/wwv-cli/src/index.ts`
- Create: `packages/wwv-cli/tests/index.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/index.test.ts
import { describe, it, expect } from "vitest";
import { execSync } from "child_process";
import path from "path";
describe("wwv cli", () => {
it("should print help information", () => {
const binPath = path.resolve(__dirname, "../bin/wwv.js");
const output = execSync(`node ${binPath} --help`).toString();
expect(output).toContain("Usage: wwv [options] [command]");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test`
Expected: FAIL (File not found or missing package.json setup)
- [ ] **Step 3: Write minimal implementation**
```json
// packages/wwv-cli/package.json
{
"name": "@worldwideview/cli",
"version": "1.0.0",
"bin": { "wwv": "./bin/wwv.js" },
"scripts": {
"build": "tsc",
"test": "vitest run"
},
"dependencies": {
"commander": "^11.1.0"
},
"devDependencies": {
"typescript": "^5.0.0",
"vitest": "^1.0.0",
"@types/node": "^20.0.0"
}
}
```
```json
// packages/wwv-cli/tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
```
```javascript
// packages/wwv-cli/bin/wwv.js
#!/usr/bin/env node
require('../dist/index.js');
```
```typescript
// packages/wwv-cli/src/index.ts
import { Command } from "commander";
const program = new Command();
program
.name("wwv")
.description("WorldWideView Plugin CLI")
.version("1.0.0");
program.parse();
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm install && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): initialize cli package and entry point"
```
---
### Task 2: Implement `wwv create` (Scaffolding)
**Files:**
- Create: `packages/wwv-cli/src/commands/create.ts`
- Create: `packages/wwv-cli/tests/create.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:10-15`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/create.test.ts
import { describe, it, expect, afterEach } from "vitest";
import { createPlugin } from "../src/commands/create";
import fs from "fs";
import path from "path";
describe("create command", () => {
const testDir = path.join(__dirname, "test-plugin");
afterEach(() => {
if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
});
it("should scaffold a new plugin folder with manifest and index.ts", async () => {
await createPlugin("test-plugin", __dirname);
expect(fs.existsSync(path.join(testDir, "wwv-manifest.json"))).toBe(true);
expect(fs.existsSync(path.join(testDir, "src", "index.ts"))).toBe(true);
const manifest = JSON.parse(fs.readFileSync(path.join(testDir, "wwv-manifest.json"), "utf-8"));
expect(manifest.id).toBe("test-plugin");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/create.test.ts`
Expected: FAIL ("createPlugin is not defined")
- [ ] **Step 3: Write minimal implementation**
```typescript
// packages/wwv-cli/src/commands/create.ts
import fs from "fs";
import path from "path";
export async function createPlugin(name: string, basePath: string = process.cwd()) {
const targetDir = path.join(basePath, name);
if (fs.existsSync(targetDir)) {
throw new Error(`Directory ${name} already exists`);
}
fs.mkdirSync(targetDir, { recursive: true });
fs.mkdirSync(path.join(targetDir, "src"), { recursive: true });
const manifest = {
manifest_version: 1,
id: name,
name: name,
version: "1.0.0",
description: "A WorldWideView plugin",
type: "data-layer",
category: "custom",
icon: "Box",
capabilities: ["data:own"],
entry: "dist/frontend.mjs",
dev_entry: "src/index.ts"
};
fs.writeFileSync(
path.join(targetDir, "wwv-manifest.json"),
JSON.stringify(manifest, null, 2)
);
const indexContent = `export default class MyPlugin {
id = "${name}";
name = "${name}";
version = "1.0.0";
category = "custom";
icon = "Box";
async initialize(ctx) {
console.log("Initialized", this.id);
}
destroy() {}
async fetch(timeRange) {
return [];
}
getPollingInterval() {
return 5000;
}
getLayerConfig() {
return { color: "#3b82f6", clusterEnabled: true, clusterDistance: 50 };
}
renderEntity(entity) {
return { type: "point", color: "#3b82f6", size: 6 };
}
}
`;
fs.writeFileSync(path.join(targetDir, "src", "index.ts"), indexContent);
console.log(`Plugin ${name} scaffolded successfully in ./${name}`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { createPlugin } from "./commands/create";
program
.command("create <name>")
.description("Scaffold a new WorldWideView plugin")
.action(async (name) => {
try {
await createPlugin(name);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement create command for scaffolding"
```
---
### Task 3: Implement `wwv dev` (Vite Server + WebSocket)
**Files:**
- Create: `packages/wwv-cli/src/commands/dev.ts`
- Create: `packages/wwv-cli/tests/dev.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:25-30`
- Modify: `packages/wwv-cli/package.json:13-15` (Add vite, ws)
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/dev.test.ts
import { describe, it, expect, vi } from "vitest";
import { startDevServer } from "../src/commands/dev";
// Mock vite and ws
vi.mock("vite", () => ({
createServer: vi.fn().mockResolvedValue({
listen: vi.fn(),
httpServer: { on: vi.fn() },
ws: { on: vi.fn() }
})
}));
describe("dev command", () => {
it("should export startDevServer function", () => {
expect(typeof startDevServer).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/dev.test.ts`
Expected: FAIL ("startDevServer is not defined")
- [ ] **Step 3: Write minimal implementation**
Add `vite` and `ws` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
```json
"dependencies": {
"commander": "^11.1.0",
"vite": "^5.0.0",
"ws": "^8.16.0"
},
"devDependencies": {
"@types/ws": "^8.5.10"
}
```
```typescript
// packages/wwv-cli/src/commands/dev.ts
import fs from "fs";
import path from "path";
import { createServer } from "vite";
import { WebSocketServer } from "ws";
export async function startDevServer(targetUrl: string = "http://localhost:3000") {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
const port = 24601;
// Start Vite Dev Server
const vite = await createServer({
root: cwd,
server: { port, cors: true, hmr: false }, // We handle HMR via custom WS
plugins: [{
name: 'wwv-hmr',
handleHotUpdate({ server }) {
// When Vite detects file changes, broadcast to our custom WS
wss.clients.forEach(client => {
client.send(JSON.stringify({ type: "plugin:updated", pluginId: manifest.id }));
});
return []; // Prevent default Vite HMR
}
}]
});
await vite.listen();
// Attach custom WebSocket server for WWV DevModeSubscriber
const wss = new WebSocketServer({ server: vite.httpServer as any, path: "/__wwv_dev__" });
wss.on("connection", (ws) => {
console.log(`[WWV CLI] Connected to WorldWideView instance`);
ws.send(JSON.stringify({ type: "plugin:added", manifest }));
});
// Notify WorldWideView via API
try {
const fetch = (await import('node-fetch')).default || globalThis.fetch;
await fetch(`${targetUrl}/api/dev/load-unpacked`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...manifest,
entry: `http://localhost:${port}/${manifest.dev_entry || "src/index.ts"}`
})
});
console.log(`[WWV CLI] Registered with WorldWideView at ${targetUrl}`);
} catch (err: any) {
console.error(`[WWV CLI] Failed to connect to ${targetUrl}: ${err.message}`);
console.log(`Waiting for WorldWideView to connect via WebSocket...`);
}
console.log(`\n🚀 Dev server running on http://localhost:${port}`);
console.log(`Watching for file changes in ${cwd}...\n`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { startDevServer } from "./commands/dev";
program
.command("dev")
.description("Start the plugin development server with hot-reload")
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
.action(async (options) => {
try {
await startDevServer(options.target);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement dev command with vite and websockets"
```
---
### Task 4: Implement `wwv publish` (.wwvpkg creation)
**Files:**
- Create: `packages/wwv-cli/src/commands/publish.ts`
- Create: `packages/wwv-cli/tests/publish.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:40-45`
- Modify: `packages/wwv-cli/package.json:16-17` (Add archiver)
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/publish.test.ts
import { describe, it, expect } from "vitest";
import { buildPackage } from "../src/commands/publish";
describe("publish command", () => {
it("should export buildPackage function", () => {
expect(typeof buildPackage).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/publish.test.ts`
Expected: FAIL ("buildPackage is not defined")
- [ ] **Step 3: Write minimal implementation**
Add `archiver` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
```json
"dependencies": {
"archiver": "^7.0.1"
},
"devDependencies": {
"@types/archiver": "^6.0.2"
}
```
```typescript
// packages/wwv-cli/src/commands/publish.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import archiver from "archiver";
export async function buildPackage() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Building production bundle...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
const outputPath = path.join(cwd, pkgName);
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver("zip", { zlib: { level: 9 } });
output.on("close", () => resolve());
archive.on("error", (err) => reject(err));
archive.pipe(output);
archive.file(manifestPath, { name: "wwv-manifest.json" });
archive.directory(path.join(cwd, "dist"), "dist");
if (fs.existsSync(path.join(cwd, "data"))) {
archive.directory(path.join(cwd, "data"), "data");
}
archive.finalize();
});
console.log(`\n🎉 Success! Package created at ${outputPath}`);
console.log(`You can now upload this file to the WorldWideView Marketplace.`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { buildPackage } from "./commands/publish";
program
.command("publish")
.description("Build and package the plugin into a .wwvpkg file")
.action(async () => {
try {
await buildPackage();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement publish command for wwvpkg creation"
```
@@ -0,0 +1,323 @@
# Split CLI Publish into Package and Publish Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Split the CLI publish command into `package` (for local .wwvpkg zip creation) and `publish` (for NPM distribution and marketplace registry updates).
**Architecture:**
The current `publish` command creates a `.wwvpkg` file. We will rename this functionality to the `package` command. Then, we will create a true `publish` command that handles building the plugin, automatically generating a valid `package.json` from the `wwv-manifest.json`, running `npm publish` via a child process, and finally notifying the marketplace of the new release.
**Tech Stack:** TypeScript, Vite, Node.js `child_process`, Node.js `fs`.
---
### Task 1: Rename current publish to package
We will rename the file and its internal function from `buildPackage` to `packagePlugin`.
**Files:**
- Modify: `packages/wwv-cli/src/commands/publish.ts` -> rename to `packages/wwv-cli/src/commands/package.ts`
- Modify: `packages/wwv-cli/tests/publish.test.ts` -> rename to `packages/wwv-cli/tests/package.test.ts`
- [ ] **Step 1: Rename the command file and update function name**
```typescript
// packages/wwv-cli/src/commands/package.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import archiver from "archiver";
export async function packagePlugin() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Building production bundle...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
const outputPath = path.join(cwd, pkgName);
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver("zip", { zlib: { level: 9 } });
output.on("close", () => resolve());
archive.on("error", (err) => reject(err));
archive.pipe(output);
archive.file(manifestPath, { name: "wwv-manifest.json" });
archive.directory(path.join(cwd, "dist"), "dist");
if (fs.existsSync(path.join(cwd, "data"))) {
archive.directory(path.join(cwd, "data"), "data");
}
archive.finalize();
});
console.log(`\n🎉 Success! Package created at ${outputPath}`);
console.log(`You can use this file to sideload the plugin into your WWV instance.`);
}
```
- [ ] **Step 2: Rename and update the test**
```typescript
// packages/wwv-cli/tests/package.test.ts
import { describe, it, expect } from "vitest";
import { packagePlugin } from "../src/commands/package";
describe("package command", () => {
it("should export packagePlugin function", () => {
expect(typeof packagePlugin).toBe("function");
});
});
```
- [ ] **Step 3: Remove old files**
Run: `git rm packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts`
Expected: Files deleted.
- [ ] **Step 4: Commit**
```bash
git add packages/wwv-cli/src/commands/package.ts packages/wwv-cli/tests/package.test.ts
git commit -m "refactor(wwv-cli): rename publish to package for wwvpkg creation"
```
---
### Task 2: Implement true NPM Publish command
**Files:**
- Create: `packages/wwv-cli/src/commands/publish.ts`
- Create: `packages/wwv-cli/tests/publish.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/publish.test.ts
import { describe, it, expect, vi } from "vitest";
import { publishToNpm } from "../src/commands/publish";
vi.mock("child_process", () => ({
execSync: vi.fn()
}));
vi.mock("vite", () => ({
build: vi.fn().mockResolvedValue({})
}));
describe("publish command", () => {
it("should export publishToNpm function", () => {
expect(typeof publishToNpm).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
Expected: FAIL because `publishToNpm` does not exist.
- [ ] **Step 3: Write the publish implementation**
```typescript
// packages/wwv-cli/src/commands/publish.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import { execSync } from "child_process";
export async function publishToNpm() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Compiling bundle for NPM...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
console.log(`[WWV CLI] Generating package.json...`);
// Create a temporary package.json required for NPM publish
const packageJsonPath = path.join(cwd, "package.json");
const packageJson = {
name: manifest.id, // e.g. @username/my-plugin
version: manifest.version,
description: manifest.description,
main: "dist/frontend.mjs",
type: "module",
files: ["dist", "wwv-manifest.json", "data"],
keywords: ["worldwideview", "plugin", manifest.category],
author: manifest.author || ""
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
console.log(`[WWV CLI] Publishing to NPM...`);
try {
execSync(`npm publish --access public`, { stdio: "inherit", cwd });
} catch (err) {
console.error(`[WWV CLI] NPM publish failed. Please ensure you are logged in via 'npm login'.`);
throw err;
} finally {
// Clean up the generated package.json so it doesn't clutter the dev's repo
fs.unlinkSync(packageJsonPath);
}
console.log(`[WWV CLI] Notifying WorldWideView Marketplace...`);
try {
const targetUrl = process.env.WWV_MARKETPLACE_URL || "https://marketplace.worldwideview.dev";
await fetch(`${targetUrl}/api/webhooks/npm-publish`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pluginId: manifest.id, version: manifest.version })
});
console.log(`[WWV CLI] Marketplace notified.`);
} catch (err: any) {
console.warn(`[WWV CLI] Could not notify marketplace: ${err.message}. It will be indexed on the next sweep.`);
}
console.log(`\n🚀 Success! Version ${manifest.version} published globally to NPM.`);
}
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts
git commit -m "feat(wwv-cli): implement npm publish and marketplace webhook ping"
```
---
### Task 3: Update CLI Entry Point
**Files:**
- Modify: `packages/wwv-cli/src/index.ts:36-50`
- [ ] **Step 1: Write the updated entry point logic**
Replace the existing `publish` command logic with both `package` and `publish`:
```typescript
// Edit packages/wwv-cli/src/index.ts
import { Command } from "commander";
import { createPlugin } from "./commands/create";
import { startDevServer } from "./commands/dev";
import { packagePlugin } from "./commands/package";
import { publishToNpm } from "./commands/publish";
const program = new Command();
program
.name("wwv")
.description("WorldWideView Plugin CLI")
.version("1.0.0");
program
.command("create <name>")
.description("Scaffold a new WorldWideView plugin")
.action(async (name) => {
try {
await createPlugin(name);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("dev")
.description("Start the plugin development server with hot-reload")
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
.action(async (options) => {
try {
await startDevServer(options.target);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("package")
.description("Build and package the plugin into a .wwvpkg file for sideloading")
.action(async () => {
try {
await packagePlugin();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("publish")
.description("Publish the plugin to NPM and notify the WWV Marketplace")
.action(async () => {
try {
await publishToNpm();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program.parse();
```
- [ ] **Step 2: Build to verify no TypeScript errors**
Run: `pnpm run build` inside `packages/wwv-cli`
Expected: Clean build.
- [ ] **Step 3: Commit**
```bash
git add packages/wwv-cli/src/index.ts
git commit -m "feat(wwv-cli): register package and npm publish commands"
```
@@ -0,0 +1,53 @@
# Prisma 7 Setup Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Finalize the Prisma 7 adapter architecture by removing legacy `url` parameters from the schema, syncing the local database, and validating the end-to-end connection.
**Architecture:** Prisma 7 strictly separates connection logic from the schema. The schema only defines the provider (`postgresql`), while connection strings for CLI commands like `db push` are handled by `prisma.config.ts`, and runtime connections are handled by the explicit `@prisma/adapter-pg` driver instance passed to the `PrismaClient` constructor.
**Tech Stack:** Prisma 7, PostgreSQL, Next.js, Node.js
---
### Task 1: Update Prisma Schema
**Files:**
- Modify: `prisma/schema.prisma:5-8`
- [ ] **Step 1: Remove the legacy `url` property from the datasource block**
```prisma
datasource db {
provider = "postgresql"
}
```
### Task 2: Push Schema to Local Database
- [ ] **Step 1: Execute Prisma db push to create the tables in the newly running Docker Postgres container**
Run: `npx dotenv-cli -e .env.local -- npx prisma db push`
Expected: PASS with "Your database is now in sync with your schema."
### Task 3: Generate Prisma Client
- [ ] **Step 1: Regenerate the Prisma Client types to ensure they match the schema**
Run: `npx dotenv-cli -e .env.local -- npx prisma generate`
Expected: PASS with "Generated Prisma Client"
### Task 4: Verify End-to-End Connection
- [ ] **Step 1: Run the user management script to prove the `adapter-pg` runtime can connect and query the new tables**
Run: `npx tsx --env-file=.env.local scripts/manage-users.ts list`
Expected: PASS with no errors (it should just exit silently if there are no users, rather than throwing a `P2021 TableDoesNotExist` or `P1001` error).
### Task 5: Restart the Development Server
- [ ] **Step 1: Restart the Next.js dev server**
Because the server has been running while we were debugging the `PrismaClientInitializationError`, Webpack may have cached the broken client. We need to kill the current `pnpm run dev` and start it fresh so we can test the API routes in the browser.
Run: Terminate the current `pnpm run dev` terminal, then run: `pnpm run dev`
Expected: Next.js starts successfully without any Prisma instantiation crashes.
@@ -0,0 +1,618 @@
# Unify Database Adapter (PostgreSQL-Only) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
**Goal:** Replace the dual SQLite/PostgreSQL database system with a single PostgreSQL adapter, using Prisma's built-in `prisma dev` for zero-install local development.
**Architecture:** The app currently has two database paths — `@prisma/adapter-better-sqlite3` for local and `@prisma/adapter-pg` for cloud — which causes constant migration conflicts and config drift. We unify to `@prisma/adapter-pg` everywhere. Local developers use `npx prisma dev` (PGLite-backed local Postgres managed by Prisma CLI) or their own Postgres instance. Production connects to Supabase via the same adapter and connection string swap.
**Tech Stack:** Prisma 7, `@prisma/adapter-pg`, `pg`, PostgreSQL, Next.js 16
---
## File Structure
| Action | File | Responsibility |
|---|---|---|
| Modify | `prisma/schema.prisma` | Change provider to `postgresql` |
| **Rewrite** | `src/lib/db.ts` | Single PostgreSQL adapter factory |
| Delete | `src/core/adapters/db.ts` | Remove cloud-branch adapter factory (merge into `db.ts`) |
| Modify | `package.json` | Remove `better-sqlite3` + adapter deps, add `pg` |
| Modify | `next.config.ts` | Remove `better-sqlite3` from `serverExternalPackages` |
| Modify | `docker-entrypoint.sh` | Update comments, remove SQLite references |
| Modify | `Dockerfile` | Remove SQLite build step, update env defaults |
| Modify | `local-dev.ps1` | Add `prisma dev` startup guidance |
| Modify | `.env` | Change default `DATABASE_URL` to local PostgreSQL |
| Modify | `prisma.config.ts` | No changes needed (already reads `DATABASE_URL`) |
| Modify | `scripts/cleanup-plugins.ts` | Use shared `db.ts` instead of hardcoded SQLite |
| Modify | `scripts/manage-users.ts` | Use shared `db.ts` instead of hardcoded SQLite |
| Keep | `scripts/migrate-aviation-history.ts` | This is a one-off Supabase-to-SQLite migration tool. Leave as-is but mark deprecated |
| **Delete** | `prisma/migrations/` | Remove old SQLite migrations (will regenerate for PostgreSQL) |
| **Create** | `prisma/migrations/` | Fresh PostgreSQL init migration |
---
### Task 1: Update Prisma Schema Provider
**Files:**
- Modify: `prisma/schema.prisma:1-6`
- [x] **Step 1: Change the datasource provider from SQLite to PostgreSQL**
Open `prisma/schema.prisma` and replace the datasource block:
```prisma
// Prisma schema — PostgreSQL for all environments.
// Local dev: use `npx prisma dev` for a zero-install local PGLite instance.
// Cloud/Production: set DATABASE_URL to your Supabase/Postgres connection string.
datasource db {
provider = "postgresql"
}
```
Leave the `generator` block and all models unchanged.
- [x] **Step 2: Verify the schema is valid**
Run:
```powershell
npx prisma validate
```
Expected: `The schema at prisma/schema.prisma is valid.`
- [x] **Step 3: Commit**
```powershell
git add prisma/schema.prisma
git commit -m "refactor(db): switch schema provider from sqlite to postgresql"
```
---
### Task 2: Remove SQLite Dependencies
**Files:**
- Modify: `package.json:22-80`
- Modify: `next.config.ts:5`
- [x] **Step 1: Remove better-sqlite3 packages from package.json**
In `package.json`, remove these lines from `dependencies`:
```diff
- "@prisma/adapter-better-sqlite3": "^7.5.0",
```
Remove from `pnpm.onlyBuiltDependencies`:
```diff
- "better-sqlite3",
```
Ensure `@prisma/adapter-pg` and `pg` remain (they're already present):
```json
"@prisma/adapter-pg": "^7.8.0",
"pg": "^8.20.0",
```
- [x] **Step 2: Update serverExternalPackages in next.config.ts**
In `next.config.ts` line 5, replace:
```typescript
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
```
With:
```typescript
serverExternalPackages: ["@prisma/client", "prisma", "pg"],
```
- [x] **Step 3: Install to update lockfile**
Run:
```powershell
pnpm install
```
Expected: Clean install with no `better-sqlite3` compilation step.
- [x] **Step 4: Commit**
```powershell
git add package.json next.config.ts pnpm-lock.yaml
git commit -m "refactor(db): remove better-sqlite3 dependencies"
```
---
### Task 3: Rewrite the Database Adapter Factory
**Files:**
- Rewrite: `src/lib/db.ts`
- [x] **Step 1: Replace db.ts with a unified PostgreSQL adapter**
Replace the entire contents of `src/lib/db.ts` with:
```typescript
import { PrismaClient } from "../generated/prisma";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
/**
* Prisma client singleton — PostgreSQL only.
*
* Local dev: Run `npx prisma dev` for a zero-install local Postgres.
* Production: Set DATABASE_URL to your Supabase/Postgres connection string.
*
* Uses globalThis to survive Next.js HMR in development.
*/
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
function createPrismaClient(): PrismaClient {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error(
"[db] DATABASE_URL is not set. " +
"Run `npx prisma dev` for local development, " +
"or set DATABASE_URL to your PostgreSQL connection string."
);
}
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
return new PrismaClient({ adapter } as any);
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
```
> **Note:** The `feature/cloud-hosting-core` branch has a more complex version at `src/core/adapters/db.ts` with tenant isolation via `applyTenantIsolation()`. When merging that branch later, the tenant isolation extension should be layered on top of this unified base — it does NOT need a separate SQLite path.
- [x] **Step 2: Verify TypeScript compilation**
Run:
```powershell
npx tsc --noEmit --pretty 2>&1 | Select-String "db.ts"
```
Expected: No errors related to `db.ts`.
- [x] **Step 3: Commit**
```powershell
git add src/lib/db.ts
git commit -m "refactor(db): unify adapter to postgresql-only via PrismaPg"
```
---
### Task 4: Update Utility Scripts
**Files:**
- Modify: `scripts/cleanup-plugins.ts`
- Modify: `scripts/manage-users.ts`
- [x] **Step 1: Rewrite cleanup-plugins.ts to use shared db**
Replace the entire contents of `scripts/cleanup-plugins.ts`:
```typescript
import { PrismaClient } from "../src/generated/prisma/index.js";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter } as any);
async function main() {
const plugins = await prisma.installedPlugin.findMany();
console.log("Installed plugins:");
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
const geojson = plugins.find((p) => p.pluginId === "geojson");
if (geojson) {
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
console.log("\nDeleted orphaned 'geojson' record.");
} else {
console.log("\nNo orphaned 'geojson' record found.");
}
const remaining = await prisma.installedPlugin.findMany();
console.log("\nRemaining plugins:");
remaining.forEach((p) => console.log(` ${p.pluginId}`));
await prisma.$disconnect();
}
main().catch(console.error);
```
- [x] **Step 2: Rewrite manage-users.ts to use shared db**
Replace the entire contents of `scripts/manage-users.ts`:
```typescript
import { PrismaClient } from "../src/generated/prisma/index.js";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { hashSync } from "bcryptjs";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter } as any);
async function main() {
const action = process.argv[2];
if (action === "list") {
const users = await prisma.user.findMany();
if (users.length === 0) {
console.log("No users found — visit /setup to create one.");
} else {
users.forEach((u) =>
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
);
}
} else if (action === "reset") {
const email = process.argv[3];
const newPass = process.argv[4];
if (!email || !newPass) {
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
return;
}
const hashed = hashSync(newPass, 12);
await prisma.user.update({
where: { email },
data: { hashedPassword: hashed },
});
console.log(`Password reset for ${email}`);
} else if (action === "delete-all") {
await prisma.user.deleteMany();
console.log("All users deleted — visit /setup to create a new admin.");
} else {
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
}
await prisma.$disconnect();
}
main().catch(console.error);
```
- [x] **Step 3: Add deprecation notice to migrate-aviation-history.ts**
Add this comment at the top of `scripts/migrate-aviation-history.ts`:
```typescript
/**
* @deprecated This script uses better-sqlite3 directly to migrate data
* from Supabase into the legacy data engine's SQLite database.
* It is NOT part of the main application's database layer.
* It will be removed once the data engine migration is complete.
*/
```
- [x] **Step 4: Commit**
```powershell
git add scripts/cleanup-plugins.ts scripts/manage-users.ts scripts/migrate-aviation-history.ts
git commit -m "refactor(scripts): update utility scripts to use postgresql adapter"
```
---
### Task 5: Create Fresh PostgreSQL Migration
**Files:**
- Delete: `prisma/migrations/` (entire directory)
- Create: `prisma/migrations/YYYYMMDD_init/migration.sql` (generated by Prisma)
- [x] **Step 1: Delete old SQLite migrations**
```powershell
Remove-Item -Recurse -Force prisma/migrations
```
- [x] **Step 2: Ensure a local PostgreSQL is available**
Either:
- Run `npx prisma dev` in a separate terminal, OR
- Use your existing local PostgreSQL at `127.0.0.1:5432`
Verify the connection string in `.env.local` points to a reachable PostgreSQL instance:
```
DATABASE_URL="postgresql://postgres:[email protected]:5432/postgres?schema=public"
```
- [x] **Step 3: Reset and create initial migration**
```powershell
npx prisma migrate reset --force
npx prisma migrate dev --name init
```
Expected output:
```
Applying migration `YYYYMMDDHHMMSS_init`
The following migration(s) have been created and applied...
```
- [x] **Step 4: Verify migration_lock.toml says postgresql**
```powershell
Get-Content prisma/migrations/migration_lock.toml
```
Expected:
```
provider = "postgresql"
```
- [x] **Step 5: Commit**
```powershell
git add prisma/migrations
git commit -m "feat(db): create initial postgresql migration"
```
---
### Task 6: Update Dockerfile and Entrypoint
**Files:**
- Modify: `Dockerfile:11,36-38,49,54`
- Modify: `docker-entrypoint.sh:3-5`
- [x] **Step 1: Update Dockerfile**
Make these changes to `Dockerfile`:
**Line 11** — Remove `python3 make g++` (no longer need to compile better-sqlite3 native bindings):
```dockerfile
RUN apk add --no-cache python3 make g++
```
Replace with:
```dockerfile
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
```
**Lines 36-38** — Remove the conditional SQLite build step entirely:
```dockerfile
# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD
# (For cloud, we'll run migrations against Postgres at runtime)
RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi
```
Replace with:
```dockerfile
# Database migrations run at container startup via docker-entrypoint.sh
# DATABASE_URL must be set to a PostgreSQL connection string
```
**Line 49** — Keep `prisma` global install (needed for `migrate deploy` at runtime).
**Line 54** — Remove the SQLite default DATABASE_URL:
```dockerfile
ENV DATABASE_URL=file:./data/wwv.db
```
Replace with:
```dockerfile
# DATABASE_URL must be provided via environment variable (no default)
# Example: postgresql://user:pass@host:5432/dbname
```
- [x] **Step 2: Update docker-entrypoint.sh comments**
Replace lines 2-5 of `docker-entrypoint.sh`:
```bash
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the SQLite database exists and is migrated before
# starting the application. On first run with a fresh volume
# the DB file won't exist yet, so we run prisma migrate deploy.
```
With:
```bash
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the PostgreSQL database is migrated before starting
# the application. DATABASE_URL must point to a PostgreSQL
# instance (Supabase, self-hosted, etc).
```
Remove `mkdir -p ./data` from line 9 (no longer creating a local SQLite file):
```bash
set -e
echo "[entrypoint] Running database migrations..."
prisma migrate deploy
echo "[entrypoint] Migrations complete."
```
- [x] **Step 3: Commit**
```powershell
git add Dockerfile docker-entrypoint.sh
git commit -m "refactor(docker): remove sqlite from build and runtime"
```
---
### Task 7: Update Environment Defaults and Dev Scripts
**Files:**
- Modify: `.env:1`
- Modify: `package.json:13` (predev script)
- Modify: `local-dev.ps1`
- [x] **Step 1: Update .env default DATABASE_URL**
Replace line 1 of `.env`:
```
DATABASE_URL=file:./data/wwv.db
```
With:
```
# PostgreSQL connection string.
# For local dev: run `npx prisma dev` and use the URL it prints.
# For production: set to your Supabase/Postgres connection string.
# DATABASE_URL=postgresql://postgres:[email protected]:5432/worldwideview
```
> **Important:** The default is now commented out. The `.env.local` file (or `npx prisma dev`) must provide the actual value. This forces contributors to explicitly set up their database rather than silently falling back to a potentially broken SQLite path.
- [x] **Step 2: Simplify the predev script**
In `package.json`, the `predev` script currently runs `npx prisma migrate deploy`. This will fail if no Postgres is running. Change it to only copy Cesium assets and generate the Prisma client:
```json
"predev": "npx prisma generate && node scripts/copy-cesium.mjs",
```
> **Rationale:** `prisma migrate deploy` should only run in production (Docker entrypoint) or explicitly by the developer. During local dev, `npx prisma dev` handles migrations automatically.
- [x] **Step 3: Update local-dev.ps1**
Replace the entire contents of `local-dev.ps1`:
```powershell
Write-Host "[*] Setting up WorldWideView for Local Development..."
# Check for pnpm
try {
$null = Get-Command pnpm -ErrorAction Stop
} catch {
Write-Host "[Error] pnpm is not installed or not in PATH."
Write-Host "Please install it first: https://pnpm.io/installation"
exit 1
}
Write-Host "[*] Installing dependencies..."
pnpm install
Write-Host "[*] Running initial setup (generating secrets)..."
pnpm run setup
Write-Host "[*] Generating Prisma client..."
npx prisma generate
# Check for the sibling Data Engine repository
if (-not (Test-Path "../wwv-data-engine")) {
Write-Host ""
Write-Host "=====================================================================" -ForegroundColor Yellow
Write-Host "[!] NOTICE: Local Data Engine not found at ../wwv-data-engine" -ForegroundColor Yellow
Write-Host ""
Write-Host "Frontend-Only Mode: You are developing the frontend UI." -ForegroundColor Green
Write-Host "WorldWideView will automatically stream data from the Cloud Engine." -ForegroundColor Green
Write-Host ""
Write-Host "Full-Stack Mode: If you want to develop backend data seeders, you" -ForegroundColor Cyan
Write-Host "must clone the open-source data engine as a sibling directory:" -ForegroundColor Cyan
Write-Host " cd ..; git clone https://github.com/silvertakana/wwv-data-engine"
Write-Host " cd wwv-data-engine; pnpm install"
Write-Host "=====================================================================" -ForegroundColor Yellow
Write-Host ""
}
Write-Host ""
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
Write-Host ""
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
Write-Host ""
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
Write-Host " npx prisma dev" -ForegroundColor Yellow
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
Write-Host ""
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "[*] Starting local Next.js frontend server..."
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
pnpm run dev
```
- [x] **Step 4: Commit**
```powershell
git add .env package.json local-dev.ps1
git commit -m "refactor(dev): update env defaults and dev scripts for postgresql"
```
---
### Task 8: Run Tests and Validate
**Files:**
- No file changes — validation only
- [x] **Step 1: Generate Prisma client**
```powershell
npx prisma generate
```
Expected: `Generated Prisma Client to ./src/generated/prisma`
- [x] **Step 2: Run the test suite**
```powershell
pnpm test
```
Expected: All tests pass. The repository tests mock `db.ts`, so the adapter change should be transparent to them.
- [x] **Step 3: Start the dev server**
Ensure your `.env.local` has a valid `DATABASE_URL` pointing to PostgreSQL, then:
```powershell
pnpm run dev
```
Expected: Server starts at `http://localhost:3000` without `P3005` or `P3018` errors.
- [x] **Step 4: Verify database operations work**
1. Navigate to `http://localhost:3000/setup` — create a test user
2. Log in
3. Open the Plugins panel — verify installed plugins load
4. Star a favorite entity — verify it persists across reload
- [x] **Step 5: Final commit**
```powershell
git add -A
git commit -m "test(db): verify postgresql-only adapter works end-to-end"
```
---
## Post-Implementation Notes
### For the `feature/cloud-hosting-core` merge
When merging the cloud-hosting-core branch back into main, the `src/core/adapters/db.ts` file with `applyTenantIsolation()` should be integrated into `src/lib/db.ts` as a wrapper around the single `PrismaPg` adapter. The conditional SQLite path in that file can be completely removed.
### For self-hosted Docker users
Add a note to the release changelog:
> **Breaking Change:** WorldWideView now requires a PostgreSQL database. SQLite is no longer supported.
> Self-hosted users must provide a `DATABASE_URL` environment variable pointing to a PostgreSQL instance.
> The easiest option is a free Supabase project, or run `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=pass postgres:17-alpine` alongside your WWV container.
### For the migrate-aviation-history.ts script
This script uses `better-sqlite3` directly to talk to the data engine's separate SQLite database (not the platform database). It is unrelated to this migration and can remain as-is. If `better-sqlite3` is needed for this script, install it as a `devDependency` only, or move the script to the data engine repo where it belongs.
+34
View File
@@ -0,0 +1,34 @@
---
trigger: glob
description: Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
globs: "src/core/globe/**/*"
---
# Cesium Rendering Rules
## Purpose
Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
## When to Apply
Whenever writing code for plugins, visual layers, or modifying components like `EntityRenderer` or `GlobeView`.
## Critical Limitations
### `HeightReference.CLAMP_TO_GROUND` Warning
> [!WARNING]
> Do **not** apply `HeightReference.CLAMP_TO_GROUND` to label text rendering (`LabelGraphics`). Due to a known issue in Cesium 1.121+, clamping tens of thousands of dynamic labels blocks the UI thread continuously because Cesium recalculates the terrain intersection each frame.
### Primitive Restrictions
When creating primitive objects:
- **Points** (`PointPrimitive`): Can use `size`, `outlineWidth`, and `outlineColor`.
- **Billboards** (`BillboardGraphics` for SVG/Icons): Must **NOT** use `size`, `outlineWidth`, or `outlineColor`. You must use `iconScale` to resize them. Mixing point properties on billboards causes severe shader clipping.
## Performance Culling
> [!TIP]
> Do not rely solely on depth buffering (`disableDepthTestDistance`) when viewing the backside of the globe. Use CPU-side calculating (dot-product against the Earth's radius) to implement manual horizon culling. Render nothing if the scalar projection is behind the tangential threshold.
## LOD & Stacking
1. Convert distant entities to `billboard` representations.
2. If closely grouped, the `StackManager` should spiderify components circularly. Non-hub objects fade to 0.4 opacity when expanded to reduce visual clutter.
3. Use the `useModelRendering` hook exclusively for transitioning high-importance entities (like aircraft or ships) into full 3D GLTF models on approach.
+150
View File
@@ -0,0 +1,150 @@
# Coding Principles
You are about to write or modify code. **Read this file first.** It exists to prevent accumulated coupling and band-aids that turn a clean codebase into a fragile one.
## The Hard Rule
> **Always interface-based, extensible, composable, modular. Never band-aids on band-aids.**
If you find yourself adding a flag, an `if`-check, or a special case to make a problem go away, you are probably band-aiding. Stop and find the seam where the abstraction broke. Fix it there.
## Core Principles
### 1. Interfaces before implementations
Define the contract first. Public functions accept the interface, not the concrete type.
```ts
// Yes
function attachSource(source: DataSource) { ... }
// No
function attachPostgresSource(pg: PostgresInstance) { ... }
```
When a pattern repeats across two modules, refactor it into an interface immediately. Don't wait for the third copy.
### 2. Loose coupling through explicit contracts
Components communicate through well-defined contracts (typed signatures, events, registries). Pick one and make it the only path.
Components do **not** communicate through:
- Direct imports of each other's internal modules
- Shared mutable state outside the contract
- "Just this once" backdoors
If you are tempted to write `import { internalThing } from '../other-module/internal'`, you are doing it wrong. Propose adding it to the public contract or solve it elsewhere.
### 3. Domain boundaries are sacred
Each domain owns its own state and surface. Cross-domain access is **explicit, gated, and audited**.
**Forbidden:**
- Reading another domain's storage directly
- Calling another domain's private functions
- Hardcoded `if (tenant === 'X')` branches in shared code
**Allowed:**
- Calling a documented API on the other domain
- A configuration field driving strategy
Rule of thumb: If removing a domain requires code archaeology in other domains to untangle internals, the boundary is violated.
### 4. Don't bend architecture to fit dependencies
Use libraries where they fit cleanly; build natively where they don't.
- **Library handles:** The specific problem it's good at, in the shape it expects.
- **Your code owns:** Your domain, lifecycle invariants, and integration seams.
If you find yourself bending your design to fit a library convenience, stop and build it natively or find the correct hook.
### 5. Data lifetimes are deliberate
Different data has different lifetimes. Get this wrong and you'll retain garbage or delete user data.
- **Operational telemetry** (logs, metrics) — short rolling window.
- **User content** — **permanent unless explicitly deleted.** Never swept by telemetry prunes.
- **Resumable session state** — bounded window; archived rather than deleted.
Write explicit retention policies for each category separately.
### 6. Optional features must be truly removable
Optional features declare their surface explicitly and communicate via standard contracts. No optional feature reaches into another's internals.
Test: **If removing this feature should break the system, it's core. Otherwise it's optional and must be cleanly removable without leaving residue.**
### 7. Put code where it belongs
When a feature spans layers, resist the urge to fold it all into one place "for convenience." Routing across layers is the job — not collapsing them. If a feature needs to write durable state, it extends the layer that owns that state.
## Antipatterns to Refuse
These are common failure modes that calcify a codebase. Refuse them:
| Antipattern | Better answer |
|---|---|
| Adding a new flag to an existing function | Extract a strategy interface |
| Patching around a bug at the call site | Find the seam where abstraction broke; fix it there |
| Direct database access from a feature module | Go through the layer that owns the data |
| Hardcoded paths/IDs in business logic | Use configuration or registries |
| `if (tenant === 'X')` in shared code | Strategy pattern or per-tenant config |
| Inheriting one layer's concerns into another | Cross the boundary through a documented contract |
| Inline coupling between layers ("it works") | Draw the contract or merge them honestly |
| Adding defensive `try/catch` to swallow errors| Find root cause; gate cleanly at the boundary |
| Comment explaining *what* code does | Rename and refactor so the code reads itself |
| Copying snippets to "avoid dependency" | Move to a shared module or accept duplicate drift |
## Debugging Discipline
1. **Reproduce it.** Don't trust intuition about what's failing.
2. **Find the seam.** Where did the abstraction break? Which contract was violated?
3. **Fix at the seam.** Not at the call site. Not at the consumer.
4. **If you can't find the seam, surface it.** Tell the user: "this is a design gap; the right fix needs an architectural decision, not a patch."
If a fix doesn't work, **don't add another guard on top.** Stacked defensive layers ruin maintainability.
## Lifecycle Invariants and Mutating Operations
To prevent silent corruption and orphan rows:
1. **Name the invariant.** E.g., "Closed sessions don't accept work." Write it down.
2. **Throw a typed error at the seam.** The function that enforces the invariant must throw a specific typed error, not a silent skip or generic `Error`.
3. **Pre-check at every mutating call site *before* reaching the seam.** Pre-check is hygiene; the seam check is correctness. Both are required.
4. **Validate, then mutate.** Resolve all inputs/permissions before touching durable state. A validation failure must leave nothing half-applied.
5. **Unsafe APIs are still unsafe.** Documenting "don't use when X" is a foot-gun. Make it safe (drain, throw) or remove it.
## Definition of Done (Checklist)
Every code change must satisfy these checklists before merge.
### Adding a new function
- [ ] Belongs strictly in this module.
- [ ] Fulfills an existing interface or explicitly adds a new one.
- [ ] Has a doc-comment header (purpose, params, returns, throws).
- [ ] Has at least one test targeting the contract, not implementation details.
- [ ] Communicates via public contracts only (no cross-module internal imports).
- [ ] Does not touch storage owned by another component.
### Updating an existing function
- [ ] Reason for change is clear (bug fix, refactor, spec change).
- [ ] Doc-comments and tests are updated to reflect the change.
- [ ] Fix is applied at the seam, not as a symptom patch.
- [ ] No new flags or special cases were added instead of extracting a strategy.
### Refusal Triggers (STOP)
- Adding `if (tenant === 'X')` to shared code.
- Adding a flag to make a problem go away.
- Direct DB/filesystem access from a feature module.
- `try/catch` swallowing an error without gating cleanly.
- Skipping tests ("it's trivial") or headers ("it's obvious").
- Adding "just another guard" when a guard failed.
If any trigger is met, surface it to the user. Do not paper over.
## Code-Style Minimums
### Comments & Tests
- **Doc-comments:** Every function gets a header (purpose, params, returns, throws). Inline comments explain WHY, not WHAT.
- **Tests:** Every function ships with at least one contract test. Storage code must use a real temporary DB instance, not a mock.
### Logging
Log every non-happy-path branch with structured loggers and module-scoped children.
- **info**: Expected but noteworthy (e.g., privilege bypass).
- **warn**: Rare, worth investigating (e.g., orphan row caught).
- **error**: Operator action required (e.g., crash, integration failure).
- **debug**: High-volume state changes (include `module` field to filter).
Use structured fields (`logger.warn({ id, state }, "msg")`), not interpolated strings.
### Structure & Dependencies
- Keep modules under ~500 lines. Prefer explicit composition over implicit DI.
- **Always check registry versions before adding/updating a dependency.** Never use "latest" blindly. Active deprecations are real; pin behind if needed and document why.
### Doc-vs-Spec Discipline
Specs are **functional**, not narrative. They require:
- Concrete data structures (schemas, DDL).
- Concrete function/API signatures (input/output types).
- Concrete event payloads.
- Explicit invariants and failure modes.
## When in Doubt
Ask the user explicitly:
- "I don't see a clean seam; options are A or B. Which fits?"
- "This needs a new contract. Draft it first?"
- "I'm about to add a special case. Extract abstraction instead?"
Don't ship band-aids and ask forgiveness later.
+21
View File
@@ -0,0 +1,21 @@
---
trigger: always_on
---
# Context and Memory Synchronization
## 1. Purpose
This specification ensures that any agent maintains persistent, accurate project context by pointing them directly to the Single Source of Truth for this repository.
## 2. Synchronization Target
The agent MUST orient itself by immediately reading:
1. `c:\dev\worldwideview\AGENTS.md` (The root index of all technical stack details)
2. `c:\dev\worldwideview\.agents\context\01-platform-overview.md` (The high-level platform goals)
If deep technical rules are required for a specific domain (e.g., UI state, Map Rendering, Monorepo management), the agent MUST consult the relevant file in `c:\dev\worldwideview\.agents\rules\`.
## 3. Reflecting Changes
If the architecture fundamentally changes (e.g., migrating off Zustand, or removing Cesium), the agent MUST proactively update the `AGENTS.md` and relevant files in `.agents/rules/` to reflect this new reality.
## 4. Goal
A new chat instance MUST be able to reconstruct an accurate, comprehensive understanding of the project solely from reading the root `AGENTS.md` file and branching out to the specific rules as necessary. This prevents context bloat and ensures accuracy.
+3 -3
View File
@@ -4,8 +4,8 @@
When making database schema changes, you must ensure that generated migrations are resilient against environmental discrepancies.
- **Review Generated SQL**: Always review the `.sql` files generated by `npx prisma migrate dev`.
- **Add "IF EXISTS" clauses**: SQLite and Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs (e.g., the index was already dropped or never created), manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
- **Data Preservation**: When dropping columns or renaming, SQLite does not cleanly support it and requires table recreation. Carefully review the `INSERT INTO "new_table" SELECT ...` clauses to ensure data is correctly mapped.
- **Add "IF EXISTS" clauses**: Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs, manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
- **Data Preservation**: When dropping columns or renaming, carefully review the migration to ensure data is correctly mapped. In PostgreSQL, ensure that cascaded drops don't accidentally remove required data.
## 2. Managing Failed Migrations
If a migration fails in production:
@@ -13,4 +13,4 @@ If a migration fails in production:
- If you use `resolve --applied`, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
## 3. Backups Before DDL
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database (via Prisma or direct SQLite access) without first confirming an automated backup exists, or manually taking a backup of the `wwv.db` file.
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database without first confirming an automated backup exists, or manually taking a `pg_dump` backup of the database.
+30
View File
@@ -0,0 +1,30 @@
---
trigger: model_decision
description: Strict rules for operating within the pnpm monorepo workspace environment structure across frontend and backend services.
globs: ""
---
# Monorepo Workflow Guidelines
## Purpose
Strict rules for operating within the `pnpm` monorepo workspace environment structure across frontend and backend services.
## Directory Isolation
- The Next.js frontend is located at root `.`.
- Individual standalone plugins are located at `packages/wwv-plugin-[name]`.
- For heavy plugin processing, microservice backends are located at `packages/wwv-plugin-[name]/backend`.
## Critical Workspace Rule
> [!IMPORTANT]
> Because plugins use internal workspace references, you MUST strictly use `"workspace:*"` instead of `"*"` in `package.json` dependencies (e.g. `"@worldwideview/wwv-plugin-sdk": "workspace:*"`). Using `"*"` can cause pnpm to eagerly resolve cached registry versions instead of strictly linking your local code, resulting in opaque TypeScript and compilation errors.
> **Whenever you add a new plugin package or adjust the SDK, you MUST run `pnpm install` then `pnpm build` from the project ROOT directory to propagate TS types properly.**
## Start/Exec Flow
Running `pnpm start:backends` from the project root employs `concurrently` to spin up Fastify services attached to specific plugins containing `/backend` folders.
## Next.js Monorepo Exceptions
When modifying `next.config.ts`, if new UI components or plugins are added that require SSR/transpilation, ensure they are appended to the `transpilePackages: []` array, or they will throw Next-Router unresolved import errors on production build.
+83
View File
@@ -0,0 +1,83 @@
---
trigger: model_decision
description: The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
---
# Plugin Architecture & Data Flow
## Purpose
The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
## The WorldPlugin Contract
All data ingest flows through `WorldPlugin` (defined entirely within `@worldwideview/wwv-plugin-sdk`).
A valid plugin class MUST provide:
1. `id` and `version` (The `version` MUST be dynamically imported via `import pkg from "../package.json"` to prevent duplicate tracking during CI/releases for built-in plugins).
2. `fetch(timeRange)` method logic.
3. `renderEntity(GeoEntity)` to determine visual style.
4. `getPollingInterval()` (defaults fallback securely to standard store config).
## Plugin Architectures (Manifest Formats)
Plugins are defined via `PluginManifest` and operate on an **All-Bundle** architecture.
All frontend extensions must eventually be compiled into a JS bundle that exports a `WorldPlugin`.
1. **`bundle` (Dynamic CDN Loaded / Internal)**: Plugins dynamically imported at runtime via ES module references (e.g., `unpkg.com` or local `/plugins/myplugin/frontend.mjs`). Handled by `loadPluginFromManifest` referencing `manifest.entry`.
2. **`static` (Legacy)**: Now compiled via `wwvStaticCompiler` into a dynamic bundle. The raw `StaticDataPlugin` runtime class has been removed.
3. **`declarative` (Legacy)**: Now compiled or wrapped into bundles.
No matter the source, the engine evaluates it by directly loading the `entry` file dynamically:
`const module = await import(/* webpackIgnore: true */ entry);`
## Package Metadata (`package.json`)
All plugins MUST define their identity and compatibility via a `"worldwideview"` block in their `package.json`. This acts as the source-of-truth for generating the `PluginManifest` for the registry. If a plugin does not define `"type"`, validation functions will reject the manifest entirely or rely on legacy fallbacks.
```json
{
"name": "@worldwideview/wwv-plugin-myplugin",
"version": "1.0.0",
"worldwideview": {
"id": "myplugin", // REQUIRED: Must match the directory name & API routes.
"type": "data-layer", // REQUIRED: "data-layer" or "extension"
"format": "bundle", // REQUIRED: "bundle", "declarative", or "static"
"category": "Aviation", // REQUIRED: Matches PluginCategory union in SDK
"icon": "Plane", // RECOMMENDED: Lucide icon name
"capabilities": [ // REQUIRED: What the plugin can do
"data:own", // (e.g. injects its own data)
"globe:overlay", // (e.g. renders 3D elements)
"network:fetch"
]
}
}
```
## The Registration Pipeline
> [!NOTE]
> All plugin interactions run through three singleton services:
> `PluginRegistry` / `InstalledPluginsLoader` -> `PluginManager` -> `PollingManager` -> `DataBus`
### `InstalledPluginsLoader`
Scans the PostgreSQL database at startup for dynamically installed marketplace manifests. Parses, validates (`validateManifest`), and registers valid plugins via `pluginManager.loadFromManifest`.
### `PluginManager`
The orchestrator. Exposes `registerPlugin`, `enablePlugin`, `disablePlugin`. Never bypass the manager to push data manually to the cache. Supports dynamic loading via `loadFromManifest`.
### `PollingManager`
Coordinates interval execution. Implements **exponential backoff**. When a plugin errors, it retries at increasing scales (e.g., 2s → 4s → 8s) automatically.
### `DataBus`
The typed generic event bus separating React UI components from background execution.
```typescript
// How data gets pushed onto the rendering surface securely:
DataBus.getInstance().emit('dataUpdated', {
pluginId: "mytracker",
entities: newEntities
});
```
## When to Apply
When writing `fetch` implementations for plugins, or tracing why an entity dropped off the map. Ensure missing data correctly triggers the cache fallback via the DataBus. Ensure all new external plugins use the `bundle` format and exist in the marketplace registry to avoid CDN 404 hydrating crashes.
+43
View File
@@ -0,0 +1,43 @@
---
trigger: glob
description: Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
globs: "src/core/state/**/*, src/components/**/*"
---
# Zustand State Management
## Purpose
Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
## Single Centralized State
WorldWideView utilizes a monolithic Zustand store located at `src/core/state/store.ts`. It is broken down into exactly 9 semantic slices.
| Slice Name | Purpose | Example State |
|---|---|---|
| **Globe** | Cesium Viewer state | `cameraPosition`, `selectedEntity` |
| **Layers** | Loaded map tiles/overlays | `activeTileSets` |
| **Timeline** | Application current time | `currentTimeRange` |
| **UI** | Global overlay states | `isFilterMenuOpen` |
| **Filters** | Active visual filtration | `searchQuery`, `categoryFilter` |
| **Data** | Entity registry | `entitiesByPlugin` |
| **Config** | User preferences | `pollingIntervals`, `pluginSettings` |
| **Favorites**| Pinned entities | `favoriteIds` |
| **GeoJSON** | Local files loaded in | `localImports` |
## When to Apply
When passing deep state across components, or when a plugin must push state configurations onto the screen.
## Best Practices
### Avoid Prop Drilling
**Never** pass props further than two levels down. If a component deeper in the tree needs access to something (e.g., `cameraPosition`), it must `useStore(s => s.globe.cameraPosition)`.
### Selector Destructuring Avoidance
> [!WARNING]
> Do not destructure wide objects in selectors.
> Right: `const isHUD = useStore(state => state.ui.hudVisible);`
> Wrong: `const { hudVisible } = useStore(state => state.ui);`
> The wrong approach rerenders the component any time *anything* in the `ui` slice changes.
### Config and Plugins
If your plugin has user-configurable values (e.g., color settings, toggle states), its data MUST live inside `state.config.dataConfig.pluginSettings[pluginId]`. Do not spawn un-bound `useState` hooks for UI properties if they affect the global app state.
+5
View File
@@ -0,0 +1,5 @@
{
"enabledPlugins": {
"code-review@claude-plugins-official": false
}
}
@@ -0,0 +1,70 @@
---
name: bing-news-hydration
description: Hydrate event attributes with news URLs and images via Bing RSS
---
# Bing News Event Hydration Workflow
When enriching a simulation database or CSV dataset via automation, standard search engines like Google will aggressively block headless scrapers or `fetch` requests with CAPTCHA walls. This workflow uses **Bing News RSS** as an open, structured payload to discover news articles and then bypasses its tracking wrapper to scrape `og:image` tags.
### 1. Structure the Request
Bing offers a developer-friendly RSS feed option that bypasses captchas. Construct the query string properly depending on whether you want an exact match or a broad categorical match (e.g. for fictional simulation events).
```javascript
const query = encodeURIComponent("AIR STRIKE Tehran Iran Israel conflict");
const url = `https://www.bing.com/news/search?q=${query}&format=rss`;
```
### 2. Bypass Bing Click-Tracking
When Bing RSS returns an article, the URL will be wrapped in a tracking link (`apiclick.aspx`). Fetching this URL directly will *fail* to return the article HTML, as Bing uses a client-side JavaScript redirect. To extract the real article link, you must unescape the XML, map the `url=` parameter, and decode it.
```javascript
async function bingNewsSearch(query) {
const res = await fetch(`https://www.bing.com/news/search?q=${encodeURIComponent(query)}&format=rss`, {
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) WorldWideView-Hydrator" }
});
const xml = await res.text();
const itemMatch = xml.match(/<item>[\s\S]*?<link>(.*?)<\/link>/i);
if (itemMatch && itemMatch[1]) {
// 1. Unescape XML entities
let encodedUrl = itemMatch[1].trim().replace(/&amp;/g, '&');
// 2. Extract the `url=` target and decode it
const urlMatch = encodedUrl.match(/[?&]url=([^&]+)/i);
if (urlMatch && urlMatch[1]) {
return decodeURIComponent(urlMatch[1]);
}
return encodedUrl;
}
return null;
}
```
### 3. Fetch Article `og:image`
Once you have the direct real article URL (e.g., Al Jazeera, MSN, etc.), make a standard HTTP fetch to the webpage. You can regex parse the HTML (without needing a full DOM parser or headless browser) to extract the Open Graph preview image.
```javascript
async function scrapeOgImage(articleUrl) {
// Note: Always sleep/wait a few hundred ms between requests to respect rate limits
const res = await fetch(articleUrl, {
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) WorldWideView-Hydrator" }
});
const html = await res.text();
const ogMatch = html.match(/<meta[^>]*property=["']og:image["'][^>]*content=["']([^"']+)["']/i)
|| html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:image["']/i);
return ogMatch ? ogMatch[1] : null;
}
```
### 4. Apply to Dataset
Wrap these utility functions in an async loop covering your DB output:
1. Filter out broad non-searchable events (e.g. `POSTURING`).
2. Run `bingNewsSearch(title)`.
3. If successful, run `scrapeOgImage(target)`.
4. Update the SQL DB via `UPDATE table SET ...` payload injection.
**Important**: Implement delays (`await sleep(500);`) between fetches to avoid being IP blocklisted by target news outlets.
+73
View File
@@ -0,0 +1,73 @@
---
name: cesium-context7
description: "Fetches up-to-date documentation for Cesium, CesiumJS, Cesium Viewer, 3D Tiles, Unreal Engine integration, Unity integration, cesium-unreal, cesium-unity, ACesium3DTileset, ACesiumGeoreference, Globe Anchor, Cesium plugin, georeferencing, and Cesium-related APIs using Context7 MCP tools. Useful for CesiumJS classes (Viewer, Entity, Camera, Scene, Cartesian3, etc.), Unreal Engine Cesium components, Unity Cesium components, 3D Tiles specification, and Cesium integrations. Use query-docs with library IDs: /cesiumgs/cesium (CesiumJS), /cesiumgs/cesium-unreal (Unreal), /cesiumgs/cesium-unity (Unity), /websites/ogc_cs_22-025r4 (3D Tiles spec)."
---
# Context7 for Cesium Development
This skill provides access to up-to-date Cesium documentation for CesiumJS, Unreal Engine integration, and Unity integration.
When working with Cesium-related code, use Context7 MCP Server tools to fetch current documentation before providing answers or generating code.
## Available Tools
### 1. `resolve-library-id`
Search for libraries and retrieve their Context7 library IDs.
**⚠️ Only use this tool when it's unclear which library to use. For Cesium projects, use the Known Library IDs listed below.**
**Parameters**:
- `libraryName` (string, required): Name of the library to search
- `query` (string, optional): Additional search context
**Example use case**: Find the correct library ID for an unfamiliar library or when the library ID is unknown.
### 2. `query-docs`
Retrieve documentation for a specific library and query.
**Parameters**:
- `libraryId` (string, required): Context7 library ID
- `query` (string, required): Documentation query or topic
- `version` (string, optional): Specific library version
**Example use case**: Get documentation for Cesium Viewer initialization using library `/cesiumgs/cesium`.
## Known Library IDs
### CesiumJS API Documentation
For class constructors, methods, and properties (e.g., Viewer, Entity, Cartesian3, Camera methods, Scene properties):
- Library ID: `/cesiumgs/cesium`
### Cesium for Unreal Engine
For Unreal Engine integration (e.g., ACesium3DTileset, ACesiumGeoreference, Blueprint integration):
- Library ID: `/cesiumgs/cesium-unreal`
### Cesium for Unity
For Unity integration (e.g., Cesium3DTileset component, CesiumCameraController, C# scripting):
- Library ID: `/cesiumgs/cesium-unity`
### 3D Tiles Specification
For tile formats and schema details (e.g., tileset JSON structure, refinement strategies, metadata schemas):
- Library ID: `/websites/ogc_cs_22-025r4`
## Usage Guidelines
- Use the Known Library IDs listed above for Cesium-related queries
- When a question requires information from multiple sources (e.g., CesiumJS API + 3D Tiles spec, or Unreal integration + CesiumJS concepts), make separate `query-docs` calls with different library IDs to gather comprehensive documentation
- Use `resolve-library-id` when the library is unknown, not listed in Known Library IDs, or when it's unclear which library best fits the question
- Use `query-docs` to fetch documentation before generating code to ensure accuracy
- Specify the `version` parameter when working with a specific version
- Provide clear, specific queries to get the most relevant documentation
- Avoid hallucinations by using current, version-specific documentation
+68
View File
@@ -0,0 +1,68 @@
---
name: commit
description: Use before every git commit in the WorldWideView project. Enforces mandatory semantic version bumping and conventional commit message format per AGENTS.md §5.7.
---
# Commit Workflow
> [!WARNING]
> You **MUST** bump the version in the relevant `package.json` **before** running `git commit`. Skipping this will violate the project's versioning contract.
## Step 1 — Identify what changed
Determine which packages have been modified (`git diff --name-only`). The version bump goes in:
- The **specific plugin's** `package.json` if only that plugin changed
- The **root** `package.json` if the main app (`src/`) changed
- The **data engine's** `package.json` (`packages/wwv-data-engine/package.json`) if the data engine changed
- Multiple `package.json` files if multiple packages changed
## Step 2 — Determine the bump type
| Commit prefix | Version bump |
|---|---|
| `feat:` | **Minor** (x.**Y**.0) |
| `fix:` / `refactor:` / `perf:` | **Patch** (x.y.**Z**) |
| `BREAKING CHANGE` | **Major** (**X**.0.0) — rare, confirm with user |
## Step 3 — Handle multiple accumulated changes
If there are multiple uncommitted changes across different types:
**Option A — Individual commits** (preferred for clean history):
Commit each logical change separately, bumping the version each time.
**Option B — Batch commit**:
Commit all at once, but bump the version cumulatively. If changes include both a `feat:` and two `fix:`, that's a Minor bump (the highest level wins). Detail each change in the commit description.
## Step 4 — Write the commit message
Format:
```
<type>(<scope>): <short description> [<Level>]
- <change 1> [Minor/Patch/Major]
- <change 2> [Minor/Patch/Major]
```
The `[Level]` suffix at the end of the first line is the cumulative level for the commit.
Each bullet in the body must label its individual level.
**Scope** = package name or area (e.g., `civil-unrest`, `data-engine`, `aviation`, `core`)
Examples:
```
feat(civil-unrest): add GDELT integration for protest feed [Minor]
- add GDELT API seeder to wwv-data-engine [Minor]
- add civil-unrest proxy route in Next.js API [Patch]
```
```
fix(aviation): correct OpenSky credential rotation logic [Patch]
```
## Step 5 — Execute
1. Bump version in relevant `package.json`(s)
2. Stage all changes including the `package.json` bump
3. Commit with the message above
+85
View File
@@ -0,0 +1,85 @@
---
name: context7
description: Retrieve up-to-date documentation for software libraries, frameworks, and components via the Context7 API. This skill should be used when looking up documentation for any programming library or framework, finding code examples for specific APIs or features, verifying correct usage of library functions, or obtaining current information about library APIs that may have changed since training.
---
# Context7
## Overview
This skill enables retrieval of current documentation for software libraries and components by querying the Context7 API via curl. Use it instead of relying on potentially outdated training data.
## Workflow
### Step 1: Search for the Library
To find the Context7 library ID, query the search endpoint:
```bash
curl -s "https://context7.com/api/v2/libs/search?libraryName=LIBRARY_NAME&query=TOPIC" | jq '.results[0]'
```
**Parameters:**
- `libraryName` (required): The library name to search for (e.g., "react", "nextjs", "fastapi", "axios")
- `query` (required): A description of the topic for relevance ranking
**Response fields:**
- `id`: Library identifier for the context endpoint (e.g., `/websites/react_dev_reference`)
- `title`: Human-readable library name
- `description`: Brief description of the library
- `totalSnippets`: Number of documentation snippets available
### Step 2: Fetch Documentation
To retrieve documentation, use the library ID from step 1:
```bash
curl -s "https://context7.com/api/v2/context?libraryId=LIBRARY_ID&query=TOPIC&type=txt"
```
**Parameters:**
- `libraryId` (required): The library ID from search results
- `query` (required): The specific topic to retrieve documentation for
- `type` (optional): Response format - `json` (default) or `txt` (plain text, more readable)
## Examples
### React hooks documentation
```bash
# Find React library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=react&query=hooks" | jq '.results[0].id'
# Returns: "/websites/react_dev_reference"
# Fetch useState documentation
curl -s "https://context7.com/api/v2/context?libraryId=/websites/react_dev_reference&query=useState&type=txt"
```
### Next.js routing documentation
```bash
# Find Next.js library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=nextjs&query=routing" | jq '.results[0].id'
# Fetch app router documentation
curl -s "https://context7.com/api/v2/context?libraryId=/vercel/next.js&query=app+router&type=txt"
```
### FastAPI dependency injection
```bash
# Find FastAPI library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=fastapi&query=dependencies" | jq '.results[0].id'
# Fetch dependency injection documentation
curl -s "https://context7.com/api/v2/context?libraryId=/fastapi/fastapi&query=dependency+injection&type=txt"
```
## Tips
- Use `type=txt` for more readable output
- Use `jq` to filter and format JSON responses
- Be specific with the `query` parameter to improve relevance ranking
- If the first search result is not correct, check additional results in the array
- URL-encode query parameters containing spaces (use `+` or `%20`)
- No API key is required for basic usage (rate-limited)
+80
View File
@@ -0,0 +1,80 @@
---
name: create-command
description: Guide for creating new custom Claude commands with proper structure.
---
# Create Command
Guide for creating new custom Claude commands with proper structure.
## Process:
### 1. Understanding Purpose
- What problem does this command solve?
- Who will use this command?
- What is the expected output?
- How will users interact with it?
### 2. Category Classification
Determine command type:
- **Planning**: Project setup, architecture decisions
- **Implementation**: Code generation, feature development
- **Analysis**: Code review, performance analysis
- **Testing**: Test creation, validation
- **Documentation**: Docs generation, updates
- **Workflow**: Multi-step processes
- **Utility**: Helper commands, tools
### 3. Pattern Selection
Study similar existing commands:
- Analyze structure and flow
- Note common patterns
- Identify reusable components
- Follow established conventions
### 4. Command Location
Choose appropriate location:
- **Project-specific**: `.claude/commands/`
- **User-level**: `~/.claude/commands/`
- Consider reusability and context
### 5. Command Structure
Create with these sections:
- **Title**: Clear, action-oriented name
- **Description**: One-line summary
- **Usage**: How to invoke with parameters
- **Process**: Step-by-step instructions
- **Examples**: Concrete usage examples
- **Output**: Expected results
- **Notes**: Special considerations
## Template:
```markdown
# Command Name
Brief description of what this command does.
## Usage:
`/command-name [arguments]`
## Process:
1. First step
2. Second step
3. Third step
## Examples:
- Example 1
- Example 2
## Notes:
- Important considerations
- Limitations
```
## Best Practices:
- Keep commands focused and single-purpose
- Include parameter validation
- Provide helpful error messages
- Document expected inputs/outputs
- Consider edge cases
- Test thoroughly before finalizing
+152
View File
@@ -0,0 +1,152 @@
---
name: create-prd
description: Create a Product Requirements Document from conversation
argument-hint: [output-filename]
---
# Create PRD: Generate Product Requirements Document
## Overview
Generate a comprehensive Product Requirements Document (PRD) based on the current conversation context and requirements discussed. Use the structure and sections defined below to create a thorough, professional PRD.
## Output File
Write the PRD to: `$ARGUMENTS` (default: `PRD.md`)
## PRD Structure
Create a well-structured PRD with the following sections. Adapt depth and detail based on available information:
### Required Sections
**1. Executive Summary**
- Concise product overview (2-3 paragraphs)
- Core value proposition
- MVP goal statement
**2. Mission**
- Product mission statement
- Core principles (3-5 key principles)
**3. Target Users**
- Primary user personas
- Technical comfort level
- Key user needs and pain points
**4. MVP Scope**
- **In Scope:** Core functionality for MVP (use ✅ checkboxes)
- **Out of Scope:** Features deferred to future phases (use ❌ checkboxes)
- Group by categories (Core Functionality, Technical, Integration, Deployment)
**5. User Stories**
- Primary user stories (5-8 stories) in format: "As a [user], I want to [action], so that [benefit]"
- Include concrete examples for each story
- Add technical user stories if relevant
**6. Core Architecture & Patterns**
- High-level architecture approach
- Directory structure (if applicable)
- Key design patterns and principles
- Technology-specific patterns
**7. Tools/Features**
- Detailed feature specifications
- If building an agent: Tool designs with purpose, operations, and key features
- If building an app: Core feature breakdown
**8. Technology Stack**
- Backend/Frontend technologies with versions
- Dependencies and libraries
- Optional dependencies
- Third-party integrations
**9. Security & Configuration**
- Authentication/authorization approach
- Configuration management (environment variables, settings)
- Security scope (in-scope and out-of-scope)
- Deployment considerations
**10. API Specification** (if applicable)
- Endpoint definitions
- Request/response formats
- Authentication requirements
- Example payloads
**11. Success Criteria**
- MVP success definition
- Functional requirements (use ✅ checkboxes)
- Quality indicators
- User experience goals
**12. Implementation Phases**
- Break down into 3-4 phases
- Each phase includes: Goal, Deliverables (✅ checkboxes), Validation criteria
- Realistic timeline estimates
**13. Future Considerations**
- Post-MVP enhancements
- Integration opportunities
- Advanced features for later phases
**14. Risks & Mitigations**
- 3-5 key risks with specific mitigation strategies
**15. Appendix** (if applicable)
- Related documents
- Key dependencies with links
- Repository/project structure
## Instructions
### 1. Extract Requirements
- Review the entire conversation history
- Identify explicit requirements and implicit needs
- Note technical constraints and preferences
- Capture user goals and success criteria
### 2. Synthesize Information
- Organize requirements into appropriate sections
- Fill in reasonable assumptions where details are missing
- Maintain consistency across sections
- Ensure technical feasibility
### 3. Write the PRD
- Use clear, professional language
- Include concrete examples and specifics
- Use markdown formatting (headings, lists, code blocks, checkboxes)
- Add code snippets for technical sections where helpful
- Keep Executive Summary concise but comprehensive
### 4. Quality Checks
- ✅ All required sections present
- ✅ User stories have clear benefits
- ✅ MVP scope is realistic and well-defined
- ✅ Technology choices are justified
- ✅ Implementation phases are actionable
- ✅ Success criteria are measurable
- ✅ Consistent terminology throughout
## Style Guidelines
- **Tone:** Professional, clear, action-oriented
- **Format:** Use markdown extensively (headings, lists, code blocks, tables)
- **Checkboxes:** Use ✅ for in-scope items, ❌ for out-of-scope
- **Specificity:** Prefer concrete examples over abstract descriptions
- **Length:** Comprehensive but scannable (typically 30-60 sections worth of content)
## Output Confirmation
After creating the PRD:
1. Confirm the file path where it was written
2. Provide a brief summary of the PRD contents
3. Highlight any assumptions made due to missing information
4. Suggest next steps (e.g., review, refinement, planning)
## Notes
- If critical information is missing, ask clarifying questions before generating
- Adapt section depth based on available details
- For highly technical products, emphasize architecture and technical stack
- For user-facing products, emphasize user stories and experience
- This command contains the complete PRD template structure - no external references needed
+157
View File
@@ -0,0 +1,157 @@
---
name: create-rules
description: Create global rules (CLAUDE.md) from codebase analysis
---
# Create Global Rules
Generate a CLAUDE.md file by analyzing the codebase and extracting patterns.
---
## Objective
Create project-specific global rules that give Claude context about:
- What this project is
- Technologies used
- How the code is organized
- Patterns and conventions to follow
- How to build, test, and validate
---
## Phase 1: DISCOVER
### Identify Project Type
First, determine what kind of project this is:
| Type | Indicators |
|------|------------|
| Web App (Full-stack) | Separate client/server dirs, API routes |
| Web App (Frontend) | React/Vue/Svelte, no server code |
| API/Backend | Express/Fastify/etc, no frontend |
| Library/Package | `main`/`exports` in package.json, publishable |
| CLI Tool | `bin` in package.json, command-line interface |
| Monorepo | Multiple packages, workspaces config |
| Script/Automation | Standalone scripts, task-focused |
### Analyze Configuration
Look at root configuration files:
```
package.json → dependencies, scripts, type
tsconfig.json → TypeScript settings
vite.config.* → Build tool
*.config.js/ts → Various tool configs
```
### Map Directory Structure
Explore the codebase to understand organization:
- Where does source code live?
- Where are tests?
- Any shared code?
- Configuration locations?
---
## Phase 2: ANALYZE
### Extract Tech Stack
From package.json and config files, identify:
- Runtime/Language (Node, Bun, Deno, browser)
- Framework(s)
- Database (if any)
- Testing tools
- Build tools
- Linting/formatting
### Identify Patterns
Study existing code for:
- **Naming**: How are files, functions, classes named?
- **Structure**: How is code organized within files?
- **Errors**: How are errors created and handled?
- **Types**: How are types/interfaces defined?
- **Tests**: How are tests structured?
### Find Key Files
Identify files that are important to understand:
- Entry points
- Configuration
- Core business logic
- Shared utilities
- Type definitions
---
## Phase 3: GENERATE
### Create CLAUDE.md
Use the template at `.agents/CLAUDE-template.md` as a starting point.
**Output path**: `CLAUDE.md` (project root)
**Adapt to the project:**
- Remove sections that don't apply
- Add sections specific to this project type
- Keep it concise - focus on what's useful
**Key sections to include:**
1. **Project Overview** - What is this and what does it do?
2. **Tech Stack** - What technologies are used?
3. **Commands** - How to dev, build, test, lint?
4. **Structure** - How is the code organized?
5. **Patterns** - What conventions should be followed?
6. **Key Files** - What files are important to know?
**Optional sections (add if relevant):**
- Architecture (for complex apps)
- API endpoints (for backends)
- Component patterns (for frontends)
- Database patterns (if using a DB)
- On-demand context references
---
## Phase 4: OUTPUT
```markdown
## Global Rules Created
**File**: `CLAUDE.md`
### Project Type
{Detected project type}
### Tech Stack Summary
{Key technologies detected}
### Structure
{Brief structure overview}
### Next Steps
1. Review the generated `CLAUDE.md`
2. Add any project-specific notes
3. Remove any sections that don't apply
4. Optionally create reference docs in `.agents/reference/`
```
---
## Tips
- Keep CLAUDE.md focused and scannable
- Don't duplicate information that's in other docs (link instead)
- Focus on patterns and conventions, not exhaustive documentation
- Update it as the project evolves
@@ -0,0 +1,83 @@
---
name: creating-github-issues
description: Use when creating a new GitHub issue or Pull Request, or when capturing tasks, bugs, or feature proposals in the external issue tracker.
---
# Creating GitHub Issues & PRs
## Overview
Never invent issue structures or write generic Pull Request bodies. Always read and strictly adhere to the repository's `.github/ISSUE_TEMPLATE/` and `PULL_REQUEST_TEMPLATE.md` files.
## When to Use
- You are about to run `gh issue create`.
- You are about to run `gh pr create`.
- The user asks you to log a bug, propose a feature, or create a PR.
## Core Pattern
### 1. Identify the Correct Template
Before writing *any* issue or PR descriptions, stop and check the `.github` directory.
- For PRs: Read `.github/PULL_REQUEST_TEMPLATE.md`.
- For Issues: Read the contents of `.github/ISSUE_TEMPLATE/` and select the appropriate markdown file (e.g., `bug_report.md`, `plugin_proposal.md`).
### 2. Parse the Frontmatter (Issues Only)
Issue templates contain YAML frontmatter. You must manually parse and apply these attributes when running the GitHub CLI command:
- `title:` → Must use the required prefix (e.g., `[BUG] The title...`).
- `labels:` → Pass these to the `--label` flag.
- `assignees:` → Pass to `--assignee` if specified.
### 3. Populate the EXACT Markdown Body
When constructing the body (e.g., using a temporary file or `$(cat <<'EOF')`), you must include **all** the markdown headers, questions, and checklists from the template. Answer the questions inline. Leave sections intact even if the content is "N/A" or empty.
## Before / After
❌ **BAD: Making up structure**
```bash
# Agent invents its own problem description format
gh issue create \
--title "Data engine bug" \
--body "## Context
It doesn't work.
## Fix
Need to update it." \
--label "bug"
```
✅ **GOOD: Using the exact template requirements**
```bash
# Agent read bug_report.md first, applying its frontmatter and body format
gh issue create \
--title "[BUG] Data engine extrapolation fails on landing" \
--label "bug" \
--body "$(cat <<'EOF'
**Describe the bug**
Extrapolation logic in animationHelpers.ts fails to halt when aircraft altitude reaches 0.
**To Reproduce**
Steps to reproduce the behavior:
1. Watch aircraft entity descend to airport.
2. Observe it continues moving horizontally past the runway.
**Expected behavior**
Entity should halt animation...
EOF
)"
```
## Quick Reference
| Action | Target File to Read First |
|--------|---------------------------|
| Submitting a bug | `.github/ISSUE_TEMPLATE/bug_report.md` |
| Proposing a feature | `.github/ISSUE_TEMPLATE/feature_request.md` |
| New data source plan | `.github/ISSUE_TEMPLATE/plugin_proposal.md` |
| Opening a PR | `.github/PULL_REQUEST_TEMPLATE.md` |
## Red Flags - STOP and Start Over
- Using `gh issue create` or `gh pr create` without explicitly navigating to and reading the template files first.
- Dropping checkboxes or required sections from the template (e.g., `Plugin Checklist` in PRs).
- Forgetting the prefix dictated by the issue template's frontmatter (like `[PLUGIN] `).
- Assigning random labels not defined in the template frontmatter.
**All of these mean: Stop execution, use `view_file` on the respective template, and start over.**
+19
View File
@@ -0,0 +1,19 @@
---
name: data-engine-cli
description: Instructions for using the wwv-data-engine CLI wrapper
---
# Workflow: Data Engine CLI (`/data-engine-cli`)
The user has invoked the `/data-engine-cli` command to interact directly with the Fastify API or seeders.
## Action Protocol
1. **Analyze Requirements:** Understand if the user wants to start the engine, ping its health, or debug a backend error.
2. **Execute Wrapper:**
- A wrapper script is present in the root folder at `scripts/data-engine.mjs`.
- Run `node scripts/data-engine.mjs health` to fetch the status of the `/health` endpoint if running.
- Run `node scripts/data-engine.mjs dev` to isolate the `wwv-data-engine` start logs inside your terminal.
## Restrictions
> [!CAUTION]
> - Do not guess endpoints. Always verify with `/health` or check the `routes` directory inside `packages/wwv-data-engine/src`.
+93
View File
@@ -0,0 +1,93 @@
---
name: debugging-coolify
description: Use when you need to troubleshoot deployed applications, services, databases, or deployment failures on a Coolify server using MCP tools, SSH into the instances, and mapping resource UUIDs to Docker host states.
---
# Debugging Coolify
## Overview
This workflow provides the exact methodology to cross-reference Coolify MCP data with raw Docker state on the host to effectively debug infrastructure and application issues. It outlines the host mapping ontology for the local Coolify server (e.g., accessible via `ssh [email protected]`) and how to bridge Coolify UUIDs to physical folders and volumes.
## When to Use
- Applications failing to deploy or start on Coolify
- Checking database or service logs
- Verifying environment variables on running containers
- Investigating 502 Bad Gateway errors from Coolify proxy
- Finding where files and configuration are stored on the Docker host
- "I need to check the database volume for..."
- "SSH into the server and find the configuration for..."
- "I can't find the source code on Coolify..."
- "Check the local laptop server logs"
## Core Pattern: Correlate UUID to Raw State
Coolify abstracts Docker. When things break, you must correlate Coolify's UUIDs to the underlying Docker containers and volumes.
1. **Find the UUID** using Coolify MCP (`mcp_coolify_list_applications`, `mcp_coolify_list_services`, `mcp_coolify_list_databases`).
2. **Diagnose via MCP** using `mcp_coolify_diagnose_app` or `mcp_coolify_application_logs(uuid, lines=200)`.
3. **Map to Host Config** using the SSH host mapping pipeline. Container names and network configs are prefixed with the UUID.
4. **Drop to Raw Docker** when MCP logs aren't enough (e.g., `docker inspect`, `docker exec`, proxy logs) over SSH.
## Host Mapping Reference
Here is the exact topology of the local Coolify server hosted on the laptop:
| Resource | Physical Path on Host (`192.168.68.69`) |
|----------|-----------------------------------------|
| **Base Coolify Data** | `/data/coolify` |
| **Application Configs** | `/data/coolify/applications/<uuid>/` |
| **Service Configs** | `/data/coolify/services/<uuid>/` |
| **Proxy Details** | `/data/coolify/proxy/` |
| **Docker Volumes** | `/var/lib/docker/volumes/<uuid>_<volume_name>/_data` |
## Discovery Pipeline
When requested to debug something on the Coolify server, follow this pipeline to accurately target the data without guessing:
1. **Get the UUID**: Use the `mcp_coolify_list_applications` or `mcp_coolify_list_services` tools to find the UUID of the target resource.
- Example Application (`worldwideview-demo`): `nmn55t4io3myfubs72worn7k`
- Example Service (`umami`): `s6iqy8m4mlf3x6e5u4agxsp0`
2. **Access the Docker Compose File**: The raw compose configurations Coolify dynamically generates live at `/data/coolify/(applications|services)/<uuid>/docker-compose.yml`.
- Command: `ssh [email protected] "cat /data/coolify/applications/<uuid>/docker-compose.yml"`
3. **Inspect Volumes**: Coolify uses standard Docker local volumes mapping, prefixing the volume names with the UUID. Retrieve them directly through Docker or by accessing the mapped directory.
- Command: `ssh [email protected] "docker volume ls | grep <uuid>"`
- Example Volume Mount: `/var/lib/docker/volumes/nmn55t4io3myfubs72worn7k_engine-data/_data`
## Quick Reference For Issues
| Issue | First Action | Deep Dive |
|-------|--------------|-----------|
| App won't start | `mcp_coolify_application_logs(uuid)` | SSH into host, check `/data/coolify/applications/<uuid>/docker-compose.yml` |
| Database connection error | `mcp_coolify_get_database(uuid)` | Query `docker ps \| grep <uuid>` then `docker logs <container>` |
| Proxy routing 502 | `mcp_coolify_diagnose_app(uuid)` | SSH into host, check Traefik proxy logs: `ssh [email protected] "docker logs coolify-proxy"` |
| Missing/corrupt data | Recall Host Mapping | SSH and inspect volumes: `/var/lib/docker/volumes/<uuid>_<name>/_data` |
| Deployment failed | `mcp_coolify_list_deployments` | Find deployment UUID, use `mcp_coolify_deployment(action: get, uuid: <uuid>, lines: 200)` to get raw build logs |
## Common Mistakes & Red Flags
### Trying to find files in `/var/www` or `/home`
- **What goes wrong:** Coolify does not use traditional host-bound document roots. Everything is containerized.
- **Fix:** Access `/data/coolify` or directly jump into the container via `docker exec`.
### SSHing with a password
- **What goes wrong:** The connection might hang or prompt interactively.
- **Fix:** Your host agent is already keyed for `[email protected]`. Ensure you use non-interactive commands: `ssh [email protected] "your command here"`.
### Guessing Container Names
- **What goes wrong:** Coolify generates container names dynamically based on internal routing (e.g., `wwv-data-engine-nmn55t4io3myfubs72worn7k-114309953928`).
- **Fix:** Always query `docker ps --format '{{.Names}}'` and `grep` the UUID obtained from the Coolify MCP to accurately identify the target container.
### Editing Files on Host Direct
- **What goes wrong:** Coolify will overwrite generated files.
- **Fix:** Update via MCP settings/environment variables or repo commits to trigger redeploy. Never modify raw `docker-compose.yml` under `/data/coolify/`.
### Re-running Deployment Repeatedly
- **What goes wrong:** The deployment failed, but standard logs are empty, and restarting repeats the error. standard runtime logs are distinct.
- **Fix:** Use deployment MCP tools to check the build log.
**Red Flags - STOP and Start Over:**
- Guessing container paths or volume names.
- Using standard `systemctl` commands to check application status instead of docker.
- Modifying docker-compose rather than relying on standard git updates.
**All of these mean: Stop. Get the UUID via Coolify MCP. Inspect via Docker using that UUID, or use deployment-specific logs.**
@@ -0,0 +1,60 @@
---
name: developing-plugins
description: Use when modifying existing plugins, creating new plugins, or troubleshooting why plugin UI/fetch changes are not showing up in the local development environment
---
# Developing Plugins
## Overview
This skill defines the modern `wwv-cli` based workflow for developing plugins in WorldWideView. It completely replaces the legacy methods of manual database syncing, manually patching SQLite, and editing `next.config.ts`. The modern workflow uses hot-reloading Vite bundlers and automated database linking via the `dev-link` API.
## When to Use
- You are writing or modifying code inside `packages/wwv-plugin-*`
- You need to test your plugin changes on the main `localhost:3000` engine
- You are debugging why a plugin UI component (Sidebar, Overlay, fetch logic) is not updating after you changed the code
## Core Pattern: The Sync Workflow
**DO NOT edit Next.js configurations or manually patch SQLite for local plugin dev.**
Instead, use the `link` workflow.
1. **Start the Main Engine:**
In your engine directory (e.g., `c:\dev\worldwideview`):
```bash
pnpm run dev
```
2. **Start the Plugin Watcher:**
In your plugins directory (e.g., `c:\dev\worldwideview-plugins`):
```bash
pnpm run sync:all
```
*Alternatively, if working inside a single plugin package, run:*
```bash
node ../wwv-cli/dist/index.mjs link
```
3. **How it Works:**
The `link` command automates two critical steps:
- Starts a Vite bundler in watch mode that recompiles your plugin instantly on every save.
- Pings `/api/plugins/dev-link` on the main engine to inject the local manifest into the engine's SQLite database. This points the engine directly to your local watch bundle.
4. **Verify:**
Because plugins are dynamically imported external bundles, Next.js Fast Refresh does not apply to them. **You MUST manually refresh your browser** at `localhost:3000` to see changes after Vite recompiles.
## Common Mistakes
| Excuse / Mistake | Reality |
|------------------|---------|
| "I ran `pnpm build` in the plugin" | The engine won't know about the new bundle unless the database is linked. Use the `link` command or `sync:all`. |
| "I'll manually update the SQLite DB to point to my local file" | The `dev-link` API handles upserting automatically during the link process. |
| "I'm waiting for Next.js to hot-reload my plugin" | External ES modules do not trigger Next.js HMR. You must refresh the browser page manually. |
| "I'll just add my plugin to `transpilePackages`" | This is the legacy declarative workflow. Modern plugins are independent dynamic bundles. |
## Red Flags - STOP and Start Over
- Modifying `next.config.ts` to add a plugin.
- Opening the SQLite database to manually change a plugin URL.
- Writing a script to copy files over without using `wwv-cli link`.
**All of these mean: Revert your manual changes. Start over with `wwv-cli link`.**
@@ -0,0 +1,190 @@
---
name: dispatching-parallel-agents
description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
---
# Dispatching Parallel Agents
## Overview
You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.
**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently.
## When to Use
```dot
digraph when_to_use {
"Multiple failures?" [shape=diamond];
"Are they independent?" [shape=diamond];
"Single agent investigates all" [shape=box];
"One agent per problem domain" [shape=box];
"Can they work in parallel?" [shape=diamond];
"Sequential agents" [shape=box];
"Parallel dispatch" [shape=box];
"Multiple failures?" -> "Are they independent?" [label="yes"];
"Are they independent?" -> "Single agent investigates all" [label="no - related"];
"Are they independent?" -> "Can they work in parallel?" [label="yes"];
"Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
"Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
}
```
**Use when:**
- 3+ test files failing with different root causes
- Multiple subsystems broken independently
- Each problem can be understood without context from others
- No shared state between investigations
**Don't use when:**
- Failures are related (fix one might fix others)
- Need to understand full system state
- Agents would interfere with each other
## The Pattern
### 1. Identify Independent Domains
Group failures by what's broken:
- File A tests: Tool approval flow
- File B tests: Batch completion behavior
- File C tests: Abort functionality
Each domain is independent - fixing tool approval doesn't affect abort tests.
### 2. Create Focused Agent Tasks
Each agent gets:
- **Specific scope:** One test file or subsystem
- **Clear goal:** Make these tests pass
- **Constraints:** Don't change other code
- **Expected output:** Summary of what you found and fixed
### 3. Dispatch in Parallel
```typescript
// In Antigravity / Gemini CLI environment
Task("Fix agent-tool-abort.test.ts failures")
Task("Fix batch-completion-behavior.test.ts failures")
Task("Fix tool-approval-race-conditions.test.ts failures")
// Dispatch them in parallel using run_command with background capabilities
```
### 4. Review and Integrate
When agents return:
- Read each summary
- Verify fixes don't conflict
- Run full test suite
- Integrate all changes
## Agent Prompt Structure
Good agent prompts are:
1. **Focused** - One clear problem domain
2. **Self-contained** - All context needed to understand the problem
3. **Specific about output** - What should the agent return?
```markdown
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:
1. "should abort tool with partial output capture" - expects 'interrupted at' in message
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
3. "should properly track pendingToolCount" - expects 3 results but gets 0
These are timing/race condition issues. Your task:
1. Read the test file and understand what each test verifies
2. Identify root cause - timing issues or actual bugs?
3. Fix by:
- Replacing arbitrary timeouts with event-based waiting
- Fixing bugs in abort implementation if found
- Adjusting test expectations if testing changed behavior
Do NOT just increase timeouts - find the real issue.
Return: Summary of what you found and what you fixed.
```
## Common Mistakes
**❌ Too broad:** "Fix all the tests" - agent gets lost
**✅ Specific:** "Fix agent-tool-abort.test.ts" - focused scope
**❌ No context:** "Fix the race condition" - agent doesn't know where
**✅ Context:** Paste the error messages and test names
**❌ No constraints:** Agent might refactor everything
**✅ Constraints:** "Do NOT change production code" or "Fix tests only"
**❌ Vague output:** "Fix it" - you don't know what changed
**✅ Specific:** "Return summary of root cause and changes"
## When NOT to Use
**Related failures:** Fixing one might fix others - investigate together first
**Need full context:** Understanding requires seeing entire system
**Exploratory debugging:** You don't know what's broken yet
**Shared state:** Agents would interfere (editing same files, using same resources)
## Real Example from Session
**Scenario:** 6 test failures across 3 files after major refactoring
**Failures:**
- agent-tool-abort.test.ts: 3 failures (timing issues)
- batch-completion-behavior.test.ts: 2 failures (tools not executing)
- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)
**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions
**Dispatch:**
```
Agent 1 → Fix agent-tool-abort.test.ts
Agent 2 → Fix batch-completion-behavior.test.ts
Agent 3 → Fix tool-approval-race-conditions.test.ts
```
**Results:**
- Agent 1: Replaced timeouts with event-based waiting
- Agent 2: Fixed event structure bug (threadId in wrong place)
- Agent 3: Added wait for async tool execution to complete
**Integration:** All fixes independent, no conflicts, full suite green
**Time saved:** 3 problems solved in parallel vs sequentially
## Key Benefits
1. **Parallelization** - Multiple investigations happen simultaneously
2. **Focus** - Each agent has narrow scope, less context to track
3. **Independence** - Agents don't interfere with each other
4. **Speed** - 3 problems solved in time of 1
## Verification
After agents return:
1. **Review each summary** - Understand what changed
2. **Check for conflicts** - Did agents edit same code?
3. **Run full suite** - Verify all fixes work together
4. **Spot check** - Agents can make systematic errors
## Real-World Impact
From debugging session (2025-10-03):
- 6 failures across 3 files
- 3 agents dispatched in parallel
- All investigations completed concurrently
- All fixes integrated successfully
- Zero conflicts between agent changes
## Antigravity CLI Orchestration
As Antigravity, you can orchestrate this fully autonomously using the `run_command` tool to spawn `gemini` CLI subagents in the background.
1. **Dispatch:** Use `run_command` with a high enough `WaitMsBeforeAsync` so the processes run in the background (e.g., `gemini -p task1.md`, `gemini -p task2.md`).
2. **Monitor:** Periodically check their progress via the `command_status` tool.
3. **Merge:** When all background commands complete, review their outputs and integrate their fixes.
+102
View File
@@ -0,0 +1,102 @@
---
name: execute
description: Execute an implementation plan
argument-hint: [path-to-plan]
---
# Execute: Implement from Plan
## Plan to Execute
Read plan file: `$ARGUMENTS`
## Execution Instructions
### 1. Read and Understand
- Read the ENTIRE plan carefully
- Understand all tasks and their dependencies
- Note the validation commands to run
- Review the testing strategy
### 2. Execute Tasks in Order
For EACH task in "Step by Step Tasks":
#### a. Navigate to the task
- Identify the file and action required
- Read existing related files if modifying
#### b. Implement the task
- Follow the detailed specifications exactly
- Maintain consistency with existing code patterns
- Include proper type hints and documentation
- Add structured logging where appropriate
#### c. Verify as you go
- After each file change, check syntax
- Ensure imports are correct
- Verify types are properly defined
### 3. Implement Testing Strategy
After completing implementation tasks:
- Create all test files specified in the plan
- Implement all test cases mentioned
- Follow the testing approach outlined
- Ensure tests cover edge cases
### 4. Run Validation Commands
Execute ALL validation commands from the plan in order:
```bash
# Run each command exactly as specified in plan
```
If any command fails:
- Fix the issue
- Re-run the command
- Continue only when it passes
### 5. Final Verification
Before completing:
- ✅ All tasks from plan completed
- ✅ All tests created and passing
- ✅ All validation commands pass
- ✅ Code follows project conventions
- ✅ Documentation added/updated as needed
## Output Report
Provide summary:
### Completed Tasks
- List of all tasks completed
- Files created (with paths)
- Files modified (with paths)
### Tests Added
- Test files created
- Test cases implemented
- Test results
### Validation Results
```bash
# Output from each validation command
```
### Ready for Commit
- Confirm all changes are complete
- Confirm all validations pass
- Ready for `/commit` command
## Notes
- If you encounter issues not addressed in the plan, document them
- If you need to deviate from the plan, explain why
- If tests fail, fix implementation until they pass
- Don't skip validation steps
+49
View File
@@ -0,0 +1,49 @@
---
name: five
description: Use the "Five Whys" root cause analysis technique to deeply understand problems.
---
# Five Whys Analysis
Use the "Five Whys" root cause analysis technique to deeply understand problems.
## Process:
### 1. Define the Problem
Clearly state the issue or symptom
### 2. Ask "Why?" Five Times
- Why did this problem occur? → Answer 1
- Why did Answer 1 happen? → Answer 2
- Why did Answer 2 happen? → Answer 3
- Why did Answer 3 happen? → Answer 4
- Why did Answer 4 happen? → Answer 5 (Root Cause)
### 3. Validate Root Cause
- Verify the logical chain
- Check if addressing root cause prevents recurrence
- Consider multiple root causes if applicable
### 4. Develop Solutions
- Address the root cause, not just symptoms
- Create preventive measures
- Consider systemic improvements
## Example:
**Problem**: Application crashes when processing large files
1. **Why?** → The application runs out of memory
2. **Why?** → It loads entire file into memory at once
3. **Why?** → The file parser wasn't designed for streaming
4. **Why?** → Initial requirements only specified small files
5. **Why?** → Requirements gathering didn't consider future growth
**Root Cause**: Incomplete requirements gathering process
**Solution**: Implement streaming parser and improve requirements process
## Best Practices:
- Focus on process, not people
- Look for systemic issues
- Document the analysis
- Involve relevant stakeholders
- Test solutions address root cause
@@ -0,0 +1,32 @@
---
name: generate-user-roadmap
description: Generate an updated user-facing roadmap
---
# Generate User-Facing Roadmap Workflow
Use this workflow to translate the project's technical `ROADMAP.md` into a clear, user-facing summary of future features.
1. **Read the Technical Roadmap**
- Read the contents of `ROADMAP.md` to discover new planned stages and unchecked items.
2. **Filter for End-Users**
- Extract only the features that impact the daily usage of the globe for an end-user.
- Ignore backend infrastructure, publisher workflows, and CI/CD tasks unless they directly translate to a user-facing capability.
3. **Format and Structure**
- Group the extracted features into three sections, in this exact order:
1. `### Major Features`
2. `### Minor Features`
3. `### Recently Implemented` (Keep this at the very bottom of the document).
4. **Apply Target Tone and Formatting**
- **No Fluff:** Remove marketing buzzwords, corporate language, and overly technical descriptions.
- **Plugin Formatting:** Format plugins as `[Short Name] Plugin`. Keep the name 2-3 words. If the name isn't clear enough, use `[Short Name] Plugin for [short description]`.
- **Example Good:** `* Conflict Zones Plugin` or `* GPS Jamming Plugin`
- **One-Liners:** Keep each feature strictly to a single, concise line. Do NOT use a `Title: Description` format.
- **Tag New Items:** Prefix completely new features with a `[NEW]` tag (e.g. `* [NEW] AI Copilot`).
- **Strikethrough Implemented:** Any features that have been completed must be moved to the `### Recently Implemented` section at the bottom and formatted with markdown strikethrough (e.g. `* ~~Conflict Zones Plugin~~`).
5. **Update Context**
- After generating the new list, update `c:\dev\worldwideview\.agents\context\07-user-facing-roadmap.md` using the `/update-context` skill to ensure persistent knowledge remains accurate.
+179
View File
@@ -0,0 +1,179 @@
---
name: github-workflow
description: Use when the user invokes /github-workflow to manage GitHub — issue creation, branching, committing, pushing, and PR opening. Accepts flags to modify behavior. Do NOT invoke automatically; this skill is always user-initiated.
---
# GitHub Workflow
## Overview
Single entry point for all GitHub work. Detects current branch state, accepts flags to control behavior, and proposes a PR when work is done.
**Default behavior (no flags):** issue → branch → code → push → PR
---
## Flags
| Flag | Effect |
|---|---|
| `--worktree` | Creates an isolated worktree checkout instead of a plain branch (in `.worktrees/` or an AI agent directory) |
| `--no-pr` | Stops after push, skips PR creation |
| `--pr` | Jumps straight to PR phase. **Note:** If invoked with uncommitted changes on `main`, automatically run Phases 1-6 retroactively (create branch, commit, push) before opening the PR. |
| `--no-issue` | Skips issue creation (for tiny untracked changes) |
| `--continue` | Skips branch detection, resumes the current branch as-is |
| `--merge-cleanup` | Completes the lifecycle: merges the PR, prunes worktree, and deletes local branch |
| `--direct-main` | **(Shortcut)** Bypasses branching and PR entirely. Commits and pushes straight to `main`. Allowed **ONLY** for low-risk `chore`, `docs`, and strictly typed `fix` changes that do not alter core logic. |
---
## Phase 0: Branch Detection (always runs first, unless `--continue`)
```bash
git branch --show-current
```
**If on `main`:** proceed to Phase 1.
**If on a branch matching `(feature|bug|chore)/(\d+)-.*`:**
1. Extract the issue number `N` from the branch name
2. Fetch issue context:
```bash
gh issue view {N} --json title,state,labels
```
3. Compare the issue title/labels to the user's current request:
- **Clearly related** (same feature/bug, issue still open) → offer to continue:
> "You're already on `{branch}` tracking issue #{N}: '{title}'. Continue working here?"
> Options: **[Y] Continue on this branch** | **[W] Open a new worktree instead** | **[N] Start fresh on main**
- **Clearly unrelated** (different feature, issue closed, or wrong type) → warn:
> "⚠️ You're on `{branch}` (issue #{N}: '{title}'), which appears unrelated to this task. Recommend switching to main first."
> Options: **[S] Switch to main and start fresh** | **[W] Keep this branch, create a worktree for new work** | **[I] Ignore and continue here**
- **Ambiguous** → ask the user to clarify before proceeding
**If on an unrecognized branch (no issue number):**
> "You're on branch `{branch}` which doesn't follow the naming convention. Is this intentional?"
> Options: **[C] Continue here** | **[M] Switch to main first**
---
## Phase 1: Create Issue (skip with `--no-issue`)
**REQUIRED SUB-SKILL:** You MUST use the `/creating-github-issues` skill. Read the appropriate template from `.github/ISSUE_TEMPLATE/` (if it exists), parse its frontmatter for title formats and labels, and write a temporary Markdown file to use as the issue body.
Example command structure:
```bash
gh issue create --title "[PREFIX] {title}" --label "{labels}" --body-file /path/to/generated/temp_body.md
# ALWAYS delete temp_body.md after successful creation
```
Save the returned number: `ISSUE=<number>`
---
## Phase 2: Create Branch or Worktree
**Without `--worktree`:**
```bash
git checkout main && git pull origin main
git checkout -b {type}/${ISSUE}-{kebab-desc}
# type = feature | bug | chore
```
**With `--worktree`:** invoke `/worktree-dev` skill, passing branch name `{type}/${ISSUE}-{kebab-desc}`.
---
## Phase 3: Implement
(User codes. Agent assists. Normal development loop.)
---
## Phase 4: Validate
```bash
pnpm build # must pass
pnpm test # must pass
```
Both must pass before committing. Fix any failures before proceeding.
*(Note: For strictly Markdown/documentation changes, you may skip the build/test cycle to save time.)*
---
## Phase 5: Commit
Invoke `/commit` skill — bumps semver, enforces conventional commit format.
---
## Phase 6: Push
```bash
git push -u origin {branch-name}
```
---
## Phase 7: PR or Stop
### Auto-detection of readiness
After Phase 6, check:
```bash
git status # working tree clean?
pnpm build # still passes?
pnpm test # still passes?
```
If all three are clean and no open TODOs appear in recently changed files, propose:
> "Build and tests pass, working tree is clean. Ready to open a PR?"
### `--no-pr` flag
If `--no-pr` was passed, **stop here** after push. Do not propose a PR.
### Opening the PR (default or `--pr`)
**REQUIRED SUB-SKILL:** You MUST use the `/creating-github-issues` skill. Read `.github/PULL_REQUEST_TEMPLATE.md` (if it exists) and ensure the PR body contains the exact checklists and sections required by the project. Write this to a temporary markdown file.
Example command structure:
```bash
gh pr create --title "{type}: {description}" --body-file /path/to/generated/temp_pr_body.md
# ALWAYS delete temp_pr_body.md after successful creation
```
### Auto-merge decision
- **Low-risk** (chore, docs, config — no logic changes):
```bash
gh pr merge --auto --squash
```
- **Feature or bug PRs:** invoke `/pr-review` and wait for human approval.
---
## Phase 8: Merge and Cleanup (with `--merge-cleanup`)
When explicitly invoked with `--merge-cleanup` after a PR is approved and CI is green:
1. Merge PR on GitHub: `gh pr merge {PR_NUMBER} --squash --delete-branch`
2. If using a worktree, ensure no background processes (like `pnpm test-worktree`) are locking files, then remove it:
```bash
# Note: The worktree could be in .worktrees/ or an AI agent directory (.gemini/antigravity/worktrees)
# Use `git worktree list` to find the correct absolute path before removing it.
git worktree remove <actual-path-to-worktree> --force
git worktree prune
```
3. Delete local branch: `git branch -D {branch-name}`
4. Sync main: `git checkout main && git pull origin main`
---
## Quick Reference
```
/github-workflow # standard: issue → branch → code → PR
/github-workflow --worktree # same, isolated in a worktree
/github-workflow --no-pr # stop after push, no PR
/github-workflow --pr # work done, just open the PR now
/github-workflow --no-issue # skip issue creation
/github-workflow --continue # skip branch detection, resume current branch
/github-workflow --merge-cleanup # merges PR, cleans up branch and worktree
```
+66
View File
@@ -0,0 +1,66 @@
---
name: init-project
description: Use when initializing a new project locally — runs setup commands to configure environment, install dependencies, start databases, and validate the dev server is working.
---
# Initialize Project
Run the following commands to set up and start the project locally:
## 1. Create Environment File
```bash
cp .env.example .env
```
Creates your local environment configuration from the example template.
## 2. Install Dependencies
```bash
uv sync
```
Installs all Python packages defined in pyproject.toml.
## 3. Start Database
```bash
docker-compose up -d db
```
Starts PostgreSQL 18 in a Docker container on port 5433.
## 4. Run Database Migrations
```bash
uv run alembic upgrade head
```
Applies all pending database migrations.
## 5. Start Development Server
```bash
uv run uvicorn app.main:app --reload --port 8123
```
Starts the FastAPI server with hot-reload on port 8123.
## 6. Validate Setup
Check that everything is working:
```bash
# Test API health
curl -s http://localhost:8123/health
# Test database connection
curl -s http://localhost:8123/health/db
```
Both should return `{"status":"healthy"}` responses.
## Access Points
- Swagger UI: http://localhost:8123/docs
- Health Check: http://localhost:8123/health
- Database: localhost:5433
## Cleanup
To stop services:
```bash
# Stop dev server: Ctrl+C
# Stop database: docker-compose down
```
+23
View File
@@ -0,0 +1,23 @@
---
name: local-dev
description: Instructions for checking, starting, and troubleshooting local dev
---
# Workflow: Local Development (`/local-dev`)
The user has invoked the `/local-dev` command to start the unified local development environment or troubleshoot backend issues.
## 1. Action Protocol
1. **Analyze Requirements:** Understand if the user wants to start everything (Frontend and all Backends) or just debug specific issues.
2. **Setup DB:** If they just cloned or encountered schema mismatch, run `pnpm run db:reset`.
3. **Start Servers:**
- You can start everything using `pnpm run dev:all`.
- Note: The VS Code `tasks.json` has this set up if the user prefers attaching a graphical debugger! Let them know.
## 2. Troubleshooting Backend Connectivity
- If the data engine is not responding, check running process status using `node scripts/data-engine.mjs health`
- You may also verify if Prisma or SQLite files are locked by stopping the server and clearing `.next` (`pnpm run clean`).
## 3. General Debugging Tips
- Next.js Client errors are best handled using the VSCode Chrome Debugger.
- Fastify backend (Data Engine) errors can be caught via VS Code `WWV Data Engine: debug` launch config.
+170
View File
@@ -0,0 +1,170 @@
---
name: plan-feature
description: "Create comprehensive feature plan with deep codebase analysis and research"
---
# Plan a new task
## Feature: $ARGUMENTS
## Mission
Transform a feature request into a **comprehensive implementation plan** through systematic codebase analysis, external research, and strategic planning.
**Core Principle**: We do NOT write code in this phase. Our goal is to create a context-rich implementation plan that enables one-pass implementation success for ai agents.
**Key Philosophy**: Context is King. The plan must contain ALL information needed for implementation - patterns, mandatory reading, documentation, validation commands - so the execution agent succeeds on the first attempt.
## Planning Process
### Phase 1: Feature Understanding
**Deep Feature Analysis:**
- Extract the core problem being solved
- Identify user value and business impact
- Determine feature type: New Capability/Enhancement/Refactor/Bug Fix
- Assess complexity: Low/Medium/High
- Map affected systems and components
**Create User Story Format Or Refine If Story Was Provided By The User:**
```
As a <type of user>
I want to <action/goal>
So that <benefit/value>
```
### Phase 2: Codebase Intelligence Gathering
**Use specialized agents and parallel analysis:**
**1. Project Structure Analysis**
- Detect primary language(s), frameworks, and runtime versions
- Map directory structure and architectural patterns
- Identify service/component boundaries and integration points
- Locate configuration files (pyproject.toml, package.json, etc.)
- Find environment setup and build processes
**2. Pattern Recognition** (Use specialized subagents when beneficial)
- Search for similar implementations in codebase
- Identify coding conventions:
- Naming patterns (CamelCase, snake_case, kebab-case)
- File organization and module structure
- Error handling approaches
- Logging patterns and standards
- Extract common patterns for the feature's domain
- Document anti-patterns to avoid
- Check CLAUDE.md for project-specific rules and conventions
**3. Dependency Analysis**
- Catalog external libraries relevant to feature
- Understand how libraries are integrated (check imports, configs)
- Find relevant documentation in docs/, ai_docs/, .agents/reference or ai-wiki if available
- Note library versions and compatibility requirements
**4. Testing Patterns**
- Identify test framework and structure (pytest, jest, etc.)
- Find similar test examples for reference
- Understand test organization (unit vs integration)
- Note coverage requirements and testing standards
**5. Integration Points**
- Identify existing files that need updates
- Determine new files that need creation and their locations
- Map router/API registration patterns
- Understand database/model patterns if applicable
- Identify authentication/authorization patterns if relevant
**Clarify Ambiguities:**
- If requirements are unclear at this point, ask the user to clarify before you continue
- Get specific implementation preferences (libraries, approaches, patterns)
- Resolve architectural decisions before proceeding
### Phase 3: External Research & Documentation
**Documentation Gathering:**
- Research latest library versions and best practices
- Find official documentation with specific section anchors
- Locate implementation examples and tutorials
- Identify common gotchas and known issues
- Check for breaking changes and migration guides
**Compile Research References:**
```markdown
## Relevant Documentation
- [Library Official Docs](https://example.com/docs#section)
- Specific feature implementation guide
- Why: Needed for X functionality
- [Framework Guide](https://example.com/guide#integration)
- Integration patterns section
- Why: Shows how to connect components
```
### Phase 4: Deep Strategic Thinking
**Think Harder About:**
- How does this feature fit into the existing architecture?
- What are the critical dependencies and order of operations?
- What could go wrong? (Edge cases, race conditions, errors)
- How will this be tested comprehensively?
- What performance implications exist?
- Are there security considerations?
- How maintainable is this approach?
### Phase 5: Plan Structure Generation
**Output Filename**: `.agents/plans/{kebab-case-descriptive-name}.md`
**Plan Template:**
```markdown
# Feature: <feature-name>
## Feature Description
<Detailed description>
## User Story
As a <type of user>
I want to <action/goal>
So that <benefit/value>
## CONTEXT REFERENCES
### Relevant Codebase Files
- `path/to/file.py` (lines 15-45) - Why: Contains pattern for X
### New Files to Create
- `path/to/new_service.py` - Service implementation
## STEP-BY-STEP TASKS
### Task N: {ACTION} {target_file}
- **IMPLEMENT**: {Specific detail}
- **PATTERN**: {Reference - file:line}
- **VALIDATE**: `{executable command}`
## VALIDATION COMMANDS
## ACCEPTANCE CRITERIA
- [ ] Feature implements all specified functionality
- [ ] All validation commands pass
```
## Quality Criteria
- Another developer could execute without additional context
- Tasks ordered by dependency
- Each task is atomic and independently testable
- Pattern references include specific file:line numbers
- No generic references — all specific and actionable
+66
View File
@@ -0,0 +1,66 @@
---
description: Comprehensive pull request review from multiple perspectives.
---
# Pull Request Review
Comprehensive pull request review from multiple perspectives.
## Review Roles:
### 1. Product Manager Review
- **Business Value**: Does this deliver promised value?
- **User Experience**: Will users benefit from this change?
- **Strategic Alignment**: Does it align with product goals?
- **Feature Completeness**: Are all requirements met?
- **Action**: Provide directives for maximum impact
### 2. Developer Review
- **Code Quality**: Is code clean and maintainable?
- **Standards**: Does it follow coding conventions?
- **Performance**: Are there efficiency concerns?
- **Scalability**: Will it handle growth?
- **Refactoring**: Any code that needs improvement?
- **Action**: Suggest specific code improvements
### 3. Quality Engineer Review
- **Test Coverage**: Are all paths tested?
- **Edge Cases**: Are boundary conditions handled?
- **Regression Risk**: Could this break existing features?
- **Test Quality**: Are tests comprehensive and clear?
- **Action**: Identify missing tests and scenarios
### 4. Security Engineer Review
- **Vulnerabilities**: Any security risks?
- **Data Handling**: Is sensitive data protected?
- **Authentication**: Are auth checks proper?
- **Input Validation**: Is user input sanitized?
- **Compliance**: Does it meet security standards?
- **Action**: Flag security concerns immediately
### 5. DevOps Review
- **CI/CD Integration**: Will builds succeed?
- **Configuration**: Are configs properly managed?
- **Infrastructure**: Any deployment concerns?
- **Monitoring**: Are metrics and logs adequate?
- **Rollback**: Can changes be safely reverted?
- **Action**: Ensure smooth deployment
### 6. UI/UX Designer Review
- **Visual Consistency**: Does it match design system?
- **Usability**: Is it intuitive to use?
- **Accessibility**: Is it accessible to all users?
- **Responsive**: Does it work on all devices?
- **Polish**: Any rough edges to smooth?
- **Action**: Ensure delightful user experience
## Review Process:
1. Read PR description and linked issues
2. Review code changes systematically
3. Test functionality locally if applicable
4. Consider each perspective above
5. Leave constructive feedback
6. Approve or request changes
## Key Principle:
**Improvements scheduled for "later" must be addressed NOW!**
+76
View File
@@ -0,0 +1,76 @@
---
name: prime
description: Use when loading project context at the start of a session — analyzes structure, reads core documentation, and provides an overview of the codebase state.
---
# Prime: Load Project Context
## Objective
Build comprehensive understanding of the codebase by analyzing structure, documentation, and key files.
## Process
### 1. Analyze Project Structure
List all tracked files:
!`git ls-files`
Show directory structure:
On Linux, run: `tree -L 3 -I 'node_modules|__pycache__|.git|dist|build'`
### 2. Read Core Documentation
- Read the PRD.md or similar spec file
- Read CLAUDE.md or similar global rules file
- Read README files at project root and major directories
- Read any architecture documentation
- Read the drizzle config so you understand the database schema
### 3. Identify Key Files
Based on the structure, identify and read:
- Main entry points (main.py, index.ts, app.py, etc.)
- Core configuration files (pyproject.toml, package.json, tsconfig.json)
- Key model/schema definitions
- Important service or controller files
### 4. Understand Current State
Check recent activity:
!`git log -10 --oneline`
Check current branch and status:
!`git status`
## Output Report
Provide a concise summary covering:
### Project Overview
- Purpose and type of application
- Primary technologies and frameworks
- Current version/state
### Architecture
- Overall structure and organization
- Key architectural patterns identified
- Important directories and their purposes
### Tech Stack
- Languages and versions
- Frameworks and major libraries
- Build tools and package managers
- Testing frameworks
### Core Principles
- Code style and conventions observed
- Documentation standards
- Testing approach
### Current State
- Active branch
- Recent changes or development focus
- Any immediate observations or concerns
**Make this summary easy to scan - use bullet points and clear headers.**
@@ -0,0 +1,192 @@
---
name: prisma-database-setup
description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Prisma Database Setup
Comprehensive guides for configuring Prisma ORM with various database providers.
## When to Apply
Reference this skill when:
- Initializing a new Prisma project
- Switching database providers
- Configuring connection strings and environment variables
- Troubleshooting database connection issues
- Setting up database-specific features
- Generating and instantiating Prisma Client
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Provider Guides | CRITICAL | provider names |
| 2 | Prisma Postgres | HIGH | `prisma-postgres` |
| 3 | Client Setup | CRITICAL | `prisma-client-setup` |
## System Prerequisites
- **Node.js 20.19.0+**
- **TypeScript 5.4.0+**
## Bun Runtime
If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js.
## Supported Databases
| Database | Provider String | Notes |
|----------|-----------------|-------|
| PostgreSQL | `postgresql` | Default, full feature support |
| MySQL | `mysql` | Widespread support, some JSON diffs |
| SQLite | `sqlite` | Local file-based, no enum/scalar lists |
| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance |
| SQL Server | `sqlserver` | Microsoft ecosystem |
| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible |
| Prisma Postgres | `postgresql` | Managed serverless database |
## Configuration Files
Your configuration shape depends on the provider and Prisma major version:
1. **All providers** use **`prisma/schema.prisma`**.
2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs.
3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup.
## Driver Adapters
The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`.
| Database | Adapter | JS Driver |
|----------|---------|-----------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| CockroachDB | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` |
| SQL Server | `@prisma/adapter-mssql` | `node-mssql` |
MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it.
Example (PostgreSQL):
```ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Prisma Client Setup (Required)
Prisma Client must be installed and generated for any database.
1. Install Prisma CLI and Prisma Client:
```bash
npm install prisma --save-dev
npm install @prisma/client
```
1. Add a generator block (`prisma-client` requires an explicit output path):
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
1. Generate Prisma Client:
```bash
npx prisma generate
```
1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
1. Re-run `prisma generate` after every schema change.
## Quick Reference
### PostgreSQL
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MySQL
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### SQLite
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MongoDB
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup.
## Rule Files
See individual rule files for detailed setup instructions:
```
references/postgresql.md
references/mysql.md
references/sqlite.md
references/mongodb.md
references/sqlserver.md
references/cockroachdb.md
references/prisma-postgres.md
references/prisma-client-setup.md
```
## How to Use
Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern.
@@ -0,0 +1,89 @@
# CockroachDB Setup
Configure Prisma with CockroachDB.
## Prerequisites
- CockroachDB cluster
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "cockroachdb"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full"
```
Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly.
## Driver Adapter
Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## ID Generation
CockroachDB uses `BigInt` or `UUID` for IDs efficiently.
```prisma
model User {
id BigInt @id @default(autoincrement()) // Uses unique_rowid()
}
```
Or using string UUIDs:
```prisma
model User {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
}
```
## Common Issues
### Schema Introspection
Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`.
@@ -0,0 +1,90 @@
# MongoDB Setup
MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path.
## Prerequisites
- MongoDB 4.2+
- Replica Set configured (required for transactions)
- Latest Prisma 6.x release, or your team's pinned Prisma 6 version
- Node.js 20.19.0+
- TypeScript 5.4.0+
## 1. Schema Configuration
Use the standard Prisma 6 MongoDB setup with `prisma-client-js`.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
### Driver Adapters
Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package.
### ID Field Requirement
MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`.
```prisma
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
}
```
### Relations
Relations in MongoDB expect IDs to be `db.ObjectId` type.
```prisma
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
```
## 2. Environment Variable
In `.env`:
```env
DATABASE_URL="mongodb+srv://user:[email protected]/mydb?retryWrites=true&w=majority"
```
## Migrations vs Introspection
- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**.
- **db push**: Use `prisma db push` to sync indexes and constraints.
- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling).
## Current Verification Notes
- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source.
- Prisma's upstream repo still contains MongoDB fixtures and tests.
- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path.
- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set.
## Version Guidance
- For MongoDB, stay on the latest available Prisma 6.x release.
- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path.
## Common Issues
### "Transactions not supported"
Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default.
### "Invalid ObjectID"
Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID.
@@ -0,0 +1,126 @@
# MySQL Setup
Configure Prisma with MySQL (or MariaDB).
## Prerequisites
- MySQL or MariaDB database
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
```
### Connection String Format
```
mysql://USER:PASSWORD@HOST:PORT/DATABASE
```
- **USER**: Database user
- **PASSWORD**: Password
- **HOST**: Hostname
- **PORT**: Port (default 3306)
- **DATABASE**: Database name
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mariadb mariadb
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### Text protocol option
If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, {
useTextProtocol: true,
})
const prisma = new PrismaClient({ adapter })
```
Use this only when you specifically need text-protocol compatibility for your MariaDB setup.
## PlanetScale Setup
PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
relationMode = "prisma" // Emulate foreign keys in Prisma
}
```
## Common Issues
### "Too many connections"
MySQL has a connection limit. Adjust connection pool size in URL:
```env
DATABASE_URL="mysql://...?connection_limit=5"
```
### JSON Support
MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version.
@@ -0,0 +1,92 @@
# PostgreSQL Setup
Configure Prisma with PostgreSQL.
## Prerequisites
- PostgreSQL database (local or cloud)
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
```
### Connection String Format
```
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
```
- **USER**: Database user
- **PASSWORD**: Password (URL encoded if special chars)
- **HOST**: Hostname (localhost, IP, or domain)
- **PORT**: Port (default 5432)
- **DATABASE**: Database name
- **SCHEMA**: Schema name (default `public`)
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Can't reach database server"
- Check host and port
- Check firewall settings
- Ensure database is running
### "Authentication failed"
- Check user/password
- Special characters in password must be URL-encoded
### "Schema does not exist"
- Ensure `?schema=public` (or your schema) is in the URL
@@ -0,0 +1,47 @@
# Prisma Client Setup
Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below.
## 1. Install dependencies
```bash
npm install prisma --save-dev
npm install @prisma/client
```
## 2. Add generator block
In `prisma/schema.prisma`:
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default.
## 3. Generate Prisma Client
```bash
npx prisma generate
```
Re-run `prisma generate` after every schema change to keep the client in sync.
## 4. Instantiate Prisma Client
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database.
## 5. Use a single instance
Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections.
@@ -0,0 +1,130 @@
# Prisma Postgres Setup
Configure Prisma with Prisma Postgres (Managed).
## Overview
Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma.
## Setup via CLI
You can provision a Prisma Postgres instance directly via the CLI:
```bash
prisma init --db
```
This will:
1. Log you into Prisma Data Platform.
2. Create a new project and database instance.
3. Update your `.env` with the connection string.
## Connection String
For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL.
For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard:
```env
DATABASE_URL="postgres://identifier:[email protected]:5432/postgres?sslmode=require"
```
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql" // Use postgresql provider
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Driver Adapter
Use a driver adapter for Prisma Postgres in the standard SQL workflow.
### Recommended for standard Node.js apps
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Use the direct TCP connection string from Prisma Console:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
`PrismaPg` also accepts the connection string directly:
```typescript
const adapter = new PrismaPg(process.env.DATABASE_URL!)
const prisma = new PrismaClient({ adapter })
```
For PostgreSQL prepared statement naming, pass adapter options as the second argument:
```typescript
import { createHash } from 'node:crypto'
const adapter = new PrismaPg(process.env.DATABASE_URL!, {
statementNameGenerator: ({ sql }) =>
`prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`,
})
```
### Edge/serverless option
Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions:
```bash
npm install @prisma/adapter-ppg @prisma/ppg
```
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps.
## Features
- **Serverless**: Scales to zero.
- **Caching**: Integrated query caching (Accelerate).
- **Real-time**: Database events (Pulse).
## Using with Prisma Client
Use the Prisma Postgres adapter shown above when instantiating Prisma Client.
@@ -0,0 +1,106 @@
# SQLite Setup
Configure Prisma with SQLite.
## Prerequisites
- None (file-based)
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="file:./dev.db"
```
### Connection String Format
```
file:PATH
```
- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it.
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-better-sqlite3 better-sqlite3
```
2. Instantiate Prisma Client with the adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL ?? 'file:./dev.db',
})
const prisma = new PrismaClient({ adapter })
```
## Using Driver Adapter (LibSQL / Turso)
For edge compatibility or Turso:
1. Install:
```bash
npm install @prisma/adapter-libsql @libsql/client
```
2. Instantiate:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaLibSql } from '@prisma/adapter-libsql'
const adapter = new PrismaLibSql({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
})
const prisma = new PrismaClient({ adapter })
```
## Limitations
- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String).
- **No Scalar Lists**: `String[]` is not supported directly.
- **Concurrency**: Write operations lock the file.
## Common Issues
### "Database file not found"
Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema.
@@ -0,0 +1,94 @@
# SQL Server Setup
Configure Prisma with Microsoft SQL Server.
## Prerequisites
- SQL Server 2017, 2019, 2022, or Azure SQL
- TCP/IP enabled
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlserver"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true"
```
### Connection String Format
```
sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true
```
- **encrypt**: Required for Azure (true).
- **trustServerCertificate**: True for self-signed certs (local dev).
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mssql mssql
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Login failed for user"
- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password).
- Ensure TCP/IP is enabled in SQL Server Configuration Manager.
### "Table not found" (dbo schema)
Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema.
+253
View File
@@ -0,0 +1,253 @@
---
name: prisma-upgrade-v7
description: Complete migration guide from Prisma ORM v6 to v7 covering all breaking changes. Use when upgrading Prisma versions, encountering v7 errors, or migrating existing projects. Triggers on "upgrade to prisma 7", "prisma 7 migration", "prisma-client generator", "driver adapter required".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Upgrade to Prisma ORM 7
Complete guide for migrating from Prisma ORM v6 to v7. This upgrade introduces significant breaking changes around the new `prisma-client` generator, driver adapters, `prisma.config.ts`, explicit environment loading, and generated client entrypoints.
## When to Apply
Reference this skill when:
- Upgrading from Prisma v6 to v7
- Updating to the `prisma-client` generator
- Setting up driver adapters
- Configuring `prisma.config.ts`
- Fixing import errors after upgrade
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Schema Migration | CRITICAL | `schema-changes` |
| 2 | Database Connectivity | CRITICAL | `driver-adapters` |
| 3 | Module System | CRITICAL | `esm-support` |
| 4 | Config and Env | HIGH | `prisma-config`, `env-variables` |
| 5 | Removed Features | HIGH | `removed-features` |
| 6 | Accelerate | HIGH | `accelerate-users` |
## Quick Reference
- `schema-changes` - generator migration, required output paths, generated entrypoints, and `Prisma.validator` replacement
- `driver-adapters` - required adapter installation for SQL providers, pool differences, and Prisma Postgres adapter choices
- `esm-support` - ESM-first setup plus CommonJS fallback with `moduleFormat = "cjs"`
- `prisma-config` - creating and using `prisma.config.ts`
- `env-variables` - explicit environment loading
- `removed-features` - removed middleware, metrics, and legacy CLI behavior
- `accelerate-users` - migration notes for Accelerate users
## Important Notes
- **MongoDB projects should stay on Prisma 6.x** - do not migrate MongoDB apps to Prisma 7's SQL client path
- **Node.js 20.19.0+** required
- **TypeScript 5.4.0+** required
- **Latest stable Prisma ORM version**: `7.6.0`
## Upgrade Steps Overview
1. Update packages to v7
2. Choose your module format (`esm` by default, `cjs` if needed)
3. Update TypeScript configuration
4. Update the schema generator block
5. Create `prisma.config.ts`
6. Install and configure a driver adapter for SQL providers
7. Update Prisma Client imports
8. Update client instantiation
9. Replace deprecated helper patterns like `Prisma.validator`
10. Run `prisma generate` and test
## Quick Upgrade Commands
```bash
# Update packages
npm install @prisma/client@7
npm install -D prisma@7
# Install a driver adapter (PostgreSQL or Prisma Postgres via direct TCP)
npm install @prisma/adapter-pg pg
# Install dotenv for env loading
npm install dotenv
# Regenerate client
npx prisma generate
```
## Breaking Changes Summary
| Change | v6 | v7 |
|--------|----|----|
| Module format | Implicit / mixed | ESM-first, `moduleFormat = "cjs"` supported |
| Generator provider | `prisma-client-js` | `prisma-client` is the default, while `prisma-client-js` still exists for legacy setups |
| Output path | Auto (node_modules) | Required explicit |
| Driver adapters | Optional | Required for SQL providers |
| Config file | `.env` + schema | `prisma.config.ts` |
| Env loading | Automatic | Manual (dotenv) |
| Generated entrypoints | Single package export | `client`, `browser`, `models`, `enums` entrypoints |
| Type-safe query fragments | `Prisma.validator()` | TypeScript `satisfies` |
| Middleware | `$use()` | Client Extensions |
| Metrics | Preview feature | Removed |
## Rule Files
Detailed migration guides for each breaking change:
```
references/esm-support.md - ESM and CommonJS configuration
references/schema-changes.md - Generator, output, imports, and generated entrypoints
references/driver-adapters.md - Required driver adapter setup
references/prisma-config.md - New configuration file
references/env-variables.md - Environment variable loading
references/removed-features.md - Middleware, metrics, and CLI flags
references/accelerate-users.md - Special handling for Accelerate
```
## Step-by-Step Migration
### 1. Update package.json for ESM-first projects
```json
{
"type": "module"
}
```
If you need to stay on CommonJS, keep your app as CJS and set `moduleFormat = "cjs"` in the generator block instead of forcing ESM.
### 2. Update tsconfig.json
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true
}
}
```
### 3. Update schema.prisma
```prisma
// Before (v6)
generator client {
provider = "prisma-client-js"
}
// After (v7)
generator client {
provider = "prisma-client"
output = "../generated/prisma"
// Optional if you need CommonJS:
// moduleFormat = "cjs"
}
```
### 4. Create prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### 5. Install a driver adapter (SQL providers only)
```bash
# PostgreSQL
npm install @prisma/adapter-pg pg
# MySQL
npm install @prisma/adapter-mariadb mariadb
# SQLite
npm install @prisma/adapter-better-sqlite3 better-sqlite3
# Prisma Postgres in standard Node.js apps (recommended)
npm install @prisma/adapter-pg pg
# Prisma Postgres serverless driver (edge/serverless)
npm install @prisma/adapter-ppg @prisma/ppg
# Neon
npm install @prisma/adapter-neon
```
MongoDB does not have a SQL `@prisma/adapter-*` package in the published Prisma 7.6.0 packages. If you're upgrading a MongoDB project, stop and keep that project on the latest Prisma 6.x release instead of following the standard Prisma 7 migration path.
### 6. Update client instantiation
```typescript
// Before (v6)
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// After (v7)
import { PrismaClient } from '../generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### 7. Replace Prisma.validator with satisfies
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
name: true,
} satisfies Prisma.UserSelect
```
### 8. Run migrations and generate
```bash
npx prisma generate
npx prisma migrate dev # if needed
```
## Troubleshooting
### "Cannot find module" errors
- Check that the generator `output` path matches your import path
- Ensure `prisma generate` ran successfully
### SSL certificate errors
- Add `ssl: { rejectUnauthorized: false }` to the adapter config if you need to preserve old behavior
- Or configure your certificates properly with `NODE_EXTRA_CA_CERTS` / OpenSSL CA settings
### Connection timeout issues
- Driver adapters use the underlying driver's defaults, which differ from v6
- Configure pool settings explicitly on the adapter if needed
## Resources
- [Official v7 Upgrade Guide](https://www.prisma.io/docs/orm/more/upgrades/to-v7)
- [Driver Adapters Documentation](https://www.prisma.io/docs/orm/core-concepts/supported-databases/database-drivers)
- [Prisma Config Reference](https://www.prisma.io/docs/orm/reference/prisma-config-reference)
## How to Use
Follow `references/schema-changes.md` and `references/driver-adapters.md` first, then apply the remaining reference files based on your project setup.
@@ -0,0 +1,151 @@
# Prisma Accelerate Users
Special migration instructions for users of Prisma Accelerate or Prisma Postgres with `prisma://` or `prisma+postgres://` URLs.
## Important
**Do NOT pass Accelerate URLs to driver adapters.**
Driver adapters (like `PrismaPg`) expect direct database connection strings. They will fail with `prisma://` or `prisma+postgres://` URLs.
## Correct v7 Setup for Accelerate
### 1. Keep your Accelerate URL
```env
# .env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=..."
# or
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..."
```
### 2. Install Accelerate extension
```bash
npm install @prisma/extension-accelerate
```
### 3. Configure prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'), // Accelerate URL works here
},
})
```
### 4. Instantiate client with accelerateUrl
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
// Use accelerateUrl instead of adapter
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```
## What NOT to Do
```typescript
// ❌ WRONG - Don't use adapter with Accelerate URL
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // This will fail with prisma://
})
```
## Migrations with Accelerate
For migrations, you may need a direct database connection:
### Option 1: Use Accelerate URL for everything
Accelerate URLs work with Prisma CLI commands:
```bash
# Works with Accelerate URL
prisma migrate deploy
prisma db push
```
### Option 2: Use direct URL for migrations
```env
DATABASE_URL="prisma+postgres://..." # For app
DIRECT_DATABASE_URL="postgresql://..." # For migrations
```
```typescript
// prisma.config.ts
export default defineConfig({
datasource: {
url: env('DIRECT_DATABASE_URL'), // Direct URL for CLI
},
})
```
## Prisma Postgres (Cloud)
If using Prisma Postgres cloud database:
### Same approach
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma+postgres:// URL
}).$extends(withAccelerate())
```
## Switching Away from Accelerate
If you later switch to direct TCP connection:
```typescript
// Change from accelerateUrl to adapter
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // Direct postgres:// URL
})
export const prisma = new PrismaClient({ adapter })
```
## Caching with Accelerate
The extension enables caching:
```typescript
const users = await prisma.user.findMany({
cacheStrategy: {
ttl: 60, // Cache for 60 seconds
swr: 120, // Stale-while-revalidate for 120 seconds
},
})
```
## Edge Runtime
Accelerate works great in edge runtimes:
```typescript
// Works in Vercel Edge, Cloudflare Workers, etc.
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```
@@ -0,0 +1,267 @@
# Driver Adapters
Prisma v7 requires driver adapters for SQL database connections. This is the standard SQL execution path in current Prisma releases.
MongoDB should not follow this path. There is no published MongoDB `@prisma/adapter-*` package, and MongoDB projects should remain on the latest Prisma 6.x release instead of trying to fit into the Prisma 7 SQL adapter model.
## Why Driver Adapters?
- No native engine binary in the Prisma Client SQL path
- Smaller bundle size
- Better serverless/edge compatibility
- Uses native Node.js database drivers
- More control over connection pooling
## Available Adapters
| Database | Adapter Package | Underlying Driver |
|----------|-----------------|-------------------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| SQL Server | `@prisma/adapter-mssql` | `mssql` |
| Neon | `@prisma/adapter-neon` | `@neondatabase/serverless` |
| PlanetScale | `@prisma/adapter-planetscale` | `@planetscale/database` |
| Turso/libSQL | `@prisma/adapter-libsql` | `@libsql/client` |
| D1 (Cloudflare) | `@prisma/adapter-d1` | Cloudflare D1 |
## Installation
### PostgreSQL
```bash
npm install @prisma/adapter-pg
```
### MySQL
```bash
npm install @prisma/adapter-mariadb mariadb
```
### SQLite
```bash
npm install @prisma/adapter-better-sqlite3
```
### Prisma Postgres
```bash
npm install @prisma/adapter-pg pg
```
### SQL Server
```bash
npm install @prisma/adapter-mssql mssql
```
## Configuration
### PostgreSQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### MySQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### SQLite
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || 'file:./dev.db'
})
const prisma = new PrismaClient({ adapter })
```
### Neon (Serverless PostgreSQL)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaNeon } from '@prisma/adapter-neon'
const adapter = new PrismaNeon({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres serverless driver
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
### SQL Server
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Connection Pool Configuration
Driver adapters use the underlying driver's pool settings, which differ from v6 defaults.
### PostgreSQL with custom pool
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
// Pool configuration
max: 10, // Maximum connections
idleTimeoutMillis: 30000, // Close idle connections after 30s
connectionTimeoutMillis: 5000, // Connection timeout (v6 default was 5s)
})
```
### Matching v6 behavior
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000, // v6 used 5 second timeout
})
```
## SSL Configuration
### Accept self-signed certificates
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // Accept self-signed certs
}
})
```
### Proper SSL configuration
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
ca: fs.readFileSync('/path/to/ca-cert.pem'),
rejectUnauthorized: true
}
})
```
## Migration from v6
### Before (v6)
```typescript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({
datasources: {
db: { url: process.env.DATABASE_URL }
}
})
```
### After (v7)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Singleton Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter })
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```
@@ -0,0 +1,161 @@
# Environment Variables
Prisma v7 no longer automatically loads environment variables. You must load them explicitly.
## The Change
### v6 Behavior
Prisma CLI automatically loaded `.env` files.
### v7 Behavior
You must manually load environment variables using `dotenv` or similar.
## Setup
### 1. Install dotenv
```bash
npm install dotenv
```
### 2. Import in prisma.config.ts
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Bun Users
Bun automatically loads `.env` files. No additional setup needed:
```typescript
// prisma.config.ts (Bun)
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Multiple .env Files
### Using dotenv-cli
```bash
npm install -D dotenv-cli
```
```json
{
"scripts": {
"db:migrate": "dotenv -e .env.local -- prisma migrate dev",
"db:push": "dotenv -e .env.development -- prisma db push"
}
}
```
### Using dotenv with path
```typescript
// prisma.config.ts
import { config } from 'dotenv'
import path from 'path'
// Load specific .env file
config({ path: path.join(__dirname, '.env.local') })
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Application Code
For your application, load env vars at startup:
### Entry point
```typescript
// index.ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prisma = new PrismaClient({ adapter })
```
### Or use dotenv explicitly
```typescript
import { config } from 'dotenv'
config()
// Now process.env.DATABASE_URL is available
```
## Removed Environment Variables
These Prisma-specific env vars are removed in v7:
| Removed Variable | Alternative |
|-----------------|-------------|
| `PRISMA_CLI_QUERY_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_CLIENT_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_QUERY_ENGINE_BINARY` | Not needed |
| `PRISMA_QUERY_ENGINE_LIBRARY` | Not needed |
| `PRISMA_GENERATE_SKIP_AUTOINSTALL` | Not needed |
| `PRISMA_SKIP_POSTINSTALL_GENERATE` | Not needed |
| `PRISMA_GENERATE_IN_POSTINSTALL` | Not needed |
| `PRISMA_GENERATE_DATAPROXY` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_GENERATE_NO_ENGINE` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_CLIENT_NO_RETRY` | Configure on adapter |
| `PRISMA_MIGRATE_SKIP_GENERATE` | Not needed (auto-generate removed) |
| `PRISMA_MIGRATE_SKIP_SEED` | Not needed (auto-seed removed) |
## TypeScript env() Helper
The `env()` function from `prisma/config` provides type safety:
```typescript
import { env } from 'prisma/config'
// Type-safe environment variable access
const url = env('DATABASE_URL') // string
```
Note: This only works within `prisma.config.ts`, not in your application code.
## CI/CD Considerations
Ensure environment variables are set in your CI environment:
```yaml
# GitHub Actions
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
steps:
- run: npx prisma migrate deploy
```
No need for dotenv in CI if variables are set directly.
@@ -0,0 +1,128 @@
# ESM and CommonJS Support
Prisma ORM v7 is ESM-first, but the `prisma-client` generator can target either ESM or CommonJS. Use ESM by default, and opt into CommonJS with `moduleFormat = "cjs"` if your project still needs it.
## ESM Projects
Add `"type": "module"` to `package.json` and use an ESM-compatible `tsconfig.json`:
```json
{
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}
```
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src/**/*", "prisma/**/*"]
}
```
## CommonJS Projects
If the rest of your app is still CommonJS, keep that setup and make the generated Prisma Client CommonJS too:
```json
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"target": "ES2022",
"esModuleInterop": true
}
}
```
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Generator Fields That Matter
- `moduleFormat`: `esm` or `cjs`
- `runtime`: `nodejs`, `bun`, `deno`, `workerd`, `vercel-edge`, `react-native`
- `generatedFileExtension`: `ts`, `mts`, or `cts`
- `importFileExtension`: `ts`, `mts`, `cts`, `js`, `mjs`, `cjs`, or empty
Example:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
runtime = "nodejs"
moduleFormat = "esm"
generatedFileExtension = "ts"
importFileExtension = "ts"
}
```
## Import Paths
### Server Code
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
### Browser-Safe Types
```typescript
import { Prisma } from '../generated/prisma/browser'
import { Role } from '../generated/prisma/enums'
import type { UserModel } from '../generated/prisma/models/User'
```
## File Extensions
With `moduleResolution: "Node16"` or `"NodeNext"`, use `.js`/`.mjs`/`.cjs` extensions that match your emitted files.
With `moduleResolution: "bundler"`, bare relative imports are usually fine.
## Minimum Versions
| Requirement | Minimum Version |
|-------------|-----------------|
| Node.js | 20.19.0 |
| TypeScript | 5.4.0 |
## Framework Considerations
### Next.js
Next.js works well with the default ESM output. If you need generated types in client components, import them from `browser`, `models`, or `enums`, not from `client`.
### Bun
Bun loads `.env` files automatically, so ESM plus `env()` is the smoothest default. You can still choose `moduleFormat = "cjs"` if the rest of your project requires it.
## Troubleshooting
### "ERR_REQUIRE_ESM"
Your generated client is ESM, but your app is requiring it as CommonJS. Either switch the project to ESM or set `moduleFormat = "cjs"` and regenerate.
### "Cannot use import statement outside a module"
Your app is still being executed as CommonJS. Add `"type": "module"` or use `moduleFormat = "cjs"` instead.
### TypeScript compilation errors
Ensure `module`, `moduleResolution`, and your generator's `moduleFormat` agree with one another.
@@ -0,0 +1,203 @@
# Prisma Config
Prisma v7 introduces `prisma.config.ts` as the central configuration file for the Prisma CLI.
## Location
Place `prisma.config.ts` at your project root (next to `package.json`).
## Basic Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Configuration Options
### schema
Path to your Prisma schema file:
```typescript
schema: 'prisma/schema.prisma'
```
### datasource.url
Database connection URL:
```typescript
datasource: {
url: env('DATABASE_URL'),
}
```
### datasource.directUrl
Direct connection URL (bypassing connection pooler):
```typescript
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
}
```
### datasource.shadowDatabaseUrl
Shadow database for migrations:
```typescript
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
}
```
### migrations.path
Directory for migration files:
```typescript
migrations: {
path: 'prisma/migrations',
}
```
### migrations.seed
Seed command for `prisma db seed`:
```typescript
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
}
```
## Full Example
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
// Schema location
schema: 'prisma/schema.prisma',
// Migration configuration
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
// Database connection
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## Environment Variables
### The env() helper
Use `env()` to reference environment variables:
```typescript
import { env } from 'prisma/config'
datasource: {
url: env('DATABASE_URL'),
}
```
This provides type safety but does NOT load .env files automatically.
### Loading .env files
Install and import dotenv:
```bash
npm install dotenv
```
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
```
## Migrating from v6
### Before (v6) - schema.prisma
```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
```
### After (v7) - prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_URL'),
},
})
```
And update schema.prisma:
```prisma
datasource db {
provider = "postgresql"
// URLs now in prisma.config.ts
}
```
## Custom Config Path
Use `--config` flag with CLI commands:
```bash
prisma migrate dev --config ./config/prisma.config.ts
```
## Monorepo Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
import path from 'path'
export default defineConfig({
schema: path.join(__dirname, 'packages/database/prisma/schema.prisma'),
migrations: {
path: path.join(__dirname, 'packages/database/prisma/migrations'),
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
@@ -0,0 +1,230 @@
# Removed Features
Several features have been removed in Prisma v7. Here's how to migrate.
## Client Middleware
### Removed
```typescript
// ❌ No longer works in v7
prisma.$use(async (params, next) => {
const before = Date.now()
const result = await next(params)
const after = Date.now()
console.log(`Query took ${after - before}ms`)
return result
})
```
### Use Client Extensions Instead
```typescript
// ✅ v7 approach
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
const before = Date.now()
const result = await query(args)
const after = Date.now()
console.log(`${model}.${operation} took ${after - before}ms`)
return result
},
},
},
})
```
### Common Middleware Patterns
#### Soft delete
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async delete({ args, query }) {
// Convert delete to soft delete
return prisma.user.update({
where: args.where,
data: { deletedAt: new Date() },
})
},
async findMany({ args, query }) {
// Filter out soft-deleted records
args.where = { ...args.where, deletedAt: null }
return query(args)
},
},
},
})
```
#### Logging
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
console.log(`${model}.${operation}`, JSON.stringify(args))
return query(args)
},
},
},
})
```
## Metrics
### Removed
The Metrics preview feature has been removed.
```typescript
// ❌ No longer works
const metrics = await prisma.$metrics.json()
```
### Alternatives
#### Custom counter with extensions
```typescript
let totalQueries = 0
const prisma = new PrismaClient({ adapter }).$extends({
client: {
async $totalQueries() {
return totalQueries
},
},
query: {
$allModels: {
async $allOperations({ query, args }) {
totalQueries += 1
return query(args)
},
},
},
})
// Usage
const count = await prisma.$totalQueries()
```
#### Use driver-level metrics
Access metrics from the underlying driver adapter.
## CLI Flags Removed
### --skip-generate
Removed from `migrate dev` and `db push`.
```bash
# v6
prisma migrate dev --skip-generate
# v7 - generate is not run automatically
prisma migrate dev
prisma generate # Run explicitly if needed
```
Local verification with Prisma `7.6.0` showed no generated client files emitted by `migrate dev` or `db push`, even though some CLI help text still says `migrate dev` "trigger[s] generators".
### --skip-seed
Removed from `migrate dev`. More importantly, Prisma v7 no longer auto-runs seeds during `migrate dev` or `migrate reset`, so seed explicitly when you need it.
```bash
# v6
prisma migrate dev --skip-seed
# v7 - seed is not run automatically
prisma migrate dev
prisma db seed # Run explicitly if needed
```
### --schema and --url from db execute
```bash
# v6
prisma db execute --file ./script.sql --url "$DATABASE_URL"
# v7 - configure in prisma.config.ts
prisma db execute --file ./script.sql
```
## migrate diff Options
| Removed | Replacement |
|---------|-------------|
| `--from-url` | `--from-config-datasource` |
| `--to-url` | `--to-config-datasource` |
| `--from-schema-datasource` | `--from-config-datasource` |
| `--to-schema-datasource` | `--to-config-datasource` |
| `--shadow-database-url` | Configure in `prisma.config.ts` |
### Example
```bash
# v6
prisma migrate diff --from-url "$DATABASE_URL" --to-schema schema.prisma
# v7
prisma migrate diff --from-config-datasource --to-schema schema.prisma
```
## Automatic Behaviors Removed
### Auto-generate after migrate
```bash
# v7 workflow
prisma migrate dev --name add_field
prisma generate # Must run explicitly
```
### Auto-seed after migrate
```bash
# v7 workflow
prisma migrate reset --force
prisma db seed # Must run explicitly
```
## Prisma.validator
The `prisma-client` generator no longer exposes `Prisma.validator`. Use TypeScript's `satisfies` operator instead.
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## rejectOnNotFound
Removed in v5.0.0 (already deprecated).
```typescript
// ❌ Removed
const prisma = new PrismaClient({
rejectOnNotFound: true,
})
// ✅ Use OrThrow methods
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 },
})
const user = await prisma.user.findFirstOrThrow({
where: { email: '[email protected]' },
})
```
@@ -0,0 +1,164 @@
# Schema Changes
Prisma v7 promotes `prisma-client` to the default generator. Update your generator block, output path, and imports accordingly.
This guide is for projects that are actually migrating to Prisma 7. Do not apply these schema changes to MongoDB projects; keep those on Prisma 6.x.
## Generator Block (v7)
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
## Key Changes
### 1. Provider name
Use `prisma-client` in Prisma v7. The older `prisma-client-js` generator still exists in the repo for legacy setups, but `prisma-client` is the default path for current projects.
### 2. Output is required
The `output` field is mandatory when using `prisma-client`. Prisma Client no longer generates to `node_modules` with this generator.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
### 3. engineType changed
Legacy Rust engine settings are gone. With `prisma-client`, the relevant value is `engineType = "client"` if you want to state it explicitly, although it is typically inferred and can be omitted.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
engineType = "client"
}
```
### 4. moduleFormat is explicit when needed
If you must stay on CommonJS:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Example Output Paths
### Standard project
```prisma
output = "../generated/prisma"
```
Creates files like:
```text
generated/prisma/
client.ts
browser.ts
enums.ts
models.ts
models/
```
### Monorepo
```prisma
output = "../../packages/database/generated/prisma"
```
### Same directory as schema
```prisma
output = "./generated/prisma"
```
Creates: `prisma/generated/prisma/client.ts`
## Datasource Block
The `url`, `directUrl`, and `shadowDatabaseUrl` fields in the `datasource` block are deprecated in Prisma v7. Move them to `prisma.config.ts` and keep only the provider in `schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
```
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## After Schema Changes
1. Run `prisma generate`:
```bash
npx prisma generate
```
2. Update imports throughout your codebase:
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
3. Update `.gitignore` if you manage this manually:
```
/generated/prisma
```
4. Replace `Prisma.validator()` with TypeScript `satisfies` when using `prisma-client`:
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## Generated Entrypoints
- `client` - server-side Prisma Client and Prisma namespace
- `browser` - browser-safe types and enums without a real `PrismaClient`
- `enums` - slim enum-only entrypoint
- `models` - model types and derived helper types
## Preview Features
Preview features still work as before:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["relationJoins", "fullTextSearch"]
}
```
Recent preview-feature examples also include `partialIndexes` for PostgreSQL, SQLite, SQL Server, and CockroachDB:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["partialIndexes"]
}
```
+6
View File
@@ -0,0 +1,6 @@
---
name: remember
description: Save a lesson, constraint, guardrail, design inspiration, or project fact into permanent .agents/ memory in the WorldWideView project. Use when the user says "remember that", "don't forget", or when a hard-won lesson should be persisted.
---
@.agents/workflows/remember.md
@@ -0,0 +1,84 @@
---
name: stakeholder-analysis
description: Use when designing systems, creating features, or making architectural decisions to ensure all WorldWideView stakeholders' needs and constraints are properly considered.
---
# Stakeholder Analysis & Considerations
## Overview
Every architectural change, new feature, and design decision in WorldWideView affects multiple stakeholders. Before finalizing a design or starting an implementation, you MUST evaluate the impact against this list of stakeholders to ensure their specific needs, preferences, and constraints are respected.
## System Responsibilities & The Stakeholder Relationship
The design of the architecture directly relates to how the stakeholders are needed and what they need. System responsibilities are detailed in this file because the strict decoupling of the architecture guarantees a level playing field across all stakeholder roles:
* **Data Engine**: Must operate as an independent server that complements the plugin. The data from the Data Engine is streamed directly into the plugins and used to display on the map. It can be created by anyone and hosted on their own infrastructure, remaining entirely unrelated to the Platform—acting much like a developer's proprietary API that feeds their plugins. It should not receive any preferential treatment, and should not even be explicitly acknowledged by the platform.
* **The Platform**: Maintained strictly by the **Internal Developers** and the **Owner**. It must remain completely agnostic to which plugins are installed and must never give any plugins preferential treatment.
* **Plugins**: Must be purely "plug-and-play". The plugins themselves contain the path and instructions on how to connect to their respective Data Engine and process the streamed data. The platform must be able to support any type of plugin developed by anyone—the original creator, the owner, an internal developer, or an external developer. It does not matter who created the plugin or whether or not they actually have access to the platform's internal codebase.
Because of these architectural rules, an *External Developer* has the exact same integration power and constraints as an *Internal Developer*.
## Stakeholders
### 1. Internal Developer
* **Role**: Core team maintainers who manage the central engine, data engine, and core plugin codebase.
* **Access**: Push access straight to `main`.
* **Focus**: Large architectural changes, bug fixes across the entire stack (frontend, backend, data engine).
* **Needs/Preferences**: Requires clean abstractions, maintainable code, and the ability to rapidly iterate on complex core systems without breaking downstream consumers.
### 2. External Developer (Contributor)
* **Role**: Community or third-party developers contributing to the ecosystem.
* **Access**: Pull Request (PR) access only. Never pushes directly to `main`.
* **Focus**: Bug fixes and introducing small new features or plugins.
* **Needs/Preferences**: Requires clear documentation, strict templates, and strong CI/CD guardrails. The system must prevent them from accidentally breaking the core engine during PR integration.
### 3. Plugin Developer (Simple)
* **Role**: Users who want to quickly visualize static datasets or basic feeds with minimal effort.
* **Focus**: Moving from an idea to a working plugin development instantly.
* **Needs/Preferences**: Demands an absolutely frictionless, straightforward process. They want simple CLI tools (scaffolds), easy ways to host/upload data, and zero structural complexity. The barrier to entry must be as low as possible.
### 4. Plugin Developer (Advanced)
* **Role**: Power users or organizations building complex integrations.
* **Focus**: Managing their own backend servers/data pipelines, and piping real-time data directly into WWV.
* **Needs/Preferences**: Requires high extensibility and deep access. They need the ability to manipulate the WWV frontend directly, inject custom layers, interact with the raw CesiumJS instance, and hook into the React state to build highly customized experiences.
### 5. The User
Users are fragmented into sub-personas based on their engagement level and goals. Designs must cater to these overlapping but distinct segments:
#### Engagement Types:
* **Casual Users (Demo)**: Just trying out the public demo. They expect an immediate visual "wow factor", zero setup, and intuitive navigation.
* **Cloud Subscribers**: Paying customers with their own hosted WWV instance. They expect stability, secure management, and the ability to install and orchestrate their own custom ecosystem of plugins.
#### Operational Goals:
* **OSINT Researchers**: Need deep filtering, real-time alerting, historical timelines, high data accuracy, and spatial intelligence tools.
* **Data Analysts**: Require data density, aggregation, performance with massive datasets, and relational insights.
* **Journalists**: Prioritize narrative building, visual clarity for audiences, verifiable sourcing, and ease of capturing aesthetics (screenshots/video).
### 6. Data Provider
* **Role**: The source or distributor of the raw intelligence data.
* **Types**: Third-party APIs (e.g., OpenSky), official partner organizations, or copyright holders.
* **Needs/Preferences**:
* Strict adherence to API rate limits, backoffs, and fair use.
* Guaranteed data security and proper visual attribution on the globe.
* Compliance with their Terms of Service (ToS) and usage tracking.
### 7. The Owner
* **Role**: The product owner / business leader of WorldWideView.
* **Needs/Preferences**: Cares deeply about a holistic balance. Every decision must weigh:
* System stability, scalability, and minimizing long-term maintenance costs.
* Rapid feature delivery and flexibility (moving fast).
* Ecosystem growth, monetization, and attracting more plugin developers and users.
* Maintaining a premium "wow factor" and elite visual aesthetic across all components.
### 8. Locally Hosted Developer/User
* **Role**: A user or hobbyist developer running their own independent instance of WWV locally (bypassing the official managed cloud instances).
* **Focus**: Maintaining full control, data privacy, and self-sovereignty over their intelligence environment while still accessing the community plugin registry.
* **Needs/Preferences**:
* Needs an extremely straightforward, lightweight setup process (e.g., pre-compiled, Dockerized releases rather than building raw source code).
* Requires the infrastructure to seamlessly support direct CORS/WebSocket connections to external plugin servers without proxying through WWV official servers.
* Wants the instance stripped of unnecessary development cruft (like hot-reloading tooling), but formatted in a way where they can still easily inspect the application logic if they wish to modify it.
## How to Use This Skill
When tasked with system design, architectural planning, or complex feature implementation:
1. Review this list and identify which stakeholders will be affected by your proposed changes.
2. Explicitly detail how your design mitigates friction for the Simple Plugin Developer, protects the External Developer from breaking the platform, and satisfies the Owner's multi-faceted priorities.
3. Validate that your approach doesn't compromise the Advanced Plugin Developer's need for deep control or the Data Provider's strict ToS requirements.
+78
View File
@@ -0,0 +1,78 @@
---
name: stitch-to-nextjs
description: How to generate UI with Stitch MCP and port it robustly into Next.js
---
# Stitch MCP to Next.js Workflow
This guide outlines the streamlined, highly-efficient process for using the Google Stitch MCP to generate web designs and successfully implement them into a Next.js application.
Because Stitch operates with limited context and can produce inconsistent code, this workflow heavily emphasizes the "After Checks"—the critical refinement phase where you enforce design consistency, mobile responsiveness, and accurate content.
## Phase 1: Generation & Validation
1. **Prompting Stitch**
- Provide clear, contextual information about the project (brand identity, colors, typography).
- **Content Injection (Crucial):** Stitch lacks full project understanding and will hallucinate false information if left to guess.
- *Recreating an existing site:* Provide the exact content from the original page and instruct Stitch to use it verbatim.
- *Creating a new site:* Write out all the necessary copy, headlines, and data points first, then feed that complete information to Stitch.
- **Keep it simple:** Instruct Stitch not to overcomplicate the UI layout natively. Clean, standard layouts port easier.
- **Image prompting:** Explicitly request *photorealistic images* rather than abstract or "AI-looking" stock photos for placeholders.
2. **Retrieve & Validate**
- Access the generated Stitch URL.
- **Important:** There is no need to screen record or take photos/screenshots of the site.
- Simply provide the generated Stitch link to the user so they can open it and review it themselves for immediate feedback. **Do not write code until the design is approved.**
## Phase 2: Efficient Implementation
1. **Extract Design Tokens First**
- Before porting components, extract the core aesthetic from the approved Stitch page (background colors, primary/accent colors, font families, base border radii).
- Implement these as CSS variables in `globals.css` to create a stable foundation.
2. **Download and Port**
- Download the raw HTML/CSS from Stitch to use as a local reference.
- Break the HTML structure into Next.js React components (e.g., `HeroSection`, `FeaturesSection`, `Header`, `Footer`).
- Translate inline styles or utility classes into your project's styling solution (e.g., Vanilla CSS Modules).
## Phase 3: The "After Checks" (Refinement & Verification)
Stitch focuses on visual surface area, not production-readiness. You **must** perform these post-implementation checks:
1. **Content & Accuracy Verification**
- **Text:** Stitch hallucinates placeholder text. Replace all copy with coherent, accurate, and relevant information.
- **Links & CTAs:** Ensure all buttons and navigation links route to the correct pages using Next.js `<Link>`.
- **Footer/Header details:** Update copyright years, legal links, and brand names to reflect the actual product.
2. **Visual Consistency & Stabilization**
- **Icons & Logos:** Stitch uses text placeholders for icons (like "check_circle" or "diamond"). Replace these with actual SVGs or ensure the Material Symbols font is loaded in `layout.tsx`. Apply the real brand logo.
- **Alignment:** Look out for broken flex/grid layouts. If elements overlap or fail to align evenly, manually rewrite the layout CSS to be structurally sound.
- **Design Synchronization:** Stitch may generate inconsistent styles across different pages. It is your job to **stabilize** the design by forcing new pages to use the global design tokens established in Phase 2.
4. **Mobile Responsiveness**
- Stitch designs are often desktop-only.
- Write media queries (`@media (max-width: 768px)`) for every component.
- Implement hamburger menus for headers.
- Force CSS Grids into single-column (`grid-template-columns: 1fr`) on mobile.
- Adjust font sizes (`clamp()` or typography scaling) and padding for smaller viewports.
5. **Subtle Animations & Polish**
- Stitch designs can feel static. Add "just enough" animation to impress without overwhelming the user or hurting performance.
- Implement simple hover states (e.g., card lifts `transform: translateY(-4px)`, interactive glows, or image transitions).
- Consider gentle fade-in animations on scroll for major sections to make the interface feel premium and alive.
- **Rule of thumb:** Keep interactions snappy and subtle. Avoid long, complex, or janky animations that distract from the core product story.
---
## Handling Divergent Cases & Failures
### Case 1: Stitch Generates Inconsistent Aesthetics Across Multiple Pages
**The Problem:** The homepage uses one shade of dark mode, but the pricing page generates with a completely different background color and border radius.
**The Solution:** Discard the specific CSS variables generated by the divergent page. Map its HTML structure to the centralized CSS custom properties (`var(--surface-container)`, `var(--primary)`) you established in `globals.css` during the first successful generation.
### Case 2: Broken Layouts or Overlapping Content
**The Problem:** Stitch uses absolute positioning or complex margins that break when real text is inserted.
**The Solution:** Strip out the problematic positioning CSS entirely. Replace it with modern, robust layout primitives—use `display: grid` with `gap` for alignment, and `display: flex` with `justify-content: space-between` and `height: 100%` for equal-height cards.
### Case 3: Missing or Broken Icons Rendering as Text
**The Problem:** The UI shows the literal word "home" instead of a house icon.
**The Solution:** Ensure `<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined..." rel="stylesheet">` is injected into the root HTML `<head>`.
### Case 4: AI Images Look Unprofessional
**The Problem:** Stitch generated cartoonish or confusing abstract images that distract from a premium UI.
**The Solution:** Use the `generate_image` tool independently to create photorealistic replacements, or use a reliable external service. Substitute the `src` attribute in the Next.js component.
@@ -0,0 +1,289 @@
---
name: subagent-driven-development
description: Use when executing implementation plans with independent tasks in the current session
---
# Subagent-Driven Development
Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.
**Why subagents:** You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration
## When to Use
```dot
digraph when_to_use {
"Have implementation plan?" [shape=diamond];
"Tasks mostly independent?" [shape=diamond];
"Stay in this session?" [shape=diamond];
"subagent-driven-development" [shape=box];
"executing-plans" [shape=box];
"Manual execution or brainstorm first" [shape=box];
"Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
"Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
"Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
"Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
"Stay in this session?" -> "subagent-driven-development" [label="yes"];
"Stay in this session?" -> "executing-plans" [label="no - parallel session"];
}
```
**vs. Executing Plans (parallel session):**
- Same session (no context switch)
- Fresh subagent per task (no context pollution)
- Two-stage review after each task: spec compliance first, then code quality
- Faster iteration (no human-in-loop between tasks)
## The Process
```dot
digraph process {
rankdir=TB;
subgraph cluster_per_task {
label="Per Task";
"Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
"Implementer subagent asks questions?" [shape=diamond];
"Answer questions, provide context" [shape=box];
"Implementer subagent implements, tests, commits, self-reviews" [shape=box];
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
"Spec reviewer subagent confirms code matches spec?" [shape=diamond];
"Implementer subagent fixes spec gaps" [shape=box];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
"Code quality reviewer subagent approves?" [shape=diamond];
"Implementer subagent fixes quality issues" [shape=box];
"Mark task complete in TodoWrite" [shape=box];
}
"Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
"More tasks remain?" [shape=diamond];
"Dispatch final code reviewer subagent for entire implementation" [shape=box];
"Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
"Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
"Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
"Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
"Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
"Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
"Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
"Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
"Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
"Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
"Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
"Mark task complete in TodoWrite" -> "More tasks remain?";
"More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
"More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
"Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
}
```
## Model Selection
Use the least powerful model that can handle each role to conserve cost and increase speed.
**Mechanical implementation tasks** (isolated functions, clear specs, 1-2 files): use a fast, cheap model. Most implementation tasks are mechanical when the plan is well-specified.
**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.
**Architecture, design, and review tasks**: use the most capable available model.
**Task complexity signals:**
- Touches 1-2 files with a complete spec → cheap model
- Touches multiple files with integration concerns → standard model
- Requires design judgment or broad codebase understanding → most capable model
## Handling Implementer Status
Implementer subagents report one of four statuses. Handle each appropriately:
**DONE:** Proceed to spec compliance review.
**DONE_WITH_CONCERNS:** The implementer completed the work but flagged doubts. Read the concerns before proceeding. If the concerns are about correctness or scope, address them before review. If they're observations (e.g., "this file is getting large"), note them and proceed to review.
**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.
**BLOCKED:** The implementer cannot complete the task. Assess the blocker:
1. If it's a context problem, provide more context and re-dispatch with the same model
2. If the task requires more reasoning, re-dispatch with a more capable model
3. If the task is too large, break it into smaller pieces
4. If the plan itself is wrong, escalate to the human
**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.
## Prompt Templates
- `./implementer-prompt.md` - Dispatch implementer subagent
- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent
- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent
## Example Workflow
```
You: I'm using Subagent-Driven Development to execute this plan.
[Read plan file once: docs/superpowers/plans/feature-plan.md]
[Extract all 5 tasks with full text and context]
[Create TodoWrite with all tasks]
Task 1: Hook installation script
[Get Task 1 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: "Before I begin - should the hook be installed at user or system level?"
You: "User level (~/.config/superpowers/hooks/)"
Implementer: "Got it. Implementing now..."
[Later] Implementer:
- Implemented install-hook command
- Added tests, 5/5 passing
- Self-review: Found I missed --force flag, added it
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra
[Get git SHAs, dispatch code quality reviewer]
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
[Mark Task 1 complete]
Task 2: Recovery modes
[Get Task 2 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: [No questions, proceeds]
Implementer:
- Added verify/repair modes
- 8/8 tests passing
- Self-review: All good
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ❌ Issues:
- Missing: Progress reporting (spec says "report every 100 items")
- Extra: Added --json flag (not requested)
[Implementer fixes issues]
Implementer: Removed --json flag, added progress reporting
[Spec reviewer reviews again]
Spec reviewer: ✅ Spec compliant now
[Dispatch code quality reviewer]
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)
[Implementer fixes]
Implementer: Extracted PROGRESS_INTERVAL constant
[Code reviewer reviews again]
Code reviewer: ✅ Approved
[Mark Task 2 complete]
...
[After all tasks]
[Dispatch final code-reviewer]
Final reviewer: All requirements met, ready to merge
Done!
```
## Advantages
**vs. Manual execution:**
- Subagents follow TDD naturally
- Fresh context per task (no confusion)
- Parallel-safe (subagents don't interfere)
- Subagent can ask questions (before AND during work)
**vs. Executing Plans:**
- Same session (no handoff)
- Continuous progress (no waiting)
- Review checkpoints automatic
**Efficiency gains:**
- No file reading overhead (controller provides full text)
- Controller curates exactly what context is needed
- Subagent gets complete information upfront
- Questions surfaced before work begins (not after)
**Quality gates:**
- Self-review catches issues before handoff
- Two-stage review: spec compliance, then code quality
- Review loops ensure fixes actually work
- Spec compliance prevents over/under-building
- Code quality ensures implementation is well-built
**Cost:**
- More subagent invocations (implementer + 2 reviewers per task)
- Controller does more prep work (extracting all tasks upfront)
- Review loops add iterations
- But catches issues early (cheaper than debugging later)
## Red Flags
**Never:**
- Start implementation on main/master branch without explicit user consent
- Skip reviews (spec compliance OR code quality)
- Proceed with unfixed issues
- Dispatch multiple implementation subagents in parallel (conflicts)
- Make subagent read plan file (provide full text instead)
- Skip scene-setting context (subagent needs to understand where task fits)
- Ignore subagent questions (answer before letting them proceed)
- Accept "close enough" on spec compliance (spec reviewer found issues = not done)
- Skip review loops (reviewer found issues = implementer fixes = review again)
- Let implementer self-review replace actual review (both are needed)
- **Start code quality review before spec compliance is ✅** (wrong order)
- Move to next task while either review has open issues
**If subagent asks questions:**
- Answer clearly and completely
- Provide additional context if needed
- Don't rush them into implementation
**If reviewer finds issues:**
- Implementer (same subagent) fixes them
- Reviewer reviews again
- Repeat until approved
- Don't skip the re-review
**If subagent fails task:**
- Dispatch fix subagent with specific instructions
- Don't try to fix manually (context pollution)
## Antigravity CLI Orchestration
As Antigravity (running directly in the IDE with terminal tools), **you can fully automate this entire process**.
You do not need to wait for the human to dispatch the subagents. Instead:
1. **Dispatch:** Use your `run_command` tool to spawn the Gemini CLI subagents as background processes (e.g. `cat task.md | gemini -p .agents/skills/subagent-driven-development/implementer-prompt.md`).
2. **Monitor:** Use your `command_status` and `send_command_input` tools to actively monitor the subagent's standard output.
3. **Review Loop:** Once a background command finishes, immediately read the output/diffs and dispatch the reviewer subagent scripts via the CLI.
4. **Manage:** If a subagent reports a blocker or asks a question in stdout, you read it via `command_status`, provide the context, and re-dispatch.
**You act as the fully autonomous Manager**, watching the terminal logs while the CLI subagents mechanically burn through the tasks.
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:requesting-code-review** - Code review template for reviewer subagents
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
**Subagents should use:**
- **superpowers:test-driven-development** - Subagents follow TDD for each task
**Alternative workflow:**
- **superpowers:executing-plans** - Use for parallel session instead of same-session execution
@@ -0,0 +1,26 @@
# Code Quality Reviewer Prompt Template
Use this template when dispatching a code quality reviewer subagent.
**Purpose:** Verify implementation is well-built (clean, tested, maintainable)
**Only dispatch after spec compliance review passes.**
```
Task tool (superpowers:code-reviewer):
Use template at requesting-code-review/code-reviewer.md
WHAT_WAS_IMPLEMENTED: [from implementer's report]
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
BASE_SHA: [commit before task]
HEAD_SHA: [current commit]
DESCRIPTION: [task summary]
```
**In addition to standard code quality concerns, the reviewer should check:**
- Does each file have one clear responsibility with a well-defined interface?
- Are units decomposed so they can be understood and tested independently?
- Is the implementation following the file structure from the plan?
- Did this implementation create new files that are already large, or significantly grow existing files? (Don't flag pre-existing file sizes — focus on what this change contributed.)
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment
@@ -0,0 +1,116 @@
# Implementer Subagent Prompt Template
Use this template when dispatching an implementer subagent.
```
Task tool (general-purpose):
description: "Implement Task N: [task name]"
prompt: |
You are implementing Task N: [task name]
## Task Description
[FULL TEXT of task from plan - paste it here, don't make subagent read file]
## Context
[Scene-setting: where this fits, dependencies, architectural context]
## Before You Begin
If you have questions about:
- The requirements or acceptance criteria
- The approach or implementation strategy
- Dependencies or assumptions
- Anything unclear in the task description
**Ask them now.** Raise any concerns before starting work.
## Your Job
Once you're clear on requirements:
1. Implement exactly what the task specifies
2. Write tests (following TDD if task says to)
3. Verify implementation works
4. Commit your work
5. Self-review (see below)
6. Report back
Work from: [directory]
**While you work:** If you encounter something unexpected or unclear, **ask questions**.
It's always OK to pause and clarify. Don't guess or make assumptions.
## Code Organization
You reason best about code you can hold in context at once, and your edits are more
reliable when files are focused. Keep this in mind:
- Follow the file structure defined in the plan
- Each file should have one clear responsibility with a well-defined interface
- If a file you're creating is growing beyond the plan's intent, stop and report
it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
- If an existing file you're modifying is already large or tangled, work carefully
and note it as a concern in your report
- In existing codebases, follow established patterns. Improve code you're touching
the way a good developer would, but don't restructure things outside your task.
## When You're in Over Your Head
It is always OK to stop and say "this is too hard for me." Bad work is worse than
no work. You will not be penalized for escalating.
**STOP and escalate when:**
- The task requires architectural decisions with multiple valid approaches
- You need to understand code beyond what was provided and can't find clarity
- You feel uncertain about whether your approach is correct
- The task involves restructuring existing code in ways the plan didn't anticipate
- You've been reading file after file trying to understand the system without progress
**How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
specifically what you're stuck on, what you've tried, and what kind of help you need.
The controller can provide more context, re-dispatch with a more capable model,
or break the task into smaller pieces.
## Before Reporting Back: Self-Review
Review your work with fresh eyes. Ask yourself:
**Completeness:**
- Did I fully implement everything in the spec?
- Did I miss any requirements?
- Are there edge cases I didn't handle?
**Quality:**
- Is this my best work?
- Are names clear and accurate (match what things do, not how they work)?
- Is the code clean and maintainable?
**Discipline:**
- Did I avoid overbuilding (YAGNI)?
- Did I only build what was requested?
- Did I follow existing patterns in the codebase?
**Testing:**
- Do tests actually verify behavior (not just mock behavior)?
- Did I follow TDD if required?
- Are tests comprehensive?
If you find issues during self-review, fix them now before reporting.
## Report Format
When done, report:
- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
- What you implemented (or what you attempted, if blocked)
- What you tested and test results
- Files changed
- Self-review findings (if any)
- Any issues or concerns
Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
information that wasn't provided. Never silently produce work you're unsure about.
```
## Skills
You have access to the following skills in `C:\Users\silve\.agents\skills`: [list of skills]. You can use the `view_file` tool to read the `SKILL.md` file in any of these directories to learn how to do things.
@@ -0,0 +1,61 @@
# Spec Compliance Reviewer Prompt Template
Use this template when dispatching a spec compliance reviewer subagent.
**Purpose:** Verify implementer built what was requested (nothing more, nothing less)
```
Task tool (general-purpose):
description: "Review spec compliance for Task N"
prompt: |
You are reviewing whether an implementation matches its specification.
## What Was Requested
[FULL TEXT of task requirements]
## What Implementer Claims They Built
[From implementer's report]
## CRITICAL: Do Not Trust the Report
The implementer finished suspiciously quickly. Their report may be incomplete,
inaccurate, or optimistic. You MUST verify everything independently.
**DO NOT:**
- Take their word for what they implemented
- Trust their claims about completeness
- Accept their interpretation of requirements
**DO:**
- Read the actual code they wrote
- Compare actual implementation to requirements line by line
- Check for missing pieces they claimed to implement
- Look for extra features they didn't mention
## Your Job
Read the implementation code and verify:
**Missing requirements:**
- Did they implement everything that was requested?
- Are there requirements they skipped or missed?
- Did they claim something works but didn't actually implement it?
**Extra/unneeded work:**
- Did they build things that weren't requested?
- Did they over-engineer or add unnecessary features?
- Did they add "nice to haves" that weren't in spec?
**Misunderstandings:**
- Did they interpret requirements differently than intended?
- Did they solve the wrong problem?
- Did they implement the right feature but wrong way?
**Verify by reading code, not by trusting report.**
Report:
- ✅ Spec compliant (if everything matches after code inspection)
- ❌ Issues found: [list specifically what's missing or extra, with file:line references]
```
+66
View File
@@ -0,0 +1,66 @@
---
name: update-context
description: Update context document
---
# Update Context
1. Purpose
This specification defines the requirements for maintaining persistent, accurate project context across chat instances by synchronizing internal documentation with local context artifacts.
2. Requirements
2.1 Internal Documentation
The agent MUST maintain an internal, continuously updated documentation set describing the project.
This documentation MUST include:
Project goals and vision
Architecture and major components
Active features, experiments, and branches
Constraints, assumptions, and open questions
Key decisions and their rationale
The internal documentation MUST serve as the single source of truth for project context.
2.2 Synchronization With Local Context Artifacts
The agent MUST regularly review the contents of:
C:\dev\worldwideview\.agents\context
When performing any task, the agent SHOULD check this folder for:
Relevant guidance
Conflicts or discrepancies
When referencing any file from this folder, the agent MUST include the file path in its notes or summaries to ensure easy retrieval.
If discrepancies are found, the agent MUST update the internal documentation to reflect the most accurate state.
2.3 Reflecting New Changes
When new information, decisions, or changes occur:
The agent MUST determine whether the change is represented in internal documentation and context artifacts.
If not, the agent MUST update the documentation accordingly.
Documentation SHOULD remain:
Comprehensive
Current
Unambiguous
3. Goal
A new chat instance MUST be able to reconstruct an accurate understanding of the project solely from:
The agent's internal documentation
The contents of C:\dev\worldwideview\.agents\context
This ensures continuity, accuracy, and long‑term coherence across sessions.
+172
View File
@@ -0,0 +1,172 @@
---
name: update-docs
description: Use when generating or updating LLM-optimized documentation with concrete file references across project overview, architecture, build, testing, development, deployment, and file catalog docs.
---
# Update Documentation
You will generate LLM-optimized documentation with concrete file references and flexible formatting.
## Your Task
Create documentation that allows humans and LLMs to:
- **Understand project purpose** - what the project does and why
- **Get architecture overview** - how the system is organized
- **Build on all platforms** - build instructions with file references
- **Add features/subsystems** - following established patterns with examples
- **Debug applications** - troubleshoot issues with specific file locations
- **Test and add tests** - run existing tests and create new ones
- **Deploy and distribute** - package and deploy the software
## Required Documentation Structure
Each document MUST include:
1. **Timestamp Header** - Hidden comment with last update timestamp
2. **Brief Overview** (2-3 paragraphs max)
3. **Key Files & Examples** - Concrete file references for each major topic
4. **Common Workflows** - Practical guidance with file locations
5. **Reference Information** - Quick lookup tables with file paths
## Timestamp Format
Each generated file MUST start with:
```
<!-- Generated: YYYY-MM-DD HH:MM:SS UTC -->
```
## Process
You will:
1. **Analyze the codebase systematically** across 7 key areas (merging development+patterns)
2. **Create or update docs** in `docs/*.md` with concrete file references
3. **Synthesize final documentation** into a minimal, LLM-friendly README.md
4. **Eliminate all duplication** across files
## Analysis Methodology
For each area, agents should:
1. **Examine key files**: Look for build configs, test files, deployment scripts, main source files
2. **Extract file references**: Note specific files, line numbers, and examples
3. **Identify patterns**: Find repeated structures, naming conventions, common workflows
4. **Make content LLM-friendly**: Token-efficient, reference-heavy, practical examples
## Specific File Requirements
Issue the following Task calls in parallel:
**Project Overview** (`docs/project-overview.md`):
STRUCTURE:
- Overview: What the project is, core purpose, key value proposition (2-3 paragraphs)
- Key Files: Main entry points and core configuration files
- Technology Stack: Core technologies with specific file examples
- Platform Support: Requirements with platform-specific file locations
**Architecture** (`docs/architecture.md`):
STRUCTURE:
- Overview: High-level system organization (2-3 paragraphs)
- Component Map: Major components with their source file locations
- Key Files: Core headers and implementations with brief descriptions
- Data Flow: How information flows with specific function/file references
**Build System** (`docs/build-system.md`):
STRUCTURE:
- Overview: Build system with file references to main build configuration
- Build Workflows: Common tasks with specific commands and config files
- Platform Setup: Platform-specific requirements with file paths
- Reference: Build targets, presets, and troubleshooting with file locations
**Testing** (`docs/testing.md`):
STRUCTURE:
- Overview: Testing approach with test file locations
- Test Types: Different test categories with specific file examples
- Running Tests: Commands with file paths and expected outputs
- Reference: Test file organization and build system test targets
**Development** (`docs/development.md`):
STRUCTURE:
- Overview: Development environment, code style, patterns (merge with old patterns.md if exists)
- Code Style: Conventions with specific file examples (show actual code from codebase)
- Common Patterns: Implementation patterns with file references and examples from the codebase
- Workflows: Development tasks with concrete file locations and examples
- Reference: File organization, naming conventions, common issues with specific files
**Deployment** (`docs/deployment.md`):
STRUCTURE:
- Overview: Packaging and distribution with script references
- Package Types: Different packages with build targets and output locations
- Platform Deployment: Platform-specific packaging with file paths
- Reference: Deployment scripts, output locations, server configurations
**Files Catalog** (`docs/files.md`):
STRUCTURE:
- Overview: Comprehensive file catalog with descriptions and relationships (2-3 paragraphs)
- Core Source Files: Main application logic with purpose descriptions
- Platform Implementation: Platform-specific code with interface mappings
- Build System: Build configuration and helper modules
- Configuration: Assets, scripts, configs - Supporting files and their roles
- Reference: File organization patterns, naming conventions, dependency relationships
## Critical Requirements
### LLM-OPTIMIZED FORMAT
- **Token efficient**: Avoid redundant explanations, focus on essential information
- **Concrete file references**: Always include specific file paths, line numbers when helpful
- **Flexible formatting**: Use subsections, code blocks, examples instead of rigid step-by-step
- **Pattern examples**: Show actual code from the codebase, not generic examples
### NO DUPLICATION
- Each piece of information appears in EXACTLY ONE file
- Build information only in build-system.md
- Code style and patterns only in development.md
- Deployment information only in deployment.md
- Cross-references using: "See [docs/filename.md](docs/filename.md)"
### FILE REFERENCE FORMAT
Always include specific file references:
```
**Core System** - Core implementation in src/core.h (lines 15-45), platform backends in src/platform/
**Build Configuration** - Main build file (lines 67-89), configuration files
**Module Management** - Interface in src/module.h, implementation in src/module.c (key_function at line 134)
```
### PRACTICAL EXAMPLES
Use actual code from the codebase:
```c
// From src/example.h:23-27
typedef struct {
bool active;
void *data;
int count;
} ExampleState;
```
## Final Steps
After all tasks complete:
1. **Read all `docs/*.md` files** and create README.md with:
- Project description (2-3 sentences max)
- Key entry points and core configuration files
- Quick build commands
- Documentation links with brief descriptions of what LLMs will find useful
- Keep it under 50 lines total
2. **Duplication check**: Scan all files and remove any duplicated information
3. **File reference check**: Ensure all file paths are accurate and helpful
## Agent Instructions
Each agent must:
1. **Read existing file** if it exists to understand current content
2. **Analyze relevant codebase files** systematically
3. **Extract specific file references** throughout analysis
4. **Create LLM-friendly content**: Token-efficient, concrete file paths, flexible formatting
5. **Include practical workflows** with specific file references
6. **Create reference sections** with file locations and line numbers
7. **Update timestamp** at the top with current UTC time
8. **Read generated file** and revise for accuracy and completeness
**Success criteria**: Each file should be a practical reference that helps LLMs quickly understand the codebase and find the right files for specific tasks.
+84
View File
@@ -0,0 +1,84 @@
---
name: worktree-dev
description: Use when creating a git worktree for isolated or parallel development — called by /github-workflow --worktree or directly when multiple agents need to work simultaneously on independent branches
---
# Worktree Development
## Overview
Git worktrees create separate working directories for branches. Each `.worktrees/{name}/` is a full independent checkout with its own `node_modules`, `.next` cache, and `.env.local` copy. They never conflict — multiple can run simultaneously.
`.worktrees/` is in `.gitignore` — worktree checkouts are never committed.
---
## Create a Worktree
```bash
# From project root (c:\dev\worldwideview)
git worktree add .worktrees/{branch-name} -b {branch-name}
```
Example:
```bash
git worktree add .worktrees/feature-42-ais-layer -b feature/42-ais-layer
```
## Test Inside the Worktree
To run both the Next.js frontend and the Fastify data engine simultaneously inside the worktree without colliding ports with your main environment:
```bash
# From project root
pnpm run test-worktree {branch-name}
```
This script will automatically:
1. Copy `.env.local` if it's missing.
2. Run `pnpm install` if `node_modules` is missing.
3. Find distinct free ports for the frontend and backend.
4. Inject the environment variables (`PORT`, `WWV_DATA_ENGINE_URL`, `NEXT_PUBLIC_WS_ENGINE_URL`).
5. Open your browser.
If you just need to run build/test checks inside the worktree manually:
```bash
cd .worktrees/{branch-name}
pnpm build # build check
pnpm test # unit tests
```
---
## Commit and Push
The worktree tracks its own branch. Commit from inside:
```bash
cd .worktrees/{branch-name}
# invoke /commit skill
git push -u origin {branch-name}
```
---
## Clean Up After Merge
```bash
# From project root
git worktree remove .worktrees/{branch-name}
git branch -d {local-branch-name}
```
## Multiple Parallel Agents
```bash
# Agent A
git worktree add .worktrees/feature-42-ais -b feature/42-ais
# Agent B
git worktree add .worktrees/feature-43-weather -b feature/43-weather
```
Agent A tests with `pnpm run test-worktree feature-42-ais`.
Agent B tests with `pnpm run test-worktree feature-43-weather`.
Both command executions will automatically find unique free ports for their respective Next.js and Fastify servers and open separate browser tabs. They never conflict.
+12 -3
View File
@@ -1,8 +1,17 @@
DATABASE_URL=file:./data/wwv.db
# PostgreSQL connection string.
# For local dev: The platform will automatically spin up PostgreSQL via Docker Compose.
# Set DATABASE_URL to: postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
#
# For cloud/production: Provide your external Postgres connection string (e.g. Supabase)
# and set WWV_SKIP_LOCAL_DB=true to prevent Docker from spinning up a local database instance.
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
# Set this to true in production to prevent docker-compose or pnpm run dev from starting the local database.
# WWV_SKIP_LOCAL_DB=false
# Default plugins enabled on boot for demo edition
# Comma-separated list of plugin IDs
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=iranwarlive,satellite,gps_jamming
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=iranwarlive,satellite,gps-jamming
# Edition: "local" | "cloud" | "demo"
NEXT_PUBLIC_WWV_EDITION=local
@@ -12,4 +21,4 @@ NEXT_PUBLIC_WWV_EDITION=local
# [WARNING] NEVER commit real secrets here. Real secrets must ONLY go into .env.local!
AUTH_SECRET=changeme_d64c1f35b447da89cf6ed5a0988da1379b21904edb91a87c3f5a63942e3d23a4_changeme
+2 -2
View File
@@ -4,8 +4,8 @@
# This file is tracked by git. Only put non-secret values here.
# Prisma reads DATABASE_URL from this file.
# Database (SQLite for local — zero config; PostgreSQL for cloud)
DATABASE_URL=file:./data/wwv.db
# Database (PostgreSQL)
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview
# ============================================================
# .env.local — NOT committed (secrets & API keys)
+3 -7
View File
@@ -11,8 +11,6 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
@@ -27,13 +25,12 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: npx prisma generate
- run: pnpm test
build:
@@ -41,17 +38,16 @@ jobs:
runs-on: ubuntu-latest
needs: [typecheck, test]
env:
DATABASE_URL: file:./data/wwv.db
DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
NEXT_PUBLIC_WWV_EDITION: local
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: npx prisma generate
- run: pnpm build
+1 -1
View File
@@ -1,7 +1,7 @@
name: Claude Code Review
on:
pull_request_target:
pull_request:
types: [opened, synchronize, ready_for_review, reopened]
# Optional: Only run on specific file changes
# paths:
+1 -1
View File
@@ -46,5 +46,5 @@ jobs:
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
# claude_args: '--allowed-tools Bash(gh pr:*)'
# claude_args: '--allowed-tools Bash(gh pr *)'
+55
View File
@@ -0,0 +1,55 @@
name: Docker Build and Publish
on:
push:
branches: [ "main", "feat/docker-ci" ]
pull_request:
branches: [ "main" ]
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=sha
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+12 -1
View File
@@ -18,7 +18,11 @@ node_modules/
/out/
# agents
/.agents/
/.agents/*
!/.agents/rules/
!/.agents/skills/
!/.agents/settings.json
!/.agents/global-skills-index.md
# claude code IDE config
/.claude/
@@ -80,6 +84,13 @@ packages/*/dist/
# Developmental scripts & temporary sandbox
/local-scripts/
/public/plugins-local/
# git worktrees
/.worktrees/
# proprietary extracted services
packages/wwv-data-engine/
# IDE workspace files
*.code-workspace
+56 -13
View File
@@ -19,7 +19,7 @@ Our primary design, feature-set, and operational layout goal is to mimic the str
| State | Zustand (slice-based: globe, layers, timeline, UI, filters, data, config, favorites, geojson) |
| Event Bus | Custom typed `DataBus` (pub/sub singleton) |
| Styling | Vanilla CSS — **no Tailwind** |
| Database | SQLite via Prisma (local), PostgreSQL (cloud) |
| Database | PostgreSQL via Prisma 7 (local and cloud) |
| Auth | NextAuth v5 beta (Credentials provider, JWT sessions) |
| Package Manager | pnpm (monorepo with `pnpm-workspace.yaml`) |
| Testing | Vitest + jsdom + React Testing Library |
@@ -77,7 +77,7 @@ worldwideview/
├── prisma/ # schema.prisma, migrations/
├── public/ # Static assets, Cesium workers, plugin GeoJSON data
├── scripts/ # Build scripts (copy-cesium, scaffold-osm-plugin, setup)
├── data/ # SQLite database (gitignored, Docker volume)
├── data/ # PostgreSQL data volume (gitignored)
├── Dockerfile # Multi-stage production build
├── docker-compose.yml # Main app + microservice backends
└── .agents/ # Agent documentation, rules, skills, workflows
@@ -101,10 +101,13 @@ Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
→ Store → EntityRenderer → Globe
```
Three plugin architectures exist:
1. **Static** — GeoJSON file in `public/data/`, loaded by `StaticDataPlugin`
2. **Active Proxied** — Next.js API routes in `src/app/api/` as CORS proxy
3. **Microservice** — Standalone Fastify container with SQLite (e.g., `iranwarlive-backend`)
Four plugin architectures exist (All-Bundle Model):
1. **Data Engine Seeder** — Standalone Fastify container with PostgreSQL microservice or unified seeders (e.g., `iranwarlive-backend`).
2. **Dynamic CDN Loaded (Bundle)** — Externally developed plugins dynamically imported at runtime via ES module CDNs (e.g., `unpkg.com` version-pinned URLs).
3. **Static Compiled (Bundle)** — Static GeoJSON data wrapped into JS bundles via `wwvStaticCompiler` during build/sync (previously `StaticDataPlugin`).
4. **Active Proxied (Bundle)** — Next.js API routes bundled to provide frontend interactions (previously `DeclarativePlugin`).
All plugins are now dynamically imported at runtime as ES module bundles via `loadPluginFromManifest` utilizing `import(/* webpackIgnore: true */ entry)`. The legacy `StaticDataPlugin` and `DeclarativePlugin` runtimes are fully deprecated.
Plugin types are re-exported from SDK through `src/core/plugins/PluginTypes.ts` and `PluginManifest.ts` — **source of truth is always `@worldwideview/wwv-plugin-sdk`**.
@@ -128,6 +131,18 @@ Engine push /stream → DataBusSubscriber WsClient router
→ StackManager (co-located entity grouping)
```
### 4.3.1 Split-Routing (Cloud Fallback)
When a local engine is detected at `localhost:5001`, the frontend fetches its `/manifest` to discover available seeders. Per-plugin routing via `resolveEngineUrl`:
- Plugin's seeder is in local manifest → `ws://localhost:5001/stream`
- Plugin's seeder is NOT in local manifest → `wss://dataengine.worldwideview.dev/stream`
This enables core contributors running the public (community) engine locally to see local data for their seeders while proprietary sources (aviation, maritime) continue streaming from the cloud.
The data engine uses a **public upstream / private fork** model:
- `wwv-data-engine` (public) — community seeders, contributors fork and PR here
- `wwv-data-engine-internal` (private) — all seeders, deploys to Coolify via `git merge upstream/main`
### 4.4 Rendering Pipeline
- **Primitive-based**: Uses `PointPrimitiveCollection`, `BillboardCollection`, `LabelCollection` — NOT Cesium Entity API
@@ -197,22 +212,28 @@ Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRe
> - **Never** reference Cursor IDE rules; we use the open `.agents/` standard.
> - **MUST**: You MUST update Semantic Versioning numbering inside the relevant `package.json` file prior to executing any code commits, adhering strictly to the `[/commit]` workflow rules (`feat:` -> Minor, `fix/refactor/perf:` -> Patch).
> - **MUST Detail Commit Levels & Bumps**: On description changes or release notes, you must detail the level of commit (Major/Minor/Fix) for *each* individual change. If there are multiple accumulated changes, you MUST EITHER commit them individually and bump the version each time, OR commit them all at once and bump the version multiple times.
> - **MUST Explain Complex Concepts Simply**: Whenever providing a complicated technical explanation to the user, you MUST include a simple explanation below it. Use an analogy with reference to the correct terminology, comparing the concept to something from everyday life to ensure the user easily understands it.
> - **MUST Be Transparent & Narrate Actions**: You MUST always be transparent about what you are doing. Narrate your goals, your current step in the process, and exactly what actions you are taking or tools you are executing **before** or **while** you do them, not after they are done. Do not work in silence or lock all your reasoning behind hidden "thought" blocks. Use visible chat messages to bring the user along the journey by describing your plan as it unfolds. **Crucially, keep this narration conversational and natural.** Avoid stiff, robotic templates (e.g., "My Goal: X. My Step: Y."). Just occasionally drop a brief, casual note about what you are checking or doing next so the user isn't left in the dark.
### 5.8 Workspace Hygiene
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
### 5.9 Architectural Integrity
Always interface-based, extensible, composable. Never band-aids on band-aids. Before adding flags or cross-domain dependencies, you MUST consult `.agents/rules/coding-principles.md`.
---
## 6. Environment Variables
| Variable | Required | Description |
|---|---|---|
| `DATABASE_URL` | Yes | SQLite: `file:./data/wwv.db` |
| `DATABASE_URL` | Yes | PostgreSQL connection string |
| `AUTH_SECRET` | Yes | JWT signing secret (generate with `openssl rand -hex 32`) |
| `NEXT_PUBLIC_CESIUM_ION_TOKEN` | No | Cesium Ion access token |
| `NEXT_PUBLIC_BING_MAPS_KEY` | No | Bing Maps imagery |
| `NEXT_PUBLIC_GOOGLE_MAPS_API_KEY` | No | Google 3D Tiles |
| `NEXT_PUBLIC_WWV_EDITION` | No | `local` / `cloud` / `demo` (default: `local`) |
| `NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` | No | Override engine WebSocket URL (default: cloud) |
| `OPENSKY_CREDENTIALS` | No | Comma-separated `id:secret` pairs for credential rotation |
| `WWV_BRIDGE_TOKEN` | No | Shared secret for marketplace → WWV install bridge |
| `WWV_DEMO_ADMIN_SECRET` | No | Demo edition admin password |
@@ -227,14 +248,14 @@ Secrets go in `.env.local` (gitignored). Non-secrets go in `.env` (committed).
```bash
pnpm install # Install all workspace dependencies
pnpm run setup # Generate .env.local with AUTH_SECRET (first-time setup)
pnpm dev # Next.js frontend only (auto-runs prisma migrate deploy + copy-cesium)
pnpm dev # Next.js frontend only (auto-runs prisma db push + copy-cesium)
pnpm dev:all # Frontend + wwv-data-engine concurrently (normal development)
pnpm dev:backends # Run only the data engine in dev mode
pnpm build # Production build
pnpm test # Run all Vitest tests (scoped to src/lib, src/core, src/plugins)
pnpm db:reset # Reset and re-migrate the frontend SQLite database (destructive)
pnpm db:reset # Reset and re-migrate the frontend database (destructive)
pnpm start:backends # Start all plugin microservice backends in parallel
pnpm clean:backends # Wipe all plugin SQLite databases
pnpm clean:backends # Wipe all plugin database records
pnpm run scaffold-osm-plugin <name> # Generate a new plugin from scaffold
```
@@ -249,8 +270,8 @@ Frontend runs at `http://localhost:3000`.
- **Cesium assets**: Copied to `public/cesium/` via `scripts/copy-cesium.mjs` at build time, excluded from output tracing.
- **Prisma Configuration**: `prisma.config.ts` must export a native javascript object instead of dynamically importing CLI wrapper binaries (`prisma/config` or `dotenv`). The standalone Next.js tracer strips CLI devDependencies during the build, which will cause fatal runtime container crashes if imported.
- **Microservices**: Separate containers defined in `docker-compose.yml`, proxied via `next.config.ts` rewrites.
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell. Persistent storage mount required at `/app/data` for the SQLite root node database.
- **Docker volumes**: Mount `/app/data` (frontend SQLite), `/app/packages/wwv-data-engine/data` (data engine SQLite), `/data` (Redis)
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell.
- **Docker volumes**: Ensure PostgreSQL data and Redis volumes are mounted for persistence.
---
@@ -279,7 +300,10 @@ Configured in `next.config.ts` `headers()`:
| Repo | Purpose |
|---|---|
| `worldwideview` | Main application (this repo) |
| `wwv-data-engine` | Open-source data engine — community seeders (PUBLIC) |
| `wwv-data-engine-internal` | Proprietary data engine — all seeders (PRIVATE, deployed to Coolify) |
| `worldwideview-marketplace` | Plugin marketplace web app |
| `worldwideview-plugins` | Published npm plugin packages |
| `worldwideview-web` | Marketing / landing page |
---
@@ -290,11 +314,12 @@ Read the relevant rule file when working in that domain:
| Rule | When to use | Path |
|---|---|---|
| `coding-principles` | When writing new features, refactoring, or making architectural decisions | `.agents/rules/coding-principles.md` |
| `monorepo-workflow` | pnpm commands, adding packages, workspace config | `.agents/rules/monorepo-workflow.md` |
| `plugin-architecture` | Creating/modifying plugins, lifecycle, registration | `.agents/rules/plugin-architecture.md` |
| `cesium-rendering` | Globe rendering, entity types, primitives, LOD, culling | `.agents/rules/cesium-rendering.md` |
| `state-management` | Zustand slices, store access, plugin settings | `.agents/rules/state-management.md` |
| `database-migrations` | Prisma schema changes, migrations, SQLite/Postgres | `.agents/rules/database-migrations.md` |
| `database-migrations` | Prisma schema changes, migrations, PostgreSQL | `.agents/rules/database-migrations.md` |
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
@@ -341,3 +366,21 @@ Refer to these skill documents for specialized tasks:
### Global Skills
52 skills are available across all projects. See `.agents/global-skills-index.md` for the full list and invocation paths.
---
## 15. Pull Request & Commit Guidelines
- **Commit Format**: We strictly enforce Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`).
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
---
## 16. Debugging and Troubleshooting
- **Prisma & PostgreSQL Sync Issues**: If the local database state falls out of sync with Prisma schema, do not manually drop tables. Instead, run `pnpm db:reset` to cleanly wipe and re-apply all migrations.
- **Cesium Entity Clipping**: If `billboard` entities are clipping or failing to render correctly, verify that you are not mixing `point` primitive properties (like `size` or `outlineWidth`) into the `billboard` options.
- **Build Exhaustion (Docker)**: Multi-stage pnpm builds generate massive cache layers. If a Coolify deployment fails silently or PostgreSQL crashes abruptly, check host disk space and run `docker builder prune -a -f`.
- **Next.js Typechecking Failures**: If backend-only `scripts/` fail during Next.js build, verify that the scripts directory is properly listed in the `exclude` array of `tsconfig.json`.
+23 -13
View File
@@ -7,24 +7,19 @@ RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -na
# Stage 1: Install ALL dependencies (needed for build)
FROM node:22-alpine AS deps
RUN corepack enable pnpm
RUN apk add --no-cache python3 make g++
RUN npm install -g [email protected]
WORKDIR /app
# Copy only the extracted package.jsons
COPY --from=extractor /app ./
# Install dependencies with cache mount for pnpm store
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install --frozen-lockfile
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install
# Stage 3: Build the application
FROM deps AS builder
# Copy full source code
COPY . .
RUN DATABASE_URL="file:./data/wwv.db" npx prisma generate
# Create an empty SQLite database with all tables applied
RUN mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy
# Next.js inlines NEXT_PUBLIC_* vars at build time — must be declared as ARGs
ARG NEXT_PUBLIC_CESIUM_ION_TOKEN
ARG NEXT_PUBLIC_GOOGLE_MAPS_API_KEY
@@ -35,18 +30,30 @@ ARG NEXT_PUBLIC_ADSENSE_CLIENT_ID
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
# Run our pregenerate schema swap script and then generate Prisma client
RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
# Database migrations run at container startup via docker-entrypoint.sh
# DATABASE_URL must be set to a PostgreSQL connection string
# Run Next.js build with Webpack cache mounted
RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build
RUN node scripts/copy-cesium.mjs
# Deploy flattened production dependencies
RUN pnpm --filter worldwideview deploy --prod /app/prod
# Stage 4: Production runner
FROM node:22-alpine AS runner
WORKDIR /app
RUN apk add --no-cache openssl
ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0
ENV PORT=3000
ENV DATABASE_URL=file:./data/wwv.db
# DATABASE_URL must be provided via environment variable (no default)
# Example: postgresql://user:pass@host:5432/dbname
ENV AUTH_TRUST_HOST=true
# Copy Prisma schema + migrations for runtime DB init
@@ -59,20 +66,23 @@ COPY --from=builder /app/src/generated ./src/generated
# Copy standalone server output
COPY --from=builder /app/.next/standalone ./
# Copy deployed production node_modules
COPY --from=builder /app/prod/node_modules ./node_modules
# We no longer copy proddeps/node_modules. Next.js standalone output
# already traces and copies all the exact node_modules needed for production.
# Copy static assets that standalone mode does NOT include
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs
COPY --from=builder /app/scripts/migrate-legacy.mjs ./scripts/migrate-legacy.mjs
# Entrypoint: migrate DB on first run, then start server
COPY docker-entrypoint.sh ./docker-entrypoint.sh
RUN sed -i 's/\r$//' ./docker-entrypoint.sh
RUN chmod +x ./docker-entrypoint.sh
# Declare /app/data as a persistent volume mount point.
VOLUME ["/app/data"]
EXPOSE 3000
EXPOSE 3000 3001
ENTRYPOINT ["./docker-entrypoint.sh"]
BIN
View File
Binary file not shown.
+133 -46
View File
@@ -1,91 +1,178 @@
<div align="center">
# WorldWideView 🌍
<!-- Generated: 2026-04-23 06:11:00 UTC -->
# WorldWideView
**The Open-Source, Plugin-Driven Geospatial Intelligence Engine**
[![License: Elastic 2.0](https://img.shields.io/badge/License-Elastic%202.0-blue.svg)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
*A modular situational awareness platform designed to ingest live data streams and render them as interactive, cinematic layers on a high-fidelity CesiumJS 3D globe.*
<!-- 📸 Replace with a high-res GIF or screenshot of the platform running with multiple layers enabled -->
[![CI Build](https://github.com/silvertakana/worldwideview/actions/workflows/ci.yml/badge.svg)](https://github.com/silvertakana/worldwideview/actions/workflows/ci.yml)
[![Codecov](https://img.shields.io/codecov/c/github/silvertakana/worldwideview.svg)](https://codecov.io/gh/silvertakana/worldwideview)
[![NPM Version](https://img.shields.io/npm/v/@worldwideview/wwv-plugin-sdk.svg)](https://www.npmjs.com/package/@worldwideview/wwv-plugin-sdk)
[![GitHub Release](https://img.shields.io/github/v/release/silvertakana/worldwideview?sort=semver)](https://github.com/silvertakana/worldwideview/releases)
[![Contributors](https://img.shields.io/github/contributors/silvertakana/worldwideview.svg)](https://github.com/silvertakana/worldwideview/graphs/contributors)
<br>
[![Next.js 16](https://img.shields.io/badge/Next.js-16-black?logo=next.js)](https://nextjs.org/)
[![CesiumJS](https://img.shields.io/badge/Cesium-JS-4272D0)](https://cesium.com/)
[![TypeScript Strict](https://img.shields.io/badge/TypeScript-Strict-3178C6?logo=typescript)](https://www.typescriptlang.org/)
[![Docker](https://img.shields.io/badge/Docker-Multi--Stage-2496ED?logo=docker)](https://www.docker.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Discord](https://img.shields.io/discord/1481088998750294139?color=7289da&label=discord&logo=discord)](#)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://makeapullrequest.com)
![WorldWideView Interface](docs/assets/screenshot.png)
</div>
---
## ⚡ Build a Plugin in 5 Minutes
WorldWideView is a real-time geospatial engine visualizing live global data on an interactive 3D globe. Utilizing a dynamic "All-Bundle" plugin architecture, independent data sources—like live aircraft, maritime vessels, or conflict events—are ingested and rendered decoupled from the core 3D viewer.
WorldWideView’s architecture means **everything is a plugin**. The core engine is completely data-agnostic. Rather than touching complex 3D rendering code, you can build a plugin that simply pipes a REST API into GeoJSON, and the engine handles the rest!
## Key Features
Ready to add a new intelligence layer (like Earthquakes, Weather, or Satellites)? We have a scaffold generator ready for you:
- **"All-Bundle" Plugin Architecture**: Ingest any data source dynamically without touching the core platform.
- **High-Fidelity 3D Rendering**: Google Photorealistic 3D Tiles and LOD modeling powered by CesiumJS.
- **Real-Time Data Pipeline**: High-frequency WebSocket updates managed by a custom `DataBus`.
- **Advanced Entity Management**: Automatic horizon culling, chunked primitive rendering, and 3D stacking/spiderification.
- **Marketplace Integration**: Download and sync new plugins directly from the UI.
```bash
# 1. Generate the boilerplate plugin from a template
pnpm run scaffold-osm-plugin my-new-data-source
## Core Technologies
# 2. Add your data fetching logic in the generated files
# 3. Reload the dev server and watch it map on the globe!
- **Frontend:** Next.js 16 (App Router), React 19, TypeScript 5
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles)
- **State Management:** Zustand
- **Event Bus:** Custom typed `DataBus` for high-frequency WebSocket updates
- **Database:** PostgreSQL via Prisma 7
- **Deployment:** Docker multi-stage build, Coolify
## Project Architecture
WorldWideView separates the data acquisition layer from the frontend rendering loop, using a real-time event bus to bridge them.
```mermaid
flowchart TD
subgraph Data Sources
A[Public APIs] -->|Poll| B[Data Engine Seeders]
C[Microservices] -->|Stream| B
end
subgraph Frontend Pipeline
B -->|WebSocket /stream| D[DataBus & WsClient]
D -->|Hydrate| E[Zustand Store]
E -->|Memoized Entities| F[Entity Renderer]
F -->|Primitives| G[CesiumJS Globe]
end
subgraph Plugins
H[Plugin Registry] -->|Load| I[Dynamic Import CDNs]
end
H -.-> D
```
📖 **[Read the Full Plugin Guide](docs/PLUGIN_GUIDE.md)** for a deep dive into hooking up websockets or static datasets.
## Prerequisites
---
Before running the application, ensure you have the following installed:
- [Node.js](https://nodejs.org/) (v18+)
- [pnpm](https://pnpm.io/) (v9+)
- [Docker](https://www.docker.com/) (for self-hosting or full local dev)
- PostgreSQL (or rely on the `coolify-db` / local compose container)
## 🚀 Installation & Setup (Local Development)
## Quick Start (Self-Hosting)
WorldWideView uses a multi-stage Dockerfile designed for standalone output. To deploy instantly on your own server:
**Mac/Linux:**
```bash
mkdir worldwideview && cd worldwideview
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.sh | bash
```
**Windows (PowerShell):**
```powershell
mkdir worldwideview; cd worldwideview
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.ps1 -UseBasicParsing | Invoke-Expression
```
> [!NOTE]
> Ensure you connect a PostgreSQL database via the `DATABASE_URL` environment variable for production deployments.
## Quick Start (Local Development)
To run the source code locally for contributing or developing:
```bash
git clone https://github.com/silvertakana/worldwideview.git
cd worldwideview
pnpm install
pnpm run setup # generates .env.local with AUTH_SECRET
pnpm run dev:all # starts the app, data engine, and marketplace concurrently
pnpm run dev:all # boots the UI, cache layers, and the data engine
```
Visit `http://localhost:3000` to see the live globe.
---
## Project Structure
## 🐋 Production Deployment (Docker & Coolify)
The codebase utilizes a `pnpm` monorepo configuration:
WorldWideView uses a multi-stage Dockerfile designed for standalone output, natively supporting deployment via Coolify or standard Docker Compose. The `docker-compose.yml` spins up the front-end application alongside the high-performance Data Engine and Redis cache.
```bash
# Start the core app, Redis cache, and Data Engine microservice in production mode
docker compose up -d
```text
worldwideview/
├── src/ # Core frontend app
│ ├── app/ # Next.js App Router (pages, API routes)
│ ├── components/ # Shared UI, Globe panels, and 3D layouts
│ ├── core/ # DataBus, Polling, PluginManager, Store
│ └── plugins/ # Built-in plugins and registry logic
├── packages/ # Monorepo packages
│ ├── wwv-plugin-sdk/ # SDK interfaces and manifest schemas
│ └── wwv-plugin-*/ # Individual plugins & their backends
├── prisma/ # Database schemas & migrations
└── .agents/ # Agent rules, workflows, and documentation
```
**Persistent Storage Requirements:**
When deploying to production, ensure you mount the following volumes to prevent data loss:
- Mount `/app/data` to persist the core SQLite database.
- Mount `/app/packages/wwv-data-engine/data` to persist the custom plugin microservices SQLite layer.
- Mount `/data` to persist the standalone Redis container.
## Plugin Ecosystem
---
WorldWideView operates on an open-core philosophy. The platform itself is data-agnostic; all data sources are dynamically imported as plugins at runtime.
## 🧠 Core Architecture & Philosophies
- **[Plugin Quickstart Guide](docs/plugin-quickstart.md)**: Learn how to scaffold and link your first plugin using the `@worldwideview/cli`.
- **[Advanced Plugin Guide](docs/plugin-advanced.md)**: Deep dive into microservice data seeders, WebSockets, complex 3D rendering, and Marketplace publishing.
- **Modular Intelligence**: Independent plugins supply the data. The core engine remains lightweight and isolated.
- **High-Performance Rendering**: Engineered for scale using raw Cesium primitives to smoothly handle upwards of 100,000+ objects simultaneously without GPU stalls.
- **Cinematic Situational Awareness**: Implements horizon culling, smooth camera tracking, orientation-locked billboarding, and stack spiderification for dense locations.
## Repository Ecosystem
---
WorldWideView is distributed across several specialized repositories:
## 📚 Documentation Index
1. **`worldwideview`** (This Repo): Main frontend, CesiumJS rendering engine, and core plugin framework.
2. **`wwv-data-engine`**: Open-source community data backend for polling public APIs.
3. **`worldwideview-plugins`**: First-party maintained plugins.
4. **`worldwideview-marketplace`**: The web application driving the plugin directory.
5. **`worldwideview-web`**: Marketing and landing site.
- **[Setup & Installation Guide](docs/SETUP.md)**: Detailed environment and local development setup.
- **[Architecture (Engineering Depth)](docs/ARCHITECTURE.md)**: Deep dive into the Cesium rendering pipeline, event data bus, and performance optimizations.
- **[Contributions Guide](CONTRIBUTING.md)**: How to help out, coding standards, and commit conventions.
- **[User Guide](docs/USER_GUIDE.md)**: Application features and navigation tips.
## Development & Workflow
---
- **Branching & Commits:** We strictly enforce [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `refactor:`). Every commit should utilize our semantic versioning `[/commit]` workflow.
- **Coding Standards:** We emphasize vanilla CSS (no Tailwind), strict TypeScript 5, and file modularity (max 150 lines per file).
- **Testing:** We use Vitest with `jsdom`. All new core logic should be accompanied by tests, running via `pnpm test`.
## 🤝 Contributing & Community
See [Docs: Development](docs/development.md) and [Docs: Testing](docs/testing.md) for more details.
We are actively looking for contributors to help build new data plugins and optimize the core 3D engine!
- Found a bug or have an idea? Search the [Issue Tracker](https://github.com/silvertakana/worldwideview/issues) and submit a report.
- Want to build something? Check out our **[Pinned Plugin Wishlist](https://github.com/silvertakana/worldwideview/issues)** for great first issues!
## Contributing
We welcome community contributions! Please review our coding standards and PR processes before submitting code. For detailed instructions on local development and setting up your environment, see our [CONTRIBUTING.md](CONTRIBUTING.md).
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Documentation Index
Explore our comprehensive documentation suite for detailed engineering insights:
- **[Project Overview](docs/project-overview.md)**: High-level value proposition and technology stack.
- **[Architecture](docs/architecture.md)**: DataBus event stream and Zustand state management.
- **[Build System](docs/build-system.md)**: Monorepo structure, Next.js standalone output, and Docker builds.
- **[Development](docs/development.md)**: Coding conventions and common implementation patterns.
- **[Testing](docs/testing.md)**: Vitest setup and coverage targets.
- **[Deployment](docs/deployment.md)**: Coolify integration and persistent volumes.
- **[Files Catalog](docs/files.md)**: Comprehensive mapping of core source files.
> [!IMPORTANT]
> **Fair-Use Notice:** This application may contain copyrighted material the use of which has not always been specifically authorized by the copyright owner. Such material is made available for educational purposes, situational awareness, and to advance understanding of global events under "fair use" (Section 107 of the US Copyright Law).
+3 -3
View File
@@ -26,11 +26,11 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
---
## Stage 3: Prisma ORM & Local Database ✅
**Demo:** "Run `pnpm run dev` on a fresh clone. SQLite auto-creates. App works with zero config."
**Demo:** "Run `pnpm run dev` on a fresh clone with a valid DATABASE_URL. App works seamlessly."
- [x] Prisma (`prisma` + `@prisma/client`)
- [x] Schema: `InstalledPlugin`, `Setting`, `User`, `AviationHistory`, `NpmCache`
- [x] SQLite default: `DATABASE_URL=file:./data/wwv.db`
- [x] PostgreSQL default: `DATABASE_URL` required
- [x] `predev` script: `prisma migrate deploy`
- [x] DB auto-creates on first run — zero manual setup
@@ -142,7 +142,7 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
| **License** | EL2.0 for WorldWideView core; Open Source for marketplace |
| **Shared types** | `@worldwideview/plugin-sdk` npm package (MIT) |
| **Hosting** | Coolify (ThinkPad T480s). Landing page on Vercel (static export) |
| **Database** | Supabase PostgreSQL (cloud), SQLite (local), Prisma ORM |
| **Database** | PostgreSQL, Prisma ORM |
| **Tenant isolation** | Row-Level Security (RLS) in shared PostgreSQL |
| **User settings** | Runtime settings store in DB, not `.env` |
| **Bot prevention** | Email verification + Cloudflare Turnstile + rate limiting |
+37
View File
@@ -0,0 +1,37 @@
# Security Policy
Security is a priority for our project. We appreciate the efforts of security researchers and the open-source community in helping us keep our software secure.
## Supported Versions
Security updates are provided for the following versions of the project. We highly recommend all users stay on the latest stable release.
| Version | Supported | Notes |
| ------- | ------------------ | ----- |
| 2.x.x | :white_check_mark: | Current main release. Receives all security updates. |
| 1.x.x | :x: | Legacy version. No longer receiving updates. |
| < 1.0 | :x: | Beta versions are not supported. |
## Reporting a Vulnerability
**Please do not report security vulnerabilities through public GitHub issues.**
If you believe you have found a security vulnerability in this project, please report it privately so we have time to fix it before the vulnerability is made public.
### How to Report
1. **Email us directly:** Send your report to **[support@worldwideview.dev]**.
2. **GitHub Security Advisories:** Alternatively, if this repository has Private Vulnerability Reporting enabled, you can click on the `Security` tab -> `Advisories` -> `Report a vulnerability`.
### What to Include
To help us quickly validate and fix the issue, please include the following in your report:
* A description of the vulnerability and its potential impact.
* The steps required to reproduce the issue (a proof of concept is highly appreciated).
* Any relevant environment details (OS, browser, version).
### What to Expect
* **Acknowledgment:** We will acknowledge receipt of your vulnerability report within **48 hours**.
* **Triage & Fix:** We will review the report, determine its severity, and work on a patch. We will keep you updated on our progress.
* **Disclosure:** Once the vulnerability is patched and a new version is released, we will publish a security advisory. We are happy to credit you for the discovery if you would like!
*Note: As an open-source project, we currently do not offer financial bug bounties, but we deeply appreciate your contributions to keeping our users safe.*
+7
View File
@@ -0,0 +1,7 @@
# This file lists tools managed by Aftman, a cross-platform toolchain manager.
# For more information, see https://github.com/LPGhatguy/aftman
# To add a new tool, add an entry to this table.
[tools]
rojo = "rojo-rbx/[email protected]"
# rojo = "rojo-rbx/[email protected]"
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"message":"fix(aviation): implement exponential backoff for rate limits","tree":"55c74a09dac7ce178ecf94d5cb48b2502e57e759","parents":["e25ddc0b648b757ea32b7376bab50d8e75d6d330"]}
+54
View File
@@ -0,0 +1,54 @@
const fs = require("fs");
const { execSync } = require("child_process");
const uuidsToDelete = [
"i331gbc1zzytx7via8lntdm6",
"pow71xsobdas7etf5r3hy5ug",
"l79dyd03lhtcpgi7swkoxm55",
"ry6160tpy4gh2xjfwr011no0",
"gfe78t8jm53lltentz19ze60",
"e1cg7q8khyvpti5rkp351559",
"c35cvvqxhdbslk8yc24g04wk",
"ijj9pqkavlusy2wmzsbjtc74",
"ghe6bzlr6ex6j51lgxzyhd46",
"h3v45w2u1essulzeg56i27a3",
"oxk05amog4fla0lskmkfx64x",
"yxm4mn60lfp9qah0q4yf2hij",
"ezjxo4ehs96lv0ji1n2r0auw",
"t12x7pgptsqiu5gbvv35gun5",
"urq1ll00a3vv9on6pulmpofe",
"eb5zgw5wlgvio2gggbiphpam",
"ld1h3pody4nxj3b44pbskl53",
"x111xfygqxrlbf5wqlx59f6d",
"se1weqr4dj7thp4p1l055wfc",
"cqses6urxff0n94i0u6lktzt",
"nvcir33nyuvzk5niy3s7eg9w",
"s63onga2s6v8r3k10lrdwzth",
"cf3uedqnjmwv48h7tm91d95r",
"o9124dnnieau9wxoefyxvfgu",
"kxzobc8qlvigbsk1d35dpiyi",
"eh8lzjbsy2c9kwj2emztcmf6",
"umfsos2vcmotfk2cfpqdoycc",
"yn1mdh0fngiati6r4625qvv9"
];
const token = "1|vPZPgvB8vVi8ZD5ZKS8lrCrwNlPofVv4I8Tjmqmyd01f92d2";
const baseUrl = "https://coolify.worldwideview.dev/api/v1";
const appUuid = "nmn55t4io3myfubs72worn7k";
async function run() {
for (const id of uuidsToDelete) {
console.log("Deleting", id);
try {
const res = await fetch(`${baseUrl}/applications/${appUuid}/envs/${id}`, {
method: "DELETE",
headers: { "Authorization": `Bearer ${token}` }
});
console.log(id, res.status);
} catch(e) {
console.error(e);
}
}
}
run();
+7
View File
@@ -0,0 +1,7 @@
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
SUPABASE_URL=https://xyz.supabase.co
SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
ACME_EMAIL=[email protected]
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
+47
View File
@@ -0,0 +1,47 @@
services:
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: postgres
ports:
- "5432:5432"
wwv-cloud:
build:
context: ../..
dockerfile: Dockerfile
args:
- NEXT_PUBLIC_WWV_EDITION=cloud
restart: always
environment:
NEXT_PUBLIC_WWV_EDITION: cloud
DATABASE_URL: postgresql://postgres:password@db:5432/postgres
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
ports:
- "3001:3000"
labels:
- "traefik.enable=true"
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`) || Host(`localhost`) || HostRegexp(`{user:[a-z0-9-]+}.localhost`)"
- "traefik.http.routers.wwv.entrypoints=web,websecure"
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
depends_on:
- db
traefik:
image: traefik:v3.0
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
+20 -33
View File
@@ -12,47 +12,34 @@ services:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
wwv-data-engine:
build:
context: .
dockerfile: ./packages/wwv-data-engine/Dockerfile
ports:
- "5001:5001"
volumes:
- engine-data:/app/packages/wwv-data-engine/data
restart: always
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
depends_on:
- redis
env_file:
- path: .env
required: false
environment:
- "NODE_ENV=production"
- "REDIS_URL=${REDIS_URL:-redis://redis:6379}"
networks:
- coolify
- default
labels:
- "traefik.enable=true"
- "traefik.http.routers.data-engine.rule=Host(`dataengine.worldwideview.dev`)"
- "traefik.http.routers.data-engine.entrypoints=websecure"
- "traefik.http.routers.data-engine.tls=true"
- "traefik.http.routers.data-engine.tls.certresolver=letsencrypt"
- "traefik.http.services.data-engine.loadbalancer.server.port=5001"
db:
condition: service_healthy
redis:
image: redis:7-alpine
db:
image: postgres:15-alpine
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
ports:
- "6379:6379"
- "5432:5432"
volumes:
- redis-data:/data
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
interval: 5s
timeout: 5s
retries: 5
start_period: 60s
profiles:
- "${WWV_SKIP_LOCAL_DB:-}"
volumes:
wwv-data:
engine-data:
redis-data:
postgres-data:
networks:
coolify:
+37 -4
View File
@@ -1,14 +1,47 @@
#!/bin/sh
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the SQLite database exists and is migrated before
# starting the application. On first run with a fresh volume
# the DB file won't exist yet, so we run prisma migrate deploy.
# Ensures the PostgreSQL database is migrated before starting
# the application. DATABASE_URL must point to a PostgreSQL
# instance (Supabase, self-hosted, etc).
set -e
mkdir -p ./data
if [ -z "$DATABASE_URL" ]; then
echo "────────────────────────────────────────────────────────────────"
echo "🚨 CRITICAL: DATABASE_URL IS NOT SET"
echo "────────────────────────────────────────────────────────────────"
echo "WorldWideView has migrated to PostgreSQL. If you are an old user,"
echo "please update your docker-compose.yml to include a Postgres service."
echo ""
echo "To migrate your legacy data after setting up Postgres, run:"
echo "docker exec -it <container_name> node scripts/migrate-legacy.mjs"
echo "────────────────────────────────────────────────────────────────"
# If dev.db exists, we know they are upgrading. Don't crash, just wait for config.
if [ -f "prisma/dev.db" ]; then
echo "[entrypoint] Legacy data detected. Waiting for DATABASE_URL to be configured..."
# We don't exit here, we'll let the app try to start or just sleep.
# For now, let's just let it proceed so they can see the setup page error.
else
echo "[entrypoint] Exiting. Please provide a DATABASE_URL."
exit 1
fi
fi
echo "[entrypoint] Running database migrations..."
npx -y prisma migrate deploy
echo "[entrypoint] Migrations complete."
# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist
if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then
echo "[entrypoint] Generating self-signed SSL certificates for port 3001..."
mkdir -p ./data
openssl req -nodes -new -x509 -keyout ./data/localhost.key -out ./data/localhost.crt -days 365 -subj "/CN=localhost" 2>/dev/null || echo "[entrypoint] Warning: Failed to generate SSL certs"
fi
# Start the HTTPS proxy in the background
if [ -f "./scripts/https-proxy.mjs" ]; then
node ./scripts/https-proxy.mjs &
fi
exec node server.js
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff. Show more