PROJECT SENTRY
PROJECT SENTRY / DOCS / 07_web_frontend_architecture.md

Project SENTRY: Web Frontend Architecture & Jamstack Workstation

1. Monorepo Architecture & Technology Stack

Project SENTRY adopts a decoupled monorepo architecture where the public analytical workstation resides in web/ while the private econometric and spatial downscaling engines reside in src/. The static presentation layer is completely isolated from the backend Python execution environment, compiling via Astro v5 and Vite into zero-server-cost, pre-rendered static HTML, CSS, JavaScript, and sanitized JSON contracts.

sentry/
├── docs/                        # Technical documentation suite
│   ├── 01_architecture_and_methodology.md
│   ├── 02_data_dictionary_and_sources.md
│   └── ... [5 more chapters: 03–07]
├── src/                         # Econometric & spatial core
│   ├── models/                  # DFM, ElasticNet, MIDAS, Spatial
│   ├── pipelines/               # Nowcasting & telemetry
│   └── ... [2 more packages: features, sentry]
└── web/                         # Jamstack web platform
    ├── public/                  # Static assets & JSON data contracts
    │   ├── data/                # Multi-horizon data contracts
    │   └── ... [2 more folders: scripts, fonts]
    ├── src/                     # Workstation UI & React islands
    │   ├── components/          # ECharts & analytical visualizers
    │   ├── pages/               # Workstation & docs routes
    │   └── ... [2 more folders: data, layouts]
    ├── astro.config.mjs         # SSG build configuration
    ├── package.json             # Workspace dependencies
    └── ... [2 more configuration files]

2. The Open Core Contract & Data Sanitization Policy

To guarantee mathematical integrity while ensuring zero exposure of proprietary scraper code, internal directory structures, or infrastructure credentials, Project SENTRY enforces a strict data isolation barrier:

  1. Client Isolation: The web workstation fetches exclusively pre-computed, static JSON payloads hosted under web/public/data/. The client runtime makes zero database queries, evaluates no serverless functions, and executes no dynamic server code.
  2. Deterministic Sanitization: The nowcasting pipeline (src/pipelines/run_nowcast.py) evaluates all outgoing string fields against regular expression filters (_PRIVATE_PATH_RE), stripping absolute Windows/Unix filesystem paths (C:\WORKSPACE\..., /home/...), internal tokens, and raw API secrets.
  3. Aggregated Analytical Bounds: Data contracts publish only aggregated regional and provincial growth projections, 95% conformal prediction intervals ([y^L,y^U][\hat{y}_L, \hat{y}_U]), directional probabilities, and row-normalized spatial weights.

Static JSON Contract Manifest

File Name Typical Size Record Scope Description
summary_metrics.json ~0.5 KB 1 summary record National real GDP projection, weighted growth, spatial ρ\rho, and maximum conservation residual (106\le 10^{-6}).
provincial_ppa_latest.json ~61 KB 117–135 jurisdictions Provincial Product Accounts (PPA) with baseline, reconciled levels, growth, conformal intervals, and cluster classifications.
spatial_spillovers.json ~8 KB 18 regions Administrative regions with baseline GRDP, nowcast growth, domestic demand components, and spatial transmission spillovers.
ragged_edge_convergence.json ~1.2 KB 4 countdown horizons 90-day countdown intervals (T90dT0dT-90\text{d} \to T-0\text{d}), displaying information accumulation and interval compression.
model_scorecards.json ~8 KB 4 constituent models Out-of-sample empirical metrics (MAE, RMSE, directional accuracy, 95% coverage, Diebold-Mariano statistics).
spatial_gravity_matrix.json ~9.6 KB 18×18 flow matrix Row-normalized Commodity Flow Survey (CFS) trade matrix WCFSW_{\text{CFS}} (α=0.65\alpha^* = 0.65) and bilateral maritime corridors.
pipeline_status.json ~2.7 KB 6 tracked series Real-time release poller status, publication lags (Δt\Delta t), automated retraining signals, and CI telemetry logs.

3. Dual Workstation Operating Modes

Project SENTRY caters to both executive decision-makers requiring high-level synthesis and technical econometricians conducting granular empirical audits.

