diff --git a/.claudedocs/sentry-triage/2026-02-19.md b/.claudedocs/sentry-triage/2026-02-19.md
new file mode 100644
index 000000000..c079e8be4
--- /dev/null
+++ b/.claudedocs/sentry-triage/2026-02-19.md
@@ -0,0 +1,32 @@
+# Sentry Triage — 2026-02-19
+
+Commit: `09174fd` on `main`
+
+## Issues Triaged (5)
+
+### ACTIONABLE — Fixed in Code
+
+| ID | Title | Events | Users | Fix |
+|---|---|---|---|---|
+| WORLDMONITOR-1G | `Error: ML request unload-model timed out after 120000ms` | 30 | 27 | Wrapped `unloadModel()` in try/catch; timeout no longer leaks as unhandled rejection. Cleans up `loadedModels` set on failure. |
+| WORLDMONITOR-1F | `Error: ML request unload-model timed out after 120000ms` | 9 | 9 | Same root cause as 1G (different release build hash). |
+| WORLDMONITOR-1K | `TypeError: this.player.playVideo is not a function` | 1 | 1 | Added optional chaining (`playVideo?.()`, `pauseVideo?.()`) in `LiveNewsPanel.ts`. YT IFrame API player object may not have methods ready during initialization race. |
+
+### NOISE — Filtered
+
+| ID | Title | Events | Users | Filter |
+|---|---|---|---|---|
+| WORLDMONITOR-1J | `InternalError: too much recursion` | 1 | 1 | i18next internal `translate -> extractFromKey` cycle on Firefox 147. Added `/too much recursion/` to `ignoreErrors`. |
+| WORLDMONITOR-1H | `TypeError: Cannot read properties of null (reading 'id')` | 1 | 1 | maplibre-gl internal render crash (`_drawLayers -> renderLayers`). Extended `beforeSend` regex to suppress null `id`/`type` when stack is in map chunk. |
+
+## Files Modified
+
+| File | Change |
+|---|---|
+| `src/services/ml-worker.ts` | `unloadModel()`: try/catch around `this.request()`, clean `loadedModels` on failure |
+| `src/components/LiveNewsPanel.ts` | Optional chaining on `playVideo?.()` and `pauseVideo?.()` |
+| `src/main.ts` | Added `/too much recursion/` to `ignoreErrors`; extended maplibre `beforeSend` filter for null `id`/`type` |
+
+## Sentry Status
+
+All 5 issues marked **resolved (in next release)** via API. They will auto-reopen if errors recur after deployment.
diff --git a/.env.example b/.env.example
new file mode 100644
index 000000000..258a21d05
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,130 @@
+# ============================================
+# World Monitor — Environment Variables
+# ============================================
+# Copy this file to .env.local and fill in the values you need.
+# All keys are optional — the dashboard works without them,
+# but the corresponding features will be disabled.
+#
+# cp .env.example .env.local
+#
+# ============================================
+
+
+# ------ AI Provider (Vercel / Desktop Sidecar) ------
+
+# Unified OpenAI-compatible provider at https://api.ai4u.now
+# API docs: /Users/nad/My Drive (duc.a.nguyen@gmail.com)/ai4u.now/apps/api4llms/docs/llm-proxy-user-manual.md
+AI4U_API_KEY=
+
+# Optional: override base URL (defaults to https://api.ai4u.now/v1)
+# AI4U_BASE_URL=https://api.ai4u.now/v1
+
+# Optional: model overrides
+# AI4U_CHAT_MODEL=sonnet-4.5
+# AI4U_SUMMARY_MODEL=sonnet-4.5
+# AI4U_SUMMARY_FALLBACK_MODEL=gemini-3-flash
+# AI4U_CLASSIFY_MODEL=gemini-3-flash
+# AI4U_COUNTRY_INTEL_MODEL=sonnet-4.5
+# AI4U_EMBEDDING_MODEL=text-embedding-005
+
+
+# ------ Cross-User Cache (Vercel — Upstash Redis) ------
+
+# Used to deduplicate AI calls and cache risk scores across visitors.
+# Create a free Redis database at: https://upstash.com/
+UPSTASH_REDIS_REST_URL=
+UPSTASH_REDIS_REST_TOKEN=
+
+
+# ------ Market Data (Vercel) ------
+
+# Finnhub (primary stock quotes — free tier available)
+# Register at: https://finnhub.io/
+FINNHUB_API_KEY=
+
+
+# ------ Energy Data (Vercel) ------
+
+# U.S. Energy Information Administration (oil prices, production, inventory)
+# Register at: https://www.eia.gov/opendata/
+EIA_API_KEY=
+
+
+# ------ Economic Data (Vercel) ------
+
+# FRED (Federal Reserve Economic Data)
+# Register at: https://fred.stlouisfed.org/docs/api/api_key.html
+FRED_API_KEY=
+
+
+# ------ Aircraft Tracking (Vercel) ------
+
+# Wingbits aircraft enrichment (owner, operator, type)
+# Contact: https://wingbits.com/
+WINGBITS_API_KEY=
+
+
+# ------ Conflict & Protest Data (Vercel) ------
+
+# ACLED (Armed Conflict Location & Event Data — free for researchers)
+# Register at: https://acleddata.com/
+ACLED_ACCESS_TOKEN=
+
+
+# ------ Internet Outages (Vercel) ------
+
+# Cloudflare Radar API (requires free Cloudflare account with Radar access)
+CLOUDFLARE_API_TOKEN=
+
+
+# ------ Satellite Fire Detection (Vercel) ------
+
+# NASA FIRMS (Fire Information for Resource Management System)
+# Register at: https://firms.modaps.eosdis.nasa.gov/
+NASA_FIRMS_API_KEY=
+
+
+# ------ Railway Relay (scripts/ais-relay.cjs) ------
+# The relay server handles AIS vessel tracking and OpenSky aircraft data.
+# Deploy on Railway with: node scripts/ais-relay.cjs
+
+# AISStream API key for live vessel positions
+# Get yours at: https://aisstream.io/
+AISSTREAM_API_KEY=
+
+# OpenSky Network OAuth2 credentials (higher rate limits for cloud IPs)
+# Register at: https://opensky-network.org/
+OPENSKY_CLIENT_ID=
+OPENSKY_CLIENT_SECRET=
+
+
+# ------ Railway Relay Connection (Vercel → Railway) ------
+
+# Server-side URL (https://) — used by Vercel edge functions to reach the relay
+WS_RELAY_URL=
+
+# Client-side URL (wss://) — used by the browser to connect via WebSocket
+VITE_WS_RELAY_URL=
+
+
+# ------ Public Data Sources (no keys required) ------
+
+# UCDP (Uppsala Conflict Data Program) — public API, no auth
+# UNHCR (UN Refugee Agency) — public API, no auth (CC BY 4.0)
+# Open-Meteo — public API, no auth (processes Copernicus ERA5)
+# WorldPop — public API, optional key for higher rate limits
+# WORLDPOP_API_KEY=
+
+
+# ------ Site Configuration ------
+
+# Site variant: "full" (worldmonitor.app) or "tech" (tech.worldmonitor.app)
+VITE_VARIANT=full
+
+# Client-side Sentry DSN (optional). Leave empty to disable error reporting.
+VITE_SENTRY_DSN=
+
+# Map interaction mode:
+# - "flat" keeps pitch/rotation disabled (2D interaction)
+# - "3d" enables pitch/rotation interactions (default)
+VITE_MAP_INTERACTION_MODE=3d
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 000000000..d9b509b31
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,85 @@
+name: Bug Report
+description: Report a bug in World Monitor
+labels: ["bug"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for taking the time to report a bug! Please fill out the sections below so we can reproduce and fix it.
+
+ - type: dropdown
+ id: variant
+ attributes:
+ label: Variant
+ description: Which variant are you using?
+ options:
+ - worldmonitor.app (Full / Geopolitical)
+ - tech.worldmonitor.app (Tech / Startup)
+ - finance.worldmonitor.app (Finance)
+ - Desktop app (Windows)
+ - Desktop app (macOS)
+ validations:
+ required: true
+
+ - type: dropdown
+ id: area
+ attributes:
+ label: Affected area
+ description: Which part of the app is affected?
+ options:
+ - Map / Globe
+ - News panels / RSS feeds
+ - AI Insights / World Brief
+ - Market Radar / Crypto
+ - Service Status
+ - Trending Keywords
+ - Country Brief pages
+ - Live video streams
+ - Desktop app (Tauri)
+ - Settings / API keys
+ - Other
+ validations:
+ required: true
+
+ - type: textarea
+ id: description
+ attributes:
+ label: Bug description
+ description: A clear description of what the bug is.
+ placeholder: Describe the bug...
+ validations:
+ required: true
+
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ description: Steps to reproduce the behavior.
+ placeholder: |
+ 1. Go to '...'
+ 2. Click on '...'
+ 3. Scroll down to '...'
+ 4. See error
+ validations:
+ required: true
+
+ - type: textarea
+ id: expected
+ attributes:
+ label: Expected behavior
+ description: What you expected to happen.
+ validations:
+ required: true
+
+ - type: textarea
+ id: screenshots
+ attributes:
+ label: Screenshots / Console errors
+ description: If applicable, add screenshots or paste browser console errors.
+
+ - type: input
+ id: browser
+ attributes:
+ label: Browser & OS
+ description: e.g. Chrome 120 on Windows 11, Safari 17 on macOS Sonoma
+ placeholder: Chrome 120 on Windows 11
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 000000000..fbad4f7b8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Documentation
+ url: https://github.com/koala73/worldmonitor/blob/main/docs/DOCUMENTATION.md
+ about: Read the full documentation before opening an issue
+ - name: Discussions
+ url: https://github.com/koala73/worldmonitor/discussions
+ about: Ask questions and share ideas in Discussions
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 000000000..eda98ee68
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,55 @@
+name: Feature Request
+description: Suggest a new feature or improvement
+labels: ["enhancement"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Have an idea for World Monitor? We'd love to hear it!
+
+ - type: dropdown
+ id: area
+ attributes:
+ label: Feature area
+ description: Which area does this feature relate to?
+ options:
+ - Map / Globe / Data layers
+ - News panels / RSS feeds
+ - AI / Intelligence analysis
+ - Market data / Crypto
+ - Desktop app
+ - UI / UX
+ - API / Backend
+ - Other
+ validations:
+ required: true
+
+ - type: textarea
+ id: description
+ attributes:
+ label: Description
+ description: A clear description of the feature you'd like.
+ placeholder: I'd like to see...
+ validations:
+ required: true
+
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem it solves
+ description: What problem does this feature address? What's the use case?
+ placeholder: This would help with...
+ validations:
+ required: true
+
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
+ description: Have you considered any alternative solutions or workarounds?
+
+ - type: textarea
+ id: context
+ attributes:
+ label: Additional context
+ description: Any mockups, screenshots, links, or references that help illustrate the idea.
diff --git a/.github/ISSUE_TEMPLATE/new_data_source.yml b/.github/ISSUE_TEMPLATE/new_data_source.yml
new file mode 100644
index 000000000..e610b0983
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/new_data_source.yml
@@ -0,0 +1,69 @@
+name: New Data Source
+description: Suggest a new RSS feed, API, or map layer
+labels: ["data-source"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ World Monitor aggregates 100+ feeds and data layers. Suggest a new one!
+
+ - type: dropdown
+ id: type
+ attributes:
+ label: Source type
+ description: What kind of data source is this?
+ options:
+ - RSS / News feed
+ - API integration
+ - Map layer (geospatial data)
+ - Live video stream
+ - Status page
+ - Other
+ validations:
+ required: true
+
+ - type: dropdown
+ id: variant
+ attributes:
+ label: Target variant
+ description: Which variant should this appear in?
+ options:
+ - Full (Geopolitical)
+ - Tech (Startup)
+ - Finance
+ - All variants
+ validations:
+ required: true
+
+ - type: input
+ id: source-name
+ attributes:
+ label: Source name
+ description: Name of the source or organization.
+ placeholder: e.g. RAND Corporation, CoinDesk, USGS
+ validations:
+ required: true
+
+ - type: input
+ id: url
+ attributes:
+ label: Feed / API URL
+ description: Direct URL to the RSS feed, API endpoint, or data source.
+ placeholder: https://example.com/rss
+ validations:
+ required: true
+
+ - type: textarea
+ id: description
+ attributes:
+ label: Why add this source?
+ description: What value does this source bring? What does it cover that existing sources don't?
+ placeholder: This source provides coverage of...
+ validations:
+ required: true
+
+ - type: textarea
+ id: notes
+ attributes:
+ label: Additional notes
+ description: Any details about rate limits, authentication requirements, data format, or category placement.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 000000000..68136d4e5
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,36 @@
+## Summary
+
+
+
+## Type of change
+
+- [ ] Bug fix
+- [ ] New feature
+- [ ] New data source / feed
+- [ ] New map layer
+- [ ] Refactor / code cleanup
+- [ ] Documentation
+- [ ] CI / Build / Infrastructure
+
+## Affected areas
+
+- [ ] Map / Globe
+- [ ] News panels / RSS feeds
+- [ ] AI Insights / World Brief
+- [ ] Market Radar / Crypto
+- [ ] Desktop app (Tauri)
+- [ ] API endpoints (`/api/*`)
+- [ ] Config / Settings
+- [ ] Other:
+
+## Checklist
+
+- [ ] Tested on [worldmonitor.app](https://worldmonitor.app) variant
+- [ ] Tested on [tech.worldmonitor.app](https://tech.worldmonitor.app) variant (if applicable)
+- [ ] New RSS feed domains added to `api/rss-proxy.js` allowlist (if adding feeds)
+- [ ] No API keys or secrets committed
+- [ ] TypeScript compiles without errors (`npm run typecheck`)
+
+## Screenshots
+
+
diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml
new file mode 100644
index 000000000..251742019
--- /dev/null
+++ b/.github/workflows/build-desktop.yml
@@ -0,0 +1,344 @@
+name: 'Build Desktop App'
+
+on:
+ workflow_dispatch:
+ inputs:
+ variant:
+ description: 'App variant'
+ required: true
+ default: 'full'
+ type: choice
+ options:
+ - full
+ - tech
+ draft:
+ description: 'Create as draft release'
+ required: false
+ default: true
+ type: boolean
+ push:
+ tags:
+ - 'v*'
+
+concurrency:
+ group: desktop-build-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+
+jobs:
+ build-tauri:
+ permissions:
+ contents: write
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - platform: 'macos-14'
+ args: '--target aarch64-apple-darwin'
+ node_target: 'aarch64-apple-darwin'
+ label: 'macOS-ARM64'
+ timeout: 180
+ - platform: 'macos-latest'
+ args: '--target x86_64-apple-darwin'
+ node_target: 'x86_64-apple-darwin'
+ label: 'macOS-x64'
+ timeout: 180
+ - platform: 'windows-latest'
+ args: ''
+ node_target: 'x86_64-pc-windows-msvc'
+ label: 'Windows-x64'
+ timeout: 120
+ - platform: 'ubuntu-22.04'
+ args: ''
+ node_target: 'x86_64-unknown-linux-gnu'
+ label: 'Linux-x64'
+ timeout: 120
+
+ runs-on: ${{ matrix.platform }}
+ name: Build (${{ matrix.label }})
+ timeout-minutes: ${{ matrix.timeout }}
+
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
+
+ - name: Start job timer
+ shell: bash
+ run: echo "JOB_START_EPOCH=$(date +%s)" >> "$GITHUB_ENV"
+
+ - name: Setup Node.js
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
+ with:
+ node-version: '22'
+ cache: 'npm'
+
+ - name: Install Rust stable
+ uses: dtolnay/rust-toolchain@631a55b12751854ce901bb631d5902ceb48146f7
+ with:
+ toolchain: stable
+ targets: ${{ contains(matrix.platform, 'macos') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
+
+ - name: Rust cache
+ uses: swatinem/rust-cache@ad397744b0d591a723ab90405b7247fac0e6b8db
+ with:
+ workspaces: './src-tauri -> target'
+ cache-on-failure: true
+
+ - name: Install Linux system dependencies
+ if: contains(matrix.platform, 'ubuntu')
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
+
+ - name: Install frontend dependencies
+ run: npm ci
+
+ - name: Check version consistency
+ run: npm run version:check
+
+ - name: Bundle Node.js runtime
+ shell: bash
+ env:
+ NODE_VERSION: '22.14.0'
+ NODE_TARGET: ${{ matrix.node_target }}
+ run: bash scripts/download-node.sh --target "$NODE_TARGET"
+
+ - name: Verify bundled Node.js payload
+ shell: bash
+ run: |
+ if [ "${{ matrix.node_target }}" = "x86_64-pc-windows-msvc" ]; then
+ test -f src-tauri/sidecar/node/node.exe
+ ls -lh src-tauri/sidecar/node/node.exe
+ else
+ test -f src-tauri/sidecar/node/node
+ test -x src-tauri/sidecar/node/node
+ ls -lh src-tauri/sidecar/node/node
+ fi
+
+ # ── Detect whether Apple signing secrets are configured ──
+ - name: Check Apple signing secrets
+ if: contains(matrix.platform, 'macos')
+ id: apple-signing
+ shell: bash
+ run: |
+ if [ -n "${{ secrets.APPLE_CERTIFICATE }}" ] && [ -n "${{ secrets.APPLE_CERTIFICATE_PASSWORD }}" ] && [ -n "${{ secrets.KEYCHAIN_PASSWORD }}" ]; then
+ echo "available=true" >> $GITHUB_OUTPUT
+ echo "Apple signing secrets detected"
+ else
+ echo "available=false" >> $GITHUB_OUTPUT
+ echo "No Apple signing secrets — building unsigned"
+ fi
+
+ # ── macOS Code Signing (only when secrets are valid) ──
+ - name: Import Apple Developer Certificate
+ if: contains(matrix.platform, 'macos') && steps.apple-signing.outputs.available == 'true'
+ env:
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
+ run: |
+ printf '%s' "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12
+ CERT_SIZE=$(wc -c < certificate.p12 | tr -d ' ')
+ if [ "$CERT_SIZE" -lt 100 ]; then
+ echo "::warning::Certificate file too small ($CERT_SIZE bytes) — likely invalid. Skipping signing."
+ echo "SKIP_SIGNING=true" >> $GITHUB_ENV
+ exit 0
+ fi
+
+ security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
+ security default-keychain -s build.keychain
+ security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
+ security set-keychain-settings -t 3600 -u build.keychain
+ security import certificate.p12 -k build.keychain \
+ -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign || {
+ echo "::warning::Certificate import failed — building unsigned"
+ echo "SKIP_SIGNING=true" >> $GITHUB_ENV
+ exit 0
+ }
+ security set-key-partition-list -S apple-tool:,apple:,codesign: \
+ -s -k "$KEYCHAIN_PASSWORD" build.keychain
+
+ CERT_INFO=$(security find-identity -v -p codesigning build.keychain \
+ | grep "Developer ID Application" || true)
+ if [ -n "$CERT_INFO" ]; then
+ CERT_ID=$(echo "$CERT_INFO" | head -1 | awk -F'"' '{print $2}')
+ echo "APPLE_SIGNING_IDENTITY=$CERT_ID" >> $GITHUB_ENV
+ echo "Certificate imported: $CERT_ID"
+ else
+ echo "::warning::No Developer ID certificate found in keychain — building unsigned"
+ echo "SKIP_SIGNING=true" >> $GITHUB_ENV
+ fi
+
+ # ── Determine variant ──
+ - name: Set build variant
+ shell: bash
+ run: |
+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
+ echo "BUILD_VARIANT=${{ github.event.inputs.variant }}" >> $GITHUB_ENV
+ else
+ echo "BUILD_VARIANT=full" >> $GITHUB_ENV
+ fi
+
+ # ── Build with tauri-action ──
+ # Signed builds: only when Apple signing secrets are valid and imported
+ # Unsigned builds: fallback when no signing (Windows always uses this path)
+
+ # ── Build: Full variant (signed) ──
+ - name: Build Tauri app (full, signed)
+ if: env.BUILD_VARIANT == 'full' && steps.apple-signing.outputs.available == 'true' && env.SKIP_SIGNING != 'true'
+ uses: tauri-apps/tauri-action@79c624843491f12ae9d63592534ed49df3bc4adb
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VITE_VARIANT: full
+ VITE_DESKTOP_RUNTIME: '1'
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_SIGNING_IDENTITY: ${{ env.APPLE_SIGNING_IDENTITY }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ with:
+ tagName: v__VERSION__
+ releaseName: 'World Monitor v__VERSION__'
+ releaseBody: 'See changelog below.'
+ releaseDraft: ${{ github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.draft) }}
+ prerelease: false
+ args: ${{ matrix.args }}
+ retryAttempts: 1
+
+ # ── Build: Full variant (unsigned — no Apple certs) ──
+ - name: Build Tauri app (full, unsigned)
+ if: env.BUILD_VARIANT == 'full' && (steps.apple-signing.outputs.available != 'true' || env.SKIP_SIGNING == 'true')
+ uses: tauri-apps/tauri-action@79c624843491f12ae9d63592534ed49df3bc4adb
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VITE_VARIANT: full
+ VITE_DESKTOP_RUNTIME: '1'
+ with:
+ tagName: v__VERSION__
+ releaseName: 'World Monitor v__VERSION__'
+ releaseBody: 'See changelog below.'
+ releaseDraft: ${{ github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.draft) }}
+ prerelease: false
+ args: ${{ matrix.args }}
+ retryAttempts: 1
+
+ # ── Build: Tech variant (signed) ──
+ - name: Build Tauri app (tech, signed)
+ if: env.BUILD_VARIANT == 'tech' && steps.apple-signing.outputs.available == 'true' && env.SKIP_SIGNING != 'true'
+ uses: tauri-apps/tauri-action@79c624843491f12ae9d63592534ed49df3bc4adb
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VITE_VARIANT: tech
+ VITE_DESKTOP_RUNTIME: '1'
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_SIGNING_IDENTITY: ${{ env.APPLE_SIGNING_IDENTITY }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ with:
+ tagName: v__VERSION__-tech
+ releaseName: 'Tech Monitor v__VERSION__'
+ releaseBody: 'See changelog below.'
+ releaseDraft: ${{ github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.draft) }}
+ prerelease: false
+ tauriScript: npx tauri
+ args: --config src-tauri/tauri.tech.conf.json ${{ matrix.args }}
+ retryAttempts: 1
+
+ # ── Build: Tech variant (unsigned — no Apple certs) ──
+ - name: Build Tauri app (tech, unsigned)
+ if: env.BUILD_VARIANT == 'tech' && (steps.apple-signing.outputs.available != 'true' || env.SKIP_SIGNING == 'true')
+ uses: tauri-apps/tauri-action@79c624843491f12ae9d63592534ed49df3bc4adb
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VITE_VARIANT: tech
+ VITE_DESKTOP_RUNTIME: '1'
+ with:
+ tagName: v__VERSION__-tech
+ releaseName: 'Tech Monitor v__VERSION__'
+ releaseBody: 'See changelog below.'
+ releaseDraft: ${{ github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.draft) }}
+ prerelease: false
+ tauriScript: npx tauri
+ args: --config src-tauri/tauri.tech.conf.json ${{ matrix.args }}
+ retryAttempts: 1
+
+ - name: Verify signed macOS bundle + embedded runtime
+ if: contains(matrix.platform, 'macos') && steps.apple-signing.outputs.available == 'true' && env.SKIP_SIGNING != 'true'
+ shell: bash
+ run: |
+ APP_PATH=$(find src-tauri/target -type d -path '*/bundle/macos/*.app' | head -1)
+ if [ -z "$APP_PATH" ]; then
+ echo "::error::No macOS .app bundle found after build."
+ exit 1
+ fi
+ codesign --verify --deep --strict --verbose=2 "$APP_PATH"
+ NODE_PATH=$(find "$APP_PATH/Contents/Resources" -type f -path '*/sidecar/node/node' | head -1)
+ if [ -z "$NODE_PATH" ]; then
+ echo "::error::Bundled Node runtime missing from app resources."
+ exit 1
+ fi
+ echo "Verified signed app bundle and embedded Node runtime: $NODE_PATH"
+
+ - name: Cleanup Apple signing materials
+ if: always() && contains(matrix.platform, 'macos')
+ shell: bash
+ run: |
+ rm -f certificate.p12
+ security delete-keychain build.keychain || true
+
+ - name: Report build duration
+ if: always()
+ shell: bash
+ run: |
+ if [ -z "${JOB_START_EPOCH:-}" ]; then
+ echo "::warning::JOB_START_EPOCH missing; duration unavailable."
+ exit 0
+ fi
+ END_EPOCH=$(date +%s)
+ ELAPSED=$((END_EPOCH - JOB_START_EPOCH))
+ MINUTES=$((ELAPSED / 60))
+ SECONDS=$((ELAPSED % 60))
+ echo "Build duration for ${{ matrix.label }}: ${MINUTES}m ${SECONDS}s"
+
+ # ── Update release notes with changelog after all builds complete ──
+ update-release-notes:
+ needs: build-tauri
+ if: always() && contains(needs.build-tauri.result, 'success')
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
+ with:
+ fetch-depth: 0
+
+ - name: Generate and update release notes
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ shell: bash
+ run: |
+ VERSION=$(jq -r .version src-tauri/tauri.conf.json)
+ TAG="v${VERSION}"
+ PREV_TAG=$(git describe --tags --abbrev=0 "${TAG}^" 2>/dev/null || echo "")
+
+ if [ -z "$PREV_TAG" ]; then
+ COMMITS="Initial release"
+ else
+ COMMITS=$(git log "${PREV_TAG}..${TAG}" --oneline --no-merges | sed 's/^[a-f0-9]*//' | sed 's/^ /- /')
+ fi
+
+ BODY=$(cat <
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/README.md b/README.md
index 62186786d..fdcc85958 100644
--- a/README.md
+++ b/README.md
@@ -1,362 +1,1128 @@
# World Monitor
-Real-time global intelligence dashboard aggregating news, markets, geopolitical data, and infrastructure monitoring into a unified situation awareness interface.
-
-
-
-
-
-## Features
-
-### Interactive Global Map
-- **Zoom & Pan** - Smooth navigation with mouse/trackpad gestures
-- **Multiple Views** - Global, US, and MENA region presets
-- **Layer System** - Toggle visibility of different data layers
-- **Time Filtering** - Filter events by time range (1h to 7d)
-
-### Data Layers
-
-| Layer | Description |
-|-------|-------------|
-| **Hotspots** | Intelligence hotspots with activity levels based on news correlation |
-| **Conflicts** | Active conflict zones with party information |
-| **Military Bases** | Global military installations |
-| **Pipelines** | 88 major oil & gas pipelines worldwide |
-| **Undersea Cables** | Critical internet infrastructure |
-| **Nuclear Facilities** | Power plants and research reactors |
-| **Gamma Irradiators** | IAEA-tracked radiation sources |
-| **AI Datacenters** | Major AI compute infrastructure |
-| **Earthquakes** | Live USGS seismic data |
-| **Weather Alerts** | Severe weather warnings |
-| **Internet Outages** | Network connectivity disruptions |
-| **Sanctions** | Countries under economic sanctions |
-| **Economic Centers** | Major exchanges and central banks |
-
-### News Aggregation
-
-Multi-source RSS aggregation across categories:
-- **World / Geopolitical** - BBC, Reuters, AP, Guardian, NPR
-- **Middle East / MENA** - Al Jazeera, BBC ME, CNN ME
-- **Technology** - Hacker News, Ars Technica, The Verge, MIT Tech Review
-- **AI / ML** - ArXiv, Hugging Face, VentureBeat, OpenAI
-- **Finance** - CNBC, MarketWatch, Financial Times, Yahoo Finance
-- **Government** - White House, State Dept, Pentagon, Treasury, Fed, SEC
-- **Intel Feed** - Defense One, Breaking Defense, Bellingcat, Krebs Security
-- **Think Tanks** - Foreign Policy, Brookings, CSIS, CFR
-- **Layoffs Tracker** - Tech industry job cuts
-- **Congress Trades** - Congressional stock trading activity
-
-### Market Data
-- **Stocks** - Major indices and tech stocks
-- **Commodities** - Oil, gold, natural gas, copper
-- **Crypto** - Bitcoin, Ethereum, and top cryptocurrencies
-- **Sector Heatmap** - Visual sector performance
-- **Economic Indicators** - Fed data (GDP, inflation, unemployment)
-
-### Prediction Markets
-- Polymarket integration for event probability tracking
-- Correlation analysis with news events
-
-### Search (⌘K)
-Universal search across all data sources:
-- News articles
-- Geographic hotspots and conflicts
-- Infrastructure (pipelines, cables, datacenters)
-- Nuclear facilities and irradiators
-- Markets and predictions
-
-### Data Export
-- JSON export of current dashboard state
-- Historical playback from snapshots
+**Real-time global intelligence dashboard** — AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface.
+
+[](https://github.com/koala73/worldmonitor/stargazers)
+[](https://github.com/koala73/worldmonitor/network/members)
+[](https://www.gnu.org/licenses/agpl-3.0)
+[](https://www.typescriptlang.org/)
+[](https://github.com/koala73/worldmonitor/commits/main)
+[](https://github.com/koala73/worldmonitor/releases/latest)
+
+
+
+
---
-## Signal Intelligence
+## Why World Monitor?
-The dashboard continuously analyzes data streams to detect significant patterns and anomalies. Signals appear in the header badge (⚡) with confidence scores.
+| Problem | Solution |
+|---------|----------|
+| News scattered across 100+ sources | **Single unified dashboard** with 100+ curated feeds |
+| No geospatial context for events | **Interactive map** with 35+ toggleable data layers |
+| Information overload | **AI-synthesized briefs** with focal point detection |
+| Crypto/macro signal noise | **7-signal market radar** with composite BUY/CASH verdict |
+| Expensive OSINT tools ($$$) | **100% free & open source** |
+| Static news feeds | **Real-time updates** with live video streams |
+| Web-only dashboards | **Native desktop app** (Tauri) + installable PWA with offline map support |
+| Flat 2D maps | **3D WebGL globe** with deck.gl rendering and 35+ toggleable data layers |
+| Siloed financial data | **Finance variant** with 92 stock exchanges, 19 financial centers, 13 central banks, and Gulf FDI tracking |
-### Signal Types
-
-| Signal | Trigger | What It Means |
-|--------|---------|---------------|
-| **◉ Convergence** | 3+ source types report same story within 30 minutes | Multiple independent channels confirming the same event—higher likelihood of significance |
-| **△ Triangulation** | Wire + Government + Intel sources align | The "authority triangle"—when official channels, wire services, and defense specialists all report the same thing |
-| **🔥 Velocity Spike** | Topic mention rate doubles with 6+ sources/hour | A story is accelerating rapidly across the news ecosystem |
-| **🔮 Prediction Leading** | Prediction market moves 5%+ with low news coverage | Markets pricing in information not yet reflected in news |
-| **📊 Silent Divergence** | Market moves 2%+ with minimal related news | Unexplained price action—possible insider knowledge or algorithm-driven |
+---
-### How It Works
+## Live Demos
-The correlation engine maintains rolling snapshots of:
-- News topic frequency (by keyword extraction)
-- Market price changes
-- Prediction market probabilities
+| Variant | URL | Focus |
+|---------|-----|-------|
+| **World Monitor** | [worldmonitor.app](https://worldmonitor.app) | Geopolitics, military, conflicts, infrastructure |
+| **Tech Monitor** | [tech.worldmonitor.app](https://tech.worldmonitor.app) | Startups, AI/ML, cloud, cybersecurity |
+| **Finance Monitor** | [finance.worldmonitor.app](https://finance.worldmonitor.app) | Global markets, trading, central banks, Gulf FDI |
-Each refresh cycle compares current state to previous snapshot, applying thresholds and deduplication to avoid alert fatigue. Signals include confidence scores (60-95%) based on the strength of the pattern.
+All three variants run from a single codebase — switch between them with one click via the header bar (🌍 WORLD | 💻 TECH | 📈 FINANCE).
---
-## Source Intelligence
+## Key Features
+
+### Localization & Regional Support
+
+- **Multilingual UI** — Fully localized interface supporting **English, French, Spanish, German, Italian, Portuguese, Dutch, Swedish, Russian, Arabic, Chinese, and Japanese**.
+- **RTL Support** — Native right-to-left layout support for Arabic (`ar`) and Hebrew.
+- **Localized News Feeds** — Region-specific RSS selection based on language preference (e.g., viewing the app in French loads Le Monde, Jeune Afrique, and France24).
+- **AI Translation** — Integrated LLM translation for news headlines and summaries, enabling cross-language intelligence gathering.
+- **Regional Intelligence** — Dedicated monitoring panels for Africa, Latin America, Middle East, and Asia with local sources.
-Not all sources are equal. The system implements a dual classification to prioritize authoritative information.
+### Interactive 3D Globe
-### Source Tiers (Authority Ranking)
+- **WebGL-accelerated rendering** — deck.gl + MapLibre GL JS for smooth 60fps performance with thousands of concurrent markers. Switchable between **3D globe** (with pitch/rotation) and **flat map** mode via `VITE_MAP_INTERACTION_MODE`
+- **35+ data layers** — conflicts, military bases, nuclear facilities, undersea cables, pipelines, satellite fire detection, protests, natural disasters, datacenters, displacement flows, climate anomalies, cyber threat IOCs, stock exchanges, financial centers, central banks, commodity hubs, Gulf investments, and more
+- **Smart clustering** — Supercluster groups markers at low zoom, expands on zoom in. Cluster thresholds adapt to zoom level
+- **Progressive disclosure** — detail layers (bases, nuclear, datacenters) appear only when zoomed in; zoom-adaptive opacity fades markers from 0.2 at world view to 1.0 at street level
+- **Label deconfliction** — overlapping labels (e.g., multiple BREAKING badges) are automatically suppressed by priority, highest-severity first
+- **8 regional presets** — Global, Americas, Europe, MENA, Asia, Africa, Oceania, Latin America
+- **Time filtering** — 1h, 6h, 24h, 48h, 7d event windows
+- **URL state sharing** — map center, zoom, active layers, and time range are encoded in the URL for shareable views (`?view=mena&zoom=4&layers=conflicts,bases`)
-| Tier | Sources | Characteristics |
-|------|---------|-----------------|
-| **Tier 1** | Reuters, AP, AFP, Bloomberg, White House, Pentagon | Wire services and official government—fastest, most reliable |
-| **Tier 2** | BBC, Guardian, NPR, Al Jazeera, CNBC, Financial Times | Major outlets—high editorial standards, some latency |
-| **Tier 3** | Defense One, Bellingcat, Foreign Policy, MIT Tech Review | Domain specialists—deep expertise, narrower scope |
-| **Tier 4** | Hacker News, The Verge, VentureBeat, aggregators | Useful signal but requires corroboration |
+### AI-Powered Intelligence
-When multiple sources report the same story, the **lowest tier** (most authoritative) source is displayed as the primary, with others listed as corroborating.
+- **World Brief** — LLM-synthesized summary of top global developments (Groq Llama 3.1, Redis-cached)
+- **Hybrid Threat Classification** — instant keyword classifier with async LLM override for higher-confidence results
+- **Focal Point Detection** — correlates entities across news, military activity, protests, outages, and markets to identify convergence
+- **Country Instability Index** — real-time stability scores for 22 monitored nations using weighted multi-signal blend
+- **Trending Keyword Spike Detection** — 2-hour rolling window vs 7-day baseline flags surging terms across RSS feeds, with CVE/APT entity extraction and auto-summarization
+- **Strategic Posture Assessment** — composite risk score combining all intelligence modules with trend detection
+- **Country Brief Pages** — click any country for a full-page intelligence dossier with CII score ring, AI-generated analysis, top news with citation anchoring, prediction markets, 7-day event timeline, active signal chips, infrastructure exposure, and stock market index — exportable as JSON, CSV, or image
-### Source Types (Categorical)
+### Real-Time Data Layers
-Sources are also categorized by function for triangulation detection:
+
+Geopolitical
-- **Wire** - News agencies (Reuters, AP, AFP, Bloomberg)
-- **Gov** - Official government (White House, Pentagon, State Dept, Fed, SEC)
-- **Intel** - Defense/security specialists (Defense One, Bellingcat, Krebs)
-- **Mainstream** - Major news outlets (BBC, Guardian, NPR, Al Jazeera)
-- **Market** - Financial press (CNBC, MarketWatch, Financial Times)
-- **Tech** - Technology coverage (Hacker News, Ars Technica, MIT Tech Review)
+- Active conflict zones with escalation tracking (UCDP + ACLED)
+- Intelligence hotspots with news correlation
+- Social unrest events (dual-source: ACLED protests + GDELT geo-events, Haversine-deduplicated)
+- Natural disasters from 3 sources (USGS earthquakes M4.5+, GDACS alerts, NASA EONET events)
+- Sanctions regimes
+- Cyber threat IOCs (C2 servers, malware hosts, phishing, malicious URLs) geo-located on the globe
+- Weather alerts and severe conditions
+
+
+
+
+Military & Strategic
+
+- 220+ military bases from 9 operators
+- Live military flight tracking (ADS-B)
+- Naval vessel monitoring (AIS)
+- Nuclear facilities & gamma irradiators
+- APT cyber threat actor attribution
+- Spaceports & launch facilities
+
+
+
+
+Infrastructure
+
+- Undersea cables with landing points
+- Oil & gas pipelines
+- AI datacenters (111 major clusters)
+- 83 strategic ports across 6 types (container, oil, LNG, naval, mixed, bulk) with throughput rankings
+- Internet outages (Cloudflare Radar)
+- Critical mineral deposits
+- NASA FIRMS satellite fire detection (VIIRS thermal hotspots)
+
+
+
+
+Market & Crypto Intelligence
+
+- 7-signal macro radar with composite BUY/CASH verdict
+- BTC spot ETF flow tracker (IBIT, FBTC, GBTC, and 7 more)
+- Stablecoin peg health monitor (USDT, USDC, DAI, FDUSD, USDe)
+- Fear & Greed Index with 30-day history
+- Bitcoin technical trend (SMA50, SMA200, VWAP, Mayer Multiple)
+- JPY liquidity signal, QQQ/XLP macro regime, BTC hash rate
+- Inline SVG sparklines and donut gauges for visual trends
+
+
+
+
+Tech Ecosystem (Tech variant)
+
+- Tech company HQs (Big Tech, unicorns, public)
+- Startup hubs with funding data
+- Cloud regions (AWS, Azure, GCP)
+- Accelerators (YC, Techstars, 500)
+- Upcoming tech conferences
+
+
+
+
+Finance & Markets (Finance variant)
+
+- 92 global stock exchanges — mega (NYSE, NASDAQ, Shanghai, Euronext, Tokyo), major (Hong Kong, London, NSE/BSE, Toronto, Korea, Saudi Tadawul), and emerging markets — with market caps and trading hours
+- 19 financial centers — ranked by Global Financial Centres Index (New York #1 through offshore centers: Cayman Islands, Luxembourg, Bermuda, Channel Islands)
+- 13 central banks — Federal Reserve, ECB, BoJ, BoE, PBoC, SNB, RBA, BoC, RBI, BoK, BCB, SAMA, plus supranational institutions (BIS, IMF)
+- 10 commodity hubs — exchanges (CME Group, ICE, LME, SHFE, DCE, TOCOM, DGCX, MCX) and physical hubs (Rotterdam, Houston)
+- Gulf FDI investment layer — 64 Saudi/UAE foreign direct investments plotted globally, color-coded by status (operational, under-construction, announced), sized by investment amount
+
+
+
+### Live News & Video
+
+- **150+ RSS feeds** across geopolitics, defense, energy, tech, and finance — domain-allowlisted proxy prevents CORS issues. Each variant loads its own curated feed set: ~25 categories for geopolitical, ~20 for tech, ~18 for finance
+- **8 live video streams** — Bloomberg, Sky News, Al Jazeera, Euronews, DW, France24, CNBC, Al Arabiya — with automatic live detection that scrapes YouTube channel pages every 5 minutes to find active streams
+- **Desktop embed bridge** — YouTube's IFrame API restricts playback in native webviews (error 153). The dashboard detects this and transparently routes through a cloud-hosted embed proxy with bidirectional message passing (play/pause/mute/unmute/loadVideo)
+- **Idle-aware playback** — video players pause and are removed from the DOM after 5 minutes of inactivity, resuming when the user returns. Tab visibility changes also suspend/resume streams
+- **Custom monitors** — Create keyword-based alerts for any topic, color-coded with persistent storage
+- **Entity extraction** — Auto-links countries, leaders, organizations
+- **Virtual scrolling** — news panels render only visible DOM elements, handling thousands of items without browser lag
+
+### Signal Aggregation & Anomaly Detection
+
+- **Multi-source signal fusion** — internet outages, military flights, naval vessels, protests, AIS disruptions, satellite fires, and keyword spikes are aggregated into a unified intelligence picture with per-country and per-region clustering
+- **Temporal baseline anomaly detection** — Welford's online algorithm computes streaming mean/variance per event type, region, weekday, and month over a 90-day window. Z-score thresholds (1.5/2.0/3.0) flag deviations like "Military flights 3.2x normal for Thursday (January)" — stored in Redis via Upstash
+- **Regional convergence scoring** — when multiple signal types spike in the same geographic area, the system identifies convergence zones and escalates severity
+
+### Story Sharing & Social Export
+
+- **Shareable intelligence stories** — generate country-level intelligence briefs with CII scores, threat counts, theater posture, and related prediction markets
+- **Multi-platform export** — custom-formatted sharing for Twitter/X, LinkedIn, WhatsApp, Telegram, Reddit, and Facebook with platform-appropriate formatting
+- **Deep links** — every story generates a unique URL (`/story?c=&t=`) with dynamic Open Graph meta tags for rich social previews
+- **Canvas-based image generation** — stories render as PNG images for visual sharing, with QR codes linking back to the live dashboard
+
+### Desktop Application (Tauri)
+
+- **Native desktop app** for macOS and Windows — packages the full dashboard with a local Node.js sidecar that runs all 60+ API handlers locally
+- **OS keychain integration** — API keys stored in the system credential manager (macOS Keychain, Windows Credential Manager), never in plaintext files
+- **Token-authenticated sidecar** — a unique session token prevents other local processes from accessing the sidecar on localhost. Generated per launch using randomized hashing
+- **Cloud fallback** — when a local API handler fails or is missing, requests transparently fall through to the cloud deployment (worldmonitor.app) with origin headers stripped
+- **Settings window** — dedicated configuration UI (Cmd+,) for managing 17 API keys with validation, signup links, and feature-availability indicators
+- **Verbose debug mode** — toggle traffic logging with persistent state across restarts. View the last 200 requests with timing, status codes, and error details
+- **DevTools toggle** — Cmd+Alt+I opens the embedded web inspector for debugging
+
+### Progressive Web App
+
+- **Installable** — the dashboard can be installed to the home screen on mobile or as a standalone desktop app via Chrome's install prompt. Full-screen `standalone` display mode with custom theme color
+- **Offline map support** — MapTiler tiles are cached using a CacheFirst strategy (up to 500 tiles, 30-day TTL), enabling map browsing without a network connection
+- **Smart caching strategies** — APIs and RSS feeds use NetworkOnly (real-time data must always be fresh), while fonts (1-year TTL), images (7-day StaleWhileRevalidate), and static assets (1-year immutable) are aggressively cached
+- **Auto-updating service worker** — checks for new versions every 60 minutes. Tauri desktop builds skip service worker registration entirely (uses native APIs instead)
+- **Offline fallback** — a branded fallback page with retry button is served when the network is unavailable
+
+### Additional Capabilities
+
+- Signal intelligence with "Why It Matters" context
+- Infrastructure cascade analysis with proximity correlation
+- Maritime & aviation tracking with surge detection
+- Prediction market integration (Polymarket) with 3-tier JA3 bypass (browser-direct → Tauri native TLS → cloud proxy)
+- Service status monitoring (cloud providers, AI services)
+- Shareable map state via URL parameters (view, zoom, coordinates, time range, active layers)
+- Data freshness monitoring across 14 data sources with explicit intelligence gap reporting
+- Per-feed circuit breakers with 5-minute cooldowns to prevent cascading failures
+- Browser-side ML worker (Transformers.js) for NER and sentiment analysis without server dependency
+- **Cmd+K search** — fuzzy search across 20+ result types: news headlines, countries (with direct country brief navigation), hotspots, markets, military bases, cables, pipelines, datacenters, nuclear facilities, tech companies, and more
+- **Historical playback** — dashboard snapshots are stored in IndexedDB. A time slider allows rewinding to any saved state, with live updates paused during playback
+- **Mobile detection** — screens below 768px receive a warning modal since the dashboard is designed for multi-panel desktop use
+- **UCDP conflict classification** — countries with active wars (1,000+ battle deaths/year) receive automatic CII floor scores, preventing optimistic drift
+- **HAPI humanitarian data** — UN OCHA humanitarian access metrics and displacement flows feed into country-level instability scoring with dual-perspective (origins vs. hosts) panel
+- **Idle-aware resource management** — animations pause after 2 minutes of inactivity and when the tab is hidden, preventing battery drain. Video streams are destroyed from the DOM and recreated on return
+- **Country-specific stock indices** — country briefs display the primary stock market index with 1-week change (S&P 500 for US, Shanghai Composite for China, etc.) via the `/api/stock-index` endpoint
+- **Climate anomaly panel** — 15 conflict-prone zones monitored for temperature/precipitation deviations against 30-day ERA5 baselines, with severity classification feeding into CII
+- **Country brief export** — every brief is downloadable as structured JSON, flattened CSV, or rendered PNG image, enabling offline analysis and reporting workflows
+- **Print/PDF support** — country briefs include a print button that triggers the browser's native print dialog, producing clean PDF output
+- **Oil & energy analytics** — WTI/Brent crude prices, US production (Mbbl/d), and inventory levels via the EIA API with weekly trend detection
+- **Population exposure estimation** — WorldPop density data estimates civilian population within event-specific radii (50–100km) for conflicts, earthquakes, floods, and wildfires
+- **Trending keywords panel** — real-time display of surging terms across all RSS feeds with spike severity, source count, and AI-generated context summaries
+- **Download banner** — persistent notification for web users linking to native desktop installers for their detected platform
+- **Download API** — `/api/download?platform={windows-exe|windows-msi|macos-arm64|macos-x64}` redirects to the matching GitHub Release asset, with fallback to the releases page
+- **Non-tier country support** — clicking countries outside the 22 tier-1 list opens a brief with available data (news, markets, infrastructure) and a "Limited coverage" badge; country names for non-tier countries resolve via `Intl.DisplayNames`
+- **Feature toggles** — 14 runtime toggles (AI/Groq, AI/OpenRouter, FRED economic, EIA energy, internet outages, ACLED conflicts, threat intel feeds, AIS relay, OpenSky, Finnhub, NASA FIRMS) stored in `localStorage`, allowing administrators to enable/disable data sources without rebuilding
+- **AIS chokepoint detection** — the relay server monitors 8 strategic maritime chokepoints (Strait of Hormuz, Suez Canal, Malacca Strait, Bab el-Mandeb, Panama Canal, Taiwan Strait, South China Sea, Turkish Straits) and classifies transiting vessels by naval candidacy using MMSI prefixes, ship type codes, and name patterns
+- **AIS density grid** — vessel positions are aggregated into 2°×2° geographic cells over 30-minute windows, producing a heatmap of maritime traffic density that feeds into convergence detection
+- **Panel resizing** — drag handles on panel edges allow height adjustment (span-1 through span-4 grid rows), persisted to localStorage. Double-click resets to default height
---
-## Algorithms & Design
+## Regression Testing
+
+Map overlay behavior is validated in Playwright using the map harness (`/tests/map-harness.html`).
+
+- Cluster-state cache initialization guard:
+ - `updates protest marker click payload after data refresh`
+ - `initializes cluster movement cache on first protest cluster render`
+- Run by variant:
+ - `npm run test:e2e:full -- -g "updates protest marker click payload after data refresh|initializes cluster movement cache on first protest cluster render"`
+ - `npm run test:e2e:tech -- -g "updates protest marker click payload after data refresh|initializes cluster movement cache on first protest cluster render"`
+
+---
+
+## How It Works
+
+### Country Brief Pages
+
+Clicking any country on the map opens a full-page intelligence dossier — a single-screen synthesis of all intelligence modules for that country. The brief is organized into a two-column layout:
+
+**Left column**:
+
+- **Instability Index** — animated SVG score ring (0–100) with four component breakdown bars (Unrest, Conflict, Security, Information), severity badge, and trend indicator
+- **Intelligence Brief** — AI-generated analysis (Groq Llama 3.1) with inline citation anchors `[1]`–`[8]` that scroll to the corresponding news source when clicked
+- **Top News** — 8 most relevant headlines for the country, threat-level color-coded, with source and time-ago metadata
+
+**Right column**:
+
+- **Active Signals** — real-time chip indicators for protests, military aircraft, naval vessels, internet outages, earthquakes, displacement flows, climate stress, conflict events, and the country's stock market index (1-week change)
+- **7-Day Timeline** — D3.js-rendered event chart with 4 severity-coded lanes (protest, conflict, natural, military), interactive tooltips, and responsive resizing
+- **Prediction Markets** — top 3 Polymarket contracts by volume with probability bars and external links
+- **Infrastructure Exposure** — pipelines, undersea cables, datacenters, military bases, nuclear facilities, and ports within a 600km radius of the country centroid, ranked by distance
+
+**Headline relevance filtering**: each country has an alias map (e.g., `US → ["united states", "american", "washington", "pentagon", "biden", "trump"]`). Headlines are filtered using a negative-match algorithm — if another country's alias appears earlier in the headline title than the target country's alias, the headline is excluded. This prevents cross-contamination (e.g., a headline about Venezuela mentioning "Washington sanctions" appearing in the US brief).
+
+**Export options**: briefs are exportable as JSON (structured data with all scores, signals, and headlines), CSV (flattened tabular format), or PNG image. A print button triggers the browser's native print dialog for PDF export.
+
+### Local-First Country Detection
+
+Map clicks resolve to countries using a local geometry service rather than relying on network reverse-geocoding (Nominatim). The system loads a GeoJSON file containing polygon boundaries for ~200 countries and builds an indexed spatial lookup:
+
+1. **Bounding box pre-filter** — each country's polygon(s) are wrapped in a bounding box (`[minLon, minLat, maxLon, maxLat]`). Points outside the bbox are rejected without polygon intersection testing.
+2. **Ray-casting algorithm** — for points inside the bbox, a ray is cast from the point along the positive x-axis. The number of polygon edge intersections determines inside/outside status (odd = inside). Edge cases are handled: points on segment boundaries return `true`, and polygon holes are subtracted (a point inside an outer ring but also inside a hole is excluded).
+3. **MultiPolygon support** — countries with non-contiguous territories (e.g., the US with Alaska and Hawaii, Indonesia with thousands of islands) use MultiPolygon geometries where each polygon is tested independently.
+
+This approach provides sub-millisecond country detection entirely in the browser, with no network latency. The geometry data is preloaded at app startup and cached for the session. For countries not in the GeoJSON (rare), the system falls back to hardcoded rectangular bounding boxes, and finally to network reverse-geocoding as a last resort.
+
+### Threat Classification Pipeline
+
+Every news item passes through a two-stage classification pipeline:
+
+1. **Keyword classifier** (instant) — pattern-matches against ~120 threat keywords organized by severity tier (critical → high → medium → low → info) and category (conflict, terrorism, cyber, disaster, etc.). Returns immediately with a confidence score.
+2. **LLM classifier** (async) — fires in the background via a Vercel Edge Function calling Groq's Llama 3.1 8B at temperature 0. Results are cached in Redis (24h TTL) keyed by headline hash. When the LLM result arrives, it overrides the keyword result only if its confidence is higher.
+
+This hybrid approach means the UI is never blocked waiting for AI — users see keyword results instantly, with LLM refinements arriving within seconds and persisting for all subsequent visitors.
+
+### Country Instability Index (CII)
-### News Clustering
+22 tier-1 countries receive continuous monitoring: US, Russia, China, Ukraine, Iran, Israel, Taiwan, North Korea, Saudi Arabia, Turkey, Poland, Germany, France, UK, India, Pakistan, Syria, Yemen, Myanmar, Venezuela, Brazil, and UAE. Each receives a real-time instability score (0–100) computed from:
-Related articles are grouped using **Jaccard similarity** on tokenized headlines:
+| Component | Weight | Details |
+|-----------|--------|---------|
+| **Baseline risk** | 40% | Pre-configured per country reflecting structural fragility |
+| **Unrest events** | 20% | Protests scored logarithmically for democracies (routine protests don't trigger), linearly for authoritarian states (every protest is significant). Boosted for fatalities and internet outages |
+| **Security activity** | 20% | Military flights (3pts) + vessels (5pts) from own forces + foreign military presence (doubled weight) |
+| **Information velocity** | 20% | News mention frequency weighted by event severity multiplier, log-scaled for high-volume countries |
+
+Additional boosts apply for hotspot proximity, focal point urgency, and conflict-zone floors (e.g., Ukraine is pinned at ≥55, Syria at ≥50).
+
+### Hotspot Escalation Scoring
+
+Intelligence hotspots receive dynamic escalation scores blending four normalized signals (0–100):
+
+- **News activity** (35%) — article count and severity in the hotspot's area
+- **Country instability** (25%) — CII score of the host country
+- **Geo-convergence alerts** (25%) — spatial binning detects 3+ event types (protests + military + earthquakes) co-occurring within 1° lat/lon cells
+- **Military activity** (15%) — vessel clusters and flight density near the hotspot
+
+The system blends static baseline risk (40%) with detected events (60%) and tracks trends via linear regression on 48-hour history. Signal emissions cool down for 2 hours to prevent alert fatigue.
+
+### Geographic Convergence Detection
+
+Events (protests, military flights, vessels, earthquakes) are binned into 1°×1° geographic cells within a 24-hour window. When 3+ distinct event types converge in one cell, a convergence alert fires. Scoring is based on type diversity (×25pts per unique type) plus event count bonuses (×2pts). Alerts are reverse-geocoded to human-readable names using conflict zones, waterways, and hotspot databases.
+
+### Strategic Theater Posture Assessment
+
+Nine operational theaters are continuously assessed for military posture escalation:
+
+| Theater | Key Trigger |
+|---------|-------------|
+| Iran / Persian Gulf | Carrier groups, tanker activity, AWACS |
+| Taiwan Strait | PLAAF sorties, USN carrier presence |
+| Baltic / Kaliningrad | Russian Western Military District flights |
+| Korean Peninsula | B-52/B-1 deployments, DPRK missile activity |
+| Eastern Mediterranean | Multi-national naval exercises |
+| Horn of Africa | Anti-piracy patrols, drone activity |
+| South China Sea | Freedom of navigation operations |
+| Arctic | Long-range aviation patrols |
+| Black Sea | ISR flights, naval movements |
+
+Posture levels escalate from NORMAL → ELEVATED → CRITICAL based on a composite of:
+
+- **Aircraft count** in theater (both resident and transient)
+- **Strike capability** — the presence of tankers + AWACS + fighters together indicates strike packaging, not routine training
+- **Naval presence** — carrier groups and combatant formations
+- **Country instability** — high CII scores for theater-adjacent countries amplify posture
+
+Each theater is linked to 38+ military bases, enabling automatic correlation between observed flights and known operating locations.
+
+### Military Surge & Foreign Presence Detection
+
+The system monitors five operational theaters (Middle East, Eastern Europe, Western Europe, Western Pacific, Horn of Africa) with 38+ associated military bases. It classifies vessel clusters near hotspots by activity type:
+
+- **Deployment** — carrier present with 5+ vessels
+- **Exercise** — combatants present in formation
+- **Transit** — vessels passing through
+
+Foreign military presence is dual-credited: the operator's country is flagged for force projection, and the host location's country is flagged for foreign military threat. AIS gaps (dark ships) are flagged as potential signal discipline indicators.
+
+### Infrastructure Cascade Modeling
+
+Beyond proximity correlation, the system models how disruptions propagate through interconnected infrastructure. A dependency graph connects undersea cables, pipelines, ports, chokepoints, and countries with weighted edges representing capacity dependencies:
```
-similarity(A, B) = |A ∩ B| / |A ∪ B|
+Disruption Event → Affected Node → Cascade Propagation (BFS, depth ≤ 3)
+ │
+ ┌─────────────────────┤
+ ▼ ▼
+ Direct Impact Indirect Impact
+ (e.g., cable cut) (countries served by cable)
```
-- Headlines are tokenized, lowercased, and stripped of stop words
-- Articles with similarity ≥ 0.5 are grouped into clusters
-- Clusters are sorted by source tier, then recency
-- The most authoritative source becomes the "primary" headline
+**Impact calculation**: `strength = edge_weight × disruption_level × (1 − redundancy)`
+
+Strategic chokepoint modeling captures real-world dependencies:
+
+- **Strait of Hormuz** — 80% of Japan's oil, 70% of South Korea's, 60% of India's, 40% of China's
+- **Suez Canal** — EU-Asia trade routes (Germany, Italy, UK, China)
+- **Malacca Strait** — 80% of China's oil transit
+
+Ports are weighted by type: oil/LNG terminals (0.9 — critical), container ports (0.7), naval bases (0.4 — geopolitical but less economic). This enables questions like "if the Strait of Hormuz closes, which countries face energy shortages within 30 days?"
+
+### Related Assets & Proximity Correlation
+
+When a news event is geo-located, the system automatically identifies critical infrastructure within a 600km radius — pipelines, undersea cables, data centers, military bases, and nuclear facilities — ranked by distance. This enables instant geopolitical context: a cable cut near a strategic chokepoint, a protest near a nuclear facility, or troop movements near a data center cluster.
+
+### News Geo-Location
+
+A 74-hub strategic location database infers geography from headlines via keyword matching. Hubs span capitals, conflict zones, strategic chokepoints (Strait of Hormuz, Suez Canal, Malacca Strait), and international organizations. Confidence scoring is boosted for critical-tier hubs and active conflict zones, enabling map-driven news placement without requiring explicit location metadata from RSS feeds.
+
+### Entity Index & Cross-Referencing
+
+A structured entity registry catalogs countries, organizations, world leaders, and military entities with multiple lookup indices:
+
+| Index Type | Purpose | Example |
+|-----------|---------|---------|
+| **ID index** | Direct entity lookup | `entity:us` → United States profile |
+| **Alias index** | Name variant matching | "America", "USA", "United States" → same entity |
+| **Keyword index** | Contextual detection | "Pentagon", "White House" → United States |
+| **Sector index** | Domain grouping | "military", "energy", "tech" |
+| **Type index** | Category filtering | "country", "organization", "leader" |
-### Velocity Analysis
+Entity matching uses word-boundary regex to prevent false positives (e.g., "Iran" matching "Ukraine"). Confidence scores are tiered by match quality: exact name matches score 1.0, aliases 0.85–0.95, and keyword matches 0.7. When the same entity surfaces across multiple independent data sources (news, military tracking, protest feeds, market signals), the system identifies it as a focal point and escalates its prominence in the intelligence picture.
-Each news cluster tracks publication velocity:
+### Temporal Baseline Anomaly Detection
-- **Sources per hour** = article count / time span
-- **Trend** = rising/stable/falling based on first-half vs second-half publication rate
-- **Levels**: Normal (<3/hr), Elevated (3-6/hr), Spike (>6/hr)
+Rather than relying on static thresholds, the system learns what "normal" looks like and flags deviations. Each event type (military flights, naval vessels, protests, news velocity, AIS gaps, satellite fires) is tracked per region with separate baselines for each weekday and month — because military activity patterns differ on Tuesdays vs. weekends, and January vs. July.
-### Sentiment Detection
+The algorithm uses **Welford's online method** for numerically stable streaming computation of mean and variance, stored in Redis with a 90-day rolling window. When a new observation arrives, its z-score is computed against the learned baseline. Thresholds:
-Headlines are scored against curated word lists:
+| Z-Score | Severity | Example |
+|---------|----------|---------|
+| ≥ 1.5 | Low | Slightly elevated protest activity |
+| ≥ 2.0 | Medium | Unusual naval presence |
+| ≥ 3.0 | High/Critical | Military flights 3x above baseline |
-**Negative indicators**: war, attack, killed, crisis, crash, collapse, threat, sanctions, invasion, missile, terror, assassination, recession, layoffs...
+A minimum of 10 historical samples is required before anomalies are reported, preventing false positives during the learning phase. Anomalies are ingested back into the signal aggregator, where they compound with other signals for convergence detection.
-**Positive indicators**: peace, deal, agreement, breakthrough, recovery, growth, ceasefire, treaty, alliance, victory...
+### Trending Keyword Spike Detection
-Score determines sentiment classification: negative (<-1), neutral (-1 to +1), positive (>+1)
+Every RSS headline is tokenized into individual terms and tracked in per-term frequency maps. A 2-hour rolling window captures current activity while a 7-day baseline (refreshed hourly) establishes what "normal" looks like for each term. A spike fires when all conditions are met:
-### Baseline Deviation (Z-Score)
+| Condition | Threshold |
+|-----------|-----------|
+| **Absolute count** | > `minSpikeCount` (5 mentions) |
+| **Relative surge** | > baseline × `spikeMultiplier` (3×) |
+| **Source diversity** | ≥ 2 unique RSS feed sources |
+| **Cooldown** | 30 minutes since last spike for the same term |
+
+The tokenizer extracts CVE identifiers (`CVE-2024-xxxxx`), APT/FIN threat actor designators, and 12 compound terms for world leaders (e.g., "Xi Jinping", "Kim Jong Un") that would be lost by naive whitespace splitting. A configurable blocklist suppresses common noise terms.
+
+Detected spikes are auto-summarized via Groq (rate-limited to 5 summaries/hour) and emitted as `keyword_spike` signals into the correlation engine, where they compound with other signal types for convergence detection. The term registry is capped at 10,000 entries with LRU eviction to bound memory usage. All thresholds (spike multiplier, min count, cooldown, blocked terms) are configurable via the Settings panel.
+
+### Cyber Threat Intelligence Layer
+
+Five threat intelligence feeds provide indicators of compromise (IOCs) for active command-and-control servers, malware distribution hosts, phishing campaigns, and malicious URLs:
+
+| Feed | IOC Type | Coverage |
+|------|----------|----------|
+| **Feodo Tracker** (abuse.ch) | C2 servers | Botnet C&C infrastructure |
+| **URLhaus** (abuse.ch) | Malware hosts | Malware distribution URLs |
+| **C2IntelFeeds** | C2 servers | Community-sourced C2 indicators |
+| **AlienVault OTX** | Mixed | Open threat exchange pulse IOCs |
+| **AbuseIPDB** | Malicious IPs | Crowd-sourced abuse reports |
+
+Each IP-based IOC is geo-enriched using ipinfo.io with freeipapi.com as fallback. Geolocation results are Redis-cached for 24 hours. Enrichment runs concurrently — 16 parallel lookups with a 12-second timeout, processing up to 250 IPs per collection run.
+
+IOCs are classified into four types (`c2_server`, `malware_host`, `phishing`, `malicious_url`) with four severity levels, rendered as color-coded scatter dots on the globe. The layer uses a 10-minute cache, a 14-day rolling window, and caps display at 500 IOCs to maintain rendering performance.
+
+### Natural Disaster Monitoring
+
+Three independent sources are merged into a unified disaster picture, then deduplicated on a 0.1° geographic grid:
+
+| Source | Coverage | Types | Update Frequency |
+|--------|----------|-------|------------------|
+| **USGS** | Global earthquakes M4.5+ | Earthquakes | 5 minutes |
+| **GDACS** | UN-coordinated disaster alerts | Earthquakes, floods, cyclones, volcanoes, wildfires, droughts | Real-time |
+| **NASA EONET** | Earth observation events | 13 natural event categories (30-day open events) | Real-time |
+
+GDACS events carry color-coded alert levels (Red = critical, Orange = high) and are filtered to exclude low-severity Green alerts. EONET wildfires are filtered to events within 48 hours to prevent stale data. Earthquakes from EONET are excluded since USGS provides higher-quality seismological data.
+
+The merged output feeds into the signal aggregator for geographic convergence detection — e.g., an earthquake near a pipeline triggers an infrastructure cascade alert.
+
+### Dual-Source Protest Tracking
+
+Protest data is sourced from two independent providers to reduce single-source bias:
+
+1. **ACLED** (Armed Conflict Location & Event Data) — 30-day window, tokenized API with Redis caching (10-minute TTL). Covers protests, riots, strikes, and demonstrations with actor attribution and fatality counts.
+2. **GDELT** (Global Database of Events, Language, and Tone) — 7-day geospatial event feed filtered to protest keywords. Events with mention count ≥5 are included; those above 30 are marked as `validated`.
+
+Events from both sources are **Haversine-deduplicated** on a 0.5° grid (~50km) with same-day matching. ACLED events take priority due to higher editorial confidence. Severity is classified as:
+
+- **High** — fatalities present or riot/clash keywords
+- **Medium** — standard protest/demonstration
+- **Low** — default
+
+Protest scoring is regime-aware: democratic countries use logarithmic scaling (routine protests don't trigger instability), while authoritarian states use linear scoring (every protest is significant). Fatalities and concurrent internet outages apply severity boosts.
+
+### Climate Anomaly Detection
+
+15 conflict-prone and disaster-prone zones are continuously monitored for temperature and precipitation anomalies using Open-Meteo ERA5 reanalysis data. A 30-day baseline is computed, and current conditions are compared against it to determine severity:
+
+| Severity | Temperature Deviation | Precipitation Deviation |
+|----------|----------------------|------------------------|
+| **Extreme** | > 5°C above baseline | > 80mm/day above baseline |
+| **Moderate** | > 3°C above baseline | > 40mm/day above baseline |
+| **Normal** | Within expected range | Within expected range |
+
+Anomalies feed into the signal aggregator, where they amplify CII scores for affected countries (climate stress is a recognized conflict accelerant). The Climate Anomaly panel surfaces these deviations in a severity-sorted list.
+
+### Displacement Tracking
+
+Refugee and displacement data is sourced from the UN OCHA Humanitarian API (HAPI), providing population-level counts for refugees, asylum seekers, and internally displaced persons (IDPs). The Displacement panel offers two perspectives:
+
+- **Origins** — countries people are fleeing from, ranked by outflow volume
+- **Hosts** — countries absorbing displaced populations, ranked by intake
+
+Crisis badges flag countries with extreme displacement: > 1 million displaced (red), > 500,000 (orange). Displacement outflow feeds into the CII as a component signal — high displacement is a lagging indicator of instability that persists even when headlines move on.
+
+### Population Exposure Estimation
+
+Active events (conflicts, earthquakes, floods, wildfires) are cross-referenced against WorldPop population density data to estimate the number of civilians within the impact zone. Event-specific radii reflect typical impact footprints:
+
+| Event Type | Radius | Rationale |
+|-----------|--------|-----------|
+| **Conflicts** | 50 km | Direct combat zone + displacement buffer |
+| **Earthquakes** | 100 km | Shaking intensity propagation |
+| **Floods** | 100 km | Watershed and drainage basin extent |
+| **Wildfires** | 30 km | Smoke and evacuation perimeter |
+
+API calls to WorldPop are batched concurrently (max 10 parallel requests) to handle multiple simultaneous events without sequential bottlenecks. The Population Exposure panel displays a summary header with total affected population and a per-event breakdown table.
+
+### Strategic Port Infrastructure
+
+83 strategic ports are cataloged across six types, reflecting their role in global trade and military posture:
+
+| Type | Count | Examples |
+|------|-------|---------|
+| **Container** | 21 | Shanghai (#1, 47M+ TEU), Singapore, Ningbo, Shenzhen |
+| **Oil/LNG** | 8 | Ras Tanura (Saudi), Sabine Pass (US), Fujairah (UAE) |
+| **Chokepoint** | 8 | Suez Canal, Panama Canal, Strait of Malacca |
+| **Naval** | 6 | Zhanjiang, Yulin (China), Vladivostok (Russia) |
+| **Mixed** | 15+ | Ports serving multiple roles (trade + military) |
+| **Bulk** | 20+ | Regional commodity ports |
+
+Ports are ranked by throughput and weighted by strategic importance in the infrastructure cascade model: oil/LNG terminals carry 0.9 criticality, container ports 0.7, and naval bases 0.4. Port proximity appears in the Country Brief infrastructure exposure section.
+
+### Browser-Side ML Pipeline
+
+The dashboard runs a full ML pipeline in the browser via Transformers.js, with no server dependency for core intelligence. This is automatically disabled on mobile devices to conserve memory.
+
+| Capability | Model | Use |
+|-----------|-------|-----|
+| **Text embeddings** | sentence-similarity | Semantic clustering of news headlines |
+| **Sequence classification** | threat-classifier | Threat severity and category detection |
+| **Summarization** | T5-small | Fallback when Groq and OpenRouter are unavailable |
+| **Named Entity Recognition** | NER pipeline | Country, organization, and leader extraction |
+
+**Hybrid clustering** combines fast Jaccard similarity (n-gram overlap, threshold 0.4) with ML-refined semantic similarity (cosine similarity, threshold 0.78). Jaccard runs instantly on every refresh; semantic refinement runs when the ML worker is loaded and merges clusters that are textually different but semantically identical (e.g., "NATO expands missile shield" and "Alliance deploys new air defense systems").
+
+News velocity is tracked per cluster — when multiple Tier 1–2 sources converge on the same story within a short window, the cluster is flagged as a breaking alert with `sourcesPerHour` as the velocity metric.
+
+### Signal Aggregation
+
+All real-time data sources feed into a central signal aggregator that builds a unified geospatial intelligence picture. Signals are clustered by country and region, with each signal carrying a severity (low/medium/high), geographic coordinates, and metadata. The aggregator:
+
+1. **Clusters by country** — groups signals from diverse sources (flights, vessels, protests, fires, outages, `keyword_spike`) into per-country profiles
+2. **Detects regional convergence** — identifies when multiple signal types spike in the same geographic corridor (e.g., military flights + protests + satellite fires in Eastern Mediterranean)
+3. **Feeds downstream analysis** — the CII, hotspot escalation, focal point detection, and AI insights modules all consume the aggregated signal picture rather than raw data
+
+### Data Freshness & Intelligence Gaps
+
+A singleton tracker monitors 22 data sources (GDELT, RSS, AIS, military flights, earthquakes, weather, outages, ACLED, Polymarket, economic indicators, NASA FIRMS, cyber threat feeds, trending keywords, oil/energy, population exposure, and more) with status categorization: fresh (<15 min), stale (1h), very_stale (6h), no_data, error, disabled. It explicitly reports **intelligence gaps** — what analysts can't see — preventing false confidence when critical data sources are down or degraded.
+
+### Prediction Markets as Leading Indicators
+
+Polymarket geopolitical markets are queried using tag-based filters (Ukraine, Iran, China, Taiwan, etc.) with 5-minute caching. Market probability shifts are correlated with news volume: if a prediction market moves significantly before matching news arrives, this is flagged as a potential early-warning signal.
+
+**Cloudflare JA3 bypass** — Polymarket's API is protected by Cloudflare TLS fingerprinting (JA3) that blocks all server-side requests. The system uses a 3-tier fallback:
+
+| Tier | Method | When It Works |
+|------|--------|---------------|
+| **1** | Browser-direct fetch | Always (browser TLS passes Cloudflare) |
+| **2** | Tauri native TLS (reqwest) | Desktop app (Rust TLS fingerprint differs from Node.js) |
+| **3** | Vercel edge proxy | Rarely (edge runtime sometimes passes) |
+
+Once browser-direct succeeds, the system caches this state and skips fallback tiers on subsequent requests. Country-specific markets are fetched by mapping countries to Polymarket tags with name-variant matching (e.g., "Russia" matches titles containing "Russian", "Moscow", "Kremlin", "Putin").
+
+Markets are filtered to exclude sports and entertainment (100+ exclusion keywords), require meaningful price divergence from 50% or volume above $50K, and are ranked by trading volume. Each variant gets different tag sets — geopolitical focus queries politics/world/ukraine/middle-east tags, while tech focus queries ai/crypto/business tags.
+
+### Macro Signal Analysis (Market Radar)
+
+The Market Radar panel computes a composite BUY/CASH verdict from 7 independent signals sourced entirely from free APIs (Yahoo Finance, mempool.space, alternative.me):
+
+| Signal | Computation | Bullish When |
+|--------|------------|--------------|
+| **Liquidity** | JPY/USD 30-day rate of change | ROC > -2% (no yen squeeze) |
+| **Flow Structure** | BTC 5-day return vs QQQ 5-day return | Gap < 5% (aligned) |
+| **Macro Regime** | QQQ 20-day ROC vs XLP 20-day ROC | QQQ outperforming (risk-on) |
+| **Technical Trend** | BTC vs SMA50 + 30-day VWAP | Above both (bullish) |
+| **Hash Rate** | Bitcoin mining hashrate 30-day change | Growing > 3% |
+| **Mining Cost** | BTC price vs hashrate-implied cost | Price > $60K (profitable) |
+| **Fear & Greed** | alternative.me sentiment index | Value > 50 |
+
+The overall verdict requires ≥57% of known signals to be bullish (BUY), otherwise CASH. Signals with unknown data are excluded from the denominator.
+
+**VWAP Calculation** — Volume-Weighted Average Price is computed from aligned price/volume pairs over a 30-day window. Pairs where either price or volume is null are excluded together to prevent index misalignment:
+
+```
+VWAP = Σ(price × volume) / Σ(volume) for last 30 trading days
+```
-The system maintains rolling baselines for news volume per topic:
+The **Mayer Multiple** (BTC price / SMA200) provides a long-term valuation context — historically, values above 2.4 indicate overheating, while values below 0.8 suggest deep undervaluation.
-- **7-day average** and **30-day average** stored in IndexedDB
-- Standard deviation calculated from historical counts
-- **Z-score** = (current - mean) / stddev
+### Gulf FDI Investment Database
-Deviation levels:
-- **Spike**: Z > 2.5 (statistically rare increase)
-- **Elevated**: Z > 1.5
-- **Normal**: -2 < Z < 1.5
-- **Quiet**: Z < -2 (unusually low activity)
+The Finance variant includes a curated database of 64 major foreign direct investments by Saudi Arabia and the UAE in global critical infrastructure. Investments are tracked across 12 sectors:
-This enables detection of anomalous activity even when absolute numbers seem normal.
+| Sector | Examples |
+|--------|---------|
+| **Ports** | DP World's 11 global container terminals, AD Ports (Khalifa, Al-Sokhna, Karachi), Saudi Mawani ports |
+| **Energy** | ADNOC Ruwais LNG (9.6 mtpa), Aramco's Motiva Port Arthur refinery (630K bpd), ACWA Power renewables |
+| **Manufacturing** | Mubadala's GlobalFoundries (82% stake, 3rd-largest chip foundry), Borealis (75%), SABIC (70%) |
+| **Renewables** | Masdar wind/solar (UK Hornsea, Zarafshan 500MW, Gulf of Suez), NEOM Green Hydrogen (world's largest) |
+| **Megaprojects** | NEOM THE LINE ($500B), Saudi National Cloud ($6B hyperscale datacenters) |
+| **Telecoms** | STC's 9.9% stake in Telefónica, PIF's 20% of Telecom Italia NetCo |
+
+Each investment records the investing entity (DP World, Mubadala, PIF, ADNOC, Masdar, Saudi Aramco, ACWA Power, etc.), target country, geographic coordinates, investment amount (USD), ownership stake, operational status, and year. The Investments Panel provides filterable views by country (SA/UAE), sector, entity, and status — clicking any row navigates the map to the investment location.
+
+On the globe, investments appear as scaled bubbles: ≥$50B projects (NEOM) render at maximum size, while sub-$1B investments use smaller markers. Color encodes status: green for operational, amber for under-construction, blue for announced.
+
+### Stablecoin Peg Monitoring
+
+Five major stablecoins (USDT, USDC, DAI, FDUSD, USDe) are monitored via the CoinGecko API with 2-minute caching. Each coin's deviation from the $1.00 peg determines its health status:
+
+| Deviation | Status | Indicator |
+|-----------|--------|-----------|
+| ≤ 0.5% | ON PEG | Green |
+| 0.5% – 1.0% | SLIGHT DEPEG | Yellow |
+| > 1.0% | DEPEGGED | Red |
+
+The panel aggregates total stablecoin market cap, 24h volume, and an overall health status (HEALTHY / CAUTION / WARNING). The `coins` query parameter accepts a comma-separated list of CoinGecko IDs, validated against a `[a-z0-9-]+` regex to prevent injection.
+
+### Oil & Energy Analytics
+
+The Oil & Energy panel tracks four key indicators from the U.S. Energy Information Administration (EIA) API:
+
+| Indicator | Series | Update Cadence |
+|-----------|--------|----------------|
+| **WTI Crude** | Spot price ($/bbl) | Weekly |
+| **Brent Crude** | Spot price ($/bbl) | Weekly |
+| **US Production** | Crude oil output (Mbbl/d) | Weekly |
+| **US Inventory** | Commercial crude stocks | Weekly |
+
+Trend detection flags week-over-week changes exceeding ±0.5% as rising or falling, with flat readings within the threshold shown as stable. Results are cached client-side for 30 minutes. The panel provides energy market context for geopolitical analysis — price spikes often correlate with supply disruptions in monitored conflict zones and chokepoint closures.
+
+### BTC ETF Flow Estimation
+
+Ten spot Bitcoin ETFs are tracked via Yahoo Finance's 5-day chart API (IBIT, FBTC, ARKB, BITB, GBTC, HODL, BRRR, EZBC, BTCO, BTCW). Since ETF flow data requires expensive terminal subscriptions, the system estimates flow direction from publicly available signals:
+
+- **Price change** — daily close vs. previous close determines direction
+- **Volume ratio** — current volume / trailing average volume measures conviction
+- **Flow magnitude** — `volume × price × direction × 0.1` provides a rough dollar estimate
+
+This is an approximation, not a substitute for official flow data, but it captures the direction and relative magnitude correctly. Results are cached for 15 minutes.
+
+---
+
+## Tri-Variant Architecture
+
+A single codebase produces three specialized dashboards, each with distinct feeds, panels, map layers, and branding:
+
+| Aspect | World Monitor | Tech Monitor | Finance Monitor |
+|--------|--------------|--------------|-----------------|
+| **Domain** | worldmonitor.app | tech.worldmonitor.app | finance.worldmonitor.app |
+| **Focus** | Geopolitics, military, conflicts | AI/ML, startups, cybersecurity | Markets, trading, central banks |
+| **RSS Feeds** | ~25 categories (politics, MENA, Africa, think tanks) | ~20 categories (AI, VC blogs, startups, GitHub) | ~18 categories (forex, bonds, commodities, IPOs) |
+| **Panels** | 44 (strategic posture, CII, cascade) | 31 (AI labs, unicorns, accelerators) | 30 (forex, bonds, derivatives, institutional) |
+| **Unique Map Layers** | Military bases, nuclear facilities, hotspots | Tech HQs, cloud regions, startup hubs | Stock exchanges, central banks, Gulf investments |
+| **Desktop App** | World Monitor.app / .exe | Tech Monitor.app / .exe | Finance Monitor.app / .exe |
+
+**Build-time selection** — the `VITE_VARIANT` environment variable controls which configuration is bundled. A Vite HTML plugin transforms meta tags, Open Graph data, PWA manifest, and JSON-LD structured data at build time. Each variant tree-shakes unused data files — the finance build excludes military base coordinates and APT group data, while the geopolitical build excludes stock exchange listings.
+
+**Runtime switching** — a variant selector in the header bar (🌍 WORLD | 💻 TECH | 📈 FINANCE) navigates between deployed domains on the web, or sets `localStorage['worldmonitor-variant']` in the desktop app to switch without rebuilding.
+
+---
+
+## Architecture Principles
+
+| Principle | Implementation |
+|-----------|---------------|
+| **Speed over perfection** | Keyword classifier is instant; LLM refines asynchronously. Users never wait. |
+| **Assume failure** | Per-feed circuit breakers with 5-minute cooldowns. AI fallback chain: Groq → OpenRouter → browser-side T5. Redis cache failures degrade gracefully. Every edge function returns stale cached data when upstream APIs are down. |
+| **Show what you can't see** | Intelligence gap tracker explicitly reports data source outages rather than silently hiding them. |
+| **Browser-first compute** | Analysis (clustering, instability scoring, surge detection) runs client-side — no backend compute dependency for core intelligence. |
+| **Local-first geolocation** | Country detection uses browser-side ray-casting against GeoJSON polygons rather than network reverse-geocoding. Sub-millisecond response, zero API dependency, works offline. Network geocoding is a fallback, not the primary path. |
+| **Multi-signal correlation** | No single data source is trusted alone. Focal points require convergence across news + military + markets + protests before escalating to critical. |
+| **Geopolitical grounding** | Hard-coded conflict zones, baseline country risk, and strategic chokepoints prevent statistical noise from generating false alerts in low-data regions. |
+| **Defense in depth** | CORS origin allowlist, domain-allowlisted RSS proxy, server-side API key isolation, token-authenticated desktop sidecar, input sanitization with output encoding, IP rate limiting on AI endpoints. |
+| **Cache everything, trust nothing** | Three-tier caching (in-memory → Redis → upstream) with versioned cache keys and stale-on-error fallback. Every API response includes `X-Cache` header for debugging. CDN layer (`s-maxage`) absorbs repeated requests before they reach edge functions. |
+| **Bandwidth efficiency** | Gzip compression on all relay responses (80% reduction). Content-hash static assets with 1-year immutable cache. Staggered polling intervals prevent synchronized API storms. Animations and polling pause on hidden tabs. |
+| **Baseline-aware alerting** | Trending keyword detection uses rolling 2-hour windows against 7-day baselines with per-term spike multipliers, cooldowns, and source diversity requirements — surfacing genuine surges while suppressing noise. |
+| **Run anywhere** | Same codebase produces three specialized variants (geopolitical, tech, finance) and deploys to Vercel (web), Railway (relay), Tauri (desktop), and PWA (installable). Desktop sidecar mirrors all cloud API handlers locally. Service worker caches map tiles for offline use while keeping intelligence data always-fresh (NetworkOnly). |
+
+---
+
+## Source Credibility & Feed Tiering
+
+Every RSS feed is assigned a source tier reflecting editorial reliability:
+
+| Tier | Description | Examples |
+|------|-------------|---------|
+| **Tier 1** | Wire services, official government sources | Reuters, AP, BBC, DOD |
+| **Tier 2** | Major established outlets | CNN, NYT, The Guardian, Al Jazeera |
+| **Tier 3** | Specialized/niche outlets | Defense One, Breaking Defense, The War Zone |
+| **Tier 4** | Aggregators and blogs | Google News, individual analyst blogs |
+
+Feeds also carry a **propaganda risk rating** and **state affiliation flag**. State-affiliated sources (RT, Xinhua, IRNA) are included for completeness but visually tagged so analysts can factor in editorial bias. Threat classification confidence is weighted by source tier — a Tier 1 breaking alert carries more weight than a Tier 4 blog post in the focal point detection algorithm.
+
+---
+
+## Edge Function Architecture
+
+World Monitor uses 60+ Vercel Edge Functions as a lightweight API layer. Each edge function handles a single data source concern — proxying, caching, or transforming external APIs. This architecture avoids a monolithic backend while keeping API keys server-side:
+
+- **RSS Proxy** — domain-allowlisted proxy for 100+ feeds, preventing CORS issues and hiding origin servers. Feeds from domains that block Vercel IPs are automatically routed through the Railway relay.
+- **AI Pipeline** — Groq and OpenRouter edge functions with Redis deduplication, so identical headlines across concurrent users only trigger one LLM call. The classify-event endpoint pauses its queue on 500 errors to avoid wasting API quota.
+- **Data Adapters** — GDELT, ACLED, OpenSky, USGS, NASA FIRMS, FRED, Yahoo Finance, CoinGecko, mempool.space, and others each have dedicated edge functions that normalize responses into consistent schemas
+- **Market Intelligence** — macro signals, ETF flows, and stablecoin monitors compute derived analytics server-side (VWAP, SMA, peg deviation, flow estimates) and cache results in Redis
+- **Temporal Baseline** — Welford's algorithm state is persisted in Redis across requests, building statistical baselines without a traditional database
+- **Custom Scrapers** — sources without RSS feeds (FwdStart, GitHub Trending, tech events) are scraped and transformed into RSS-compatible formats
+- **Finance Geo Data** — stock exchanges (92), financial centers (19), central banks (13), and commodity hubs (10) are served as static typed datasets with market caps, GFCI rankings, trading hours, and commodity specializations
+
+All edge functions include circuit breaker logic and return cached stale data when upstream APIs are unavailable, ensuring the dashboard never shows blank panels.
---
-## Dynamic Hotspot Activity
+## Multi-Platform Architecture
-Hotspots on the map are **not static threat levels**. Activity is calculated in real-time based on news correlation.
+All three variants run on three platforms that work together:
-Each hotspot defines keywords:
-```typescript
-{
- id: 'dc',
- name: 'DC',
- keywords: ['pentagon', 'white house', 'congress', 'cia', 'nsa', ...],
- agencies: ['Pentagon', 'CIA', 'NSA', 'State Dept'],
-}
+```
+┌─────────────────────────────────────┐
+│ Vercel (Edge) │
+│ 60+ edge functions · static SPA │
+│ CORS allowlist · Redis cache │
+│ AI pipeline · market analytics │
+│ CDN caching (s-maxage) · PWA host │
+└──────────┬─────────────┬────────────┘
+ │ │ fallback
+ │ ▼
+ │ ┌───────────────────────────────────┐
+ │ │ Tauri Desktop (Rust + Node) │
+ │ │ OS keychain · Token-auth sidecar │
+ │ │ 60+ local API handlers · gzip │
+ │ │ Cloud fallback · Traffic logging │
+ │ └───────────────────────────────────┘
+ │
+ │ https:// (server-side)
+ │ wss:// (client-side)
+ ▼
+┌─────────────────────────────────────┐
+│ Railway (Relay Server) │
+│ WebSocket relay · OpenSky OAuth2 │
+│ RSS proxy for blocked domains │
+│ AIS vessel stream · gzip all resp │
+└─────────────────────────────────────┘
```
-The system counts matching news articles in the current feed, applies velocity analysis, and assigns activity levels:
+**Why two platforms?** Several upstream APIs (OpenSky Network, CNN RSS, UN News, CISA, IAEA) actively block requests from Vercel's IP ranges. The Railway relay server acts as an alternate origin, handling:
-| Level | Criteria | Visual |
-|-------|----------|--------|
-| **Low** | <3 matches, normal velocity | Gray marker |
-| **Elevated** | 3-6 matches OR elevated velocity | Yellow pulse |
-| **High** | >6 matches OR spike velocity | Red pulse |
+- **AIS vessel tracking** — maintains a persistent WebSocket connection to AISStream.io and multiplexes it to all connected browser clients, avoiding per-user connection limits
+- **OpenSky aircraft data** — authenticates via OAuth2 client credentials flow (Vercel IPs get 403'd by OpenSky without auth tokens)
+- **RSS feeds** — proxies feeds from domains that block Vercel IPs, with a separate domain allowlist for security
-This creates a dynamic "heat map" of global attention based on live news flow.
+The Vercel edge functions connect to Railway via `WS_RELAY_URL` (server-side, HTTPS) while browser clients connect via `VITE_WS_RELAY_URL` (client-side, WSS). This separation keeps the relay URL configurable per deployment without leaking server-side configuration to the browser.
+
+All Railway relay responses are gzip-compressed (zlib `gzipSync`) when the client accepts it and the payload exceeds 1KB, reducing egress by ~80% for JSON and XML responses.
---
-## Custom Monitors
+## Desktop Application Architecture
+
+The Tauri desktop app wraps the dashboard in a native window with a local Node.js sidecar that runs all API handlers without cloud dependency:
+
+```
+┌─────────────────────────────────────────────────┐
+│ Tauri (Rust) │
+│ Window management · OS keychain · Menu bar │
+│ Token generation · Log management │
+│ Polymarket native TLS bridge │
+└─────────────────────┬───────────────────────────┘
+ │ spawn + env vars
+ ▼
+┌─────────────────────────────────────────────────┐
+│ Node.js Sidecar (port 46123) │
+│ 60+ API handlers · Gzip compression │
+│ Cloud fallback · Traffic logging │
+│ Verbose debug mode · Circuit breakers │
+└─────────────────────┬───────────────────────────┘
+ │ fetch (on local failure)
+ ▼
+┌─────────────────────────────────────────────────┐
+│ Cloud (worldmonitor.app) │
+│ Transparent fallback when local handlers fail │
+└─────────────────────────────────────────────────┘
+```
+
+### Secret Management
+
+API keys are stored in the operating system's credential manager (macOS Keychain, Windows Credential Manager) — never in plaintext config files. At sidecar launch, all 17 supported secrets are read from the keyring, trimmed, and injected as environment variables. Empty or whitespace-only values are skipped.
-Create personalized keyword alerts that scan all incoming news:
+Secrets can also be updated at runtime without restarting the sidecar: saving a key in the Settings window triggers a `POST /api/local-env-update` call that hot-patches `process.env` and clears the module cache so handlers pick up the new value immediately.
-1. Enter comma-separated keywords (e.g., "nvidia, gpu, chip shortage")
-2. System assigns a unique color
-3. Matching articles are highlighted in the Monitor panel
-4. Matching articles in clusters inherit the monitor color
+### Sidecar Authentication
-Monitors persist across sessions via LocalStorage.
+A unique 32-character hex token is generated per app launch using randomized hash state (`RandomState` from Rust's standard library). The token is:
+
+1. Injected into the sidecar as `LOCAL_API_TOKEN`
+2. Retrieved by the frontend via the `get_local_api_token` Tauri command (lazy-loaded on first API request)
+3. Attached as `Authorization: Bearer ` to every local request
+
+The `/api/service-status` health check endpoint is exempt from token validation to support monitoring tools.
+
+### Cloud Fallback
+
+When a local API handler is missing, throws an error, or returns a 5xx status, the sidecar transparently proxies the request to the cloud deployment. Endpoints that fail are marked as `cloudPreferred` — subsequent requests skip the local handler and go directly to the cloud until the sidecar is restarted. Origin and Referer headers are stripped before proxying to maintain server-to-server parity.
+
+### Observability
+
+- **Traffic log** — a ring buffer of the last 200 requests with method, path, status, and duration (ms), accessible via `GET /api/local-traffic-log`
+- **Verbose mode** — togglable via `POST /api/local-debug-toggle`, persists across sidecar restarts in `verbose-mode.json`
+- **Dual log files** — `desktop.log` captures Rust-side events (startup, secret injection counts, menu actions), while `local-api.log` captures Node.js stdout/stderr
+- **DevTools** — `Cmd+Alt+I` toggles the embedded web inspector
---
-## Snapshot System
+## Bandwidth Optimization
+
+The system minimizes egress costs through layered caching and compression across all three deployment targets:
+
+### Vercel CDN Headers
+
+Every API edge function includes `Cache-Control` headers that enable Vercel's CDN to serve cached responses without hitting the origin:
+
+| Data Type | `s-maxage` | `stale-while-revalidate` | Rationale |
+|-----------|-----------|--------------------------|-----------|
+| Classification results | 3600s (1h) | 600s (10min) | Headlines don't reclassify often |
+| Country intelligence | 3600s (1h) | 600s (10min) | Briefs change slowly |
+| Risk scores | 300s (5min) | 60s (1min) | Near real-time, low latency |
+| Market data | 3600s (1h) | 600s (10min) | Intraday granularity sufficient |
+| Fire detection | 600s (10min) | 120s (2min) | VIIRS updates every ~12 hours |
+| Economic indicators | 3600s (1h) | 600s (10min) | Monthly/quarterly releases |
+
+Static assets use content-hash filenames with 1-year immutable cache headers. The service worker file (`sw.js`) is never cached (`max-age=0, must-revalidate`) to ensure update detection.
+
+### Railway Relay Compression
+
+All relay server responses pass through `gzipSync` when the client accepts gzip and the payload exceeds 1KB. This applies to OpenSky aircraft JSON, RSS XML feeds, UCDP event data, AIS snapshots, and health checks — reducing wire size by approximately 80%.
+
+### Frontend Polling Intervals
-The dashboard captures periodic snapshots for historical analysis:
+Panels refresh at staggered intervals to avoid synchronized API storms:
-- **Automatic capture** every refresh cycle
-- **7-day retention** with automatic cleanup
-- **Stored data**: news clusters, market prices, prediction values, hotspot levels
-- **Playback**: Load historical snapshots to see past dashboard states
+| Panel | Interval | Rationale |
+|-------|----------|-----------|
+| AIS maritime snapshot | 10s | Real-time vessel positions |
+| Service status | 60s | Health check cadence |
+| Market signals / ETF / Stablecoins | 180s (3min) | Market hours granularity |
+| Risk scores / Theater posture | 300s (5min) | Composite scores change slowly |
-Baselines (7-day and 30-day averages) are stored in IndexedDB for deviation analysis.
+All animations and polling pause when the tab is hidden or after 2 minutes of inactivity, preventing wasted requests from background tabs.
---
-## Tech Stack
+## Caching Architecture
+
+Every external API call passes through a three-tier cache with stale-on-error fallback:
+
+```
+Request → [1] In-Memory Cache → [2] Redis (Upstash) → [3] Upstream API
+ │
+ ◄──── stale data served on error ────────────────┘
+```
+
+| Tier | Scope | TTL | Purpose |
+|------|-------|-----|---------|
+| **In-memory** | Per edge function instance | Varies (60s–900s) | Eliminates Redis round-trips for hot paths |
+| **Redis (Upstash)** | Cross-user, cross-instance | Varies (120s–900s) | Deduplicates API calls across all visitors |
+| **Upstream** | Source of truth | N/A | External API (Yahoo Finance, CoinGecko, etc.) |
-- **Frontend**: TypeScript, Vite
-- **Visualization**: D3.js, TopoJSON
-- **Data**: RSS feeds, REST APIs
-- **Storage**: IndexedDB for snapshots/baselines, LocalStorage for preferences
+Cache keys are versioned (`opensky:v2:lamin=...`, `macro-signals:v2:default`) so schema changes don't serve stale formats. Every response includes an `X-Cache` header (`HIT`, `REDIS-HIT`, `MISS`, `REDIS-STALE`, `REDIS-ERROR-FALLBACK`) for debugging.
-## Installation
+The AI summarization pipeline adds content-based deduplication: headlines are hashed and checked against Redis before calling Groq, so the same breaking news viewed by 1,000 concurrent users triggers exactly one LLM call.
+
+---
+
+## Security Model
+
+| Layer | Mechanism |
+|-------|-----------|
+| **CORS origin allowlist** | Only `worldmonitor.app`, `tech.worldmonitor.app`, `finance.worldmonitor.app`, and `localhost:*` can call API endpoints. All others receive 403. Implemented in `api/_cors.js`. |
+| **RSS domain allowlist** | The RSS proxy only fetches from explicitly listed domains (~90+). Requests for unlisted domains are rejected with 403. |
+| **Railway domain allowlist** | The Railway relay has a separate, smaller domain allowlist for feeds that need the alternate origin. |
+| **API key isolation** | All API keys live server-side in Vercel environment variables. The browser never sees Groq, OpenRouter, ACLED, Finnhub, or other credentials. |
+| **Input sanitization** | User-facing content passes through `escapeHtml()` (prevents XSS) and `sanitizeUrl()` (blocks `javascript:` and `data:` URIs). URLs use `escapeAttr()` for attribute context encoding. |
+| **Query parameter validation** | API endpoints validate input formats (e.g., stablecoin coin IDs must match `[a-z0-9-]+`, bounding box params are numeric). |
+| **IP rate limiting** | AI endpoints use Upstash Redis-backed rate limiting to prevent abuse of Groq/OpenRouter quotas. |
+| **Desktop sidecar auth** | The local API sidecar requires a per-session `Bearer` token generated at launch. The token is stored in Rust state and injected into the sidecar environment — only the Tauri frontend can retrieve it via IPC. Health check endpoints are exempt. |
+| **OS keychain storage** | Desktop API keys are stored in the operating system's credential manager (macOS Keychain, Windows Credential Manager), never in plaintext files or environment variables on disk. |
+| **No debug endpoints** | The `api/debug-env.js` endpoint returns 404 in production — it exists only as a disabled placeholder. |
+
+---
+
+## Quick Start
```bash
-# Clone the repository
+# Clone and run
git clone https://github.com/koala73/worldmonitor.git
cd worldmonitor
-
-# Install dependencies
npm install
+vercel dev # Runs frontend + all 60+ API edge functions
+```
+
+Open [http://localhost:3000](http://localhost:3000)
-# Start development server
-npm run dev
+> **Note**: `vercel dev` requires the [Vercel CLI](https://vercel.com/docs/cli) (`npm i -g vercel`). If you use `npm run dev` instead, only the frontend starts — news feeds and API-dependent panels won't load. See [Self-Hosting](#self-hosting) for details.
-# Build for production
-npm run build
+### Environment Variables (Optional)
+
+The dashboard works without any API keys — panels for unconfigured services simply won't appear. For full functionality, copy the example file and fill in the keys you need:
+
+```bash
+cp .env.example .env.local
```
-## API Dependencies
+The `.env.example` file documents every variable with descriptions and registration links, organized by deployment target (Vercel vs Railway). Key groups:
+
+| Group | Variables | Free Tier |
+|-------|-----------|-----------|
+| **AI** | `GROQ_API_KEY`, `OPENROUTER_API_KEY` | 14,400 req/day (Groq), 50/day (OpenRouter) |
+| **Cache** | `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN` | 10K commands/day |
+| **Markets** | `FINNHUB_API_KEY`, `FRED_API_KEY`, `EIA_API_KEY` | All free tier |
+| **Tracking** | `WINGBITS_API_KEY`, `AISSTREAM_API_KEY` | Free |
+| **Geopolitical** | `ACLED_ACCESS_TOKEN`, `CLOUDFLARE_API_TOKEN`, `NASA_FIRMS_API_KEY` | Free for researchers |
+| **Relay** | `WS_RELAY_URL`, `VITE_WS_RELAY_URL`, `OPENSKY_CLIENT_ID/SECRET` | Self-hosted |
+| **UI** | `VITE_VARIANT`, `VITE_MAP_INTERACTION_MODE` (`flat` or `3d`, default `3d`) | N/A |
+| **Observability** | `VITE_SENTRY_DSN` (optional, empty disables reporting) | N/A |
+
+See [`.env.example`](./.env.example) for the complete list with registration links.
+
+---
+
+## Self-Hosting
-The dashboard fetches data from various public APIs:
+World Monitor relies on **60+ Vercel Edge Functions** in the `api/` directory for RSS proxying, data caching, and API key isolation. Running `npm run dev` alone starts only the Vite frontend — the edge functions won't execute, and most panels (news feeds, markets, AI summaries) will be empty.
-| Service | Data |
-|---------|------|
-| RSS2JSON | News feed parsing |
-| Alpha Vantage | Stock quotes |
-| CoinGecko | Cryptocurrency prices |
-| USGS | Earthquake data |
-| NWS | Weather alerts |
-| FRED | Economic indicators |
-| Polymarket | Prediction markets |
+### Option 1: Deploy to Vercel (Recommended)
-## Project Structure
+The simplest path — Vercel runs the edge functions natively on their free tier:
+```bash
+npm install -g vercel
+vercel # Follow prompts to link/create project
```
-src/
-├── App.ts # Main application orchestrator
-├── main.ts # Entry point
-├── components/ # UI components
-│ ├── Map.ts # D3 map with all layers
-│ ├── MapPopup.ts # Info popups for map elements
-│ ├── SearchModal.ts # Universal search (⌘K)
-│ ├── SignalModal.ts # Signal intelligence display
-│ ├── NewsPanel.ts # News feed display
-│ ├── MarketPanel.ts # Stock/commodity display
-│ ├── MonitorPanel.ts # Custom keyword monitors
-│ └── ...
-├── config/ # Static data & configuration
-│ ├── feeds.ts # RSS feeds, source tiers, source types
-│ ├── geo.ts # Hotspots, conflicts, bases, cables
-│ ├── pipelines.ts # Pipeline data (88 entries)
-│ ├── ai-datacenters.ts
-│ ├── irradiators.ts
-│ └── markets.ts
-├── services/ # Data fetching & processing
-│ ├── rss.ts # RSS parsing
-│ ├── markets.ts # Stock/crypto APIs
-│ ├── earthquakes.ts # USGS integration
-│ ├── clustering.ts # Jaccard similarity clustering
-│ ├── correlation.ts # Signal detection engine
-│ ├── velocity.ts # Velocity & sentiment analysis
-│ └── storage.ts # IndexedDB snapshots & baselines
-├── styles/ # CSS
-└── types/ # TypeScript definitions
+
+Add your API keys in the Vercel dashboard under **Settings → Environment Variables**, then visit your deployment URL. The free Hobby plan supports all 60+ edge functions.
+
+### Option 2: Local Development with Vercel CLI
+
+To run everything locally (frontend + edge functions):
+
+```bash
+npm install -g vercel
+cp .env.example .env.local # Add your API keys
+vercel dev # Starts on http://localhost:3000
```
-## Usage
+> **Important**: Use `vercel dev` instead of `npm run dev`. The Vercel CLI emulates the edge runtime locally so all `api/` endpoints work. Plain `npm run dev` only starts Vite and the API layer won't be available.
-### Keyboard Shortcuts
-- `⌘K` / `Ctrl+K` - Open search
-- `↑↓` - Navigate search results
-- `Enter` - Select result
-- `Esc` - Close modals
+### Option 3: Static Frontend Only
-### Map Controls
-- **Scroll** - Zoom in/out
-- **Drag** - Pan the map
-- **Click markers** - Show detailed popup
-- **Layer toggles** - Show/hide data layers
+If you only want the map and client-side features (no news feeds, no AI, no market data):
-### Panel Management
-- **Drag panels** - Reorder layout
-- **Settings (⚙)** - Toggle panel visibility
+```bash
+npm run dev # Vite dev server on http://localhost:5173
+```
+
+This runs the frontend without the API layer. Panels that require server-side proxying will show "No data available". The interactive map, static data layers (bases, cables, pipelines), and browser-side ML models still work.
+
+### Platform Notes
+
+| Platform | Status | Notes |
+|----------|--------|-------|
+| **Vercel** | Full support | Recommended deployment target |
+| **Linux x86_64** | Works with `vercel dev` | Full local development |
+| **macOS** | Works with `vercel dev` | Full local development |
+| **Raspberry Pi / ARM** | Partial | `vercel dev` edge runtime emulation may not work on ARM. Use Option 1 (deploy to Vercel) or Option 3 (static frontend) instead |
+| **Docker** | Planned | See [Roadmap](#roadmap) |
+
+### Railway Relay (Optional)
+
+For live AIS vessel tracking and OpenSky aircraft data, deploy the WebSocket relay on Railway:
+
+```bash
+# On Railway, deploy with:
+node scripts/ais-relay.cjs
+```
+
+Set `WS_RELAY_URL` (server-side, HTTPS) and `VITE_WS_RELAY_URL` (client-side, WSS) in your environment. Without the relay, AIS and OpenSky layers won't show live data, but all other features work normally.
+
+---
+
+## Tech Stack
+
+| Category | Technologies |
+|----------|--------------|
+| **Frontend** | TypeScript, Vite, deck.gl (WebGL 3D globe), MapLibre GL, vite-plugin-pwa (service worker + manifest) |
+| **Desktop** | Tauri 2 (Rust) with Node.js sidecar, OS keychain integration (keyring crate), native TLS (reqwest) |
+| **AI/ML** | Groq (Llama 3.1 8B), OpenRouter (fallback), Transformers.js (browser-side T5, NER, embeddings) |
+| **Caching** | Redis (Upstash) — 3-tier cache with in-memory + Redis + upstream, cross-user AI deduplication. Vercel CDN (s-maxage). Service worker (Workbox) |
+| **Geopolitical APIs** | OpenSky, GDELT, ACLED, UCDP, HAPI, USGS, GDACS, NASA EONET, NASA FIRMS, Polymarket, Cloudflare Radar, WorldPop |
+| **Market APIs** | Yahoo Finance (equities, forex, crypto), CoinGecko (stablecoins), mempool.space (BTC hashrate), alternative.me (Fear & Greed) |
+| **Threat Intel APIs** | abuse.ch (Feodo Tracker, URLhaus), AlienVault OTX, AbuseIPDB, C2IntelFeeds |
+| **Economic APIs** | FRED (Federal Reserve), EIA (Energy), Finnhub (stock quotes) |
+| **Deployment** | Vercel Edge Functions (60+ endpoints) + Railway (WebSocket relay) + Tauri (desktop) + PWA (installable) |
+| **Finance Data** | 92 stock exchanges, 19 financial centers, 13 central banks, 10 commodity hubs, 64 Gulf FDI investments |
+| **Data** | 150+ RSS feeds, ADS-B transponders, AIS maritime data, VIIRS satellite imagery, 8 live YouTube streams |
+
+---
+
+---
+
+## Contributing
-## Data Sources
+Contributions welcome! See [CONTRIBUTING](./docs/DOCUMENTATION.md#contributing) for guidelines.
-### News Feeds
-Aggregates 40+ RSS feeds from major news outlets, government sources, and specialty publications with source-tier prioritization.
+```bash
+# Development
+npm run dev # Full variant (worldmonitor.app)
+npm run dev:tech # Tech variant (tech.worldmonitor.app)
+npm run dev:finance # Finance variant (finance.worldmonitor.app)
+
+# Production builds
+npm run build:full # Build full variant
+npm run build:tech # Build tech variant
+npm run build:finance # Build finance variant
+
+# Quality
+npm run typecheck # TypeScript type checking
+
+# Desktop packaging
+npm run desktop:package:macos:full # .app + .dmg (World Monitor)
+npm run desktop:package:macos:tech # .app + .dmg (Tech Monitor)
+npm run desktop:package:macos:finance # .app + .dmg (Finance Monitor)
+npm run desktop:package:windows:full # .exe + .msi (World Monitor)
+npm run desktop:package:windows:tech # .exe + .msi (Tech Monitor)
+npm run desktop:package:windows:finance # .exe + .msi (Finance Monitor)
+
+# Generic packaging runner
+npm run desktop:package -- --os macos --variant full
+
+# Signed packaging (same targets, requires signing env vars)
+npm run desktop:package:macos:full:sign
+npm run desktop:package:windows:full:sign
+```
-### Geospatial Data
-- **Hotspots**: 25+ global intelligence hotspots with keyword correlation
-- **Conflicts**: Active conflict zones with involved parties
-- **Pipelines**: 88 operating oil/gas pipelines across all continents
-- **Military Bases**: Major global installations
-- **Nuclear**: Power plants, research reactors, irradiator facilities
+Desktop release details, signing hooks, variant outputs, and clean-machine validation checklist:
-### Live APIs
-- USGS earthquake feed (M4.5+ global)
-- National Weather Service alerts
-- Internet outage monitoring
-- Cryptocurrency prices (real-time)
+- [docs/RELEASE_PACKAGING.md](./docs/RELEASE_PACKAGING.md)
---
-## Design Philosophy
+## Roadmap
+
+- [x] 60+ API edge functions for programmatic access
+- [x] Tri-variant system (geopolitical + tech + finance)
+- [x] Market intelligence (macro signals, ETF flows, stablecoin peg monitoring)
+- [x] Railway relay for WebSocket and blocked-domain proxying
+- [x] CORS origin allowlist and security hardening
+- [x] Native desktop application (Tauri) with OS keychain + authenticated sidecar
+- [x] Progressive Web App with offline map support and installability
+- [x] Bandwidth optimization (CDN caching, gzip relay, staggered polling)
+- [x] 3D WebGL globe visualization (deck.gl)
+- [x] Natural disaster monitoring (USGS + GDACS + NASA EONET)
+- [x] Historical playback via IndexedDB snapshots
+- [x] Live YouTube stream detection with desktop embed bridge
+- [x] Country brief pages with AI-generated intelligence dossiers
+- [x] Local-first country detection (browser-side ray-casting, no network dependency)
+- [x] Climate anomaly monitoring (15 conflict-prone zones)
+- [x] Displacement tracking (UNHCR/HAPI origins & hosts)
+- [x] Country brief export (JSON, CSV, PNG, PDF)
+- [x] Cyber threat intelligence layer (Feodo Tracker, URLhaus, OTX, AbuseIPDB, C2IntelFeeds)
+- [x] Trending keyword spike detection with baseline anomaly alerting
+- [x] Oil & energy analytics (EIA: WTI, Brent, production, inventory)
+- [x] Population exposure estimation (WorldPop density data)
+- [x] Country search in Cmd+K with direct brief navigation
+- [x] Entity index with cross-source correlation and confidence scoring
+- [x] Finance variant with 92 stock exchanges, 19 financial centers, 13 central banks, and commodity hubs
+- [x] Gulf FDI investment database (64 Saudi/UAE infrastructure investments mapped globally)
+- [x] AIS maritime chokepoint detection and vessel density grid
+- [x] Runtime feature toggles for 14 data sources
+- [x] Panel height resizing with persistent layout state
+- [ ] Mobile-optimized views
+- [ ] Push notifications for critical alerts
+- [ ] Self-hosted Docker image
+
+See [full roadmap](./docs/DOCUMENTATION.md#roadmap).
-**Information density over aesthetics.** Every pixel should convey signal. The dark interface minimizes eye strain during extended monitoring sessions.
+---
-**Authority matters.** Not all sources are equal. Wire services and official government channels are prioritized over aggregators and blogs.
+## Support the Project
-**Correlation over accumulation.** Raw news feeds are noise. The value is in clustering related stories, detecting velocity changes, and identifying cross-source patterns.
+If you find World Monitor useful:
-**Local-first.** No accounts, no cloud sync. All preferences and history stored locally. The only network traffic is fetching public data.
+- **Star this repo** to help others discover it
+- **Share** with colleagues interested in OSINT
+- **Contribute** code, data sources, or documentation
+- **Report issues** to help improve the platform
---
## License
-MIT
+GNU Affero General Public License v3.0 (AGPL-3.0) — see [LICENSE](LICENSE) for details.
+
+---
## Author
-**Elie Habib**
+**Elie Habib** — [GitHub](https://github.com/koala73)
---
-*Built for situational awareness and open-source intelligence gathering.*
+