3.1 LITE Mode (Policymaker & Executive View)

  • High-Density Macro KPIs: Real GDP projection, primary economic growth engine, spatial coupling coefficient (ρ\rho), and exact Stone's hierarchy conservation status.
  • Regional Economic Growth Grid: 18-region card matrix with dynamic growth badges (>6.5%> 6.5%, 5.56.5%5.5\text{–}6.5%, <5.5%< 5.5%) and interactive selection updating the regional policy briefing.
  • Regional Policy Briefing: Contextual breakdown of supply-chain transmission spillovers (+4.91 pp+4.91\text{ pp} via maritime corridors) and domestic demand resilience (+2.59 pp+2.59\text{ pp} within tight conformal bounds).
  • Embedded Sub-National Hierarchical Accounts (135 Jurisdictions):
    • Fully integrated within the LITE interface without requiring mode switching.
    • Interactive search bar filtering across all provinces and Highly Urbanized Cities (HUCs).
    • Cluster classification filter (Urban, Industrial, Agricultural).
    • Clean pagination displaying reconciled PPA levels, nowcast growth, and exact regional additivity.
    • 10-Column Data Grid Architecture: Minimum table width (1,150px1,150\text{px}) with border-separate border-spacing-0 and whitespace-nowrap guarantees unclipped presentation across all viewports.
    • React Portal Tooltip System (TooltipInfo.tsx):
      • Mounts directly to document.body via createPortal, completely bypassing parent overflow-x-auto scrolling containers and Chromium table layout stacking context restrictions.
      • Employs coordinate measuring with horizontal viewport boundary clamping (Math.max(12, Math.min(window.innerWidth - 272, left))) to prevent off-screen overflow.
      • Intercepts and stops click event propagation (e.stopPropagation()), preventing tooltip interaction from inadvertently toggling TanStack table column sort handlers.
      • Provides descriptive econometric and administrative definitions across all 10 columns (Jurisdiction, Region, Cluster, Predicted Level, PSA Benchmark, Residual Error, YoY Growth, 95% Conformal Bound, Residual ϵ\epsilon, Directional Probability).

3.2 POWER USER Mode (Econometric Terminal)

The Power User terminal exposes 7 specialized client-side React islands:

  1. MacroTerminal: Macroeconomic KPI matrix, conformal fan chart, and regional growth distribution.
  2. SimplexWeightTuner: Real-time quadratic programming weight adjustment (wk0,wk=1.0w_k \ge 0, \sum w_k = 1.0) recalculating nowcasts live across all 18 administrative regions.
  3. ConstituentInspector: Deep econometric evaluation across DFM, ElasticNet, LightGBM, and MIDAS models with Diebold-Mariano test statistics and feature attributions.
  4. SpatialGravityMap: Interactive SVG spatial network displaying inter-island bilateral commodity flows (WCFSW_{\text{CFS}}) and cross-regional spillover corridors.
  5. RaggedEdgeStepper: Information arrival simulator demonstrating how missing data diminishes from 94.2% to 0% and predictive intervals compress monotonically by 88.5% over the 90-day countdown.
  6. FanChart: High-resolution distribution-free Split Conformal Prediction interval visualizer (80% and 95% coverage bands).
  7. TelemetryView: Live pipeline monitoring dashboard displaying statistical vintage freshness, execution latencies, model drift metrics, and GitHub Actions telemetry.

4. Multi-Horizon Time Horizon Architecture & Live Nowcast Integration

4.1 Macroeconomic Horizon Taxonomies

Project SENTRY operationalizes five distinct annual horizons spanning benchmarked historical evaluations through unobserved forward nowcasts:

Horizon Vintage Classification Ground Truth Status Residual Tracking Econometric Role
2026 Active Live Nowcast Unobserved (PSA Apr 2027) UNOBSERVED (Inactive) Pure forward nowcast assimilating real-time high-frequency indicators, satellite radiance, and spatial spillovers.
2025 Preliminary Benchmark Preliminary PPA Accounts Active (y^y\widehat{y} - y
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z"/>y) Benchmarked out-of-sample evaluation against preliminary regional and provincial releases.
2024 Verified Benchmark Official PSA Verified Accounts Active (y^y\widehat{y} - y
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z"/>y) Authoritative baseline accounts with exact Stone linear balance and Denton disaggregation (ϵ106\epsilon \le 10^{-6}).
2023 Historical Baseline Official PSA Verified Accounts Active (y^y\widehat{y} - y
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z"/>y) Post-pandemic monetary tightening evaluation window under BSP rate hike cycle.
2022 Historical Baseline Official PSA Verified Accounts Active (y^y\widehat{y} - y
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z"/>y) Post-lockdown economic recovery baseline and regional convergence validation.

4.2 Hierarchical Data Contract Layout

To ensure scalable, version-controlled multi-horizon execution, data contracts are partitioned into vintage-specific subdirectories under web/public/data/, with a root index contract and backwards-compatible symlinks/mirrors:

web/public/data/
├── vintages_index.json             # Manifest catalog & active horizon
├── 2026/                           # Active Live Nowcast (default)
│   ├── summary_metrics.json
│   ├── provincial_ppa_latest.json
│   └── ... [4 more contracts: spillovers, ragged-edge, scorecards, gravity]
├── 2025/                           # 2025 Preliminary benchmarked vintage
├── 2024/                           # 2024 Verified baseline vintage
├── 2023/                           # 2023 Historical baseline vintage
├── 2022/                           # 2022 Historical recovery vintage
└── *.json                          # Mirrored root files for legacy clients

vintages_index.json

{
  "default_vintage": "2026",
  "available_vintages": ["2022", "2023", "2024", "2025", "2026"],
  "vintage_metadata": {
    "2026": { "type": "live_nowcast", "ground_truth": "unobserved", "release_date": "2027-04" },
    "2025": { "type": "preliminary", "ground_truth": "preliminary_ppa", "release_date": "2026-04" },
    "2024": { "type": "verified_benchmark", "ground_truth": "verified_ppa", "release_date": "2025-04" },
    "2023": { "type": "historical_benchmark", "ground_truth": "verified_ppa", "release_date": "2024-04" },
    "2022": { "type": "historical_benchmark", "ground_truth": "verified_ppa", "release_date": "2023-04" }
  },
  "exported_at": "2026-09-19T17:17:37.105973+00:00"
}

4.3 Client-Side Reactive State Machine & Caching

The workstation coordinates multi-horizon state dynamically across React islands and the Astro layout shell:

  1. Default Horizon Resolution: On initial client hydration, WorkstationContainer.tsx queries /data/vintages_index.json to extract default_vintage (defaulting to 2026), subsequently hydrating all 6 contracts from /data/${default_vintage}/.
  2. Zero-Latency In-Memory Cache (cacheRef): To prevent network overhead or UI jitter when switching between horizons, previously loaded vintage bundles (VintageBundle) are memoized in an in-memory cache ref (Record<number, VintageBundle>). Subsequent toggles execute synchronously in 0 ms0\text{ ms}.
  3. Cross-Island Event Bus (horizon-change): Horizon switching dispatches a decoupled window-level CustomEvent('horizon-change', { detail: { year, label } }). The Astro layout header (Layout.astro) listens to this event to update the persistent top navigation badge (#header-horizon) without requiring parent React wrapper re-renders.
  4. Conditional Presentation Logic:
    • When Horizon = 2026 (Live Nowcast):
      • Prominent warning banners render in both LiteOverview.tsx and MacroTerminal.tsx.
      • Data table renders amber badge PENDING PSA RELEASE (APR 2027) for Ground Truth.
      • Residual column displays UNOBSERVED.
      • Non-parametric conformal intervals and directional expansion probabilities (P(Δy>0)=1.0P(\Delta y > 0) = 1.0) remain fully operational.
    • When Horizon ∈ {2022, 2023, 2024, 2025} (Historical Benchmarks):
      • Data table renders realized PSA output levels.
      • Residual column displays exact signed error (y^y\widehat{y} - y) and percentage discrepancy with color-coded precision thresholds (1.5%\le 1.5%).

5. KaTeX Mathematical Typography & Interactive Clipboard Export

To bridge the gap between academic econometrics and interactive software, Project SENTRY embeds formatted mathematical equations directly into its modal specification sheets (SpotlightModal.tsx and powerUserSheets.ts):

  • In-Situ KaTeX Rendering: Mathematical operators, state-space equations, Lagrangian disaggregation objectives, and conformal interval formulations are rendered via katex.renderToString().
  • Interactive "Copy LaTeX" Button: Every specification sheet features a one-click copy button that copies the raw LaTeX source code to the user's clipboard, providing visual confirmation ("Copied!") for seamless inclusion in academic papers and policy reports.
% Example: Lagrangian Denton Disaggregation Specification
\min_{p} \sum_{t} \left( \frac{p_t}{I_t} - \frac{p_{t-1}}{I_{t-1}} \right)^2 
\quad \text{subject to} \quad 
\sum_{i \in R_r} p_{i, t} = \widehat{\text{GRDP}}_{r, t}, \quad \epsilon \le 10^{-6}

6. Cloudflare Zero Trust Documentation Gating & Security

Project SENTRY applies an enterprise-grade security posture across its static documentation portal:

  • Public Research Chapters: Chapters 01_architecture_and_methodology.md, 02_data_dictionary_and_sources.md, 05_empirical_benchmarks.md, and 07_web_frontend_architecture.md are accessible publicly without authentication.
  • Protected Operational Chapters: Chapters 03_pipeline_and_cli_reference.md, 04_deployment_and_cloud_infrastructure.md, and 06_ci_telemetry_reference.md are locked behind Cloudflare Zero Trust (Cloudflare Access).
  • Edge Access Enforcement: Requests to restricted routes are intercepted by Cloudflare Anycast edge nodes, verifying RS256-signed JWT assertions minted via GitHub OAuth 2.0.
  • Client-Side Spotlight Challenge: In unauthenticated sessions, navigation to locked chapters renders a centered spotlight modal displaying the Cloudflare Zero Trust badge and a Single Sign-On (SSO) button.
  • PII & Credential Sanitization: All personal email addresses and developer credentials have been removed from source code and public documentation, referencing exclusively public profiles (@slcls, contact@slcls.dev).

7. Zero-FOUC Responsive Mobile Viewport Restriction Gate

Due to the extreme analytical density of the financial terminal and spatial flow graphs, viewports smaller than 1024px1024\text{px} are gated at the DOM head before layout evaluation:

<script is:inline>
  (function () {
    var W = window.innerWidth || document.documentElement.clientWidth || 0;
    if (W < 1024) {
      document.documentElement.classList.add('is-mobile');
      document.addEventListener('DOMContentLoaded', function () {
        document.body.innerHTML =
          '<div style="min-height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:1.5rem; text-align:center; font-family:monospace; background-color:#09090b; color:#fafafa;">' +
          '<div style="border:1px solid #27272a; padding:2rem; max-width:28rem; border-radius:0.5rem; background-color:rgba(18,18,20,0.8);">' +
          '<div style="color:#ef4444; font-weight:700; font-size:0.75rem; letter-spacing:0.1em; margin-bottom:1rem;">[DEVICE RESTRICTED]</div>' +
          '<p style="font-size:0.875rem; line-height:1.5; color:#a1a1aa; margin-bottom:1rem;">High-density analytical terminal requires a minimum 1024px viewport width.</p>' +
          '<p style="font-size:0.875rem; line-height:1.5; color:#a1a1aa; margin-bottom:1.5rem;">Mobile and tablet access is restricted by policy. Please access from a desktop workstation.</p>' +
          '<a href="https://slcls.dev/?ref=sentry" style="display:inline-block; padding:0.5rem 1rem; font-size:0.75rem; font-weight:600; color:#0f172a; background-color:#10b981; border-radius:0.25rem; text-decoration:none;">MY PORTFOLIO ↗</a>' +
          '</div></div>';
      });
    } else {
      document.documentElement.classList.add('is-desktop');
    }
  })();
</script>

This inline script executes synchronously before stylesheets or hydration scripts mount, preventing any Flash of Unstyled Content (FOUC) while providing mobile visitors with a clear path to the researcher's primary portfolio.


8. Cloudflare Zero Trust Edge Middleware & Pages Functions (Phase 13)

Phase 13 upgrades the documentation access barrier to a production-grade Cloudflare Zero Trust edge architecture:

8.1 Edge Middleware Architecture (web/functions/docs/_middleware.ts)

Cloudflare Pages intercepts requests destined for protected operational chapters (03_pipeline_and_cli_reference, 04_deployment_and_cloud_infrastructure, 06_ci_telemetry_reference) directly at Cloudflare Anycast edge nodes:

  • Canonical Hostname Redirection: Intercepts traffic on *.pages.dev and issues a 301 Permanent Redirect to https://sentry.slcls.dev, preventing perimeter bypass.
  • Cryptographic RS256 Signature Verification (_auth_utils.ts): Evaluates Cf-Access-Jwt-Assertion or CF_Authorization cookies using the edge Web Crypto API (crypto.subtle.verify). Fetches and caches Cloudflare Access public keys from https://${teamDomain}.cloudflareaccess.com/cdn-cgi/access/certs, verifying signature, aud, and iss.
  • Identity Whitelist Verification: Validates extracted identity against ALLOWED_USERS (slcls) or ALLOWED_EMAILS (contact@slcls.dev).
  • Zero-Leakage Challenge Response: Unauthenticated requests or requests with invalid tokens are terminated immediately with a standalone 401 Zero Trust challenge HTML response. The underlying pre-rendered documentation HTML is never sent over the wire, preventing source code inspection.
  • Downstream Context Passing: For verified requests, sets X-Zero-Trust-Authenticated: true and X-Zero-Trust-Identity: slcls (Administrator) headers on the response.
  • Development Fallback Mode: In local development environments (localhost or missing Access environment variables), gracefully simulates authentication for UI testing.

8.2 Session Discovery Endpoint (web/functions/api/auth/me.ts)

A dedicated edge API endpoint allows client-side components to dynamically probe the active Zero Trust session state:

{
  "authenticated": true,
  "mode": "cloudflare_zero_trust",
  "identity": "slcls (Administrator)",
  "user_uuid": "...",
  "email": "contact@slcls.dev"
}

8.3 Dual-Mode Monorepo Edge Structure

To guarantee seamless deployment regardless of whether the Cloudflare Pages build configuration specifies Root directory: web or Root directory: /:

  • Root Workspace: Root package.json defines "workspaces": ["web"], ensuring dependency resolution succeeds under both paths.
  • Mirrored Edge Proxies: Root-level /functions/ proxies dynamically re-export Edge Functions from web/functions/, allowing Cloudflare Pages to discover middleware and API endpoints from either root.

9. Dynamic Code Splitting & Performance Optimization (Phase 13)

To ensure sub-second initial load times and achieve 60fps rendering, the frontend architecture implements aggressive dynamic code-splitting:

9.1 Dynamic Lazy Component Loading (React.lazy())

Heavy analytical visualizers that are only utilized in POWER USER mode are isolated into asynchronous client chunks wrapped in React.Suspense with an accessible skeleton loading indicator:

  • FanChart.tsx: Distribution-free conformal fan visualizer (~9 kB).
  • SpatialGravityMap.tsx: Bilateral maritime flow network (~11 kB).
  • SimplexWeightTuner.tsx: Quadratic programming weight optimizer (~6.8 kB).
  • RaggedEdgeStepper.tsx: Information arrival simulator (~9.2 kB).
  • ConstituentInspector.tsx: Deep model benchmark inspector (~3.5 kB).

9.2 Vite Vendor Chunking (web/astro.config.mjs)

Rollup output manual chunks isolate third-party dependencies into independent, long-term cached bundles:

  • vendor-echarts: Apache ECharts visualization engine (~560 kB, down from monolithic bundle).
  • vendor-katex: KaTeX mathematical typography renderer (~258 kB).
  • vendor-react: React & React DOM core runtimes (~141 kB).
  • vendor-table: TanStack React Table headless core (~53 kB).

Result: The main workstation container bundle (WorkstationContainer.js) is reduced from 961 kB to 51 kB (a 95% reduction in initial payload footprint), completely eliminating Vite bundle size warnings.


10. Cloudflare Pages Direct Edge Deployment & Security Topology (Phase 13)

Project SENTRY is optimized for zero-cost, serverless edge distribution on Cloudflare Pages ($0/month):

10.1 Cloudflare Pages Configuration (web/wrangler.toml)

name = "sentry"
compatibility_date = "2024-09-20"
compatibility_flags = ["nodejs_compat"]
pages_build_output_dir = "dist"

10.2 Strict Edge Security & Caching Headers (web/public/_headers)

  • Content Security Policy (CSP): Tailored for static Jamstack execution, restricting script, style, and frame execution while explicitly permitting navigation and iframe interaction across slcls.dev, app.slcls.dev, and staging.slcls.dev.
  • Cross-Origin Resource Sharing (CORS): Permits authenticated analytical queries across the slcls.dev domain ecosystem.
  • Immutable Long-Term Caching: Hashed assets under /_astro/* and /scripts/* are cached with Cache-Control: public, max-age=31536000, immutable.
  • Immediate Revalidation: JSON contracts under /data/* and pre-rendered HTML files enforce Cache-Control: public, max-age=0, must-revalidate to ensure real-time statistical updates.

10.3 Function Routing Filter (web/public/_routes.json)

Restricts Pages Edge Function execution strictly to /docs/0[346]* and /api/*, completely bypassing edge worker invocations for static assets, scripts, and pre-computed JSON contracts.

Mathematical typography rendered via KaTeX.
Research paper documentation compiled directly from /docs/.