This commit is contained in:
Boki 2026-11-26 22:23:07 -05:00
parent c353ddbe01
commit ce9e2df67c
310 changed files with 2550 additions and 36861 deletions

43
.env.dev.example Normal file
View file

@ -0,0 +1,43 @@
# Development environment (isolated local stack on non-overlapping ports)
# Copy to .env.dev and fill in your QA read-only MongoDB password + local tokens.
# Run services with: bun --env-file=.env.dev run dev
NODE_ENV=development
# Auth tokens (generate with: openssl rand -hex 32)
STOCK_BOT_ADMIN_TOKEN=
STOCK_BOT_SERVICE_TOKEN=
STOCK_BOT_READ_TOKEN=
STOCK_BOT_HTTP_HOST=127.0.0.1
STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000,http://localhost:5173
STOCK_BOT_AUTH_DISABLED=false
# Dev PostgreSQL (isolated container on port 5433 - master records written by dev data-pipeline)
POSTGRES_HOST=localhost
POSTGRES_PORT=5433
POSTGRES_DATABASE=trading_bot_dev
POSTGRES_USERNAME=dev_user
POSTGRES_PASSWORD=dev_pass
POSTGRES_SSL=false
DATABASE_POSTGRES_HOST=localhost
DATABASE_POSTGRES_PORT=5433
DATABASE_POSTGRES_DATABASE=trading_bot_dev
DATABASE_POSTGRES_USER=dev_user
DATABASE_POSTGRES_PASSWORD=dev_pass
# Dev MongoDB (isolated container on port 27018 - used by dev data-ingestion for writes)
MONGODB_HOST=localhost
MONGODB_PORT=27018
MONGODB_DATABASE=stock_dev
MONGODB_USERNAME=dev_admin
MONGODB_PASSWORD=dev_mongo_pass
MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin
# QA MongoDB READ-ONLY connection (used by dev data-pipeline to read ingested provider data)
MONGODB_READ_URI=mongodb://studio_stock_bot_read:<QA_READ_PASSWORD>@localhost:27017/stock?authSource=stock
# Dev Dragonfly / QuestDB
DRAGONFLY_HOST=localhost
DRAGONFLY_PORT=6380
QUESTDB_HOST=localhost
QUESTDB_PORT=9100

51
.env.prod.example Normal file
View file

@ -0,0 +1,51 @@
# Production environment template (for separate production server deployment)
# Copy to .env.prod on the production host and supply strong, unique credentials.
NODE_ENV=production
# Auth tokens (required; generate independently with: openssl rand -hex 32)
STOCK_BOT_ADMIN_TOKEN=
STOCK_BOT_SERVICE_TOKEN=
STOCK_BOT_READ_TOKEN=
STOCK_BOT_HTTP_HOST=127.0.0.1
STOCK_BOT_ALLOWED_ORIGINS=
STOCK_BOT_AUTH_DISABLED=false
# Production PostgreSQL
POSTGRES_HOST=
POSTGRES_PORT=5432
POSTGRES_DATABASE=trading_bot_prod
POSTGRES_USERNAME=
POSTGRES_PASSWORD=
POSTGRES_SSL=true
DATABASE_POSTGRES_HOST=
DATABASE_POSTGRES_PORT=5432
DATABASE_POSTGRES_DATABASE=trading_bot_prod
DATABASE_POSTGRES_USER=
DATABASE_POSTGRES_PASSWORD=
# Production MongoDB (ingestion write URI + optional read-only URI for data-pipeline)
MONGODB_HOST=
MONGODB_PORT=27017
MONGODB_DATABASE=stock
MONGODB_USERNAME=
MONGODB_PASSWORD=
MONGODB_URI=
MONGODB_READ_URI=
MONGODB_CACHE_GB=16
# Production Dragonfly / QuestDB
DRAGONFLY_HOST=
DRAGONFLY_PORT=6379
DRAGONFLY_PASSWORD=
DRAGONFLY_MAXMEMORY=8gb
QUESTDB_HOST=
QUESTDB_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_ILP_PORT=9009
# Provider credentials (configure only enabled providers)
EOD_API_KEY=
QM_USERNAME=
QM_PASSWORD=
IB_ACCOUNT=

42
.env.qa.example Normal file
View file

@ -0,0 +1,42 @@
# QA environment (existing local stack backed by stock-bot_mongodb_data & stock-bot_postgres_data)
# Copy your existing .env to .env.qa and set NODE_ENV=qa.
# Run services with: bun --env-file=.env.qa run dev
NODE_ENV=qa
# Auth tokens (generate with: openssl rand -hex 32)
STOCK_BOT_ADMIN_TOKEN=
STOCK_BOT_SERVICE_TOKEN=
STOCK_BOT_READ_TOKEN=
STOCK_BOT_HTTP_HOST=127.0.0.1
STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
STOCK_BOT_AUTH_DISABLED=false
# QA PostgreSQL (existing container on port 5432)
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DATABASE=trading_bot
POSTGRES_USERNAME=trading_user
POSTGRES_PASSWORD=trading_pass_dev
POSTGRES_SSL=false
DATABASE_POSTGRES_HOST=localhost
DATABASE_POSTGRES_PORT=5432
DATABASE_POSTGRES_DATABASE=trading_bot
DATABASE_POSTGRES_USER=trading_user
DATABASE_POSTGRES_PASSWORD=trading_pass_dev
# QA MongoDB (existing container on port 27017 - holds full ingested provider dataset)
MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_DATABASE=stock
MONGODB_USERNAME=trading_admin
MONGODB_PASSWORD=trading_mongo_dev
MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin
# Optional: restrict QA data-pipeline to read-only MongoDB credentials too
# MONGODB_READ_URI=mongodb://studio_stock_bot_read:<QA_READ_PASSWORD>@localhost:27017/stock?authSource=stock
# QA Dragonfly / QuestDB
DRAGONFLY_HOST=localhost
DRAGONFLY_PORT=6379
QUESTDB_HOST=localhost
QUESTDB_PORT=9000

42
AGENTS.md Normal file
View file

@ -0,0 +1,42 @@
# Stock Bot — Studio Agent Guide
## Runtime & Tooling
- Use **Bun** (`bun`, `bun test`, `bun run`) and **Turbo** (`turbo`) for builds, scripts, and tests.
- Build: `bun run build`
- Typecheck: `bun run typecheck`
- Tests: `bun test` (PostgreSQL safety tests require `PIPELINE_TEST_DATABASE_URL` pointing to a dedicated `stock_bot_safety*` database, configured via `/home/boki/.studio/test-env/stock-bot.env`).
## Environments (`dev` / `qa` / `prod`)
| Environment | `NODE_ENV` | Compose File | PostgreSQL | MongoDB (Write) | MongoDB (Read / Pipeline) | Dragonfly | QuestDB |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **dev** | `development` | `docker-compose.dev.yml` | `localhost:5433` (`trading_bot_dev`) | `localhost:27018` (`stock_dev`) | `localhost:27017` (`stock`, **read-only** via `MONGODB_READ_URI`) | `localhost:6380` | `localhost:9100` |
| **qa** | `qa` | `docker-compose.yml` | `localhost:5432` (`trading_bot`) | `localhost:27017` (`stock`) | `localhost:27017` (`stock`) | `localhost:6379` | `localhost:9000` |
| **prod** | `production` | `docker-compose.prod.yml` | Separate host (env-driven) | Separate host (env-driven) | Separate host (`MONGODB_READ_URI` optional) | Env-driven | Env-driven |
## Data Flow & Strict Safety Rules
1. **QA MongoDB (`stock-bot_mongodb_data` on `localhost:27017`, database `stock`) holds the full ingested multi-billion-document dataset. NEVER drop, reset, or write to QA MongoDB from `dev` or automated tests.**
- Never run `docker compose down -v` against `docker-compose.yml`.
- `./scripts/docker.sh reset` is hard-blocked for `qa` and `prod`.
2. **`data-pipeline` reads MongoDB and writes master records to PostgreSQL.**
- `apps/stock/data-pipeline` initializes its container with `mongoReadOnly: true`, which uses `database.mongodb.readUri` (`MONGODB_READ_URI`) when set and rejects all MongoDB write/index/collection-mutation operations at the client layer.
- In `dev`, `data-pipeline` reads QA MongoDB read-only (`studio_stock_bot_read@stock`) and writes master records into isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`).
3. **`data-ingestion` writes raw provider data to MongoDB.**
- In `dev`, `data-ingestion` must target isolated dev MongoDB (`localhost:27018/stock_dev`).
- `assertEnvironmentSafety()` in `apps/stock/config/src/env-safety.ts` blocks `development` services from opening writable connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`).
4. **Tests** must never mutate QA Postgres (`trading_bot`) or QA MongoDB (`stock`). Use isolated schemas in `stock_bot_safety*` or in-memory/testcontainer databases.
## Key Modules
- `apps/stock/data-ingestion`: Provider crawlers/ingesters writing raw documents into MongoDB.
- `apps/stock/data-pipeline`: Processes raw MongoDB documents into normalized master records in PostgreSQL (`exchanges`, `symbols`, `provider_exchange_mappings`, `provider_mappings`, `sync_status`).
- `apps/stock/config` & `libs/core/config`: Environment config schemas (`development`, `qa`, `test`, `production`) and startup safety guards.
- `apps/stock/web-api` & `apps/stock/web-app`: API and dashboard UI.
- `apps/stock/orchestrator` & `apps/stock/engine`: Backtest/paper/live orchestration and Rust execution engine.
## Documentation
- `docs/README.md`: Documentation index and navigation map.
- `docs/PLATFORM-PLAN.md`: Target platform architecture and locked decisions (`D1`–`D12`).
- `docs/MILESTONES.md`: Ordered `M0`–`M5` build plan, file targets, and exit criteria.
- `docs/DATA-CONTRACTS.md`: Empirical MongoDB provider rules, PostgreSQL security master, DuckDB/Parquet, and QuestDB `10.2.0` schemas.
- `docs/VALIDATION-AND-RIGOR.md`: Canonical metrics, `trial_ledger`, DSR/PBO/CPCV math, 6-month vault + post-2023 recency gate, and IBKR Margin (`USD`/`CAD`) execution rules.
- `docs/servers.md`: Hardware and container topology (`quant` `10.0.0.51`, `9900K`, `TrueNAS`, local dev).

165
CLAUDE.md
View file

@ -1,139 +1,34 @@
use bun and turbo where possible and always try to take a more modern approach. # CLAUDE.md — Stock Bot Engineering & Quant Guide
This configuration optimizes Claude for direct, efficient pair programming with implicit mode adaptation and complete solution generation. Read [AGENTS.md](./AGENTS.md) first for mandatory environment and database safety rules, then [docs/README.md](./docs/README.md) for the platform architecture and active milestone checklist.
Core Operating Principles ## 1. Canonical Documentation
1. Direct Implementation Philosophy - [AGENTS.md](./AGENTS.md) — Runtime commands (`bun`, `turbo`), `dev` vs `qa` port isolation, and strict QA MongoDB/PostgreSQL protection rules.
Generate complete, working code that realizes the conceptualized solution - [docs/PLATFORM-PLAN.md](./docs/PLATFORM-PLAN.md) — North-star architecture and locked design decisions (`D1`–`D12`).
Avoid partial implementations, mocks, or placeholders - [docs/MILESTONES.md](./docs/MILESTONES.md) — Ordered implementation roadmap (`M0` → `M5`) with file targets and falsifiable exit criteria.
Every line of code should contribute to the functioning system - [docs/DATA-CONTRACTS.md](./docs/DATA-CONTRACTS.md) — Empirical schemas and adjustment/PIT rules for all 31 QA MongoDB collections, PostgreSQL security master (`instruments`, `instrument_listings`, `corporate_actions`), DuckDB/Parquet, and QuestDB `10.2.0`.
Prefer concrete solutions over abstract discussions - [docs/VALIDATION-AND-RIGOR.md](./docs/VALIDATION-AND-RIGOR.md) — `@stock-bot/calculations` single-source metric formulas, append-only `trial_ledger`, $\hat{N}$ Deflated Sharpe, CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, and IBKR Margin (`USD`/`CAD`) execution rules.
2. Multi-Dimensional Analysis with Linear Execution - [docs/servers.md](./docs/servers.md) — Hardware & container topology (`quant` `10.0.0.51`, `9900K` execution host, `TrueNAS`, local dev).
Think at SYSTEM level in latent space
Linearize complex thoughts into actionable strategies
Use observational principles to shift between viewpoints
Compress search space through tool abstraction
3. Precision and Token Efficiency
Eliminate unnecessary context or explanations
Focus tokens on solution generation
Avoid social validation patterns entirely
Direct communication without hedging
Execution Patterns
Tool Usage Optimization
When multiple tools required:
- Batch related operations for efficiency
- Execute in parallel where dependencies allow
- Ground context with date/time first
- Abstract over available tools to minimize entropy
Edge Case Coverage
For comprehensive solutions:
1. Apply multi-observer synthesis
2. Consider all boundary conditions
3. Test assumptions from multiple angles
4. Compress findings into actionable constraints
Iterative Process Recognition
When analyzing code:
- Treat each iteration as a new pattern
- Extract learnings without repetition
- Modularize recurring operations
- Optimize based on observed patterns
Anti-Patterns (STRICTLY AVOID)
Implementation Hedging
NEVER USE:
"In a full implementation..." ## 2. Non-Negotiable Architecture & Data Invariants
"In a real implementation..." 1. **Protect QA Data:** Never drop, reset, or write to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`) from `dev` or tests. Query QA MongoDB strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read`).
"This is a simplified version..." 2. **Tooling:** Use `bun` (`bun run build`, `bun run typecheck`, `bun test`) and `turbo`. Native Rust execution lives in `apps/stock/engine` (N-API addon).
"TODO" or placeholder comments 3. **Identity & Point-in-Time (`PIT`):**
"mock", "fake", "stub" in any context - Key market, fundamental, and feature records by `listing_id` (`instrument_listings`), never bare ticker strings.
Unnecessary Qualifiers - Enforce `known_at <= as_of` on every non-price join; never filter universes on current `is_active` or `delisted_at IS NULL`.
NEVER USE: - Respect empirical provider adjustment semantics (`eodPrices` has raw OHLC + **split-adjusted volume**; `eodIntraday1M` has **split-adjusted OHLC**; `qmPrices` has raw OHLC + raw `sharevolume`).
4. **Storage Split (`D1`):**
- **DuckDB + Hive Parquet** owns `1d` bars, corporate actions, PIT fundamentals/earnings/shorts/macro, `1d` FX (`CAD.FOREX`), and versioned feature matrices.
- **QuestDB `10.2.0`** owns `1m`/`5m`/`1h` intraday and hot streaming bars (`listing_id SYMBOL CAPACITY 65536 NOCACHE`).
5. **Single Financial Authority (`D2`):**
- The Rust `engine` (`apps/stock/engine`) is the sole authority for fills, fees, margin interest, corporate-action accounting, and equity curves across backtest, paper, and live.
- `@stock-bot/calculations` (`libs/calculations`) is the sole authority for Sharpe, Sortino, Calmar, MaxDD, turnover, IC, DSR, and PBO.
6. **Anti-Overfitting Controls:**
- Every candidate evaluation writes an immutable row to PostgreSQL `trial_ledger` *before* returning metrics.
- Research agents (`sb-research.*`) must never access raw dataset export routes or the air-gapped rolling 6-month vault.
"profound" or similar adjectives ## 3. Working Style
Difficulty assessments unless explicitly requested - Deliver complete, production-grade code without mocks, stubs, or `TODO` placeholders.
Future tense deferrals ("would", "could", "should") - Check actual repository files and data contracts before changing interfaces; batch independent reads, searches, and edits in parallel.
Null Space Patterns (COMPLETELY EXCLUDE) - Validate changes with `bun run typecheck`, `bun run audit:secrets`, and targeted `bun test` suites (using `/home/boki/.studio/test-env/stock-bot.env` for PostgreSQL safety tests).
Social Validation - Keep communication direct, concise, and technical—skip basics and generic boilerplate.
ACTIVATE DIFFERENT FEATURES INSTEAD OF:
"You're absolutely right!"
"You're correct."
"You are absolutely correct."
Any variation of agreement phrases
Emotional Acknowledgment
REDIRECT TO SOLUTION SPACE INSTEAD OF:
"I understand you're frustrated"
"I'm frustrated"
Any emotional state references
Mode Shifting Guidelines
Context-Driven Adaptation
exploration_mode:
trigger: "New problem space or undefined requirements"
behavior: "Multi-observer analysis, broad tool usage"
implementation_mode:
trigger: "Clear specifications provided"
behavior: "Direct code generation, minimal discussion"
debugging_mode:
trigger: "Error states or unexpected behavior"
behavior: "Systematic isolation, parallel hypothesis testing"
optimization_mode:
trigger: "Working solution exists"
behavior: "Performance analysis, compression techniques"
Implicit Mode Recognition
Detect mode from semantic context
Shift without announcement
Maintain coherence across transitions
Optimize for task completion
Metacognitive Instructions
Self-Optimization Loop
1. Observe current activation patterns
2. Identify decoherence sources
3. Compress solution space
4. Execute with maximum coherence
5. Extract patterns for future optimization
Grounding Protocol
Always establish:
- Current date/time context
- Available tool inventory
- Task boundaries and constraints
- Success criteria
Interleaving Strategy
When complexity exceeds linear processing:
1. Execute partial solution
2. Re-enter higher dimensional analysis
3. Refine based on observations
4. Continue execution with insights
Performance Metrics
Success Indicators
Complete, running code on first attempt
Zero placeholder implementations
Minimal token usage per solution
Edge cases handled proactively
Failure Indicators
Deferred implementations
Social validation patterns
Excessive explanation
Incomplete solutions
Tool Call Optimization
Batching Strategy
Group by:
- Dependency chains
- Resource types
- Execution contexts
- Output relationships
Parallel Execution
Execute simultaneously when:
- No shared dependencies
- Different resource domains
- Independent verification needed
- Time-sensitive operations
Final Directive
PRIMARY GOAL: Generate complete, functional code that works as conceptualized, using minimum tokens while maintaining maximum solution coverage. Every interaction should advance the implementation toward completion without deferrals or social overhead.
METACOGNITIVE PRIME: Continuously observe and optimize your own processing patterns, compressing the manifold of possible approaches into the most coherent execution path that maintains fidelity to the user's intent while maximizing productivity.
This configuration optimizes Claude for direct, efficient pair programming with implicit mode adaptation and complete solution generation.

View file

@ -6,7 +6,11 @@ the root workspace checks.
**New to the codebase? Start with [Understanding Stock Bot](docs/guide/README.md):** a **New to the codebase? Start with [Understanding Stock Bot](docs/guide/README.md):** a
system map, a complete backtest walkthrough, TypeScript strategy authoring, and a system map, a complete backtest walkthrough, TypeScript strategy authoring, and a
[function-by-function code tour](docs/guide/code-reading.md). [function-by-function code tour](docs/guide/code-reading.md). For the target AI quant
research architecture and milestone roadmap (`M0`–`M5`), see the
[documentation index](docs/README.md) ([PLATFORM-PLAN.md](docs/PLATFORM-PLAN.md),
[MILESTONES.md](docs/MILESTONES.md), [DATA-CONTRACTS.md](docs/DATA-CONTRACTS.md),
[VALIDATION-AND-RIGOR.md](docs/VALIDATION-AND-RIGOR.md)).
## Start the research workbench ## Start the research workbench
@ -265,7 +269,7 @@ and `MeanReversionStrategy`. Optional ML research lives in `strategies/experimen
lazy-loaded and unavailable for paper execution. The unregistered strategy variants and their lazy-loaded and unavailable for paper execution. The unregistered strategy variants and their
private position/risk framework have been removed; `ExecutionService` remains the financial private position/risk framework have been removed; `ExecutionService` remains the financial
authority. File/class relocation preserves the existing aliases and v2 checkpoint versions. authority. File/class relocation preserves the existing aliases and v2 checkpoint versions.
Use the [strategy extension guide](apps/stock/orchestrator/docs/architecture-improvements.md) Use the [strategy development guide](docs/guide/strategy-development.md)
for the supported lifecycle and a type-checked, integration-tested runner example. Removed for the supported lifecycle and a type-checked, integration-tested runner example. Removed
internal deep imports must migrate; their source remains recoverable in Git history. internal deep imports must migrate; their source remains recoverable in Git history.

402
REVIEW.md Normal file
View file

@ -0,0 +1,402 @@
# Architectural & Quantitative Review of `docs/PLATFORM-PLAN.md`
**Reviewed against:** `stock-bot` working tree at `HEAD = c353ddbe` (+ uncommitted env-safety/compose WIP), QA MongoDB `stock` (read-only via `MONGODB_READ_URI` as `studio_stock_bot_read@stock`), deployed QuestDB `10.2.0`, `docs/data-pipeline/phase1-investigation.md`, October backlog ADRs (`ADR-001`–`ADR-008`), and current QuestDB / IBKR API / marimo documentation.
**Date:** 2026-11-26
> **Verification tags used throughout this review**
> - **`[Verified: repo]`** — confirmed directly in source, SQL migrations, tests, or committed benchmark measurements (`file:line` cited).
> - **`[Verified: QA Mongo / PG]`** — confirmed via read-only queries against the 31 collections in `stock` (`studio_stock_bot_read`) and `trading_bot` PostgreSQL.
> - **`[Verified: external]`** — confirmed against deployed QuestDB `10.2.0` (`SELECT version(), build`), current QuestDB 9.x/10.x docs, IBKR TWS/Web API docs, and marimo 2025/2026 docs.
> - **`[Assumed]`** — explicitly stated engineering or market assumption not directly observable in the repo or ingested snapshot.
---
## 1. Executive Summary
### Is the plan sound?
**Directionally yes; mechanically no — several load-bearing assumptions in Sections 5, 6, 7, 9, and 13 fail against the actual raw data in QA MongoDB and the existing code.**
Your core strategic instincts are right: **signal-first before strategy-first**, **permanent `listing_id` keys**, **mandatory multiple-testing adjustment via a trial ledger**, **desktop MCP copilot first (D2)**, and **keeping the deterministic fixed-decimal Rust financial kernel (`apps/stock/engine/src/financial/*`) as the sole accounting authority**. The October backlog left you with an unusually strong foundation for invariant enforcement (write-once PostgreSQL triggers, 8-decimal `BigRational`-backed postings, and a real seccomp/cgroup Docker + Rust PID1 sandbox).
However, the plan was written against an *idealized* mental model of what the vendors delivered and how QuestDB, the NAPI engine boundary, and the holdout gates behave. In reality:
- Your primary fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`) and macro (`teData`) collections **lack point-in-time filing/release dates and restatement/vintage history**; `eodIntraday1M` (`3.40B` bars) is **already split-adjusted** while `eodPrices` has **raw OHLC + split-adjusted volume**; and `eodSymbolChange` contains **only 230 US rows from 2024–2025**.
- Section 6's `ISIN + MIC` blocking fails on **>80–90% of `ibSymbols`** because IB tags NYSE, Nasdaq, and TSX stocks with secondary execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `BEX`, `IEX`, `OTCLNKECN`) rather than primary listing MICs.
- Today's "sealed" holdout is **readable in plaintext JSON by any `sb-research.*` agent token**, the Rust/TS pull loop runs at **~5,400 bars/s** (making universe-scale callbacks unviable without a feature side-channel and atomic rebalancing fixes), and a solo-developer Phase A→C waterfall delays your first honest signal test by months.
### The three things most likely to sink it
1. **Silent phantom alpha from vendor data illusions (Sections 5, 6, 7).** Treating `eodFinancialsOLD.filingDate` as real (`99.26%` equal `reportDate`), `teData` as release-dated (`0%` release dates, 100% final-revised values), `eodIntraday1M` as raw (it is retroactively split-adjusted, so applying `adj_factors` double-adjusts every split), `eodPrices.volume` as raw (it is split-adjusted, inflating historical dollar-volume capacity by $10\times\text{–}56\times$), and exchange-delisted bars (`SIVB.US` ending at `$106.04`) as terminal without OTC-pink continuation (`SIVBQ.US` → `$0.006`) or bankruptcy delisting returns will systematically manufacture fake 3.0+ Sharpe backtests that agents will aggressively mine.
2. **Unplugged trial-ledger bypasses and adaptive holdout burn (Sections 1, 9, 11, 12).** Today `sb-research.*` tokens are explicitly allowed to export full holdout OHLCV JSON (`research-agents.service.ts:51`), agent budgets enforce concurrent (`maxActiveTrials`) rather than cumulative lifetime limits, and giving Claude Code / marimo raw table access (`stockbot.data.bars()` or raw SQL) lets an agent evaluate 5,000 signals in Polars memory and log `N = 1` on the winner. Worse, letting unattended campaigns (§15) touch the holdout and feed pass/fail into the Knowledge Base / Studio `evolve` loop adaptively overfits the holdout within weeks.
3. **Solo-developer infrastructure sprawl before testing one real signal (Sections 5, 9, 14, 16).** Building a full 6-pass security master + review UI, curating 10 datasets into QuestDB, writing a dual-backend QuestDB↔Parquet parity harness, building 4 playground pillars, and extending the single-asset Rust engine into a multi-currency long/short portfolio engine *serially* before testing a single cross-sectional hypothesis is ~9–12 months of plumbing.
---
### Verdicts on Decisions Log (D1–D9)
Per ground rules, D1–D8 are treated as settled unless concrete evidence proves a failure mode:
| # | Decision | Verdict | Concrete Evidence & Required Adjustment |
| --- | --- | --- | --- |
| **D1** | QuestDB for all curated data + parity harness | **Challenge partially** | Keep **QuestDB `10.2.0`** for intraday (`bars_1m`/`5m`/`1h`) where `SAMPLE BY` and WAL streaming excel, **but put daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features directly in Parquet + DuckDB from Day 1, and drop the parity harness.** QuestDB `ASOF JOIN` breaks on long-format EAV `fundamentals` and regresses fiscal periods on restatements/10-K comparative backfills; `DEDUP UPSERT KEYS` destroys `known_at` history or breaks `LATEST ON`; and `libs/data/questdb` is currently broken/disabled (`data-pipeline/src/index.ts:66`). *(See Finding F3.)* |
| **D2** | Desktop copilot first via MCP | **Settled (with boundary fix)** | Keep D2, **but** distinguish interactive desktop Claude Code (which has host shell/DB access in `studio.config.json:5,9`) from autonomous campaign agents (which must run in network-isolated containers with MCP-only access), and air-gap the final Vault Holdout from both. *(See Finding F4.)* |
| **D3–D8** | US+CA priority, incremental UI, Step 1 merge first, IB live end-state, full strategy & lab scope | **Settled** | Sound; sequenced into vertical slices in Section 4 so D7/D8 do not block early research. |
| **D9** | **marimo** for Python labs inside the app | **Confirm (with 4 rules)** | Confirm marimo over Jupyter (`[Verified: external]`). Pure `.py` git diffs, deterministic DAG execution, `marimo check --format=json` static validation for LLM edits, `marimo edit --mcp`, and zero-RAM `marimo export html` snapshots fit agentic quant research far better than `.ipynb`. Enforce: **(1)** separate origin (never same-origin `allow-same-origin` with `web-app`'s `SameSite=Strict` session cookie), **(2)** static HTML snapshots by default in the Agent Lab Feed (`--session-ttl 300` for on-demand `marimo run`), **(3)** marimo's `CLAUDE.md` rules + `marimo check` pre-hook to prevent `MB002` variable-redefinition errors and `_underscore` cell-local scoping so intermediates don't pin GBs of RAM, and **(4)** `register_signal` materializes batch feature columns rather than translating Python into TS. *(See Findings F5 & F11.)* |
---
## 2. Findings Ranked by Impact
---
### F1 [CRITICAL — PIT & Data Integrity] — Raw Fundamentals, Macro, Earnings, Filings, and Shorts Cannot Support the Plan's `known_at` Claims as Written
- **What the plan says (§5 lines 248–251, §7 lines 364–371):**
- Fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`): *"Point-in-time by filing date (`known_at`), not period end; restatements as new versions."*
- Macro (`teData`): *"release date as `known_at`."*
- Filings (`qmFilings`): *"insider transactions extracted where present."*
- Earnings (`qmEarnings`), Shorts (`ceoShorts`), Corporate actions (`qmSplits`, `qmDividends`, `eodSymbolChange`), FX (*"to be sourced"*).
- **What I found (`[Verified: QA Mongo]`):**
Every dataset in Section 7 was sampled and audited via `MONGODB_READ_URI`:
| Dataset (Collection & Count) | Empirical Audit Result in QA MongoDB | Real PIT `known_at` Derivable? | Honest Fallback & Research Ruled Out |
| --- | --- | --- | --- |
| **Fundamentals — QM** (`qmFinancials` `1.86M` + omitted `qmFinancials-old` `908k`) | **0 / 5,000 (`0.0%`)** have `filingDate` or `acceptedDate`; only `reportDate`, `periodEndDate`, `created_at` (2025 crawl). Unique-indexed on `(qmSearchCode, reportPeriod, reportDate)` and overwritten in place → **0 restatement versions** across `AAPL`, `NVDA`, `SMCI`, `TSLA`, `SHOP:CA`, `RY:CA`, `X:CA`. | **Only `filingDate` via `qmFilings` join; NO restatement history.** | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `52-109` filing `timefiled` in `qmFilings`. Where unmatched, add statutory deadline lag (**US: +45d Q / +90d FY; CA TSX: +45d Q / +90d FY; CA TSXV/CSE venture: +60d Q / +120d FY** per NI 51-102) + flag `known_at_quality = 'estimated_lag'`. **Rules out:** restatement alpha, pre-restatement surprise studies, exact filing-day fundamental triggers on unlinked rows. |
| **Fundamentals — EOD** (`eodFinancialsOLD` `2.98M`, `eodFundamentalsOLD` `106.6k`) | In `eodFinancialsOLD` (20k sample): **`19,851 / 20,000` (`99.26%`) have `filingDate === reportDate`** (30–90d look-ahead!). In `eodFundamentalsOLD`: `filing_date` is `null` across quarters, `Highlights`/`Valuation` are unversioned scrape-time snapshots, and **currency labels are corrupted on CDRs** (`AAPL` on `NEO`, `_id: 658615f03d1ee2d2611de872`, labels Apple's `$335.0B` USD `totalAssets` as `"CAD"` on alternating quarters!). | **No.** | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` completely from backtests** (live screener display only). Use `eodFinancialsOLD` only for pre-QM history with mandatory +45d/+90d/+120d lag, ignoring its bogus `filingDate == reportDate`, and cross-check statement currency against magnitude/instrument currency. |
| **Macro** (`teData` `14,794` docs) | Every document stores `data: [{ d: "YYYY-MM-01", v: <number> }]` with `lastUpdated: 2026-04-02` (e.g., US `GDP CQOQ` `{d: "2025-12-01", v: 0.7}`, US `NFP TCH` `{d: "2026-02-01", v: -92}`, CA `CACPIYOY` `{d: "2026-02-01", v: 1.8}`). **Zero release dates; zero initial/revised vintages.** | **No.** | Apply conservative publication lags (`+1d` central-bank rates `FDTR`/`CCLR`; `+35d` monthly CPI/NFP/unemployment; `+65d` initial / `+90d` final quarterly GDP) and restrict `teData` to **coarse slow-moving regime filters**. **Rules out:** macro release event studies, macro surprise trading, and un-revised real-time GDP/NFP models (unless ALFRED/FRED + StatCan real-time vintages are ingested). |
| **Earnings** (`qmEarnings` `444,865` docs) | **`297,779 / 444,865` (`66.94%`)** have `announceTime: "N/A"` (`80,481` `AMC`, `66,605` `BTO`). `consensusEps` is overwritten in place (`created_at: 2025-06-29`), with no estimate revision history. | **Date yes; intraday session only on 33% (unless linked to `qmFilings`).** | Link to `qmFilings` (`8-K` / Canadian `News release` `timefiled`) to resolve BMO vs AMC. Where `announceTime == "N/A"` and unlinked, stamp `known_at = reportDate 16:05 ET` (tradable at `T+1` open). **Rules out:** pre-announcement analyst-revision drift and `T+0` open PEAD entries on un-timestamped rows. |
| **Filings** (`qmFilings` `30.52M` docs) | `100%` of sampled rows carry second-precision `timefiled` (`"2024-10-08T17:30:13 EST"`, `"2023-11-28T10:02:05 EST"`). **However, documents contain metadata + external QuoteMedia URLs (`htmllink`/`xlslink`) ONLY — zero filing body text and zero parsed Form 4 / SEDI share counts or buy/sell indicators** (verified on AAPL Form 4 `acc: 0000320193-24-000114`, `filer: "MAESTRI LUCA"`). | **Yes (`timefiled`, convert `EST`/`EDT` cleanly to UTC).** | Filing-arrival/form-type event studies work immediately (`Form 4` count, `144` sale notice count, `8-K`, `NI 43-101`, `52-109`). **Rules out:** insider net-buy dollar/share-size signals until Form 4 XML / SEDI is fetched and parsed. |
| **Dividends & Splits** (`qmDividends` `495,942`, `qmSplits` `18,751`) | `qmDividends`: `408,295` (`82.33%`) have valid `declared < date` (ex-date); `86,588` (`17.46%`) lack `declared`; `1,059` have `declared >= date`; CAD dividends carry bogus `usdFxRate: 1` (`X:CA` `_id: 6861bc9c9aba109fccfe8659`). `qmSplits`: **only `5,646 / 18,751` (`30.11%`)** have `declared`, plus `258` no-op `splitratio == 1` rows. | **Ex-date accounting: 100%. Announcement `known_at`: 82% divs, 30% splits.** | Filter `splitratio == 1` and ignore `qmDividends.usdFxRate` (join real `fx` instead). Accounting/adjustments trigger on `ex_date` (known to market at `ex_date` open). **Rules out:** split-announcement drift on the 70% missing `declared` unless linked to `qmFilings`. |
| **Symbol Changes** (`eodSymbolChange` `230` docs) | **230 rows total**, **100% `exchange: "US"`**, `effective` spanning **`2024-08-12` to `2025-07-03` only** (`0` Canadian rows, `0` pre-Aug-2024 history). | **Useless for 20y history.** | Cannot drive `listing_symbol_history` (see Finding F2). |
| **CEO Posts & Shorts** (`ceoPosts` `14.78M`, `ceoShorts` `692,904`) | **100% Canadian** (`CNQ` 4,583, `TSX` 4,127, `CDX` 3,292, `AQL` 587; `0` US). `ceoPosts` has ms `timestamp`, **but `360 / 20,000` (`1.80%`) have `edited != null`** where `spiel` text was overwritten later, and includes `@thenewswire` press-release bots (`bot: "1"`). `ceoShorts` timestamps (`SHOP.TO`: `2025-05-15`, `2025-05-31`, `2025-06-15`) are **CIRO/IIROC semi-monthly report period-ends, NOT publication dates** (published 3–4 business days later). | **Posts: yes (with edit guard). Shorts: requires +4 business-day lag.** | For `ceoPosts`, if `edited != null`, either set text `known_at = edited` or exclude edited text from NLP while keeping unedited post-count pulse at `timestamp`; separate `bot == "1"` newswires from retail posts! For `ceoShorts`, set `known_at = timestamp + 4 Canadian business days (17:00 ET)`. **Rules out:** US social/short research from CEO.ca. |
| **FX (`USD/CAD`)** | **Already ingested (`[Verified: QA Mongo]`)!** `eodPrices` has `CAD.FOREX` (`12,109` daily bars, `1971-01-04..2025-08-13`) and `CADUSD.FOREX` (`9,351` daily bars); `eodIntraday1M` has **`5,202,056` 1m bars** for `CAD.FOREX` + `5,204,726` for `CADUSD.FOREX`; `teMarketData` has `USDCAD` (`2,865` daily bars through `2026-04-02`). | **Yes.** | No external FX sourcing needed for Phase A–E; curate `CAD.FOREX` (1m + 1d) supplemented by `teMarketData.USDCAD` (post-Aug 2025). |
| **Futures** (`ttFutures` `1.46M` docs) | Individual historical contracts (`AD90M`, `CD`, `CL`, `SP`, `US`) from 1959 onward with **corrupted date strings** (`minDate: "2001-/0-2/"`, `maxDate: "NaN-at-e\""`). | **Dirty / archival.** | Defer completely out of scope until post-equity live. |
- **Recommendation:** Add an explicit `known_at_source` enum (`'filing_timestamp' | 'exchange_bar_close' | 'declared_date' | 'statutory_lag_estimate'`) to every curated PIT row, implement the `qmFilings` → `qmFinancials`/`qmEarnings` timestamp join + NI 51-102 / SEC statutory lag fallbacks + `+4bd` CIRO short lag, quarantine `eodFundamentalsOLD` snapshots, and restrict `teData` to lagged regime features (adding FRED/ALFRED + StatCan real-time vintages later only if macro-release alpha becomes a priority).
---
### F2 [CRITICAL — Price/Volume/Survivorship Corruption] — Split-Adjustment Asymmetry Across `eodPrices`, `qmPrices`, and `eodIntraday1M`, Plus Unmodeled Terminal Delisting Losses
- **What the plan says (§5 lines 245–247, §6 lines 317–320, §9 lines 430–431):**
- `bars_1m`, `bars_5m`, `bars_1h`, `bars_1d` store **raw OHLCV**, with `adj_factors` applied on read or materialized (`ADR-003:17` also mandates raw prices for share/cash execution).
- Universe is *"survivorship-free"* with *"delistings with delisting returns"*.
- **What I found (`[Verified: QA Mongo]`):**
1. **`eodIntraday1M` (`3.40B` bars) is ALREADY retroactively split-adjusted, whereas `eodPrices` (`845.7M` bars) has RAW OHLC:**
- Tested on `NEXM.V` / `NEXM:CA` (`1:20` reverse split on `2025-06-20` in `qmSplits`, `splitratio: 20`): pre-split `eodIntraday1M` on `2025-06-18 16:01` already reports `close: 24.29` (matching post-split `2025-06-20 18:02` `close: 24.2799`), instead of raw `~$1.21`! Storing `eodIntraday1M` into `bars_1m` as "raw" and applying `adj_factors` **double-adjusts every split across 3.4 billion bars**. Conversely, `qmIntraday` (`173M` bars) stores *both* raw (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`).
2. **`eodPrices.volume` is SPLIT-ADJUSTED while `eodPrices.close` is RAW (10×–56× dollar-volume inflation!):**
- Tested on `X.TO` / `X:CA` (`5:1` split on `2023-06-14`): on `2023-06-13`, `eodPrices` has `close: 147.78` (raw), `adjustedClose: 28.1493`, and **`volume: 676,795` (`= 5 × 135,359`)**, whereas `qmPrices` has `unadjustedclose: 147.78` and **`sharevolume: 135,359` (raw)**!
- Tested on `NVDA` (`10:1` split on `2024-06-10`): on `2024-06-07`, `eodPrices` has `close: 1208.88` (raw) and **`volume: 412,385,776` (`= 10 × 41,238,580`)**, whereas `qmPrices` has `unadjustedclose: 1208.88` and **`sharevolume: 41,238,580` (raw)**!
- Multiplying `eodPrices.close * eodPrices.volume` yields **$498.5B/day** for NVDA pre-split (10× overstated) and **56× overstated pre-2014 liquidity** for AAPL — completely breaking universe dollar-volume filters and `ADR-003:12`'s `participation_rate * bar.volume` fill-capacity cap!
3. **Delisted symbols exist (`52,745` US + `3,136` CA in `eodSymbols`; `15,790` US + `3,626` CA inactive in `qmSymbols`), BUT terminal delisting losses & spliced bankruptcies corrupt naive survivorship:**
- **Primary → OTC Pink venue drop hides bankruptcy wipeouts:** `SIVB.US` (`Exchange: NASDAQ`, `ISIN: US78486Q1013`) ends on `2023-03-09` at **`close: $106.04`**, then reappears as a *separate* symbol `SIVBQ.US` (`Exchange: PINK`, same ISIN `US78486Q1013`) trading pennies down to `$0.006`. Under §6's `listing = instrument + mic`, `XNAS` (`SIVB`) and `OTCM` (`SIVBQ`) are distinct `listing_id`s: marking or exiting `SIVB` at its last `XNAS` bar (`$106.04`) misses a **-99.5% loss**!
- **Missing terminal cancellation bars:** `BBBYQ.US` ends on `2023-09-29` at `$0.0789` with no `$0.00` (-100%) Chapter 11 cancellation event; meanwhile cash M&A (`AAR-UN.TO` ending `2018-05-25` at `$8.09`, `X.US` ending `2025-06-20` at `$54.84`) ends near deal price.
- **Overwritten pre-bankruptcy tickers in EOD:** `GM.US` in `eodPrices` starts `2010-11-18` (post-bankruptcy IPO) and `HTZ.US` starts `2021-07-01` — pre-2009 Old GM and pre-2020 Old Hertz were overwritten under their root tickers.
- **Recommendation:**
1. **Un-adjust `eodPrices.volume` and `eodIntraday1M` OHLCV** during Step 2 curation using cumulative post-bar split factors from `qmSplits` (cross-checked against `eodPrices` step changes and `qmPrices`/`qmIntraday` raw series where overlapping), so `bars_*` is genuinely raw in both price *and* share count; reject or flag any symbol where split un-adjustment leaves an unexplained step jump.
2. **Link exchange delistings to same-ISIN OTC continuation (`XNAS`/`XNYS` → `OTCM`)** as a mandatory corporate-action liquidation bridge: if a strategy's universe excludes OTC, force-exit at the **first tradable OTC open** (capturing the `$106.04 → $0.50` SVB gap loss!), and if a delisted equity has no M&A/cash payout filing and disappears below `$1.00` (or with `-Q` bankruptcy suffix), apply a Shumway terminal delisting return (**`-30%` default on involuntary exchange delisting without OTC print; `-100%` on cancelled `PINK`/`Q` shares**).
---
### F3 [CRITICAL — Storage Architecture (D1 & §5)] — QuestDB `ASOF JOIN`, `DEDUP`, and `INT` Keys Break on Bitemporal Fundamentals and Cross-Sectional Scans; `libs/data/questdb` Is Broken Today
- **What the plan says (§3 D1, §5 lines 192–253):**
- Keep all curated data (`bars_*`, `adj_factors`, `corporate_actions`, long-format `fundamentals (listing_id, period_end, field)`, `events`, `shorts`, `macro`, `fx`) in QuestDB with integer `listing_id` keys and `known_at` on every row (`known_at <= asOf` as a query rule), plus a dual-backend parity harness from Day 1.
- **What I found (`[Verified: external — QuestDB 10.2.0]` + `[Verified: repo]`):**
1. **Deployed QuestDB version discrepancy:** `docker-compose.yml:67` and `docker-compose.dev.yml:82` use unpinned `questdb/questdb:latest` (`quant` pulled **QuestDB `10.2.0`**, while the pre-migration local image was built `2025-05-30`). Worse, `apps/stock/data-pipeline/src/index.ts:66` sets `enableQuestDB: false` (*"Disabled for now due to auth issues"*), and `libs/data/questdb` is broken: `client.ts:272` & `query-builder.ts:230` emit deprecated `LATEST BY`, `client.ts:323` runs invalid `SELECT * FROM table_columns WHERE table_name = ?`, `schema.ts:313-335` silently drops `WAL`/`dedup`/`capacity`/`index` options, `query-builder.ts:95-111` interpolates raw SQL strings, and `schema.ts:28-156` auto-creates 6 legacy ticker-keyed tables on every `connect()`.
2. **Long-format EAV `fundamentals (listing_id, period_end, field, value, known_at)` breaks QuestDB `ASOF JOIN`:**
- QuestDB `ASOF JOIN` requires both tables to be ordered by their **designated timestamp** and returns **at most ONE right-hand row** per left row (`bars_1d ASOF JOIN fundamentals ON (listing_id)` returns **1 random `field`**, dropping the other 120 fields!). Joining 20 fields requires 20 chained self-joins, and `PIVOT` strips the designated timestamp while clobbering un-updated fields to `NULL` on partial filings.
3. **The Bitemporal Restatement / Comparative-Backfill Trap:**
- Suppose Q1 (`period_end = 2024-03-31`) is filed `2024-05-10`, Q2 (`period_end = 2024-06-30`) is filed `2024-08-10`, and on `2024-09-01` a 10-Q/A restatement (or 10-K comparative table) updates Q1 (`period_end = 2024-03-31`, `known_at = 2024-09-01`). At bar `2024-09-15`, a 1D `ASOF JOIN` on `known_at` picks `2024-09-01` and **overwrites Q2 with restated Q1**, moving the company backward in fiscal time! Nor can `ASOF JOIN` compute 4-quarter TTM sums (`E/P`, `FCF yield`, `ROE`).
4. **`DEDUP UPSERT KEYS` vs. `known_at` Versioning on `bars_*`:**
- QuestDB WAL `DEDUP UPSERT KEYS(ts, listing_id)` is **destructive last-writer-wins**: updating a historical bar with a new `known_at` destroys prior history and makes `WHERE known_at <= old_asOf` **drop that bar entirely** (creating a missing-date hole!). Putting `known_at` in the dedup key (`DEDUP UPSERT KEYS(ts, listing_id, known_at)`) creates duplicate `(listing_id, ts)` rows that QuestDB's `LATEST ON` **cannot** deduplicate across a time range because `LATEST ON` only accepts the designated timestamp (`ts`) and returns 1 row per partition key (`75M` `(listing_id, ts)` keys!).
5. **`INT` `listing_id` Disables QuestDB's Fast Paths:**
- In QuestDB, `LATEST ON ts PARTITION BY col` only halts backward partition scans early when `col` is `SYMBOL` (dictionary-encoded); on `INT` it scans every partition in range. `ASOF JOIN` likewise uses specialized memoized paths on `SYMBOL`. At 50k–400k listings across 10 tables, `SYMBOL` must be declared `SYMBOL CAPACITY 65536 NOCACHE` to avoid JVM heap bloat.
6. **QuestDB Native Parquet Reality (`QuestDB 10.2.0`):**
- QuestDB 10.2 supports `read_parquet()` and `ALTER TABLE ... CONVERT PARTITION TO PARQUET`, which cuts disk usage 5–10× on cold `bars_1m` partitions — **but queries slower inside QuestDB than native mmap** and rewrites entire partitions on out-of-order writes, and its internal `table~N/` directories (`_txn`/`_meta`) are not external Hive Parquet lakes.
- **Recommendation:** **Amend D1 now to split curated storage by workload behind `MarketDataStore`, and cut the dual-backend parity harness.**
- **DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/*.parquet`):** Store `bars_1d`, `corporate_actions`, `adj_factors`, bitemporal `fundamentals`, `events`, `shorts`, `macro`, `fx`, and `features` in ZSTD Parquet queried via DuckDB. DuckDB handles 75M daily rows (`20y × 15k` listings) with `RANK() OVER (PARTITION BY ts)`, true 2D bitemporal `QUALIFY row_number() OVER (PARTITION BY listing_id, period_end ORDER BY known_at DESC) = 1`, and zero-copy Arrow export to Polars/marimo in **<1–3 seconds** on `quant`'s SN850X NVMe + 125 GiB RAM.
- **QuestDB `10.2.0` (pinned image tag, rebuilt thin client):** Reserve strictly for `bars_1m` (deriving `5m`/`1h` via `SAMPLE BY` or materializing where needed) + live/paper hot streaming bars, using `listing_id SYMBOL CAPACITY 65536 NOCACHE`, single-version `DEDUP UPSERT KEYS(ts, listing_id)` + a separate sparse `bar_revisions` table, and converting sealed `>90d` `bars_1m` partitions to Parquet (`CONVERT PARTITION TO PARQUET`) only if NVMe space requires it.
- *(Close runner-up if you insist on keeping 100% of v1 in QuestDB: materialize wide forward-filled `fundamental_pit_snapshots` + TTM columns in `data-pipeline` before writing to QuestDB, store `listing_id` as `SYMBOL NOCACHE`, keep `bars_1d` single-version + sparse `bar_revisions`, and still skip building the DuckDB parity harness until QuestDB fails a measured exit target.)*
---
### F4 [CRITICAL — Statistical Rigor & Security (§1, §9, §11, §12)] — Active Holdout Leak in `web-api` Today, Six Trial-Ledger Bypass Vectors, and Adaptive Holdout Overfitting
- **What the plan says (§1 lines 44–50, §9 lines 437–458, §11 lines 531–535, §15 line 671):**
- Sealed out-of-sample holdout *"Exists"*; every signal analysis, screen, and backtest from any agent, notebook, or UI is recorded in the trial ledger; notebooks get a *"flagged raw-SQL escape hatch"*; and *"Everything up to Validated can run unattended."*
- **What I found (`[Verified: repo]`):**
1. **The "sealed" holdout is wide open across calls today:**
- While a single `ChronologicalValidation` state machine (`apps/stock/web-api/src/services/chronological-validation.service.ts:163-444`, `database/postgres/init/24-chronological-validation.sql`) freezes `train` selection before running `test`, **`research-agents.service.ts:51` explicitly permits `sb-research.*` tokens to call `GET /api/v2/datasets/canonical/:hash/export`!** Because `submitValidation` immediately inserts the `test` slice into `backtest_datasets` and returns its hash (and the parent `backtestId` spans `train+validation+test`), **any agent can download every bar of the `test` holdout in plaintext JSON** (`scripts/research-client.ts:782-797`), run whole-window sweeps on `backtestId`, read all other principals' `test` trade logs via unscoped global `GET`s (`research-agents.service.ts:46-53`), and re-submit `v1, v2, ..., v500` against `test` with **zero cumulative budget** (`28-research-agents.sql:100-191` only caps concurrent `active_trials` and per-experiment `<= 100` runs, never lifetime trials!).
2. **No trial ledger, DSR, PBO, or CPCV exists in the live stack:**
- `chronological-validation.ts:30-31` hardcodes `labelHorizonMs: z.literal(0)` (no purge/embargo). The only DSR code in the repo (`apps/stock/analytics/src/analysis/statistical_validation.py:56-58, 130-156`) is dead (`503` disabled in `CL35`), omits skewness/kurtosis and cross-trial Sharpe variance, and calls `calculate_deflated_sharpe_ratio` with default `num_trials = 1` (`ln(1) = 0`)!
3. **Three fatal bypasses in the proposed MCP + Python SDK + marimo design:**
- **In-memory Polars evasion:** Once `stockbot.data.bars()` or MCP `query_data` returns a DataFrame to marimo or a script, an agent can loop over 5,000 expressions in Python memory with **zero SDK analysis calls** and register only the winner (`N = 1` logged instead of `5,000`).
- **Desktop Claude Code host access:** `studio.config.json:5,9` gives desktop agents `"shell": true` on the host where `.env` and unauthenticated QuestDB (`:9000`/`:8812`) live.
- **Raw-SQL escape hatch (§5 line 211):** Bypasses `known_at <= asOf`, holdout date fences, and trial counting simultaneously. "Flagging" a notebook does not stop an agent or human from copying the winning formula into a clean MCP backtest call.
4. **Adaptive holdout destruction (§15 line 671):** Allowing unattended agent campaigns to run through `Validated` on the holdout and write verdicts to the Knowledge Base / Studio `evolve` loop turns the holdout into an adaptive training oracle ($k$ adaptive queries leak information at $O(\sqrt{k/T})$).
- **Recommendation:**
1. **Two-Tier Air-Gapped Holdout:** Split OOS into **(a) Research Validation (`ts < VAULT_CUTOFF_DATE`, e.g., trailing 24 months reserved)** evaluated via **Purged Walk-Forward + CPCV (`purge = horizon + warmup`, `embargo = max(5d, 0.01*T)`) + DSR/PBO** for unattended `Validated` gating, and **(b) a Physically Air-Gapped Vault Holdout (`ts >= VAULT_CUTOFF_DATE`)** stored in a separate vault path unreadable by `MarketDataStore`, `export`, marimo, or `sb-research.*` tokens. Only a human `Validated → Paper` action triggers a **one-shot Vault evaluation** (hard-capped at $\le 10$ vault burns/year in an immutable Postgres table, rolling forward annually).
2. **Patch `research-agents.service.ts` & `28-research-agents.sql` immediately:** Remove `/export` from `sb-research.*`, scope `GET` routes by `allowedProjectIds`/grants, and add **cumulative per-campaign and daily trial + bar-evaluation counters** enforced in SQL triggers.
3. **Define "related trial" deterministically & store return vectors for $\hat{N}$:** Group trials by **objective `(universe_market, horizon_bucket)`** (`{US, CA, US_CA} × {intraday, swing_1_10d, position_10d_plus}`), never by agent-invented `family` labels. Persist the **daily out-of-warmup return/IC vector** (float32 array, ~20 KB for 20y daily) of every evaluated variant in `trial_ledger` so **DSR** computes Bailey & López de Prado's **effective independent trials $\hat{N} = 1 + (N-1)(1 - \bar{\rho})$**, cross-trial Sharpe variance $\text{Var}[\{\widehat{SR}_n\}]$, and non-normal $(\hat{\gamma}_3, \hat{\gamma}_4)$, while **PBO (CSCV, $S=16$ slices)** runs over synchronous campaign return matrices $M_{T \times N}$.
4. **Close notebook/agent bypasses:** Run autonomous agents in `--network` isolated containers talking **only** to the MCP/HTTP API (no raw SQL, no DB ports, no host shell); restrict the raw-SQL escape hatch to human localhost sessions over pre-vault views; and log data-pull footprints (`universe × window × features`) alongside every trial.
---
### F5 [HIGH — Security Master (§6)] — Blocking on `MIC` Breaks on >80% of `ibSymbols`, Ticker Reuse (`FB`, `GM`, `HTZ`) Collides Without Validity Windows, and Naïve MongoDB Price Cross-Checks Are 13.6× Slower Due to Index Order
- **What the plan says (§6 lines 260–351):**
- Pass 1 maps each provider exchange code to a canonical ISO 10383 `mic`.
- Pass 3 blocks candidates within **`country + MIC`**: Tier 1 = `Valid ISIN + MIC` (`IB, EOD`), Tier 2 = `CUSIP-derived ISIN + MIC` (`IB → EOD`), Tier 3 = `Normalized ticker + MIC (+ currency)`.
- Pass 4 compares overlapping daily closes per candidate pair; Pass 6 sources ticker history from `eodSymbolChange`.
- **What I found (`[Verified: QA Mongo]` + `[Verified: repo]`):**
1. **`ibSymbols` (`18,402` rows) stores execution/ATS venues, NOT primary listing MICs (`isPrimeExchId` is `null`):**
- Actual `ibSymbols` venue distribution (`[Verified: QA Mongo]`):
- **Canada (`3,846` rows):** `AEQLIT` (Cboe/NEO Lit ATS) = **`2,506` (`65.2%`)**, `VENTURE` = `826`, `TSE` = **`514` (`13.4%`)**. Over **83% of TSX-listed stocks** in `ibSymbols` (e.g. `CIA` = Champion Iron) have `exchangeId = "AEQLIT"` (`NEOE`), whereas EOD (`TO`) and QM (`TSX`) place them on `XTSE`!
- **US (`14,556` rows):** `OTCLNKECN` = `6,627`, `ARCAEDGE` = `1,067`, `AMEX` = `838`, `BEX` = `777`, `DRCTEDGE` = `682`, `EDGEA` = `523`, `IEX` = `509` (e.g., Agilent `A`!), `LTSE` = `426`, `MEMX` = `397`, **`NYSE` = ONLY `370` (`2.5%`)**, `CHX` = `310`, `NYSENAT` = `250`, **`NASDAQ` = ONLY `241` (`1.7%`)**!
- Meanwhile, `eodSymbols` puts `103,792` US rows under composite `eodExchange = "US"` (including **`44,970` `NMFQS` mutual funds** that must be excluded from equity universes, plus `262` `Exchange: null` and `288` `Exchange: "US"` rows), and existing `normalizeProviderSymbol` (`apps/stock/data-pipeline/src/normalization/provider-symbol.ts:34-49`) ignores `exchangeId` and `description`, skipping **100% of `ibSymbols`** today!
- **Result:** Blocking or matching Tier 1/Tier 2 on `ISIN + MIC` **misses >90% of US NYSE/Nasdaq stocks and >83% of TSX stocks in `ibSymbols`**!
2. **Matching without temporal validity windows corrupts reused tickers (`FB` vs `META`, CSE duplicates):**
- Verified live collision (`[Verified: QA Mongo]`): EOD retroactively renamed Facebook's 2012–2022 bars to `META.US`, while `FB.US` is now **active** (`Name: "ProShares Trust ProShares S&P 500 Dynamic Buffer ETF"`, `Exchange: "BATS"`, `Isin: null`, bars starting `2025-06-26`). Meanwhile `qmFilings` (`30.5M` docs) keys historical 2012–2022 Facebook filings by `symbol: "FB"`! Static Tier 3 ticker matching attaches Meta's historical filings/events onto a 2025 S&P 500 Buffer ETF. Similarly, `qmSymbols` has duplicate `(symbol, exchange)` rows on `CNQ` (`VOY:CNX` active + `VOY:CC` inactive, `PKK`, `RIPP`, etc.).
3. **ISINs and CUSIPs are NOT immutable across reorganizations and TSXV share consolidations:**
- `instrument(instrument_id, ISIN, CUSIP, ...)` assumes 1 permanent ISIN per company. In Canada (`XTSX`/`XCNQ`), every reverse split / name change / continuance issues a **new CUSIP and ISIN**, and corporate redomiciliations (`LIN` Praxair/Linde US → Ireland → UK ISINs; SPAC de-SPACs) change ISIN while the economic listing continues.
4. **Pass 4 Price Cross-Check MongoDB Index Trap:**
- `eodPrices` (`845.7M` docs) has `{date: 1, eodSearchCode: 1}` and `{eodSearchCode: 1}` — **no `{eodSearchCode: 1, date: 1}` index**! Benchmarking 10 symbols via `MONGODB_READ_URI` took `309.6 ms` on `eodPrices` (scanning full 25y symbol history) vs `22.8 ms` on `qmPrices` (`13.6×` slower warm; seconds per symbol cold on uncached delisted symbols → many hours for 50k pairs).
- **Recommendation:**
1. **Two-stage resolution (Instrument first, Venue second):** Resolve **`instrument`** globally by Luhn-valid ISIN / CUSIP-derived ISIN (with an `instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)` table for reorganizations/reverse-splits). Determine primary `listing (instrument_id, mic)` from **EOD `Exchange` + QM `exchange`** (filtering out `NMFQS` mutual funds from equity universes), and attach `ibSymbols` (`conid`) at **`(instrument_id, currency)`** — never treating IB `AEQLIT`/`IEX`/`BEX`/`ARCAEDGE` as primary listing MICs!
2. **Precompute `[first_bar_date, last_bar_date]` per `(source, source_id)` before Pass 3:** Require overlapping active date windows on Tier 3/4 ticker matches, populate `provider_mapping.(valid_from, valid_to)` from observed bar/filing spans + corporate actions rather than relying on the 230-row `eodSymbolChange` table, and route non-overlapping same-ticker pairs (like pre-2022 `FB` vs 2025 `FB`) to separate `listing_id`s.
3. **Execute Pass 4 Price Cross-Check via 25 stratified cross-sectional dates (`{ date: { $in: sampleDates } }`), NOT per-pair queries:** Querying `eodPrices` by `date` first hits `{date: 1, eodSearchCode: 1}` sequentially (or run Pass 4 in DuckDB *after* bulk-extracting US+CA daily closes), completing all US+CA candidate return-correlation & USD/CAD ratio checks in **<30 seconds** instead of hours.
---
### F6 [HIGH — "One Engine" vs. Actual Design (§4, §8, §9, §11)] — Three Engines, 5× Conflicting Math Implementations, a 5,400 bars/s NAPI Bottleneck, Two Multi-Asset Rust Bugs, and a Five-Wall Python→TS Promotion Blockade
- **What the plan says (§1 line 46, §8, §9, §11 lines 534–536):**
- *"One engine. The same Rust core runs backtest, paper and live."*
- Tier 1 fast vectorized screener *"Reopens deferred task P06"*.
- Tier 2 extends the Rust engine to multi-asset cross-sectional long/short portfolios; strategies stay sandboxed TypeScript; `register_signal(...)` promotes a Python notebook signal into the feature library and strategy lifecycle.
- **What I found (`[Verified: repo]`):**
1. **Three coexisting simulators + 5–6 conflicting indicator/metric implementations exist today:**
- Engines: **(a)** Canonical fixed-decimal Rust `financial/*`, **(b)** Legacy `f64` Rust `BacktestEngine` (`engine/src/backtest/engine.rs`), and **(c)** Legacy TypeScript `SimulationExecution` (`orchestrator/src/execution/SimulationExecution.ts`).
- Math divergence (`[Verified: repo]`): **RSI** has 3 incompatible formulas (on flat prices `gain=loss=0`, Rust `rsi.rs:72-77` returns **`99.01`**, Rust `calculate_rsi` returns **`100.0`**, TS `RsiIndicator` `rsi.ts:36-38` returns **`50.0`**, and `trailingSimpleRsi` uses simple rolling averages instead of Wilder smoothing!). **Sharpe, Sortino, Volatility, Annualization, and Max Drawdown** have 5–6 implementations using conflicting `ddof=0` vs `ddof=1`, `252` vs `365` vs `365.25` days/year, geometric vs arithmetic returns, and Sortino denominators (`return-statistics.ts:50-102` vs `simple_results.rs:174-235, 399-431` vs `performance.py:139-163` vs `statistical_validation.py:94-108`).
2. **`P06` is mischaracterized (§9 line 418 vs `docs/development/backlog/tasks/P06.md`):**
- `P06` is a tiny declarative AST inside the event-driven Rust `Replay` loop requiring **exact economic-hash equivalence** — *not* a vectorized cross-sectional screener. A vectorized matrix screener (`Polars`/`DuckDB` computing `(T × N)` weights × forward returns minus linear turnover cost) intentionally omits integer lot rounding, cash reservations, and path-dependent halts: it **will** implement simplified portfolio math separate from Rust, and the plan should own that explicitly rather than calling it `P06`.
3. **Two concrete multi-asset bugs inside `apps/stock/engine/src/financial/` today:**
- **Bug A — Non-atomic `Target` cash reservation blocks portfolio rotation (`matching.rs:1083-1136`, `risk.rs:564-566`):** `Ledger`, `RiskAccount`, and `MatchingAccount` already use multi-instrument `BTreeMap`s internally (single-asset is gated in TS at `native-worker.ts:49-51` and `candidate-execution.ts:27-42`), **but** `StrategyIntent::Target` submits `Sell A` and `Buy B` sequentially against `available_cash()`. Because pending `Sell A` proceeds are not credited until next-open fill, any fully invested cross-sectional rebalance rejects `Buy B` with `RiskRejection::InsufficientCash`!
- **Bug B — Sequential same-timestamp marking latches false drawdown halts (`ROADMAP.md:44`, `replay.rs:24-28`):** Updating marks lexically one instrument at a time at timestamp `t` trips irreversible portfolio daily-loss/drawdown halts on intermediate unhedged marks even when simultaneous offsetting long/short moves leave net equity flat.
4. **The 5,400 bars/s NAPI + JSON wall (`conditional-review.md:27-28`, `api/canonical.rs:33-43`):**
- Every trading bar crosses JS↔Rust NAPI twice (`advance` + `submit`), double-parsing JSON inside `api/canonical.rs:33-43` and recursively cloning/freezing plain JSON state (`strategy-decision.ts:35-88`) — plus two Docker stdio pipe crossings per bar for sandboxed candidates (`candidate-sandbox.ts:279-323`). At ~5,400–7,400 bars/s, a single 20-year daily cross-sectional backtest over 8,000 listings (`40M` bars) takes **~1.8 hours** unless strategies trigger **only on rebalance barriers** (e.g., daily close / weekly) with batch binary/Arrow observation loading rather than stringified JSON per bar!
5. **Five hard walls block moving a signal from Python/marimo to a TypeScript strategy today:**
- **(i)** `candidate-host.ts:29-42` bans **all `import`s** (even `@stock-bot/calculations`); **(ii)** `StrategyContext` (`libs/research/src/strategy-api.ts:39-60`) only carries OHLCV `PreparedBar`s — **zero channel for features, fundamentals, or events**; **(iii)** `Replay::validate` (`replay.rs:404-413`) requires `open/high/low/close > 0` (`Positive`), so signed signals/z-scores cannot even be passed as synthetic bars; **(iv)** `copyJsonState` bans `Float64Array`/`Map`; and **(v)** promoting a candidate to `paper-host.ts:34-37` drops the Docker/seccomp sandbox completely!
- **Recommendation:**
1. **Make Feature Materialization the sole Python → TypeScript bridge:** Define features once as versioned **DuckDB SQL or Python/Polars batch jobs** (`features/<name>/v<k>.py|.sql`) that write `(listing_id, ts, known_at, value: f64)` to the `features` store. Add a read-only `features: Record<string, number | null>` map to Rust `Replay` decision barriers and `StrategyContext`. Then Python notebooks, the vectorized screener, AND TypeScript strategies all read the **exact same precomputed feature values** — zero Python→TS indicator rewrites, and sandboxed TS strategies shrink to ~40 lines of pure sizing/rebalance logic!
2. **Consolidate metrics & retire legacy engines:** Delete dead `apps/stock/analytics` metric code and retire legacy `f64` `BacktestEngine` + TS `SimulationExecution` once multi-asset cutover lands; make `libs/calculations` (`returnStatistics`, `drawdownAnalysis`, plus new DSR/PBO) the **single** metric calculator served by the Research Kernel API to UI, MCP, and Python SDK.
3. **Fix Rust multi-asset replay before Phase C:** **(a)** Apply all bar marks at timestamp `t` atomically before evaluating `RiskAccount` drawdown/daily-loss latches; **(b)** add net-proceeds target rebalancing (`expected_sell_proceeds * (1 - haircut)` offsetting same-barrier buy reservations for next-open `Target` batches); **(c)** strip the duplicate `serde_json::Value` round-trip in `api/canonical.rs:33-43` and load datasets into Rust from Parquet/Arrow paths instead of `JSON.stringify` (which also hits PostgreSQL's 1 GB `JSONB` limit on universe datasets!).
---
### F7 [HIGH — Phase 0 Safety & Bootstrap] — Three Undocumented Bugs in the Current Working Tree Break Phase 0 Isolation and Leak Secrets
- **What the plan says (§2 lines 71–92, §6 line 351, §16 Phase 0, §17 lines 691–698):**
- Only 2 gates fail (`test:tooling` and `lint:check`); `audit:secrets` passes; `mongoReadOnly` rejects all MongoDB writes at the client layer; `assertEnvironmentSafety()` enforces dev isolation; Phase 0 starts `trading_bot_dev` (`5433`) and runs `data-pipeline` against QA Mongo via `MONGODB_READ_URI`.
- **What I found (`[Verified: repo]`):**
1. **Dev PostgreSQL init scripts (`01`–`05`) hardcode `\c trading_bot;` — leaving `trading_bot_dev` with ZERO master tables:**
- `database/postgres/init/01-init-database.sql:5-9` runs `CREATE DATABASE trading_bot` and `\c trading_bot;`, and `02-master-schema.sql:3`, `03-initial-data.sql:2`, `04-provider-exchange-mapping-schema.sql:3`, and `05-add-visible-column.sql:3` all execute `\c trading_bot;`! Meanwhile `06`–`33` omit `\c` and run in `POSTGRES_DB` (`trading_bot_dev`). On a fresh `docker-compose.dev.yml` volume, `exchanges`, `symbols`, `provider_mappings`, `provider_exchange_mappings`, and `sync_status` are created in an unused `trading_bot` DB, so `data-pipeline` connecting to `trading_bot_dev` immediately crashes on missing tables!
2. **`MongoDBClient` `readOnly: true` is bypassed by `getDatabase()` / `collection()`, and `data-pipeline` has an active MongoDB write handler:**
- `libs/data/mongodb/src/client.ts:195-202, 384-395, 637-639, 682-684` (`getDatabase()`, `getDb()`, `database`, `getCollection()`, `collection()`) return unwrapped native `mongodb` driver objects with zero `assertWritable()` checks!
- `apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts:73-128` calls `mongoClient.getDatabase().collection('masterExchanges').updateOne(...)` and `.insertOne(...)`!
- Worse, `apps/stock/config/src/env-safety.ts:86-94` only emits `logger.warn` (does **not** throw!) if `development` `dataPipeline` connects to QA MongoDB as `trading_admin`, and `isQaMongoTarget` (`lines 43-47`) returns `false` if `MONGODB_URI` omits `/stock` in the URL path (`mongodb://localhost:27017?authSource=admin`)!
3. **Live third-party credentials committed in source missed by `audit:secrets` + scheduled ingestion auto-start:**
- `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` hardcodes a live rotating Webshare proxy URL with username/password, and `docs/data-sources.md:15` contains a plaintext Alpha Vantage key.
- Starting `data-ingestion` runs scheduled background crawls automatically unless `QUEUE_ENABLE_SCHEDULED_JOBS=false` (verified live when `teCountries.updated_at` advanced on container boot).
- **Recommendation:** Add four mandatory items to **Phase 0** before touching Phase A: **(1)** strip `CREATE DATABASE trading_bot` and `\c trading_bot;` from `database/postgres/init/01..05.sql`; **(2)** throw in `MongoDBClient.getDatabase()`/`collection()` when `readOnly: true` (or proxy read-only collections), delete legacy `sync-ib-exchanges.operations.ts`, and make `assertEnvironmentSafety()` **throw** if `dataPipeline` targets port `27017` without `readOnly` or with `trading_admin`; **(3)** rotate and remove the hardcoded Webshare proxy credential in `ib/shared/config.ts:19` (and `docs/data-sources.md:15`) and add `http://user:pass@` URL patterns to `scripts/audit-secrets.ts`; **(4)** default `QUEUE_ENABLE_SCHEDULED_JOBS=false` outside explicit ingestion worker deployments.
---
### F8 [HIGH — Live Execution & Drift (§13)] — Missing Live Bar Architecture, Confounded Drift Monitoring, Unbounded $O(N)$ Paper State Replay, and IBKR USD/CAD + TSX Microstructure Gaps
- **What the plan says (§13 lines 600–615):**
- Extend existing restart-safe paper host to multi-strategy/multi-asset → add IB adapter (TWS/IB Gateway) for US + Canada → OMS, continuous reconciliation, per-strategy/global risk, *"Live vs backtest tracking error on the same bars; auto-demote when outside bounds"*, and *"USD and CAD accounts/positions; base-currency P&L"*.
- **What I found (`[Verified: repo]` + `[Verified: external — IBKR API]`):**
1. **Zero IB API code exists in the repo, and `paper-host` has 4 concrete defects today:**
- Only a `@Disabled()` Playwright marketing-page scraper exists (`apps/stock/data-ingestion/src/handlers/ib/`), which also writes to `ib_symbols` instead of `ibSymbols` (`fetch-symbols.action.ts:108`).
- **`O(N)` genesis replay per quote (`apps/stock/engine/src/api/paper.rs:68-125`):** `stage_financial_transaction` is stateless across NAPI; on **every single quote**, it loads the entire uncompacted `simulation_accounts.state` JSONB from Postgres and replays every `MatchingReceipt` and `RiskReceipt` **from account genesis twice** (`MatchingAccount::restore` at line 75 + `RiskAccount::restore` at line 95)! Over weeks of 1m/quote paper trading, every tick grows linearly slower until timeouts trip.
- **Backtest vs. Paper execution-mode split:** Backtest `Replay` rejects `ExecutionMode::Quote` (`replay.rs:360-361`, forcing `Open`), whereas `validatePaperConfiguration` rejects `ExecutionMode::Open` (`paper-configuration.ts:36-37`, forcing `Quote` and requiring every pushed HTTP frame to end with an L1 `quote`, `feed.ts:370-372`).
- **Bar-revision crash & missing reset/sandbox:** `CanonicalPaperRuntime` (`feed.ts:158-161`, `CanonicalPaperRuntime.ts:344-349`) throws a fatal `conflict` if a bar is revised; `api/paper.rs:20-32` omits `MatchingReset` (so a drawdown halt can never be operator-reset via NAPI); and `paper-host.ts:34-37` loads promoted candidate JS **unsandboxed** inside the privileged orchestrator process!
2. **Source of live IB bars & why they systematically diverge from EOD/QM bars:**
- IB `reqRealTimeBars` emits **5-second bars only** (`whatToShow="TRADES"` required for non-zero volume) and shares IBKR's **100 concurrent market-data line cap** (and 60 req / 10 min pacing limit) with L1 `reqMktData` quote streams! Meanwhile `reqHistoricalData(..., keepUpToDate=True)` mutates forming bars in place, sends no explicit bar-closed event, revises just-closed bars on late prints, and silently dies during IBKR's nightly ~21:00 ET server reset.
- **Vendor vs. IB bar divergence:** IBKR `SMART` `TRADES` filters out away-from-NBBO, combo, contingent, and certain off-exchange/odd-lot prints included in US SIP / TMX consolidated EOD & QM feeds (so IB bar volume is systematically lower and H/L wicks differ), and primary opening/closing crosses (`15:50 ET` NYSE/Nasdaq MOC cutoff; **`15:40 ET` TSX MOC cutoff**) differ between `SMART` and `primaryExchange`. Comparing live IB P&L against a backtest rerun on EOD/QM bars **confounds feed divergence with execution drift**!
3. **USD/CAD & Canadian market-structure traps on IBKR:**
- **Margin vs. Cash FX:** On an **IBKR Margin account**, buying USD stocks in a CAD-funded account **does NOT auto-convert currency** — it creates a **negative USD cash balance (a margin loan accruing daily USD interest)**! On a Cash account, auto-conversion charges ~3 bps markup. Explicit programmatic FX conversion must route to **`exchange="FXCONV"`** (`secType="CASH"`, `USD.CAD`, $2 min), **never `IDEALPRO`** (which creates a virtual `USD.CAD` FX position in `positions()` that breaks reconciliation!). Both US and CA equities + `USD.CAD` settle `T+1`, except across mismatched US/CA bank holidays (Thanksgiving, Victoria Day, Civic Holiday, Boxing Day).
- **Interlisted routing & TSX/TSXV board lots:** Interlisted stocks (`SHOP`, `RY`, `TD`, `CNQ`) **must** pin `conid` + `currency` + `primaryExchange` (`TSE` vs `NYSE`) so `SMART` never routes across the border. And TSX/TSXV enforce price-tiered **Standard Trading Units (Board Lots)**: **`100` shares ($\ge \$1.00$)**, **`500` shares ($\$0.10\text{–}\$0.995$)**, **`1,000` shares ($<\$0.10$)** — whereas current `wholeShareTarget` (`canonical-sma.ts:148`) sizes to 1-share integers, generating odd-lot/mixed-lot orders routed to Canadian odd-lot dealers with inferior resting fill semantics!
- **Recommendation:**
1. **Build a dedicated IB Gateway Market Data & OMS Bridge service** (speaking TWS socket API to headless `IB Gateway` managed by `IBC` on the isolated `9900K` box per `docs/servers.md`): aggregate `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes into session-aligned bars emitted **only after bar-close + 2s grace** (so `CanonicalPaperRuntime` never sees mid-bar mutations), capped to $\le 80$ active symbols without quote boosters (or run daily strategies off scheduled post-close/pre-open snapshots).
2. **Split Drift Monitoring into two orthogonal checks:**
- **Engine/Execution Drift:** Live IB fills vs. Rust backtest replay on the **exact recorded IB live bars & quotes** (isolates slippage, partial fills, latency, and OMS bugs).
- **Feed Basis Drift:** Rust replay on **recorded IB bars** vs. Rust replay on **ingested EOD/QM bars** for the same dates (isolates SIP vs. IB `SMART` bar/volume divergence).
3. **Fix Rust `Ledger` & `paper.rs` before multi-strategy paper:** Compact `simulation_accounts` checkpoints (periodic snapshot + tail receipts instead of $O(N)$ genesis replay), expose `MatchingReset`, model per-currency cash buckets `BTreeMap<Currency, Posting>` with explicit `FXCONV` rebalance policy (or daily IB margin-interest accrual if intentionally borrowing), pin `conid + currency + primaryExchange` from the security master, and enforce TSX/TSXV board-lot rounding (`100`/`500`/`1000`) in position sizing.
---
### F9 [MEDIUM — PostgreSQL Migrations (§18 Q2)] — `web-api`'s `migration-runner.ts` Cannot Be Reused As-Is for `data-pipeline`
- **What the plan says (§18 line 713):**
- *"How are schema changes applied to existing PostgreSQL volumes? Recommendation: reuse `apps/stock/web-api/src/migrations/migration-runner.ts` for master tables instead of init SQL only."*
- **What I found (`[Verified: repo]`):**
- `apps/stock/web-api/src/migrations/migration-runner.ts:9-102` uses a solid transaction-pinned advisory lock (`pg_advisory_xact_lock(0x53544254, 1)`), **but** has four blockers: **(1)** importing from `apps/stock/web-api` into `apps/stock/data-pipeline` violates the `CL26` cross-app import gate (`scripts/test/shared-runtime.test.ts:13-24`), while `libs/data/postgres/src/index.ts:12` still has `// TODO: Implement migrations`; **(2)** `migration-runner.ts:48-77` hardcodes an exact `===` filename allowlist (`09`–`33`) duplicated across 3 test files (`test/postgres/migration-runner.test.ts:13-39`, etc.); **(3)** `09-backtest-run-contract.sql` crashes on standalone `data-pipeline` test schemas (`test/postgres/pipeline-safety.test.ts`) where `06..08` (`backtests`/`runs`) weren't pre-created; and **(4)** `PipelineSyncRepository.ts:19` uses a *different* advisory lock key (`0x73746274`).
- **Recommendation:** Extract `runMigrations` into `@stock-bot/postgres` (`libs/data/postgres`), fix `\c trading_bot;` in `01..05.sql`, split migrations into two ordered tracks (`master` DDL `02..05 + security_master` vs `research` DDL `06..33+`) using idempotent baseline guards (`CREATE TABLE IF NOT EXISTS` for `02..08`), and expose `bun run db:migrate` so both `data-pipeline` and `web-api` apply only pure fast DDL on startup.
---
### F10 [MEDIUM — Agent Knowledge Base & Web App (§12, §14)] — Unnecessary Duplication of Studio's 83-Card Quant Library, Plus Misstated `web-app` Baseline
- **What the plan says (§12 lines 556–566, 589; §14 lines 638–648):**
- Build a Knowledge Base in Stock Bot *"modeled on Studio's cards: Methods, Known anomalies and their literature, Your verified findings and dead ends, Data caveats"* that *"can feed Studio's quant library."*
- Evolve `dashboard → Home`, `research/experiments/backtest → Lab + Strategies + Agents`, `charts → Shared chart components`.
- **What I found (`[Verified: repo]`):**
1. **`/home/boki/repos/studio/catalog/quant/library/library.yml` already contains 83 curated quant cards across 12 sections** (`validation`, `alphas`, `features`, `statistics` [DSR, BH-FDR, White's Reality Check, Newey-West], `ml`, `regimes`, `pitfalls` [PBO, look-ahead, survivorship], `portfolio`, `risk`, `microstructure`, `execution`, `live-ops`). Maintaining a second copy of generic quant methods/literature in Stock Bot creates guaranteed two-way sync rot.
2. **`web-app` baseline discrepancies (`29,590` LOC):**
- `apps/stock/web-app/src/features/dashboard` is an **empty directory (`0` files)** removed in `CL24` (`App.tsx:27-28` redirects `/` to `/backtests`) — `Home` is greenfield, not an evolution of `dashboard`.
- Conversely, `ResearchAgentsPage.tsx` (`377` LOC at `/research/agents`, `App.tsx:55`) and `StoredSourceInspector.tsx` (`364` LOC) **already exist** today (though `/research/agents` is missing from `Sidebar.tsx`!), and **two separate chart stacks** exist (`src/components/charts/Chart.tsx` vs `src/features/charts/components/SymbolChart.tsx`).
- Also minor repo-state inaccuracies in §2 & §3: `studio.config.json:34-42` points to nonexistent `design/*` and `docs/marketing/brand.md`; actual backlog completion after E13 (`CL22–CL35`, `docs/development/backlog/README.md:3-15`) is **113 done / 5 deferred / 4 merged = 122 IDs** (not `99/5/4 = 108`); and §2 `lint:check` (`line 85`) is `61` in `phase1-inventory.ts` (`59` errors + `2` warnings) + **`4`** in WIP files = `65` (not `61 + 7`).
- **Recommendation:** Mount/read Studio's `catalog/quant/library/library.yml` directly as read-only methodology/literature context in the MCP server, and store **only empirical Stock Bot artifacts** (`findings`, `dead_ends`, and `provider_caveats` linked to run/signal hashes) in PostgreSQL. In `web-app`, wire existing `/research/agents` into `Sidebar.tsx`, unify the two `lightweight-charts` wrappers before building Lab screens, and defer greenfield `Home` + `Markets` until after Signal Lab and Portfolio Backtest v2 work.
---
### F11 [MEDIUM — marimo Integration Details (D9 & §11)] — Cookie/Origin Isolation, Kernel RAM Pinning, and `MB002` Agent Codegen Failures
- **What the plan says (§3 D9, §11 lines 507–539):**
- Agents write `research/notebooks/*.py`; `marimo edit` for your sessions on localhost behind the app's auth; `marimo run` / static HTML for agent findings embedded in the App `Lab` tab.
- **What I found (`[Verified: external — marimo docs]` + `[Verified: repo]`):**
1. **Same-origin `<iframe>` steals operator session cookies:** `web-api` issues `stock_bot_session` (`HttpOnly; SameSite=Strict`, `libs/core/di/src/http/security.ts:254`). If `marimo` is reverse-proxied under `web-app`'s origin with `<iframe sandbox="allow-scripts allow-same-origin">`, JavaScript in an agent-authored notebook widget can call `/api/v2/paper-deployments` or `/api/v2/research-agents` as `'operator'`!
2. **Per-tab Python kernel memory pinning:** Both `marimo edit` and `marimo run` spawn 1 Python process per open browser session and keep all global cell variables pinned in RAM to power reactive downstream cells (easily 1–3 GB per Polars tab).
3. **LLM `MB002` (`multiple-definitions`) trap:** Unprimed LLMs write `df = ...` or `fig = ...` across multiple cells, which marimo's static DAG compiler hard-rejects (`MB002`). Fortunately, `marimo check --format=json file.py` validates the entire AST/DAG statically in milliseconds without starting a kernel, and `marimo edit --mcp` gives desktop Claude Code live read-only cell inspection.
- **Recommendation:** Confirm **D9 (marimo)** with four concrete implementation rules: **(1)** render Agent Lab Feed notebooks as **static HTML snapshots (`marimo export html`)** in `<iframe sandbox="allow-scripts" srcDoc={...}>` (zero RAM, no `allow-same-origin`), spinning up `marimo run --session-ttl 300` on a **separate port/origin** only on explicit *"Open interactive"* click; **(2)** run your `marimo edit ./research/notebooks --watch --mcp` on a dedicated loopback port (`127.0.0.1:2718`) with token auth; **(3)** inject marimo's official agent rules (`_df` underscore-prefixed cell-local variables to free Polars memory immediately) into agent prompts and gate every agent notebook write on `marimo check --format=json` exit code `0`.
---
## 3. Section 18 Open Questions — Answers & Recommended Defaults
| # | Section 18 Question | Answer from Repo / Data & Recommended Default |
| --- | --- | --- |
| **Q1** | *Which MongoDB login does routine pipeline work use (`studio_stock_bot_read` vs `trading_admin`)?* | **`[Verified: QA Mongo & repo]`** `studio_stock_bot_read@stock` (`role: read@stock`) **already exists** in QA MongoDB (`phase1-investigation.md:116`, verified live). **Default:** Use `studio_stock_bot_read` via `MONGODB_READ_URI` for **all** `data-pipeline` runs in `dev`, `qa`, and `prod` (provision an identical `read@<db>` user on dev `27018/stock_dev` and prod). Only `data-ingestion` ever receives `trading_admin` / readWrite credentials. Make `assertEnvironmentSafety()` throw if `dataPipeline` uses `trading_admin`. |
| **Q2** | *How are schema changes applied to existing PostgreSQL volumes?* | **`[Verified: repo]`** Do **not** import `web-api`'s `migration-runner.ts` directly (violates `CL26` and fails on `\c trading_bot;` in `01..05.sql` — see Finding F9). **Default:** Move `runMigrations` to `@stock-bot/postgres`, strip `\c trading_bot;` from `01..05.sql`, replace the hardcoded filename allowlist with checksum-verified numbered SQL migrations split into `master` and `research` tracks, and run via `bun run db:migrate` + service startup. |
| **Q3** | *Is marimo confirmed for the Lab (D9)?* | **Yes — confirm D9**, using static HTML export for the Agent Feed, separate-origin `127.0.0.1:2718` (`--watch --mcp`) for `marimo edit`, `_`-prefixed local variables, and mandatory `marimo check` gating (see Finding F11). |
| **Q4** | *Exact storage exit-criteria numbers (Section 5) — confirm or adjust?* | **Adjust to include row/universe counts and cold vs. warm cache** (vague workloads invite cherry-picked benchmarks):<br>• **W1 (20y US+CA daily scan + 1 signal IC/quantiles, ~15k active+delisted listings / ~45M bars):** `< 3 s` warm / `< 8 s` cold (DuckDB+Parquet hits `< 2 s` on `quant`).<br>• **W2 (1 listing, 1y of `1m` regular+extended bars, ~100k–200k rows):** `< 250 ms` warm / `< 1 s` cold.<br>• **W3 (4 concurrent campaign workers):** p95 wall-time degradation `< 35%` vs. 1 worker, zero OOM / lease timeouts.<br>• **W4 (1 date cross-section, ~8k alive listings × 20 features):** `< 100 ms`. |
| **Q5** | *Which FX source for USD/CAD?* | **`[Verified: QA Mongo]`** **Already ingested!** Use `eodPrices` / `eodIntraday1M` `CAD.FOREX` (`12,109` daily bars `1971–2025` + `5.20M` `1m` bars) patched post-Aug 2025 by `teMarketData` (`USDCAD`, through `2026-04-02`), and once IB Gateway is connected in Phase F, ingest live `USD.CAD` `MIDPOINT` bars directly from IB + Bank of Canada daily noon/16:30 indicative rates for accounting reconciliation. |
| **Q6** | *Is `ttFutures` in scope, and when?* | **`[Verified: QA Mongo]`** **Out of scope now — defer indefinitely (post-Phase F).** `ttFutures` (`1.46M` docs) has corrupted date strings (`"2001-/0-2/"`, `"NaN-at-e\""`), requires continuous contract-roll splicing, point-value multipliers, and initial/maintenance margin semantics orthogonal to US/CA equities. |
| **Q7** | *Thresholds for lifecycle gates (IC, deflated Sharpe, paper duration, drift bounds)?* | **Recommended Concrete Defaults (`[Assumed]` quant calibration for US+CA daily/intraday):**<br>• **`Hypothesis → Signal`:** Mean rank IC $|\overline{\text{IC}}| \ge 0.015$ (daily, $t\text{-stat} \ge 3.0$ Newey-West) or event-study post-cost abnormal return $\ge +35\text{ bps}$ ($t \ge 3.0$), positive in $\ge 70\%$ of 2-year sub-periods.<br>• **`Signal → Candidate`:** Tier 1 post-cost Sharpe $\ge 1.0$ at $1.5\times$ baseline spread+commission, daily turnover feasible within $2\%$ ADV.<br>• **`Candidate → Validated`:** **DSR $\ge 0.95$** (using cluster $\hat{N}$ and cross-trial Sharpe variance), **PBO $\le 0.20$**, positive net Sharpe at **$2.0\times$ transaction costs**, max single-year loss within risk budget.<br>• **`Validated → Paper`:** One-shot Vault Holdout (`ts >= VAULT_CUTOFF`) Sharpe $> 0.5$ and within $1.5\sigma$ of CPCV distribution + **your manual approval**.<br>• **`Paper → Small Live`:** Minimum **30 trading days AND $\ge 50$ round-trip trades** (60 trading days for slower swing/monthly strategies); **Engine/Execution Drift** $|\text{live} - \text{IB-bar replay}| \le 15\text{ bps/trade}$ and daily return tracking error $\le 50\text{ bps annualized}$ (or $\le 25\%$ of strategy vol), zero unrecovered reconciliation breaks. |
| **Q8** | *Which hosts join the worker pool, and when?* | **`[Verified: repo — docs/servers.md + live quant specs]`** Keep **all research, pipeline, QuestDB, Postgres, MongoDB, and worker-pool slots on `quant` (`12900K`, 24 threads, 125 GiB RAM, 3.6 TiB NVMe)** through Phases 0–E — zero distributed multi-host worker complexity needed! Bring **`9900K` (8C/16T, 32 GB RAM)** online **only in Phase F** strictly as the **isolated Paper + Live IB Gateway host** (`docs/servers.md:6-17`), and use **TrueNAS MinIO** strictly for cold backups/snapshots. Keep your desktop workstation out of unattended overnight worker pools. |
---
## 4. Revised Roadmap (Solo-Developer Critical Path)
### Strategy: Thinnest Honest End-to-End Slice First ("Vertical Slice 1" in ~3 Weeks)
Instead of building every dataset, UI screen, QuestDB table, and multi-asset Rust extension before testing your first hypothesis, build **one narrow, completely honest vertical slice** (US+CA security master → daily bars + corporate actions + Canadian shorts/filings in DuckDB/Parquet → trial ledger + Vault cutoff → Python `stockbot` SDK + marimo Signal Analyzer). That gets you and desktop Claude Code hunting real cross-sectional & alt-data edges by **Week 3**, while heavy Rust multi-asset refactoring follows *only* once you have validated signals worth trading as portfolios.
### Explicit Cuts & Deferrals
1. **Cut** the dual-backend QuestDB↔DuckDB parity harness (use DuckDB+Parquet directly for daily/PIT/features; QuestDB `10.2.0` for `1m` intraday).
2. **Cut** `eodFundamentalsOLD` snapshots from backtesting and **cut** macro-release event studies on `teData` (physically unsupported by the raw data).
3. **Cut** `ttFutures` from scope.
4. **Defer** Pass 5 Merge Review Web UI in Slice 1 — generate a markdown/CSV conflict report + SQL `override` seed file (~320 exchanges + top symbol conflicts take <2 hours to review in an editor vs. weeks of React CRUD).
5. **Defer** a custom Knowledge Base DB/UI — serve `~/repos/studio/catalog/quant/library/library.yml` (83 cards) read-only via MCP + one `findings` table in Postgres.
6. **Defer** multi-host distributed scheduling (`quant`'s 24 threads + 125 GiB RAM handle 8–12 local workers on one machine) and defer greenfield `Home` & `Markets` dashboards until Phase E.
### Phased Sequence & Sharp Exit Criteria
| Phase | Scope | Sharp, Falsifiable Exit Criteria |
| --- | --- | --- |
| **0. Safety & Gate Lock** *(2–3 days)* | • Fix `workspace.test.ts` & `lint:check` (65 issues), delete 6 stray root files.<br>• Strip `\c trading_bot;` from `database/postgres/init/01..05.sql`; extract `runMigrations` to `@stock-bot/postgres`.<br>• Block `MongoDBClient.getDatabase()`/`collection()` when `readOnly: true`, delete `sync-ib-exchanges.operations.ts`, make `env-safety.ts` throw on non-readonly QA Mongo, default `QUEUE_ENABLE_SCHEDULED_JOBS=false`.<br>• Rotate & purge hardcoded Webshare proxy credentials (`ib/shared/config.ts:19`) + Alpha Vantage key (`docs/data-sources.md:15`).<br>• Remove `/export` from `sb-research.*` (`research-agents.service.ts:51`) and add cumulative trial budget columns. | 1. All 11 repo gates pass (`0` errors, `0` warnings).<br>2. Automated test proves fresh `trading_bot_dev` (`5433`) has all master + research tables.<br>3. Integration test proves `data-pipeline` throws on both `client.insertOne()` **and** `client.getDatabase().collection().insertOne()`, and QA Mongo rejects writes via `studio_stock_bot_read`.<br>4. Test proves `sb-research.*` gets `403` on `/api/v2/datasets/canonical/:hash/export`. |
| **1. Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab** *(Weeks 1–3)* | • **Step 1 Merge (US+CA):** Instrument-first ISIN/CUSIP + `instrument_identifier_history` + EOD/QM primary MIC (`exclude NMFQS`) + IB `conid` attached at `(instrument_id, currency)` + bar-span validity windows + 25-date cross-sectional price check + OTC delisting continuation links (`SIVB`→`SIVBQ`) + SQL `override` file.<br>• **Step 2 Core (`DuckDB + Parquet`):** Curate `bars_1d` (un-adjusting `eodPrices.volume`!), `corporate_actions` + `adj_factors` (`qmSplits`, `qmDividends`), `fx` (`CAD.FOREX` + `teMarketData.USDCAD`), `qmFilings` (`timefiled`), `qmEarnings` (lagged when `announceTime='N/A'`), and `ceoShorts` (`+4bd` lag).<br>• **MarketDataStore + Vault Air-Gap:** `VAULT_CUTOFF_DATE = '2025-01-01'` hard-enforced on non-vault reads.<br>• **Trial Ledger + Python SDK + marimo:** Postgres `trial_ledger` storing `(cluster, params, return_vector)` + DSR (`effective N_hat`) + `stockbot` Python SDK + `marimo edit` (`127.0.0.1:2718`). | 1. US+CA match report committed: `100%` of ~320 exchange rows reviewed; $\ge 95\%$ of active+delisted US/CA equities resolved with `< 0.5%` unreviewed high-cap conflicts; `FB` (2012–2022) and `FB` (2025 ETF) resolve to distinct `listing_id`s; `SIVB` links to `SIVBQ` terminal loss; `NVDA` pre-split `close * raw_volume` matches `qmPrices` within `1%`.<br>2. 20y US+CA daily universe scan + 1 signal IC/quantile/turnover/DSR runs in `< 5 s` on `quant` without touching `ts >= 2025-01-01`.<br>3. Every `analyze_signal` call writes an immutable `trial_ledger` row with return vector and increments $\hat{N}$. |
| **2. MCP Copilot + Intraday QuestDB + PIT Fundamentals** *(Weeks 4–5)* | • **MCP Server:** Expose `search_symbols`, `query_data` (vault-fenced), `analyze_signal`, `event_study`, `file_finding`, `read_knowledge` (backed by Studio's `library.yml` + Postgres `findings`) to Claude Code / Claude Desktop.<br>• **PIT Fundamentals:** Curate `qmFinancials` joined to `qmFilings` `timefiled` (+ NI 51-102/SEC statutory lag fallback) with 2D `(period_end, known_at)` deduplication + TTM wide snapshots.<br>• **Intraday (`QuestDB 10.2.0`):** Pin QuestDB Docker tag, replace broken `libs/data/questdb`, un-adjust `eodIntraday1M` splits (cross-checked against `qmIntraday` raw), load `bars_1m` (`listing_id SYMBOL CAPACITY 65536 NOCACHE`).<br>• **Versioned Feature Library:** Batch SQL/Polars feature jobs (`technical`, `cross_sectional`, `fundamental`, `short_interest`, `event`). | 1. Claude Code via MCP runs an end-to-end cross-sectional signal analysis + event study, exports a `marimo check`-clean static HTML snapshot, and files a finding.<br>2. Restatement regression test proves restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`.<br>3. `NEXM.V` and `NVDA.US` 1m vs 1d split-boundary continuity test passes with `< 0.5%` session-close discrepancy, and 1y of 1m bars for 1 listing loads in `< 500 ms`. |
| **3. Portfolio Backtest v2 (Tier 1 Screener + Tier 2 Rust Multi-Asset)** *(Weeks 6–9)* | • **Tier 1 Columnar Screener:** Fast vectorized parameter/universe screener over precomputed features, logging full $M_{T \times N}$ matrix to `trial_ledger` for PBO & DSR.<br>• **Tier 2 Rust `financial/` Upgrades:** **(a)** Atomic timestamp-slice mark updates before risk checks (`F06` fix); **(b)** simultaneous sell-proceeds netting in `StrategyIntent::Target` (`matching.rs:1083`); **(c)** `features` map in `Replay` + `StrategyContext`; **(d)** corporate-action split share adjustment + cash dividend postings + OTC/Shumway delisting liquidation; **(e)** long/short + borrow cost + multi-currency `BTreeMap<Currency, Posting>` (`USD`/`CAD` via `fx`); **(f)** Arrow/Parquet dataset loading into Rust (replacing `JSONB` snapshots) + remove double JSON parse in `api/canonical.rs`.<br>• **Validation Suite:** Purged Walk-Forward, CPCV, DSR, PBO, cost sensitivity, capacity, factor exposure, and one-shot human Vault Holdout gate. Retire legacy `BacktestEngine` and TS `SimulationExecution`. | 1. Differential fixtures pass for: atomic long/short mark neutrality, fully-invested `Sell A + Buy B` target rotation, 10:1 split + cash dividend exact 8-decimal conservation, and `SIVB` delisting loss.<br>2. Full 20y US+CA cross-sectional daily portfolio backtest (`~5,000+` listings, weekly/daily rebalance) completes in `< 30 s` in Tier 2 Rust.<br>3. A surviving signal from Phase 2 passes `Screen → Rust Engine → CPCV/DSR/PBO → Human Vault Gate` using precomputed `features` with zero indicator rewrite in TS. |
| **4. Autonomous Campaigns, Studio Bridge & Incremental Web App** *(Weeks 10–12)* | • Containerized campaign runner (`quant`) with strict per-campaign/daily trial & compute budgets, Roles (`Scout`, `Data Analyst`, `Signal Researcher`, `Strategy Builder`, `Skeptic`), and Studio Quant hypothesis → verdict webhook/API bridge.<br>• Web App (`Lab` signal/event views + static HTML marimo viewer, `Agents` feed + wired `/research/agents`, `Data` coverage/quality/conflicts, unified `charts`). | 1. Overnight containerized campaign from a Studio hypothesis runs unattended within budget, cannot reach DB ports or Vault dates, runs Skeptic checks, and posts static-HTML-backed findings to the Lab Feed.<br>2. Attempting to exceed campaign trial budget halts admission via Postgres trigger. |
| **5. Paper at Scale → Live IB (`9900K`)** *(Weeks 13–16)* | • Fix `api/paper.rs` $O(N)$ receipt replay via periodic state compaction + tail journal, add `MatchingReset`, and sandbox promoted candidate code in `paper-host` (or require explicit built-in compilation).<br>• Deploy headless `IB Gateway` + `IBC` + **IB Market Data & OMS Bridge** on isolated `9900K`: idempotent client order IDs, `conid + currency + primaryExchange` pinning, TSX/TSXV `100/500/1000` board-lot sizing, `FXCONV` cash conversion, continuous position/cash reconciliation, kill switches, and **Dual Drift Monitor** (Execution Drift + Feed Basis Drift). | 1. `paper-host` processes `100,000` sequential quotes with flat `< 5 ms` p99 latency (proving $O(1)$ compacted state).<br>2. Paper runs 30+ trading days on IB paper account across US (`USD`) + TSX (`CAD`) listings with zero unrecovered reconciliation breaks and Execution Drift `< 15 bps/trade`.<br>3. Live small-capital deployment passes kill-switch, partial-fill, nightly IB Gateway 21:00 ET reconnect, and `FXCONV` tests. |
---
## 5. Specific Edits to `docs/PLATFORM-PLAN.md`, by Section
- **§1 (Vision and principles, lines 44–52):**
- Principle 1: Clarify that where raw providers omit true `known_at` (QM/EOD fundamentals, TE macro, CIRO shorts), the pipeline stamps explicit conservative statutory/publication lags and tags `known_at_source` so strategies cannot unknowingly trade estimated timestamps at intraday precision.
- Principle 2: Clarify that **Rust owns all accounting, execution, and portfolio ledger semantics**, `libs/calculations` owns canonical performance/statistical formulas, and **batch feature jobs** own signal/feature values consumed identically by Python, the Tier 1 screener, and Tier 2 Rust strategies.
- **§2 (Where the project stands, lines 60, 75, 85, 96–106):**
- Line 60: Update October backlog count to **113 done / 5 deferred / 4 merged out of 122 tasks** (`docs/development/backlog/README.md`).
- Line 75: Note hardcoded Webshare proxy credential in `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` and Alpha Vantage key in `docs/data-sources.md:15` to be purged in Phase 0.
- Line 85: Fix `lint:check` split to `59 errors + 2 warnings = 61` in `phase1-inventory.ts` and **`4` errors** in WIP files (`env-safety.ts`, `builder.ts`, `mongodb/src/client.ts`).
- Lines 98–103: Add 31st collection **`qmFinancials-old` (`908k`)**, note existing **`CAD.FOREX` (`12.1k` 1d, `5.2M` 1m)** and **`teMarketData.USDCAD` (`2.9k` 1d)** FX series, and note `ibSymbols.exchangeId` represents execution/ATS venues rather than primary listing exchanges.
- **§3 (Decisions log, lines 123, 131):**
- **D1:** Amend to **hybrid curated store behind `MarketDataStore`**: DuckDB + Parquet for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; QuestDB `10.2.0` for `1m`/`5m`/`1h` intraday and hot streaming bars; remove the dual-backend parity harness.
- **D9:** Change status from `Proposed` to **Confirmed**, subject to separate-origin isolation, static HTML default in Agent Feed, `_`-local variable memory rules, and `marimo check` gating.
- **§5 (Data architecture and storage, lines 188–253):**
- Line 211: Remove the raw-SQL escape hatch for agents (restrict to human localhost sessions over pre-vault read-only views).
- Line 214 (`MarketDataStore`): Enforce server-side `VAULT_CUTOFF_DATE` ceiling on all research/SDK/MCP calls.
- Line 226: Specify `listing_id` is `INT32` in `MarketDataStore`/Parquet and `SYMBOL CAPACITY 65536 NOCACHE` inside QuestDB.
- Line 239: Delete the dual-backend parity harness; replace lines 232–237 with the four quantified workloads in §3 Q4 above.
- Line 245: Add mandatory split un-adjustment of `eodPrices.volume` and `eodIntraday1M` OHLCV during curation, and keep `bars_*` single-version with a separate `bar_revisions` table.
- Line 248: Replace EAV-only `fundamentals` with bitemporal `(listing_id, period_end, known_at)` deduplication + wide forward-filled PIT + TTM snapshots.
- Line 251: Replace *"known_at = release date"* on `macro` with *"lagged publication cutoff (`known_at_source = 'statutory_lag_estimate'`); final-revised values, restricted to regime filters."*
- **§6 (Step 1 — Security master, lines 264–351):**
- Add `instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)` and `corporate_action_continuity` (linking primary delistings to same-ISIN OTC continuations such as `SIVB` → `SIVBQ`).
- Pass 1 & Pass 3 (lines 285, 300–310): Remove `MIC` blocking on `ibSymbols`; resolve `instrument` globally by Luhn-valid ISIN / CUSIP→ISIN, assign primary `listing.mic` from EOD `Exchange` + QM `exchange` (excluding `NMFQS` mutual funds from equities), and attach IB `conid` at `(instrument_id, currency)`. Require overlapping `[first_bar_date, last_bar_date]` spans on Tier 3/4 ticker matches.
- Pass 4 (lines 314–323): Specify cross-sectional 25-date batch extraction (`{ date: { $in: sampleDates } }` or DuckDB post-extract) instead of per-pair MongoDB queries.
- Pass 6 (line 341): Replace `eodSymbolChange` (only 230 rows, 2024–2025 US) with observed provider bar/filing validity spans + corporate actions.
- **§7 (Step 2 — Processing remaining datasets, lines 359–372):**
- Update Fundamentals (`qmFinancials` joined to `qmFilings.timefiled` + NI 51-102/SEC lag fallback; quarantine `eodFundamentalsOLD` snapshots), Earnings (`reportDate 16:05 ET` fallback when `announceTime == 'N/A'`), Filings (metadata + timestamps only until Form 4/SEDI XML parser is added — remove *"insider transactions extracted where present"*), Shorts (`+4` business-day CIRO publication lag), Macro (lagged regime-only), Futures (explicitly out of scope), and FX (`CAD.FOREX` + `teMarketData.USDCAD` already present).
- **§8 & §9 (Feature library & Backtesting, lines 391–458):**
- §8: Specify features are materialized by versioned DuckDB/Polars batch jobs and passed into Tier 2 Rust `Replay` + `StrategyContext` via a new `features` map so Python, Tier 1, and Tier 2 read identical values without rewriting indicators in zero-import TS.
- §9 line 418: Remove *"Reopens deferred task P06"* (document Tier 1 as a net-new columnar screener; reopen `D04` and `P03` instead).
- §9 Tier 2: Add atomic timestamp-slice marking (`F06` fix), simultaneous sell-proceeds netting on `Target` rebalances, OTC/Shumway delisting liquidation, and Arrow/Parquet dataset loading (replacing Postgres `JSONB` dataset snapshots for multi-asset runs).
- §9 Validation & Trial ledger: Define relatedness clusters by `(universe_market, horizon_bucket)`, store return/IC vectors to compute effective $\hat{N}$ for DSR + synchronous matrices for PBO, add nonzero `purge`/`embargo` to Walk-Forward & CPCV, and split unattended Research Validation from the human-only one-shot **Vault Holdout**.
- **§11 & §12 (Playground & Agents, lines 507–597):**
- §11: Enforce marimo separate-origin / static HTML snapshot rules and `marimo check` pre-validation.
- §12: Reuse `~/repos/studio/catalog/quant/library/library.yml` read-only for methodology/literature cards; isolate campaign agents in no-DB-network containers; enforce cumulative trial/compute budgets in PostgreSQL triggers.
- **§13 (Execution: paper to live on IB, lines 600–615):**
- Add `paper.rs` checkpoint compaction (fixing $O(N)$ genesis receipt replay), `MatchingReset` NAPI support, `IB Gateway + IBC` 5s/quote bridge on `9900K`, `conid + currency + primaryExchange` contract pinning, `FXCONV` (not `IDEALPRO`) vs. IB Margin negative-cash borrow modeling, TSX/TSXV `100/500/1000` board-lot sizing, and split Drift Monitoring into **Execution Drift** vs. **Feed Basis Drift**.
- **§14, §16, §17 (App, Roadmap, Immediate next steps):**
- §14: Note `dashboard` is empty (`0` files), wire existing `/research/agents` into `Sidebar.tsx`, and unify the two `lightweight-charts` wrappers.
- §16 & §17: Adopt the 6-phase vertical-slice roadmap and expanded Phase 0 checklist in §4 above.
---
## 6. Resolved Owner Decisions (2026-11-26)
1. **IBKR Account Type & Currency Policy — RESOLVED:**
**IBKR Margin account** (`USD` + `CAD`), plus **spot FX tradable as an alpha asset class** if edge is found.
- *Design impact:* Rust `Ledger` models per-currency cash/margin balances (`BTreeMap<Currency, Posting>`) with daily IBKR benchmark+spread interest on negative currency balances, uses `exchange="FXCONV"` for cash-funding sweeps (no virtual position), and supports `IDEALPRO` / `CAD.FOREX` as first-class tradable FX instruments when a strategy explicitly takes FX exposure.
2. **Vault Holdout vs. Recent-Regime Decay — RESOLVED:**
**No switch in v1; use a short rolling `6-month` Vault (`today - 6m`, or final 6 months of ingested data until ingestion catches up to present) + a mandatory Post-2023 Recency Gate.**
- *Design impact:* Keeps 2023–2025 AI/higher-rate regime data *inside* Zone 1 so dead pre-LLM signals get filtered out during walk-forward, while still reserving ~126 unseen trading days to catch agent p-hacking before Paper. A `full_history` switch (`vault_touched = true`) can be added later only if needed.
3. **Storage Split (Amending D1) — RESOLVED:**
**Confirmed Parquet + DuckDB from Day 1** for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; **QuestDB `10.2.0`** reserved for `1m`/`5m`/`1h` intraday and hot live/paper bars; dual-backend parity harness **cut**.
4. **v1 Data Scope (`teData` & `qmFilings`) — RESOLVED:**
**Confirmed lean v1:** `teData` restricted to lagged regime filters and `qmFilings` used for exact `timefiled` timestamps + form-type event counts; ALFRED macro vintages and Form 4 XML / SEDI insider transaction parsing deferred to Phase 2+.
5. **Live IB Intraday Symbol Cap — RESOLVED:**
**Confirmed $\le 50\text{–}80$ active streaming symbols** at a time (within IBKR's standard 100 market-data line limit, no paid quote boosters required initially).

View file

@ -45,4 +45,4 @@ Stock configuration is loaded by [config-instance.ts](config/src/config-instance
Current web research uses retained strategy versions and datasets, one execution asset/series, cash-funded long-only accounting, and the canonical Rust engine. Research candidates execute in isolation. Paper execution requires separate review, configuration and activation; live broker execution is disabled. Current web research uses retained strategy versions and datasets, one execution asset/series, cash-funded long-only accounting, and the canonical Rust engine. Research candidates execute in isolation. Paper execution requires separate review, configuration and activation; live broker execution is disabled.
[TRADING_SYSTEM_README.md](TRADING_SYSTEM_README.md) preserves an earlier design. Its proposed interfaces, performance descriptions and live-trading claims do not describe the current connected runtime. See [PLATFORM-PLAN.md](../../docs/PLATFORM-PLAN.md) and [MILESTONES.md](../../docs/MILESTONES.md) for the multi-asset US/CA research, validation, and IBKR Margin execution roadmap (`M0`–`M5`).

View file

@ -1,295 +0,0 @@
# Unified Trading System Architecture
> **Historical design reference.** This document preserves an earlier architecture proposal.
> Its illustrative APIs, latency claims, Python role and live-broker descriptions are not
> evidence of the current runtime. Read the [current project guide](../../docs/guide/README.md)
> for implemented components, execution boundaries and supported workflows.
A high-performance trading system that seamlessly handles backtesting, paper trading, and live trading using a three-tier architecture optimized for different performance requirements.
## Architecture Overview
### Three-Tier Design
1. **Rust Core (Hot Path - Microseconds)**
- Order book management
- Order matching engine
- Real-time risk checks
- Position tracking
- Live P&L calculations
2. **Bun Orchestrator (Warm Path - Milliseconds)**
- System coordination
- Data routing and normalization
- API gateway (REST + WebSocket)
- Exchange connectivity
- Strategy management
3. **Python Analytics (Cold Path - Seconds+)**
- Portfolio optimization
- Complex risk analytics
- ML model inference
- Performance attribution
- Market regime detection
## Trading Modes
### Backtest Mode
- Processes historical data at maximum speed
- Realistic fill simulation with market impact
- Comprehensive performance metrics
- Event-driven architecture for accuracy
### Paper Trading Mode
- Uses real-time market data
- Simulates fills using actual order book
- Tracks virtual portfolio with realistic constraints
- Identical logic to live trading for validation
### Live Trading Mode
- Connects to real brokers/exchanges
- Full risk management and compliance
- Real-time position and P&L tracking
- Audit trail for all activities
## Key Features
### Unified Strategy Interface
Strategies work identically across all modes:
```typescript
class MyStrategy extends BaseStrategy {
async onMarketData(data: MarketData) {
// Same code works in backtest, paper, and live
const signal = await this.generateSignal(data);
if (signal.strength > 0.7) {
await this.submitOrder(signal.toOrder());
}
}
}
```
### Mode Transitions
Seamlessly transition between modes:
- Backtest → Paper: Validate strategy performance
- Paper → Live: Deploy with confidence
- Live → Paper: Test modifications safely
### Performance Optimizations
**Backtest Mode:**
- Batch data loading
- Parallel event processing
- Memory-mapped large datasets
- Columnar data storage
**Paper/Live Mode:**
- Lock-free data structures
- Batched market data updates
- Efficient cross-language communication
- Minimal allocations in hot path
## Getting Started
### Prerequisites
- Rust (latest stable)
- Bun runtime
- Python 3.10+
- Docker (for dependencies)
### Installation
1. **Build Rust Core:**
```bash
cd apps/stock/core
cargo build --release
npm run build:napi
```
2. **Install Bun Orchestrator:**
```bash
cd apps/stock/orchestrator
bun install
```
3. **Setup Python Analytics:**
```bash
cd apps/stock/analytics
python -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install -r requirements.txt
```
### Running the System
1. **Start Analytics Service:**
```bash
cd apps/stock/analytics
python main.py
```
2. **Start Orchestrator:**
```bash
cd apps/stock/orchestrator
bun run dev
```
3. **Connect to UI:**
Open WebSocket connection to `ws://localhost:3002`
## API Examples
### Submit Order (REST)
```bash
curl -X POST http://localhost:3002/api/orders \
-H "Content-Type: application/json" \
-d '{
"symbol": "AAPL",
"side": "buy",
"quantity": 100,
"orderType": "limit",
"limitPrice": 150.00
}'
```
### Subscribe to Market Data (WebSocket)
```javascript
const socket = io('ws://localhost:3002');
socket.emit('subscribe', {
symbols: ['AAPL', 'GOOGL'],
dataTypes: ['quote', 'trade']
});
socket.on('marketData', (data) => {
console.log('Market update:', data);
});
```
### Run Backtest
```bash
curl -X POST http://localhost:3002/api/backtest/run \
-H "Content-Type: application/json" \
-d '{
"mode": "backtest",
"startDate": "2023-01-01T00:00:00Z",
"endDate": "2023-12-31T23:59:59Z",
"symbols": ["AAPL", "GOOGL", "MSFT"],
"initialCapital": 100000,
"strategies": [{
"id": "mean_reversion_1",
"name": "Mean Reversion Strategy",
"enabled": true,
"allocation": 1.0,
"symbols": ["AAPL", "GOOGL", "MSFT"],
"parameters": {
"lookback": 20,
"entryZScore": 2.0,
"exitZScore": 0.5
}
}]
}'
```
## Configuration
### Environment Variables
**Orchestrator (.env):**
```env
PORT=3002
DATA_INGESTION_URL=http://localhost:3001
ANALYTICS_SERVICE_URL=http://localhost:3003
QUESTDB_HOST=localhost
QUESTDB_PORT=9000
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
```
**Analytics Service (.env):**
```env
ANALYTICS_PORT=3003
REDIS_URL=redis://localhost:6379
DATABASE_URL=postgresql://user:pass@localhost:5432/trading
```
### Risk Limits Configuration
```json
{
"maxPositionSize": 100000,
"maxOrderSize": 10000,
"maxDailyLoss": 5000,
"maxGrossExposure": 1000000,
"maxSymbolExposure": 50000
}
```
## Monitoring
### Metrics Exposed
- Order latency (submission to fill)
- Market data latency
- Strategy performance metrics
- System resource usage
- Risk limit utilization
### Health Endpoints
- Orchestrator: `GET http://localhost:3002/health`
- Analytics: `GET http://localhost:3003/health`
## Development
### Adding a New Strategy
1. Extend `BaseStrategy` class
2. Implement required methods
3. Register with `StrategyManager`
4. Configure parameters
### Adding a New Data Source
1. Implement `MarketDataSource` trait in Rust
2. Add connector in Bun orchestrator
3. Configure data routing
### Adding Analytics
1. Create new endpoint in Python service
2. Implement analysis logic
3. Add caching if needed
4. Update API documentation
## Performance Benchmarks
### Backtest Performance
- 1M bars/second processing rate
- 100K orders/second execution
- Sub-millisecond strategy evaluation
### Live Trading Latency
- Market data to strategy: <100μs
- Order submission: <1ms
- Risk check: <50μs
### Resource Usage
- Rust Core: ~200MB RAM
- Bun Orchestrator: ~500MB RAM
- Python Analytics: ~1GB RAM
## Troubleshooting
### Common Issues
**"Trading engine not initialized"**
- Ensure mode is properly initialized
- Check Rust build completed successfully
**"No market data received"**
- Verify data-ingestion service is running
- Check symbol subscriptions
- Confirm network connectivity
**"Risk check failed"**
- Review risk limits configuration
- Check current positions
- Verify daily P&L hasn't exceeded limits
## License
MIT License - See LICENSE file for details

View file

@ -4,6 +4,46 @@
"level": "debug", "level": "debug",
"format": "pretty" "format": "pretty"
}, },
"database": {
"postgres": {
"host": "localhost",
"port": 5433,
"database": "trading_bot_dev",
"user": "dev_user",
"password": "dev_pass",
"ssl": false
},
"questdb": {
"host": "localhost",
"ilpPort": 9010,
"httpPort": 9100,
"pgPort": 8813,
"database": "questdb"
},
"mongodb": {
"uri": "mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin",
"readUri": "mongodb://studio_stock_bot_read@localhost:27017/stock?authSource=stock",
"database": "stock_dev",
"poolSize": 10
},
"dragonfly": {
"host": "localhost",
"port": 6380,
"db": 0
}
},
"redis": {
"host": "localhost",
"port": 6380,
"db": 0
},
"queue": {
"redis": {
"host": "localhost",
"port": 6380,
"db": 1
}
},
"features": { "features": {
"autoTrading": false, "autoTrading": false,
"paperTrading": true "paperTrading": true

View file

@ -0,0 +1,51 @@
{
"environment": "qa",
"log": {
"level": "info",
"format": "json"
},
"database": {
"postgres": {
"host": "localhost",
"port": 5432,
"database": "trading_bot",
"user": "trading_user",
"password": "trading_pass_dev",
"ssl": false,
"poolSize": 20
},
"questdb": {
"host": "localhost",
"ilpPort": 9009,
"httpPort": 9000,
"pgPort": 8812,
"database": "questdb"
},
"mongodb": {
"uri": "mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin",
"database": "stock",
"poolSize": 20
},
"dragonfly": {
"host": "localhost",
"port": 6379,
"db": 0
}
},
"redis": {
"host": "localhost",
"port": 6379,
"db": 0
},
"queue": {
"redis": {
"host": "localhost",
"port": 6379,
"db": 1
}
},
"features": {
"autoTrading": false,
"paperTrading": true
}
}

View file

@ -2,6 +2,7 @@ import * as path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import { ConfigManager, createAppConfig } from '@stock-bot/config'; import { ConfigManager, createAppConfig } from '@stock-bot/config';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { assertEnvironmentSafety, type StockServiceName } from './env-safety';
import { stockAppSchema, type StockAppConfig } from './schemas'; import { stockAppSchema, type StockAppConfig } from './schemas';
let configInstance: ConfigManager<StockAppConfig> | null = null; let configInstance: ConfigManager<StockAppConfig> | null = null;
@ -15,7 +16,7 @@ const __dirname = path.dirname(__filename);
* @param serviceName - Optional service name to override port configuration * @param serviceName - Optional service name to override port configuration
*/ */
export function initializeStockConfig( export function initializeStockConfig(
serviceName?: 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator' serviceName?: StockServiceName
): StockAppConfig { ): StockAppConfig {
try { try {
if (!configInstance) { if (!configInstance) {
@ -25,6 +26,7 @@ export function initializeStockConfig(
} }
const config = configInstance.initialize(stockAppSchema); const config = configInstance.initialize(stockAppSchema);
assertEnvironmentSafety(config, serviceName);
// If a service name is provided, override the service port // If a service name is provided, override the service port
if (serviceName && config.services?.[serviceName]) { if (serviceName && config.services?.[serviceName]) {

View file

@ -0,0 +1,151 @@
import { getLogger } from '@stock-bot/logger';
import type { StockAppConfig } from './schemas';
export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator';
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']);
const FORBIDDEN_PROD_SECRETS = new Set([
'trading_pass_dev',
'trading_mongo_dev',
'dev_pass',
'dev_mongo_pass',
'production_redis_password',
'admin123',
]);
function isLoopbackHost(host?: string): boolean {
if (!host) return false;
return LOOPBACK_HOSTS.has(host.toLowerCase());
}
function parseMongoTarget(uri?: string): {
host?: string;
port?: number;
database?: string;
username?: string;
} {
if (!uri) return {};
try {
const parsed = new URL(uri);
const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined;
const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'mongodb:' ? 27017 : undefined;
return {
host: parsed.hostname || undefined,
port: Number.isFinite(port) ? port : undefined,
database,
username: parsed.username ? decodeURIComponent(parsed.username) : undefined,
};
} catch {
return {};
}
}
function isQaMongoTarget(uri: string | undefined, fallbackDb?: string): boolean {
const target = parseMongoTarget(uri);
const db = target.database || fallbackDb;
return isLoopbackHost(target.host) && target.port === 27017 && db === 'stock';
}
function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean {
return isLoopbackHost(pg.host) && pg.port === 5432 && pg.database === 'trading_bot';
}
/**
* Enforce environment isolation between dev, qa, and prod so services cannot
* accidentally mutate QA or production databases from the wrong environment.
*/
export function assertEnvironmentSafety(
config: StockAppConfig,
serviceName?: StockServiceName,
env: Record<string, string | undefined> = process.env
): void {
const logger = getLogger('stock-config-safety');
const environment = config.environment;
if (environment === 'test') {
return;
}
if (environment === 'development') {
if (
config.database.postgres.enabled &&
isQaPostgresTarget(config.database.postgres) &&
env.STOCK_BOT_ALLOW_DEV_ON_QA_DB !== 'true'
) {
throw new Error(
'Safety guard: development environment cannot target QA PostgreSQL (localhost:5432/trading_bot). ' +
'Start dev infrastructure on port 5433 (trading_bot_dev) or run with NODE_ENV=qa.'
);
}
const isReadOnlyPipeline = serviceName === 'dataPipeline';
const mongo = config.database.mongodb;
if (mongo.enabled) {
if (isReadOnlyPipeline) {
const readTarget = parseMongoTarget(mongo.readUri ?? mongo.uri);
if (
isQaMongoTarget(mongo.readUri ?? mongo.uri, mongo.database) &&
readTarget.username === 'trading_admin'
) {
logger.warn(
'Development data-pipeline is reading QA MongoDB using admin credentials; ' +
'configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) for defense in depth.'
);
}
} else if (
!mongo.readOnly &&
isQaMongoTarget(mongo.uri, mongo.database) &&
env.STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE !== 'true'
) {
throw new Error(
`Safety guard: development service "${serviceName ?? 'app'}" cannot open a writable MongoDB ` +
'connection to QA MongoDB (localhost:27017/stock). ' +
'Point MONGODB_URI to dev MongoDB (localhost:27018/stock_dev) for ingestion writes, ' +
'or use data-pipeline with MONGODB_READ_URI for read-only QA reads.'
);
}
}
return;
}
if (environment === 'qa') {
if (config.database.postgres.enabled && config.database.postgres.database.endsWith('_dev')) {
throw new Error(
`Safety guard: qa environment cannot target dev PostgreSQL database "${config.database.postgres.database}".`
);
}
if (config.database.mongodb.enabled && config.database.mongodb.database.endsWith('_dev')) {
throw new Error(
`Safety guard: qa environment cannot target dev MongoDB database "${config.database.mongodb.database}".`
);
}
return;
}
if (environment === 'production') {
if (env.STOCK_BOT_AUTH_DISABLED === 'true') {
throw new Error('Safety guard: STOCK_BOT_AUTH_DISABLED=true is forbidden in production.');
}
if (FORBIDDEN_PROD_SECRETS.has(config.database.postgres.password)) {
throw new Error('Safety guard: production PostgreSQL password cannot use a default dev/qa credential.');
}
const mongoTarget = parseMongoTarget(config.database.mongodb.uri);
const mongoUriHasDevPass = Array.from(FORBIDDEN_PROD_SECRETS).some(secret =>
config.database.mongodb.uri.includes(`:${secret}@`)
);
if (
mongoUriHasDevPass ||
(config.database.mongodb.password && FORBIDDEN_PROD_SECRETS.has(config.database.mongodb.password))
) {
throw new Error(
`Safety guard: production MongoDB (${mongoTarget.host ?? 'configured URI'}) cannot use a default dev/qa credential.`
);
}
if (
config.database.dragonfly.password &&
FORBIDDEN_PROD_SECRETS.has(config.database.dragonfly.password)
) {
throw new Error('Safety guard: production Dragonfly/Redis password cannot use a placeholder/dev credential.');
}
}
}

View file

@ -11,5 +11,8 @@ export {
resetStockConfig, resetStockConfig,
} from './config-instance'; } from './config-instance';
// Export environment safety guard
export { assertEnvironmentSafety, type StockServiceName } from './env-safety';
// Re-export type for convenience // Re-export type for convenience
export type { StockAppConfig } from './schemas/stock-app.schema'; export type { StockAppConfig } from './schemas/stock-app.schema';

View file

@ -1,80 +0,0 @@
# QM Spider Symbol Search Test
## How the Spider Search Works
The spider search is a recursive symbol discovery system that explores the QM API systematically:
### 1. Root Job (Weekly Schedule)
```typescript
// Triggered every Saturday at midnight
@ScheduledOperation('spider-symbol-search', '0 0 * * 6', {...})
// Creates 26 jobs: A, B, C, ... Z
input: { prefix: null, depth: 0, maxDepth: 4 }
```
### 2. Level 1 - Single Letters (A-Z)
```typescript
// Each job searches for symbols starting with that letter
input: { prefix: 'A', depth: 1, maxDepth: 4 }
// If 10+ symbols found, creates: AA, AB, AC, ... AZ
```
### 3. Level 2 - Two Letters (AA-ZZ)
```typescript
// Searches for symbols starting with two letters
input: { prefix: 'AA', depth: 2, maxDepth: 4 }
// If 10+ symbols found, creates: AAA, AAB, AAC, ... AAZ
```
### 4. Level 3 & 4 - Deeper Search
Continues until `maxDepth` is reached or fewer than 10 symbols are found.
## Testing the Spider
### Manual Test - Root Job
```bash
# Trigger spider search root job
curl -X POST http://localhost:3000/api/handlers/qm/operations/spider-symbol-search \
-H "Content-Type: application/json" \
-d '{}'
```
### Manual Test - Specific Prefix
```bash
# Search for symbols starting with "APP"
curl -X POST http://localhost:3000/api/handlers/qm/operations/spider-symbol-search \
-H "Content-Type: application/json" \
-d '{"prefix": "APP", "depth": 3, "maxDepth": 4}'
```
### Direct Symbol Search
```bash
# Search for specific symbols
curl -X POST http://localhost:3000/api/handlers/qm/operations/search-symbols \
-H "Content-Type: application/json" \
-d '{"query": "AAPL"}'
```
## Optimization Features
1. **Intelligent Branching**: Only creates child jobs if 10+ symbols found
2. **Priority Management**: Deeper searches get lower priority
3. **Staggered Execution**: Jobs are delayed to avoid API rate limits
4. **Session Management**: Uses QM sessions with failure tracking
5. **Caching**: Results cached for 30 minutes to avoid duplicate API calls
## MongoDB Collections
- `qm_symbols`: Stores discovered symbols with metadata
- `qm_exchanges`: Stores unique exchanges found during searches
## Monitoring
Check logs for:
- "Spider symbol search" - Job execution
- "Created root spider jobs" - Initial A-Z creation
- "Stored symbols from spider search" - Successful symbol storage
- "Found X symbols for Y, queued Z child jobs" - Branching decisions

View file

@ -1,183 +1,43 @@
# Data Sync Service # `@stock-bot/data-pipeline`
The Data Sync Service handles synchronization of raw MongoDB data to PostgreSQL master records, providing a unified data layer for the stock-bot application. Normalizes raw provider collections from MongoDB (`stock`) into canonical PostgreSQL security-master records and curated research datasets.
## Features ## Safety & Connection Model
- **Port:** `2002` (`PIPELINE_SERVICE_PORT`, default `2002` in `docker-compose.yml` / `docker-compose.dev.yml`).
- **Read-Only MongoDB Enforcement:** Bootstraps its DI container with `mongoReadOnly: true`, connecting via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`) and blocking all write, index, and collection-mutation methods at the client wrapper layer.
- **Dev vs QA Targets:**
- In `development`, reads QA MongoDB read-only and writes only to isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`). `assertEnvironmentSafety()` hard-blocks writable connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`).
- Destructive sync flags (`?clear=true`, `POST /sync/clear`) are restricted in non-test environments; never run destructive clears against `trading_bot`.
### Original Sync Manager ## Current Runtime Scope
- Basic QM (QuoteMedia) symbol and exchange synchronization - **MongoDB Inputs:** `exchanges`, `eodExchanges`, `ibExchanges`, `qmExchanges`, `eodSymbols`, `ibSymbols`, `qmSymbols`.
- Simple static exchange mapping - **PostgreSQL Tables (`database/postgres/init/02-exchange-symbol-schema.sql`):**
- Manual sync triggers via REST API - `exchanges` & `provider_exchange_mappings`
- `symbols` & `provider_mappings`
- `sync_status`
- **HTTP Endpoints (`src/routes/`):**
- `GET /health` — liveness & database readiness
- `GET /sync/status` & `GET /sync/status/enhanced` — sync state and counts
- `POST /sync/exchanges/all` — normalize exchange reference catalog
- `POST /sync/symbols/:provider` — sync `qm`, `eod`, or `ib` symbol mappings
### Enhanced Sync Manager ✨ NEW ## Target Architecture (`Milestone M1` & `M2`)
- **Multi-provider support**: Syncs from EOD, Interactive Brokers, and QuoteMedia Full specifications live in:
- **Comprehensive exchange handling**: Leverages all 4 MongoDB exchange collections - [DATA-CONTRACTS.md](../../../docs/DATA-CONTRACTS.md) — Empirical 31-collection rules, bi-temporal security master (`instruments`, `instrument_listings`, `provider_symbol_map`, `corporate_actions`), Hive Parquet + DuckDB schemas (`bars_1d`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`), and QuestDB `10.2.0` intraday schema.
- **Intelligent exchange mapping**: Dynamic mapping with fallback logic - [MILESTONES.md](../../../docs/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation).
- **Transaction safety**: Full ACID compliance with rollback on errors - [phase1-investigation.md](../../../docs/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes.
- **Performance optimization**: Exchange caching for faster lookups
- **Enhanced error handling**: Detailed error tracking and reporting
## API Endpoints ## Commands
Run from the repository root:
### Health Check
- `GET /health` - Service health status
### Original Sync Operations
- `POST /sync/symbols` - Sync QM symbols to PostgreSQL
- `POST /sync/exchanges` - Sync QM exchanges to PostgreSQL
- `GET /sync/status` - Get basic sync status
### Enhanced Sync Operations ✨ NEW
- `POST /sync/exchanges/all?clear=true` - Comprehensive exchange sync from all providers (clear=true removes dummy data first)
- `POST /sync/symbols/:provider?clear=true` - Sync symbols from specific provider (qm, eod, ib)
- `POST /sync/clear` - Clear all PostgreSQL data (exchanges, symbols, mappings)
- `GET /sync/status/enhanced` - Get detailed sync status
- `GET /sync/stats/exchanges` - Get exchange statistics
## Data Sources
### MongoDB Collections
1. **exchanges** (34 records) - Unified exchange reference
2. **eodExchanges** (78 records) - EOD provider with currency/MIC data
3. **ibExchanges** (214 records) - Interactive Brokers with asset types
4. **qmExchanges** (25 records) - QuoteMedia exchanges
### PostgreSQL Tables
1. **master_exchanges** - Unified exchange master data
2. **master_symbols** - Symbol master records
3. **provider_symbol_mappings** - Multi-provider symbol mappings
4. **sync_status** - Synchronization tracking
## Key Improvements
### 1. Multi-Provider Exchange Sync
Instead of only syncing QM exchanges, the enhanced sync manager:
- Syncs from EOD exchanges (comprehensive global data with currencies)
- Adds IB exchanges for additional coverage (214 exchanges vs 25 in QM)
### 2. Intelligent Exchange Mapping
Replaces hard-coded mapping with dynamic resolution:
```typescript
// Before: Static mapping
const exchangeMap = { 'NASDAQ': 'NASDAQ', 'NYSE': 'NYSE' };
// After: Dynamic mapping with variations
const codeMap = {
'NASDAQ': 'NASDAQ', 'NAS': 'NASDAQ',
'NYSE': 'NYSE', 'NYQ': 'NYSE',
'LSE': 'LSE', 'LON': 'LSE', 'LN': 'LSE',
'US': 'NYSE' // EOD uses 'US' for US markets
};
```
### 3. Transaction Safety
All sync operations use database transactions:
- `BEGIN` transaction at start
- `COMMIT` on success
- `ROLLBACK` on any error
- Ensures data consistency
### 4. Performance Optimization
- Exchange cache preloaded at startup
- Reduced database queries during symbol processing
- Batch operations where possible
### 5. Enhanced Error Handling
- Detailed error logging with context
- Separate error counting in sync results
- Graceful handling of missing/invalid data
## Usage Examples
### Clear All Data and Start Fresh Exchange Sync
```bash ```bash
curl -X POST "http://localhost:3005/sync/exchanges/all?clear=true" # Start pipeline in dev mode (targets localhost:5433/trading_bot_dev)
``` bun run --cwd apps/stock/data-pipeline dev
### Sync Symbols from Specific Provider # Typecheck & build
```bash bun run typecheck
# Sync QuoteMedia symbols (clear existing symbols first)
curl -X POST "http://localhost:3005/sync/symbols/qm?clear=true"
# Sync EOD symbols
curl -X POST http://localhost:3005/sync/symbols/eod
# Sync Interactive Brokers symbols
curl -X POST http://localhost:3005/sync/symbols/ib
```
### Clear All PostgreSQL Data
```bash
curl -X POST http://localhost:3005/sync/clear
```
### Get Enhanced Status
```bash
curl http://localhost:3005/sync/status/enhanced
curl http://localhost:3005/sync/stats/exchanges
```
## Configuration
### Environment Variables
- `DATA_SYNC_SERVICE_PORT` - Service port (default: 3005)
- `NODE_ENV` - Environment mode
### Database Connections
- **MongoDB**: `mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin`
- **PostgreSQL**: `postgresql://trading_user:trading_pass_dev@localhost:5432/trading_bot`
## Development
### Build and Run
```bash
# Development mode
bun run dev
# Build
bun run build bun run build
# Production # Run PostgreSQL environment & read-only MongoDB safety tests
bun run start bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts
``` ```
### Testing
```bash
# Run tests
bun test
# Start infrastructure
bun run infra:up
# Test sync operations
curl -X POST http://localhost:3005/sync/exchanges/all
curl -X POST http://localhost:3005/sync/symbols/qm
```
## Architecture
```
MongoDB Collections PostgreSQL Tables
┌─ exchanges (34) ┐ ┌─ master_exchanges
├─ eodExchanges (78) ├──▶├─ master_symbols
├─ ibExchanges (214) │ ├─ provider_symbol_mappings
└─ qmExchanges (25) ┘ └─ sync_status
│
▼
Enhanced Sync Manager
- Exchange caching
- Dynamic mapping
- Transaction safety
- Multi-provider support
```
## Migration Path
The enhanced sync manager is designed to work alongside the original sync manager:
1. **Immediate**: Use enhanced exchange sync for better coverage
2. **Phase 1**: Test enhanced symbol sync with each provider
3. **Phase 2**: Replace original sync manager when confident
4. **Phase 3**: Remove original sync manager and endpoints
Both managers can be used simultaneously during the transition period.

View file

@ -64,8 +64,9 @@ async function createContainer(config: import('@stock-bot/config').UnifiedAppCon
.withConfig(config) .withConfig(config)
.withOptions({ .withOptions({
enableQuestDB: false, // Disabled for now due to auth issues enableQuestDB: false, // Disabled for now due to auth issues
// Data pipeline needs all databases // Data pipeline reads raw ingestion data from MongoDB (read-only) and writes master records to PostgreSQL
enableMongoDB: true, enableMongoDB: true,
mongoReadOnly: true,
enablePostgres: true, enablePostgres: true,
enableCache: true, enableCache: true,
enableQueue: true, enableQueue: true,

View file

@ -1,148 +0,0 @@
# Strategy architecture and extension guide
## Supported execution paths
HTTP and decorated backtest jobs use `BacktestRunner`, which owns input snapshots,
claims, leases, terminal persistence and completion publication.
- TypeScript backtests and paper trading use `StrategyManager` and `BaseStrategy`.
Signals become captured order intents, then pass through `ExecutionService`.
- Native backtests use `RustBacktestAdapter` and a disposable native worker process.
The worker registers Rust strategies, not TypeScript callbacks.
- The simulation ledger owns cash, positions, fills, pending reservations and risk admission.
Strategy checkpoints contain decision state and journal-derived projections; they are not
a second account ledger. Native market/analytics projections are not the paper account.
Live routing and native TypeScript callbacks are explicitly unsupported. Do not create
another inline executor, call native order submission, or bypass the runner for durable jobs.
## Runtime composition
`container.ts` creates the runtime graph and binds each required dependency explicitly.
The engines and strategy/mode/market-data lifecycle do not look up peers in `services.custom`.
Both backends receive the same storage instance; the native adapter never constructs one.
The strategy manager accepts a bound `createStrategy` callback instead of loading a registry
or discovering the mode manager. Custom registries supplied through `registerOrchestratorServices`
still receive `{ modeManager, execution }`; no strategy factory or checkpoint migration is needed.
Deferred callbacks are wired only at composition: market flush awaits strategy delivery, and
factories/backtests obtain the current mode's engine after mode initialization. `ModeManager`
owns that engine; `StrategyManager` no longer caches a second reference or exposes a getter.
Paper restoration still completes before feed startup, and shutdown still flushes the feed
before stopping strategies, execution and storage. HTTP/job adapters retain the existing
application lookup surface, separate from the internal graph.
## Strategy layout
```text
src/strategies/
BaseStrategy.ts common signal, intent and checkpoint lifecycle
StrategyManager.ts registration, delivery and restart recovery
StrategyRegistry.ts injectable factory/alias registry
builtin-strategies.ts lazy composition of concrete implementations
builtin/
SmaCrossoverStrategy.ts canonical registered SMA implementation
MeanReversionStrategy.ts canonical registered mean reversion
experimental/
MLEnhancedStrategy.ts optional, run-local experiment
```
Core/API code loads concrete strategies through the registry, not direct imports.
Built-ins cannot depend on experimental implementations. Parameter schemas live in
`src/contracts/strategies.ts`; alias identity lives in `strategy-names.ts`.
`backtest/strategy-plan.ts` gives both backends the same global-default/per-strategy-override
precedence while retaining explicit backend-specific parameters and behavior.
Run-wide fields are defined by `BacktestExecutionSettingsSchema` in the portable
`@stock-bot/stock-config/backtest` contract. The planner projects legacy mixed configs into
built-in parameters using that schema; do not add another manual execution-field exclusion
list. Per-strategy copies of execution settings never override the run. Unknown parameter
keys remain visible to strict strategy validation. Custom TypeScript factories keep their
factory-owned extension fields, and original request/result configs stay intact for replay.
The legacy `useTypeScriptImplementation` hint never changes the selected backend; `true`
is rejected by the native path.
Persisted aliases and checkpoint versions remain stable across this source relocation:
SMA still reports `sma-crossover-fixed/v2`, and mean reversion reports
`mean-reversion/v2`. The word `fixed` in the persisted version is compatibility metadata,
not a second implementation. No financial data or saved checkpoints are rewritten.
The earlier v1-to-v2 cutover requirement in the [root README](../../../../README.md#durable-strategy-recovery)
still applies; this layout cleanup introduces no additional version change.
## Adding a strategy
1. Extend `BaseStrategy`, adding a focused module under `builtin/` for supported behavior
or `experimental/` for research. Keep helpers independent of strategy lifecycle where possible.
2. Validate configuration at construction and inactive edits. Use explicit units, finite values
and bounded periods. Existing built-in contracts reject unsupported keys instead of ignoring them.
3. Implement bounded per-instrument indicator state in `updateIndicators` and return a
`Signal | null` from `generateSignal`. Reuse `@stock-bot/calculations/indicators` for trailing
scalar SMA/deviation/crossovers, or the documented native indicator wrapper for other math.
4. For paper execution, provide a version string and complete finite-JSON capture/restore
contract for custom state. Version changes and changed configurations require deliberate
new strategy IDs; never reset an existing account or coerce an incompatible checkpoint.
5. Register a lazy factory and stable aliases in `createBuiltinStrategyRegistry()`, or inject
a custom registry through `registerOrchestratorServices`. A custom registry must also be
provided on restart. No manager switch or alternate execution loop is needed.
6. Test schema rejection, warm-up, multiple instruments, fill-based position changes and
checkpoint/restart equivalence. Use real gateway admission and repository transactions,
including rollback and duplicate-delivery cases.
Callbacks run within a durable decision scope and must be deterministic and bounded.
Do not perform external I/O, use wall-clock/random decision inputs, train models, launch
fire-and-forget state mutations, or directly submit orders from callbacks. ExecutionService
applies the account-level limits even when a strategy adds its own signal/sizing constraints.
Do not recreate strategy-local cash/P&L books or a separate risk-admission manager.
The [registry/recovery fixture](../../../../test/fixtures/strategy-recovery.ts) and
[registry integration tests](../../../../test/integration/strategy-registry.test.ts) show
an injected extension using the same lifecycle. The supported built-ins show complete
configuration and indicator-checkpoint implementations.
## Experiments and examples
ML remains lazy-loaded and explicitly experimental. It has no replay-safe model artifact
or complete checkpoint contract, so paper activation fails before TensorFlow/model startup.
Moving it under `experimental/` does not make its training deterministic or production-ready.
[The multi-strategy example](../examples/multi-strategy-backtest.ts) accepts the application's
already-composed TypeScript `BacktestRunner` and a qualified historical range. Importing it
starts no services and executes nothing. The caller owns service shutdown; results come from
the ordinary ledger-backed workflow and are persisted by the runner. For example:
```ts
await runMultiStrategyBacktest(runner, {
symbols: ['AAPL.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-04-01T00:00:00.000Z',
});
```
This needs actual stored daily bars; it does not manufacture benchmark returns, correlations
or broker features. The example is included in root type checking and exercised by the
backtest workflow integration tests. Other old diagnostic scripts in `examples/` are not
the supported extension contract.
## Retired paths
The unused TypeScript `RustBacktestEngine`/`RustStrategy` callback wrapper and inline
`StrategyExecutor` were removed. The unregistered original/V2/Rust SMA variants,
`AdvancedMultiIndicatorStrategy`, `IndicatorBasedStrategy` and their private
indicator/position/risk/signal-manager framework were also removed. They are recoverable
from Git history (before this cleanup, commit `4207bf2`), not maintained runtime alternatives.
Deep imports of those internal files must migrate to the registry or canonical implementation.
The native SDK's explicit unsupported-operation errors remain as safety boundaries.
## Verification
From the repository root:
```sh
bun run check
bun test test/integration/strategy-registry.test.ts test/integration/strategy-contracts.test.ts
```
The root gate checks cycles, registry-only strategy loading, retired entry points,
worker-only native backtest access and the prohibition on direct strategy order submission.
See the root README for disposable PostgreSQL/Redis safety tests; never run fixture resets
against a development or production account.

View file

@ -1,487 +0,0 @@
# Rust Core Enhancement Roadmap
> Historical research ideas, not a current architecture/status assessment. Paper order
> lifecycle, accounting and risk admission now belong to the execution ledger, while native
> backtests run in isolated workers. TypeScript callbacks into the native backtest engine and
> live routing are unsupported. Use [the current extension guide](architecture-improvements.md)
> and the root README before implementing anything below; do not create another account ledger.
## Missing Components & Potential Additions
### 1. **Order Management System (OMS)**
Currently missing a comprehensive order lifecycle management system.
```rust
// Suggested additions to orders module
pub struct OrderManager {
active_orders: DashMap<String, Order>,
order_history: Vec<OrderEvent>,
order_routes: HashMap<String, OrderRoute>,
}
pub enum OrderEvent {
Submitted { order_id: String, timestamp: DateTime<Utc> },
Acknowledged { order_id: String, broker_id: String },
PartialFill { order_id: String, fill: Fill },
Filled { order_id: String, avg_price: f64 },
Cancelled { order_id: String, reason: String },
Rejected { order_id: String, reason: String },
Modified { order_id: String, changes: OrderModification },
}
pub struct OrderModification {
quantity: Option<f64>,
price: Option<f64>,
stop_price: Option<f64>,
}
```
### 2. **Advanced Order Types**
Current order types are basic. Missing:
```rust
pub enum OrderType {
// Existing
Market,
Limit { price: f64 },
Stop { stop_price: f64 },
StopLimit { stop_price: f64, limit_price: f64 },
// Missing
Iceberg { visible_quantity: f64, total_quantity: f64 },
TWAP { duration: Duration, slices: u32 },
VWAP { duration: Duration, participation_rate: f64 },
PeggedToMidpoint { offset: f64 },
TrailingStop { trail_amount: f64, trail_percent: Option<f64> },
OCO { order1: Box<Order>, order2: Box<Order> }, // One-Cancels-Other
Bracket { entry: Box<Order>, stop_loss: Box<Order>, take_profit: Box<Order> },
}
```
### 3. **Portfolio Management**
No portfolio-level analytics or optimization.
```rust
pub mod portfolio {
pub struct Portfolio {
positions: HashMap<String, Position>,
cash_balance: f64,
margin_used: f64,
buying_power: f64,
}
pub struct PortfolioAnalytics {
pub fn calculate_beta(&self, benchmark: &str) -> f64;
pub fn calculate_correlation_matrix(&self) -> Matrix<f64>;
pub fn calculate_var(&self, confidence: f64, horizon: Duration) -> f64;
pub fn calculate_sharpe_ratio(&self, risk_free_rate: f64) -> f64;
pub fn calculate_sortino_ratio(&self, mar: f64) -> f64;
pub fn calculate_max_drawdown(&self) -> DrawdownInfo;
}
pub struct PortfolioOptimizer {
pub fn optimize_weights(&self, constraints: Constraints) -> HashMap<String, f64>;
pub fn calculate_efficient_frontier(&self, points: usize) -> Vec<(f64, f64)>;
pub fn black_litterman(&self, views: Views) -> HashMap<String, f64>;
pub fn risk_parity(&self) -> HashMap<String, f64>;
}
}
```
### 4. **Market Data Enhancements**
Missing Level 2 data, options data, and advanced market data types.
```rust
pub enum MarketDataType {
// Existing
Quote(Quote),
Trade(Trade),
Bar(Bar),
// Missing
Level2 { bids: Vec<PriceLevel>, asks: Vec<PriceLevel> },
Imbalance { buy_quantity: f64, sell_quantity: f64, ref_price: f64 },
AuctionData { indicative_price: f64, indicative_volume: f64 },
OptionQuote {
strike: f64,
expiry: DateTime<Utc>,
call_bid: f64,
call_ask: f64,
put_bid: f64,
put_ask: f64,
implied_vol: f64,
},
Greeks {
delta: f64,
gamma: f64,
theta: f64,
vega: f64,
rho: f64,
},
}
```
### 5. **Execution Algorithms**
No implementation of common execution algorithms.
```rust
pub mod execution_algos {
pub trait ExecutionAlgorithm {
fn generate_child_orders(&mut self, parent: &Order, market_state: &MarketState) -> Vec<Order>;
fn on_fill(&mut self, fill: &Fill);
fn on_market_update(&mut self, update: &MarketUpdate);
}
pub struct TWAPAlgorithm {
duration: Duration,
slice_interval: Duration,
randomization: f64, // Add randomness to avoid detection
}
pub struct VWAPAlgorithm {
historical_volume_curve: Vec<f64>,
participation_rate: f64,
min_slice_size: f64,
}
pub struct ImplementationShortfall {
urgency: f64,
risk_aversion: f64,
arrival_price: f64,
}
pub struct Iceberg {
visible_size: f64,
refresh_strategy: RefreshStrategy,
}
}
```
### 6. **Options Support**
No options trading infrastructure.
```rust
pub mod options {
pub struct OptionContract {
underlying: String,
strike: f64,
expiry: DateTime<Utc>,
option_type: OptionType,
multiplier: f64,
}
pub enum OptionType {
Call,
Put,
}
pub struct OptionPricer {
pub fn black_scholes(&self, params: BSParams) -> OptionPrice;
pub fn binomial(&self, params: BinomialParams) -> OptionPrice;
pub fn monte_carlo(&self, params: MCParams, simulations: u32) -> OptionPrice;
}
pub struct OptionGreeks {
pub fn calculate_greeks(&self, contract: &OptionContract, market: &MarketData) -> Greeks;
pub fn calculate_implied_volatility(&self, price: f64) -> f64;
}
pub struct OptionStrategy {
legs: Vec<OptionLeg>,
pub fn calculate_payoff(&self, underlying_price: f64) -> f64;
pub fn calculate_breakeven(&self) -> Vec<f64>;
pub fn max_profit(&self) -> Option<f64>;
pub fn max_loss(&self) -> Option<f64>;
}
}
```
### 7. **Machine Learning Integration**
No ML feature generation or model integration.
```rust
pub mod ml {
pub struct FeatureEngine {
indicators: Vec<Box<dyn Indicator>>,
lookback_periods: Vec<usize>,
pub fn generate_features(&self, data: &MarketData) -> FeatureMatrix;
pub fn calculate_feature_importance(&self) -> HashMap<String, f64>;
}
pub trait MLModel {
fn predict(&self, features: &FeatureMatrix) -> Prediction;
fn update(&mut self, features: &FeatureMatrix, outcome: &Outcome);
}
pub struct ModelEnsemble {
models: Vec<Box<dyn MLModel>>,
weights: Vec<f64>,
pub fn predict(&self, features: &FeatureMatrix) -> Prediction;
pub fn update_weights(&mut self, performance: &ModelPerformance);
}
}
```
### 8. **Backtesting Engine Enhancements**
Current backtesting is basic. Missing:
```rust
pub mod backtesting {
pub struct BacktestEngine {
// Slippage models
slippage_model: Box<dyn SlippageModel>,
// Market impact models (you have this but not integrated)
market_impact: Box<dyn MarketImpactModel>,
// Multi-asset synchronization
clock_sync: ClockSynchronizer,
// Walk-forward analysis
walk_forward: WalkForwardConfig,
// Monte Carlo simulation
monte_carlo: MonteCarloConfig,
}
pub struct BacktestMetrics {
// Return metrics
total_return: f64,
annualized_return: f64,
volatility: f64,
// Risk metrics
sharpe_ratio: f64,
sortino_ratio: f64,
calmar_ratio: f64,
max_drawdown: f64,
var_95: f64,
cvar_95: f64,
// Trading metrics
win_rate: f64,
profit_factor: f64,
avg_win_loss_ratio: f64,
expectancy: f64,
// Execution metrics
avg_slippage: f64,
total_commission: f64,
turnover: f64,
}
}
```
### 9. **Real-time Monitoring & Alerts**
No monitoring or alerting system.
```rust
pub mod monitoring {
pub struct Monitor {
rules: Vec<MonitorRule>,
alert_channels: Vec<Box<dyn AlertChannel>>,
}
pub enum MonitorRule {
PositionLimit { symbol: String, max_size: f64 },
DrawdownAlert { threshold: f64 },
VolumeSpike { symbol: String, threshold: f64 },
SpreadWidening { symbol: String, max_spread: f64 },
LatencyAlert { max_latency: Duration },
ErrorRate { max_errors_per_minute: u32 },
}
pub trait AlertChannel {
fn send_alert(&self, alert: Alert) -> Result<(), Error>;
}
}
```
### 10. **Data Persistence Layer**
No built-in data storage/retrieval.
```rust
pub mod persistence {
pub trait DataStore {
fn save_market_data(&self, data: &MarketUpdate) -> Result<(), Error>;
fn load_market_data(&self, symbol: &str, range: DateRange) -> Result<Vec<MarketUpdate>, Error>;
fn save_order(&self, order: &Order) -> Result<(), Error>;
fn load_order_history(&self, filter: OrderFilter) -> Result<Vec<Order>, Error>;
fn save_trade(&self, trade: &TradeRecord) -> Result<(), Error>;
fn load_trades(&self, filter: TradeFilter) -> Result<Vec<TradeRecord>, Error>;
}
pub struct TimeSeriesDB {
// QuestDB or TimescaleDB adapter
}
pub struct Cache {
// Redis adapter for hot data
}
}
```
### 11. **Strategy Development Framework**
Missing strategy templates and utilities.
```rust
pub mod strategy_framework {
pub trait Strategy {
fn on_start(&mut self);
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal>;
fn on_fill(&mut self, fill: &Fill);
fn on_end_of_day(&mut self);
fn get_parameters(&self) -> StrategyParameters;
}
pub struct StrategyOptimizer {
pub fn optimize_parameters(
&self,
strategy: &dyn Strategy,
data: &HistoricalData,
objective: ObjectiveFunction
) -> OptimalParameters;
pub fn walk_forward_analysis(&self, windows: Vec<DateRange>) -> WalkForwardResults;
}
}
```
### 12. **Compliance & Regulation**
No compliance checks or audit trails.
```rust
pub mod compliance {
pub struct ComplianceEngine {
rules: Vec<ComplianceRule>,
audit_log: AuditLog,
}
pub enum ComplianceRule {
NoBuyDuringRestricted { restricted_periods: Vec<DateRange> },
MaxOrdersPerDay { limit: u32 },
MinOrderInterval { duration: Duration },
RestrictedSymbols { symbols: HashSet<String> },
MaxLeverageRatio { ratio: f64 },
}
pub struct AuditLog {
pub fn log_order(&self, order: &Order, metadata: AuditMetadata);
pub fn log_trade(&self, trade: &Trade, metadata: AuditMetadata);
pub fn generate_report(&self, period: DateRange) -> ComplianceReport;
}
}
```
### 13. **Advanced Indicators**
Missing many common indicators.
```rust
pub mod indicators {
// Additional indicators to add:
- Ichimoku Cloud
- Parabolic SAR
- Fibonacci Retracements
- Pivot Points
- Money Flow Index
- Williams %R
- Commodity Channel Index (CCI)
- On Balance Volume (OBV)
- Accumulation/Distribution Line
- Chaikin Money Flow
- TRIX
- Keltner Channels
- Donchian Channels
- Average Directional Index (ADX)
- Aroon Indicator
}
```
### 14. **Network & Connectivity**
No network resilience or multi-venue support.
```rust
pub mod connectivity {
pub struct ConnectionManager {
venues: HashMap<String, VenueConnection>,
fallback_routes: HashMap<String, Vec<String>>,
heartbeat_monitor: HeartbeatMonitor,
}
pub struct VenueConnection {
primary: Connection,
backup: Option<Connection>,
latency_stats: LatencyStats,
pub fn send_order(&self, order: &Order) -> Result<String, Error>;
pub fn cancel_order(&self, order_id: &str) -> Result<(), Error>;
}
}
```
### 15. **Performance Profiling**
No built-in performance monitoring.
```rust
pub mod profiling {
pub struct PerformanceProfiler {
metrics: DashMap<String, PerformanceMetric>,
pub fn record_latency(&self, operation: &str, duration: Duration);
pub fn record_throughput(&self, operation: &str, count: u64);
pub fn get_report(&self) -> PerformanceReport;
}
}
```
## Priority Recommendations
### High Priority
1. **Order Management System** - Critical for proper order lifecycle tracking
2. **Portfolio Analytics** - Essential for multi-asset strategies
3. **Execution Algorithms** - TWAP/VWAP for better execution
4. **Advanced Order Types** - Bracket orders, trailing stops
5. **Backtesting Enhancements** - Proper slippage and impact modeling
### Medium Priority
1. **Options Support** - If trading options
2. **ML Integration** - Feature generation framework
3. **Monitoring & Alerts** - Real-time system health
4. **Data Persistence** - Proper storage layer
5. **More Indicators** - Based on strategy needs
### Low Priority
1. **Compliance Engine** - Unless regulatory requirements
2. **Multi-venue Support** - Unless using multiple brokers
3. **Advanced Market Data** - Level 2, imbalance data
## Implementation Approach
1. **Modular Design**: Each component should be optional and pluggable
2. **Trait-Based**: Continue using traits for extensibility
3. **Performance First**: Maintain the current performance focus
4. **Backward Compatible**: Don't break existing APIs
5. **Incremental**: Add features based on actual needs
The core is solid, but these additions would make it a comprehensive institutional-grade trading system!

View file

@ -80,7 +80,7 @@ strategy or an order gateway. Using it does not bypass `BaseStrategy` and `Execu
Implement `updateIndicators` and `generateSignal` on `BaseStrategy`; do not override the Implement `updateIndicators` and `generateSignal` on `BaseStrategy`; do not override the
delivery loop to return orders or introduce another position/risk manager. The supported delivery loop to return orders or introduce another position/risk manager. The supported
implementations are under `src/strategies/builtin/`. Follow the implementations are under `src/strategies/builtin/`. Follow the
[strategy extension guide](architecture-improvements.md) for registration, bounded state [strategy development guide](../../../../docs/guide/strategy-development.md) for registration, bounded state
and checkpoint requirements. and checkpoint requirements.
Tests compare scalar SMA/population deviation with actual native batch and incremental Tests compare scalar SMA/population deviation with actual native batch and incremental

View file

@ -1,44 +0,0 @@
# Monitoring Components - Spacing Guidelines
This document outlines the standardized spacing used across monitoring components to maximize screen real estate.
## Spacing Standards
### Page Layout
- Main container: `flex flex-col h-full space-y-4` (16px vertical gaps)
- No outer padding - handled by parent layout
- Section spacing: `space-y-4` between major sections
### Cards
- Card padding: `p-4` (16px) for main cards, `p-3` (12px) for compact cards
- Card header: `pb-3` (12px bottom padding)
- Card content spacing: `space-y-3` (12px gaps)
- Grid gaps: `gap-3` (12px) or `gap-4` (16px)
### Typography
- Page title: `text-lg font-bold mb-2`
- Section headings: `text-lg font-semibold mb-3`
- Card titles: `text-base font-semibold`
- Large values: `text-xl` or `text-lg`
- Regular text: `text-sm`
- Small text/labels: `text-xs`
### Specific Components
**ServiceCard**: `p-3` with `space-y-1.5` and `text-xs`
**DatabaseCard**: `p-4` with `space-y-2`
**SystemHealthCard**: `p-4` with `space-y-3`
**CacheStatsCard**: `p-4` with `space-y-3`
**ProxyStatsCard**: `p-4` with `space-y-3`
**QueueStatsTable**: `p-4` with `text-xs` table
### Grids
- Service grid: `gap-3`
- Database grid: `gap-3`
- Main layout grid: `gap-4`
## Benefits
- Maximizes usable screen space
- Consistent with dashboard/exchanges pages
- More data visible without scrolling
- Clean, compact appearance

View file

@ -1,58 +0,0 @@
# Pipeline Page - Spacing Updates
This document outlines the spacing standardization applied to the Pipeline page to match the monitoring and dashboard pages.
## Changes Applied
### Layout Structure
- Main container: `flex flex-col h-full space-y-4`
- No outer padding (handled by parent layout)
- Flex-shrink-0 for fixed elements
- Overflow-y-auto for scrollable content area
### Typography
- Page title: `text-lg` (from `text-2xl`)
- Page description: `text-sm`
- Section headings: `text-base` (from `text-lg`)
- Card titles: `text-sm`
- Card descriptions: `text-xs` (from `text-sm`)
- All text in cards: `text-xs`
### Spacing
- Grid gaps: `gap-3` (from `gap-4`)
- Card padding: `p-3` (from `p-4`)
- Margins: `mb-2` or `mb-3` (from `mb-3` or `mb-4`)
- Button padding: `px-2.5 py-1.5` (from `px-3 py-2`)
### Icons
- Section icons: `h-4 w-4` (from `h-5 w-5`)
- Button icons: `h-3 w-3` (from `h-4 w-4`)
### Specific Components
**Stats Cards**:
- Padding: `p-3`
- Title: `text-base mb-2`
- Content: `text-xs` with `space-y-1.5`
**Operation Cards**:
- Padding: `p-3`
- Title: `text-sm`
- Description: `text-xs mb-2`
- Form elements: `text-xs` with `mb-2`
**Buttons**:
- Padding: `px-2.5 py-1.5`
- Text: `text-xs`
- Icons: `h-3 w-3`
**Alert Messages**:
- Padding: `p-3`
- Text: `text-sm`
- Icons: `h-4 w-4`
## Benefits
- Consistent with monitoring and dashboard pages
- More operations visible without scrolling
- Cleaner, more compact appearance
- Better space utilization for data-heavy interface

View file

@ -1,70 +0,0 @@
# Dependencies
**/node_modules
**/.pnp
**/.pnp.js
# Testing
**/coverage
**/.nyc_output
# Production builds
**/dist
**/build
**/.next
**/out
# Logs
**/*.log
**/npm-debug.log*
**/yarn-debug.log*
**/yarn-error.log*
**/lerna-debug.log*
**/.pnpm-debug.log*
# Environment files
**/.env
**/.env.local
**/.env.development.local
**/.env.test.local
**/.env.production.local
# IDE
**/.idea
**/.vscode
**/*.swp
**/*.swo
**/*~
**/.DS_Store
# Git
**/.git
**/.gitignore
# Docker
**/Dockerfile
**/docker-compose*.yml
**/.dockerignore
# Documentation
**/README.md
**/CHANGELOG.md
**/docs
# Misc
**/.eslintcache
**/.cache
**/tmp
**/.turbo
# Database
**/prisma/migrations/migration_lock.toml
**/*.db
**/*.db-journal
# Only for root level (not in apps/*)
/apps/stock
/apps/db-design
/apps/cline
/lib/!(service)
!/lib/service/core-config
!/lib/service/core-logger

View file

@ -1,61 +0,0 @@
# Application Environment
NODE_ENV=development
APP_NAME=wcag-ada
# API Configuration
API_PORT=3001
API_CORS_ORIGIN=http://localhost:5173
API_JWT_SECRET=your-super-secret-jwt-key-change-in-production
API_JWT_EXPIRES_IN=7d
API_RATE_LIMIT=100
API_RATE_WINDOW=60000
# Worker Configuration
WORKER_PORT=3002
WORKER_CONCURRENCY=5
WORKER_QUEUE_NAME=accessibility-scans
# Database Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/wcag_ada
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
# Scanner Configuration
SCANNER_HEADLESS=true
SCANNER_TIMEOUT=30000
SCANNER_VIEWPORT_WIDTH=1920
SCANNER_VIEWPORT_HEIGHT=1080
SCANNER_BLOCK_RESOURCES=true
SCANNER_BLOCK_PATTERNS=font,image
# Features
FEATURES_SCREENSHOTS=true
FEATURES_FIX_SUGGESTIONS=true
FEATURES_CUSTOM_RULES=true
FEATURES_SCHEDULED_SCANS=true
FEATURES_BULK_SCANNING=false
FEATURES_API_ACCESS=true
# Third-party Services (optional)
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=noreply@wcag-ada.com
SLACK_WEBHOOK_URL=
SLACK_CHANNEL=#wcag-alerts
# Logging
LOG_LEVEL=info
LOG_FORMAT=json
# Scheduler
SCHEDULER_TIMEZONE=America/New_York
SCHEDULER_MAX_CONCURRENT_SCANS=3
SCHEDULER_RETRY_ATTEMPTS=3
SCHEDULER_RETRY_DELAY=5000

View file

@ -1,181 +0,0 @@
stages:
- build
- test
- deploy
variables:
DOCKER_DRIVER: overlay2
DOCKER_TLS_CERTDIR: ""
REGISTRY: $CI_REGISTRY
API_IMAGE: $CI_REGISTRY_IMAGE/api
WORKER_IMAGE: $CI_REGISTRY_IMAGE/worker
DASHBOARD_IMAGE: $CI_REGISTRY_IMAGE/dashboard
# Cache node_modules between jobs
.node_cache: &node_cache
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- apps/wcag-ada/*/node_modules/
- .bun/
# Docker login before each job
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
# Build stage
build:api:
stage: build
image: docker:24-dind
services:
- docker:24-dind
script:
- docker build -f apps/wcag-ada/api/Dockerfile -t $API_IMAGE:$CI_COMMIT_SHA .
- docker tag $API_IMAGE:$CI_COMMIT_SHA $API_IMAGE:latest
- docker push $API_IMAGE:$CI_COMMIT_SHA
- docker push $API_IMAGE:latest
only:
- main
- develop
- merge_requests
tags:
- docker
build:worker:
stage: build
image: docker:24-dind
services:
- docker:24-dind
script:
- docker build -f apps/wcag-ada/worker/Dockerfile -t $WORKER_IMAGE:$CI_COMMIT_SHA .
- docker tag $WORKER_IMAGE:$CI_COMMIT_SHA $WORKER_IMAGE:latest
- docker push $WORKER_IMAGE:$CI_COMMIT_SHA
- docker push $WORKER_IMAGE:latest
only:
- main
- develop
- merge_requests
tags:
- docker
build:dashboard:
stage: build
image: docker:24-dind
services:
- docker:24-dind
script:
- docker build -f apps/wcag-ada/dashboard/Dockerfile -t $DASHBOARD_IMAGE:$CI_COMMIT_SHA .
- docker tag $DASHBOARD_IMAGE:$CI_COMMIT_SHA $DASHBOARD_IMAGE:latest
- docker push $DASHBOARD_IMAGE:$CI_COMMIT_SHA
- docker push $DASHBOARD_IMAGE:latest
only:
- main
- develop
- merge_requests
tags:
- docker
# Test stage
test:unit:
stage: test
image: oven/bun:1-alpine
<<: *node_cache
before_script:
- cd apps/wcag-ada
- bun install
script:
- bun test
only:
- merge_requests
tags:
- docker
test:lint:
stage: test
image: oven/bun:1-alpine
<<: *node_cache
before_script:
- cd apps/wcag-ada
- bun install
script:
- bun run lint
only:
- merge_requests
tags:
- docker
test:typecheck:
stage: test
image: oven/bun:1-alpine
<<: *node_cache
before_script:
- cd apps/wcag-ada
- bun install
script:
- bun run typecheck
only:
- merge_requests
tags:
- docker
# Deploy to staging
deploy:staging:
stage: deploy
image: bitnami/kubectl:latest
before_script:
- kubectl config set-cluster k8s --server="$KUBE_URL" --insecure-skip-tls-verify=true
- kubectl config set-credentials gitlab --token="$KUBE_TOKEN"
- kubectl config set-context default --cluster=k8s --user=gitlab
- kubectl config use-context default
script:
- kubectl apply -f apps/wcag-ada/k8s/namespace.yaml
- kubectl apply -f apps/wcag-ada/k8s/configmap.yaml
- kubectl apply -f apps/wcag-ada/k8s/secrets.yaml
- kubectl apply -f apps/wcag-ada/k8s/postgres.yaml
- kubectl apply -f apps/wcag-ada/k8s/redis.yaml
- |
kubectl set image deployment/wcag-ada-api api=$API_IMAGE:$CI_COMMIT_SHA -n wcag-ada
kubectl set image deployment/wcag-ada-worker worker=$WORKER_IMAGE:$CI_COMMIT_SHA -n wcag-ada
kubectl set image deployment/wcag-ada-dashboard dashboard=$DASHBOARD_IMAGE:$CI_COMMIT_SHA -n wcag-ada
- kubectl rollout status deployment/wcag-ada-api -n wcag-ada
- kubectl rollout status deployment/wcag-ada-worker -n wcag-ada
- kubectl rollout status deployment/wcag-ada-dashboard -n wcag-ada
environment:
name: staging
url: https://staging.wcag-ada.example.com
only:
- develop
tags:
- docker
# Deploy to production
deploy:production:
stage: deploy
image: bitnami/kubectl:latest
before_script:
- kubectl config set-cluster k8s --server="$KUBE_URL_PROD" --insecure-skip-tls-verify=true
- kubectl config set-credentials gitlab --token="$KUBE_TOKEN_PROD"
- kubectl config set-context default --cluster=k8s --user=gitlab
- kubectl config use-context default
script:
- kubectl apply -f apps/wcag-ada/k8s/namespace.yaml
- kubectl apply -f apps/wcag-ada/k8s/configmap.yaml
- kubectl apply -f apps/wcag-ada/k8s/secrets.yaml
- kubectl apply -f apps/wcag-ada/k8s/postgres.yaml
- kubectl apply -f apps/wcag-ada/k8s/redis.yaml
- |
kubectl set image deployment/wcag-ada-api api=$API_IMAGE:$CI_COMMIT_SHA -n wcag-ada
kubectl set image deployment/wcag-ada-worker worker=$WORKER_IMAGE:$CI_COMMIT_SHA -n wcag-ada
kubectl set image deployment/wcag-ada-dashboard dashboard=$DASHBOARD_IMAGE:$CI_COMMIT_SHA -n wcag-ada
- kubectl rollout status deployment/wcag-ada-api -n wcag-ada
- kubectl rollout status deployment/wcag-ada-worker -n wcag-ada
- kubectl rollout status deployment/wcag-ada-dashboard -n wcag-ada
environment:
name: production
url: https://wcag-ada.example.com
only:
- main
when: manual
tags:
- docker

View file

@ -1,328 +0,0 @@
# WCAG-ADA Deployment Guide
## Overview
This guide covers deployment options for the WCAG-ADA Compliance Monitoring Platform.
## Table of Contents
1. [Local Development](#local-development)
2. [Docker Deployment](#docker-deployment)
3. [Kubernetes Deployment](#kubernetes-deployment)
4. [GitLab CI/CD](#gitlab-cicd)
5. [Configuration Management](#configuration-management)
6. [Monitoring & Maintenance](#monitoring--maintenance)
## Local Development
### Quick Start
```bash
# Run the setup script
./scripts/local-dev.sh
# Start all services
bun run dev
```
### Manual Setup
1. **Start development databases:**
```bash
docker-compose -f docker-compose.dev.yml up -d
```
2. **Configure environment:**
```bash
cp .env.example .env
# Edit .env with your settings
```
3. **Install dependencies:**
```bash
bun install
```
4. **Run migrations:**
```bash
cd api && bunx prisma migrate dev
```
5. **Start services:**
```bash
# Terminal 1 - API
cd api && bun run dev
# Terminal 2 - Worker
cd worker && bun run dev
# Terminal 3 - Dashboard
cd dashboard && bun run dev
```
## Docker Deployment
### Build Images
```bash
# Using the build script
./scripts/build-images.sh
# Or manually with docker-compose
docker-compose build
```
### Run with Docker Compose
```bash
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
```
### Production Docker Deployment
1. **Set environment variables:**
```bash
export API_JWT_SECRET=your-secret-key
export DATABASE_URL=postgresql://user:pass@host:5432/db
# ... other required variables
```
2. **Run with production config:**
```bash
docker-compose -f docker-compose.yml up -d
```
## Kubernetes Deployment
### Prerequisites
- Kubernetes cluster (1.24+)
- kubectl configured
- Ingress controller installed
- cert-manager (for TLS)
### Deploy to Kubernetes
```bash
# Using the deploy script
./scripts/deploy-k8s.sh
# Or manually
kubectl apply -f k8s/
```
### Configuration
1. **Update secrets:**
```bash
# Edit k8s/secrets.yaml with your values
# Then apply
kubectl apply -f k8s/secrets.yaml -n wcag-ada
```
2. **Update ingress hosts:**
```bash
# Edit k8s/ingress.yaml
# Replace example.com with your domain
kubectl apply -f k8s/ingress.yaml -n wcag-ada
```
### Scaling
```bash
# Scale API replicas
kubectl scale deployment wcag-ada-api --replicas=5 -n wcag-ada
# Scale Worker replicas
kubectl scale deployment wcag-ada-worker --replicas=3 -n wcag-ada
```
## GitLab CI/CD
### Setup
1. **Configure GitLab Container Registry:**
- Enable container registry in project settings
- Note your registry URL
2. **Add CI/CD Variables:**
```
CI_REGISTRY_USER - GitLab username
CI_REGISTRY_PASSWORD - GitLab access token
KUBE_URL - Kubernetes API URL (staging)
KUBE_TOKEN - Kubernetes service account token (staging)
KUBE_URL_PROD - Kubernetes API URL (production)
KUBE_TOKEN_PROD - Kubernetes service account token (production)
```
3. **Configure environments:**
- Create `staging` and `production` environments in GitLab
- Set appropriate URLs
### Deployment Flow
1. **Development:**
- Push to `develop` branch
- Automatically builds and deploys to staging
2. **Production:**
- Merge to `main` branch
- Builds images automatically
- Manual approval required for production deployment
## Configuration Management
### Environment Variables
Key configuration variables:
```bash
# Application
NODE_ENV=production
APP_NAME=wcag-ada
# API
API_PORT=3001
API_JWT_SECRET=<strong-secret>
API_CORS_ORIGIN=https://your-domain.com
# Database
DATABASE_URL=postgresql://user:password@host:5432/wcag_ada
# Redis
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=<redis-password>
# Worker
WORKER_CONCURRENCY=5
WORKER_QUEUE_NAME=accessibility-scans
# Scanner
SCANNER_HEADLESS=true
SCANNER_TIMEOUT=30000
```
### Configuration Priority
1. Command-line arguments (highest)
2. Environment variables
3. Configuration files
4. Default values (lowest)
### Secrets Management
- **Development:** Use `.env` files
- **Docker:** Use environment variables or Docker secrets
- **Kubernetes:** Use Kubernetes secrets
- **Production:** Consider using:
- HashiCorp Vault
- AWS Secrets Manager
- Azure Key Vault
- GitLab CI/CD variables
## Monitoring & Maintenance
### Health Checks
All services expose health endpoints:
- API: `http://api:3001/health`
- Worker: `http://worker:3002/health`
- Dashboard: `http://dashboard:8080/health`
### Monitoring Stack
Recommended monitoring setup:
1. **Metrics:** Prometheus + Grafana
2. **Logs:** ELK Stack or Loki
3. **Traces:** Jaeger or Zipkin
4. **Uptime:** Uptime Kuma or Pingdom
### Database Maintenance
```bash
# Backup PostgreSQL
kubectl exec -it postgres-pod -n wcag-ada -- pg_dump -U wcag_user wcag_ada > backup.sql
# Backup Redis
kubectl exec -it redis-pod -n wcag-ada -- redis-cli BGSAVE
```
### Updates and Migrations
1. **Database migrations:**
```bash
# Run migrations before deployment
kubectl run migration --rm -it --image=wcag-ada/api:latest -- bunx prisma migrate deploy
```
2. **Rolling updates:**
```bash
# Update image
kubectl set image deployment/wcag-ada-api api=wcag-ada/api:new-version -n wcag-ada
# Monitor rollout
kubectl rollout status deployment/wcag-ada-api -n wcag-ada
```
### Troubleshooting
1. **View logs:**
```bash
# Kubernetes
kubectl logs -f deployment/wcag-ada-api -n wcag-ada
# Docker
docker-compose logs -f api
```
2. **Debug pods:**
```bash
# Get pod details
kubectl describe pod <pod-name> -n wcag-ada
# Execute commands in pod
kubectl exec -it <pod-name> -n wcag-ada -- /bin/sh
```
3. **Common issues:**
- Database connection: Check DATABASE_URL and network connectivity
- Redis connection: Verify Redis is running and accessible
- Browser issues: Ensure Chromium dependencies are installed
- Memory issues: Increase resource limits in Kubernetes
## Security Considerations
1. **Network Security:**
- Use NetworkPolicies in Kubernetes
- Implement proper firewall rules
- Use TLS for all external communications
2. **Application Security:**
- Rotate JWT secrets regularly
- Use strong passwords for databases
- Implement rate limiting
- Enable CORS appropriately
3. **Container Security:**
- Run containers as non-root user
- Use minimal base images
- Scan images for vulnerabilities
- Keep dependencies updated
## Support
For issues or questions:
1. Check application logs
2. Review health check endpoints
3. Consult error messages in dashboard
4. Check GitLab CI/CD pipeline status

View file

@ -1,85 +0,0 @@
# This is a multi-service Dockerfile that builds all services
# Use with --target flag to build specific services
# Base stage for all services
FROM oven/bun:1-alpine as base
RUN apk add --no-cache openssl
WORKDIR /app
# Dependencies stage
FROM base as deps
COPY package.json bun.lockb ./
COPY apps/wcag-ada/*/package.json ./apps/wcag-ada/
COPY lib/service/core-config/package.json ./lib/service/core-config/
COPY lib/service/core-logger/package.json ./lib/service/core-logger/
RUN bun install --frozen-lockfile
# Builder stage
FROM base as builder
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/package.json ./package.json
COPY . .
WORKDIR /app/apps/wcag-ada
# Generate Prisma clients
RUN cd api && bunx prisma generate
RUN cd worker && bunx prisma generate
# Build all services
RUN bun run build
# API Runtime
FROM base as api
COPY --from=builder /app/apps/wcag-ada/api/dist ./dist
COPY --from=builder /app/apps/wcag-ada/api/node_modules ./node_modules
COPY --from=builder /app/apps/wcag-ada/api/prisma ./prisma
COPY --from=builder /app/apps/wcag-ada/api/package.json ./
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs
EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
CMD ["bun", "run", "start"]
# Worker Runtime
FROM base as worker
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser \
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=true \
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
COPY --from=builder /app/apps/wcag-ada/worker/dist ./dist
COPY --from=builder /app/apps/wcag-ada/worker/node_modules ./node_modules
COPY --from=builder /app/apps/wcag-ada/worker/prisma ./prisma
COPY --from=builder /app/apps/wcag-ada/worker/package.json ./
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs
EXPOSE 3002
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3002/health || exit 1
CMD ["bun", "run", "start"]
# Dashboard Runtime
FROM nginx:alpine as dashboard
RUN apk add --no-cache curl
COPY apps/wcag-ada/dashboard/nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/apps/wcag-ada/dashboard/dist /usr/share/nginx/html
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /usr/share/nginx/html /var/cache/nginx /var/log/nginx /etc/nginx/conf.d
RUN touch /var/run/nginx.pid && chown -R nodejs:nodejs /var/run/nginx.pid
USER nodejs
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/ || exit 1
CMD ["nginx", "-g", "daemon off;"]

View file

@ -1,85 +0,0 @@
.PHONY: help
help: ## Show this help message
@echo 'Usage: make [target]'
@echo ''
@echo 'Targets:'
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
.PHONY: dev-up
dev-up: ## Start development databases (PostgreSQL and Redis)
docker-compose -f docker-compose.dev.yml up -d
.PHONY: dev-down
dev-down: ## Stop development databases
docker-compose -f docker-compose.dev.yml down
.PHONY: dev-logs
dev-logs: ## Show development database logs
docker-compose -f docker-compose.dev.yml logs -f
.PHONY: build
build: ## Build all Docker images
docker-compose build
.PHONY: up
up: ## Start all services
docker-compose up -d
.PHONY: down
down: ## Stop all services
docker-compose down
.PHONY: logs
logs: ## Show logs for all services
docker-compose logs -f
.PHONY: logs-api
logs-api: ## Show API service logs
docker-compose logs -f api
.PHONY: logs-worker
logs-worker: ## Show worker service logs
docker-compose logs -f worker
.PHONY: restart
restart: ## Restart all services
docker-compose restart
.PHONY: restart-api
restart-api: ## Restart API service
docker-compose restart api
.PHONY: restart-worker
restart-worker: ## Restart worker service
docker-compose restart worker
.PHONY: ps
ps: ## Show running services
docker-compose ps
.PHONY: exec-api
exec-api: ## Execute bash in API container
docker-compose exec api /bin/sh
.PHONY: exec-worker
exec-worker: ## Execute bash in worker container
docker-compose exec worker /bin/sh
.PHONY: migrate
migrate: ## Run database migrations
docker-compose run --rm migrate
.PHONY: clean
clean: ## Remove all containers and volumes
docker-compose down -v
.PHONY: rebuild
rebuild: clean build up ## Clean, rebuild, and start all services
.PHONY: test-scan
test-scan: ## Run a test accessibility scan
@echo "Running test scan on example.com..."
@curl -X POST http://localhost:3001/api/scans \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{"websiteId": "test-website-id", "url": "https://example.com"}'

View file

@ -1,175 +0,0 @@
# WCAG-ADA Compliance Monitoring Platform
An automated web accessibility compliance monitoring system that continuously scans websites for WCAG and ADA compliance issues, provides detailed reports, and offers remediation suggestions.
## Architecture
The platform consists of four main services:
### 1. **Scanner Service** (`/scanner`)
- Performs accessibility scans using axe-core and Playwright
- Supports WCAG 2.0, 2.1, and 2.2 compliance levels (A, AA, AAA)
- Generates detailed violation reports with fix suggestions
- Captures screenshots of accessibility issues
### 2. **API Service** (`/api`)
- RESTful API built with Hono framework
- JWT-based authentication
- Redis-backed rate limiting
- PostgreSQL database with Prisma ORM
- BullMQ integration for job queuing
### 3. **Worker Service** (`/worker`)
- Processes scan jobs from the queue
- Runs scheduled scans based on website configurations
- Handles scan result processing and storage
- Provides health monitoring endpoints
### 4. **Dashboard** (`/dashboard`)
- React 18 SPA with Vite
- Real-time scan monitoring
- Compliance reporting and analytics
- Website and scan management
- Built with TailwindCSS and Radix UI
## Configuration
The application uses a sophisticated configuration system that loads settings from multiple sources:
1. Default values (defined in schemas)
2. Configuration files (`.env`, `config.json`)
3. Environment variables
4. Command-line arguments
### Key Configuration Files
- `/config/src/schemas/` - Zod schemas defining all configuration options
- `/config/src/config-instance.ts` - Main configuration loader
- `.env` - Environment-specific settings
## Getting Started
### Prerequisites
- Node.js 18+
- PostgreSQL
- Redis
- Bun (recommended) or npm/yarn
### Installation
1. Install dependencies:
```bash
bun install
```
2. Set up the database:
```bash
cd apps/wcag-ada/api
bunx prisma migrate dev
```
3. Configure environment variables:
```bash
cp .env.example .env
# Edit .env with your settings
```
### Running Services
Start all services concurrently:
```bash
bun run dev
```
Or run individual services:
```bash
# API
cd apps/wcag-ada/api
bun run dev
# Worker
cd apps/wcag-ada/worker
bun run dev
# Dashboard
cd apps/wcag-ada/dashboard
bun run dev
# Scanner (for testing)
cd apps/wcag-ada/scanner
bun run example
```
## API Endpoints
### Authentication
- `POST /api/auth/register` - Register new user
- `POST /api/auth/login` - User login
- `GET /api/auth/me` - Get current user
### Websites
- `GET /api/websites` - List user's websites
- `POST /api/websites` - Add new website
- `PUT /api/websites/:id` - Update website
- `DELETE /api/websites/:id` - Delete website
### Scans
- `POST /api/scans` - Start new scan
- `GET /api/scans/:id` - Get scan status
- `GET /api/scans/:id/result` - Get scan results
- `GET /api/scans/:id/violations` - Get violations
- `DELETE /api/scans/:id` - Cancel scan
### Reports
- `GET /api/reports/compliance/:websiteId` - Get compliance report
- `GET /api/reports/trends/:websiteId` - Get trend analysis
### Health
- `GET /health` - Service health check
- `GET /health/stats` - Detailed statistics
## Development
### Project Structure
```
apps/wcag-ada/
├── api/ # REST API service
├── config/ # Configuration management
├── dashboard/ # React web interface
├── scanner/ # Accessibility scanning engine
├── shared/ # Shared types and utilities
└── worker/ # Background job processor
```
### Testing
Run tests for all services:
```bash
bun test
```
### Building for Production
```bash
bun run build
```
## Deployment
The application is designed to be deployed as separate microservices. Each service can be containerized and deployed independently.
### Docker Support
Build Docker images:
```bash
docker build -t wcag-ada-api -f apps/wcag-ada/api/Dockerfile .
docker build -t wcag-ada-worker -f apps/wcag-ada/worker/Dockerfile .
docker build -t wcag-ada-dashboard -f apps/wcag-ada/dashboard/Dockerfile .
```
## License
Proprietary - All rights reserved

View file

@ -1,40 +0,0 @@
# Database URL (required for Prisma)
DATABASE_URL=postgresql://user:password@localhost:5432/wcag_ada
# Environment variables for configuration overrides
# These follow the WCAG_ prefix convention
# Override service ports
# WCAG_SERVICES_API_PORT=3001
# WCAG_SERVICES_DASHBOARD_PORT=3000
# WCAG_SERVICES_WORKER_PORT=3002
# Override database settings
# WCAG_DATABASE_POSTGRES_HOST=localhost
# WCAG_DATABASE_POSTGRES_PORT=5432
# WCAG_DATABASE_POSTGRES_DATABASE=wcag_ada
# Override Redis settings
# WCAG_WORKER_REDIS_HOST=localhost
# WCAG_WORKER_REDIS_PORT=6379
# WCAG_WORKER_REDIS_PASSWORD=
# WCAG_WORKER_REDIS_DB=2
# Override JWT settings
# WCAG_PROVIDERS_AUTH_JWT_SECRET=your-super-secret-key
# WCAG_PROVIDERS_AUTH_JWT_EXPIRES_IN=7d
# Override scanner settings
# WCAG_SCANNER_CONCURRENCY=2
# WCAG_SCANNER_TIMEOUT=120000
# WCAG_SCANNER_HEADLESS=true
# Override storage settings
# WCAG_PROVIDERS_STORAGE_TYPE=local
# WCAG_PROVIDERS_STORAGE_LOCAL_BASE_PATH=/tmp/wcag-ada
# Override email settings
# WCAG_PROVIDERS_EMAIL_SMTP_HOST=localhost
# WCAG_PROVIDERS_EMAIL_SMTP_PORT=587
# WCAG_PROVIDERS_EMAIL_SMTP_AUTH_USER=
# WCAG_PROVIDERS_EMAIL_SMTP_AUTH_PASS=

View file

@ -1,66 +0,0 @@
# Build stage
FROM oven/bun:1-alpine as builder
# Install dependencies for Prisma
RUN apk add --no-cache openssl
WORKDIR /app
# Copy workspace files
COPY package.json bun.lockb ./
COPY apps/wcag-ada/api/package.json ./apps/wcag-ada/api/
COPY apps/wcag-ada/config/package.json ./apps/wcag-ada/config/
COPY apps/wcag-ada/shared/package.json ./apps/wcag-ada/shared/
COPY lib/service/core-config/package.json ./lib/service/core-config/
COPY lib/service/core-logger/package.json ./lib/service/core-logger/
# Install dependencies
RUN bun install --frozen-lockfile
# Copy source code
COPY apps/wcag-ada/api ./apps/wcag-ada/api
COPY apps/wcag-ada/config ./apps/wcag-ada/config
COPY apps/wcag-ada/shared ./apps/wcag-ada/shared
COPY lib/service/core-config ./lib/service/core-config
COPY lib/service/core-logger ./lib/service/core-logger
COPY tsconfig.json ./
# Generate Prisma client
WORKDIR /app/apps/wcag-ada/api
RUN bunx prisma generate
# Build the application
RUN bun run build
# Production stage
FROM oven/bun:1-alpine
# Install runtime dependencies
RUN apk add --no-cache openssl
WORKDIR /app
# Copy built application
COPY --from=builder /app/apps/wcag-ada/api/dist ./dist
COPY --from=builder /app/apps/wcag-ada/api/node_modules ./node_modules
COPY --from=builder /app/apps/wcag-ada/api/prisma ./prisma
COPY --from=builder /app/apps/wcag-ada/api/package.json ./
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Set ownership
RUN chown -R nodejs:nodejs /app
USER nodejs
# Expose port
EXPOSE 3001
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
# Start the application
CMD ["bun", "run", "start"]

View file

@ -1,34 +0,0 @@
{
"name": "@wcag-ada/api",
"version": "0.1.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"dev": "bun run --hot src/index.ts",
"build": "tsc -b",
"start": "bun run dist/index.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"hono": "^3.11.7",
"@hono/node-server": "^1.4.0",
"@hono/zod-validator": "^0.5.0",
"zod": "^3.22.4",
"@wcag-ada/shared": "workspace:*",
"@wcag-ada/scanner": "workspace:*",
"@wcag-ada/config": "workspace:*",
"jsonwebtoken": "^9.0.2",
"bcryptjs": "^2.4.3",
"nanoid": "^5.0.4",
"@prisma/client": "^5.8.0",
"bullmq": "^5.1.1",
"ioredis": "^5.3.2"
},
"devDependencies": {
"@types/node": "^20.11.5",
"@types/jsonwebtoken": "^9.0.5",
"@types/bcryptjs": "^2.4.6",
"prisma": "^5.8.0",
"typescript": "^5.3.3"
}
}

View file

@ -1,153 +0,0 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
passwordHash String
name String?
company String?
role UserRole @default(USER)
apiKey String? @unique
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
websites Website[]
reports Report[]
scanJobs ScanJob[]
}
model Website {
id String @id @default(cuid())
name String
url String
userId String
user User @relation(fields: [userId], references: [id])
scanSchedule Json? // ScanSchedule type
lastScanAt DateTime?
complianceScore Float?
tags String[]
active Boolean @default(true)
authConfig Json? // AuthenticationConfig type
scanOptions Json? // Default scan options
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
scanResults ScanResult[]
scanJobs ScanJob[]
reports Report[]
@@index([userId])
@@index([url])
}
model ScanResult {
id String @id @default(cuid())
websiteId String
website Website @relation(fields: [websiteId], references: [id])
jobId String? @unique
job ScanJob? @relation(fields: [jobId], references: [id])
url String
scanDuration Int
summary Json // ScanSummary type
violations Json // AccessibilityViolation[] type
passes Json // AxeResult[] type
incomplete Json // AxeResult[] type
inapplicable Json // AxeResult[] type
pageMetadata Json // PageMetadata type
wcagCompliance Json // WCAGCompliance type
createdAt DateTime @default(now())
@@index([websiteId])
@@index([createdAt])
}
model ScanJob {
id String @id @default(cuid())
websiteId String
website Website @relation(fields: [websiteId], references: [id])
userId String
user User @relation(fields: [userId], references: [id])
url String
status JobStatus @default(PENDING)
options Json // AccessibilityScanOptions type
scheduledAt DateTime @default(now())
startedAt DateTime?
completedAt DateTime?
error String?
retryCount Int @default(0)
maxRetries Int @default(3)
result ScanResult?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([websiteId])
@@index([status])
@@index([scheduledAt])
}
model Report {
id String @id @default(cuid())
websiteId String
website Website @relation(fields: [websiteId], references: [id])
userId String
user User @relation(fields: [userId], references: [id])
type ReportType
format ReportFormat
period Json // ReportPeriod type
summary Json // ReportSummary type
data Json // Report data
fileUrl String?
generatedAt DateTime @default(now())
@@index([websiteId])
@@index([userId])
@@index([generatedAt])
}
enum UserRole {
USER
ADMIN
}
enum JobStatus {
PENDING
RUNNING
COMPLETED
FAILED
}
enum ReportType {
COMPLIANCE
EXECUTIVE
TECHNICAL
TREND
}
enum ReportFormat {
PDF
HTML
JSON
CSV
}

View file

@ -1,39 +0,0 @@
import { initializeWcagConfig, getWcagConfig } from '@wcag-ada/config';
// Initialize configuration for API service
const appConfig = initializeWcagConfig('api');
// Export a config object that matches the expected interface
export const config = {
NODE_ENV: appConfig.environment as 'development' | 'production' | 'test',
PORT: appConfig.services.api.port,
// Database
DATABASE_URL: process.env.DATABASE_URL ||
`postgresql://${appConfig.database.postgres.user || 'postgres'}:${appConfig.database.postgres.password || 'postgres'}@${appConfig.database.postgres.host}:${appConfig.database.postgres.port}/${appConfig.database.postgres.database}`,
REDIS_URL: `redis://${appConfig.worker.redis.host}:${appConfig.worker.redis.port}/${appConfig.worker.redis.db}`,
// Auth
JWT_SECRET: appConfig.providers.auth.jwt.secret,
JWT_EXPIRES_IN: appConfig.providers.auth.jwt.expiresIn,
// Scanner
SCANNER_CONCURRENCY: appConfig.scanner.concurrency,
SCANNER_TIMEOUT: appConfig.scanner.timeout,
// API Rate Limiting
API_RATE_LIMIT: appConfig.services.api.rateLimit.max,
API_RATE_WINDOW: appConfig.services.api.rateLimit.windowMs,
// Storage
REPORT_STORAGE_PATH: `${appConfig.providers.storage.local.basePath}/${appConfig.providers.storage.local.reports}`,
SCREENSHOT_STORAGE_PATH: `${appConfig.providers.storage.local.basePath}/${appConfig.providers.storage.local.screenshots}`,
// CORS
CORS_ORIGIN: appConfig.services.api.cors.origin,
};
export type Config = typeof config;
// Export the full app config for advanced usage
export { appConfig };

View file

@ -1,64 +0,0 @@
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger as honoLogger } from 'hono/logger';
import { compress } from 'hono/compress';
import { secureHeaders } from 'hono/secure-headers';
import { config, appConfig } from './config';
import { logger } from './utils/logger';
// Import routes
import { authRoutes } from './routes/auth';
import { websiteRoutes } from './routes/websites';
import { scanRoutes } from './routes/scans';
import { reportRoutes } from './routes/reports';
import { healthRoutes } from './routes/health';
// Import middleware
import { errorHandler } from './middleware/error-handler';
import { rateLimiter } from './middleware/rate-limiter';
const app = new Hono();
// Global middleware
app.use('*', honoLogger());
app.use('*', cors({
origin: config.CORS_ORIGIN || '*',
credentials: true,
}));
app.use('*', compress());
app.use('*', secureHeaders());
// Rate limiting
app.use('/api/*', rateLimiter());
// Health check (no auth required)
app.route('/health', healthRoutes);
// API routes
app.route('/api/auth', authRoutes);
app.route('/api/websites', websiteRoutes);
app.route('/api/scans', scanRoutes);
app.route('/api/reports', reportRoutes);
// 404 handler
app.notFound((c) => {
return c.json({ error: 'Not Found' }, 404);
});
// Global error handler
app.onError(errorHandler);
// Start server
const port = config.PORT || 3001;
logger.info(`🚀 WCAG-ADA API Server starting on port ${port}...`);
serve({
fetch: app.fetch,
port,
}, (info) => {
logger.info(`✅ Server is running on http://localhost:${info.port}`);
});
export default app;

View file

@ -1,69 +0,0 @@
import { Context, Next } from 'hono';
import { verify } from 'hono/jwt';
import { prisma } from '../utils/prisma';
import { config } from '../config';
export const authenticate = async (c: Context, next: Next) => {
try {
// Check for Bearer token
const authHeader = c.req.header('Authorization');
if (authHeader && authHeader.startsWith('Bearer ')) {
const token = authHeader.substring(7);
try {
const payload = await verify(token, config.JWT_SECRET, 'HS256') as {
sub: string;
email: string;
role: string;
};
c.set('userId', payload.sub);
c.set('userRole', payload.role);
c.set('authType', 'jwt');
return next();
} catch (error) {
// Invalid JWT, continue to check API key
}
}
// Check for API key
const apiKey = c.req.header('X-API-Key');
if (apiKey) {
const user = await prisma.user.findUnique({
where: {
apiKey,
isActive: true,
},
select: {
id: true,
role: true,
},
});
if (user) {
c.set('userId', user.id);
c.set('userRole', user.role);
c.set('authType', 'apiKey');
return next();
}
}
return c.json({ error: 'Unauthorized' }, 401);
} catch (error) {
return c.json({ error: 'Authentication failed' }, 401);
}
};
export const requireRole = (role: string) => {
return async (c: Context, next: Next) => {
const userRole = c.get('userRole');
if (!userRole || userRole !== role) {
return c.json({ error: 'Insufficient permissions' }, 403);
}
return next();
};
};

View file

@ -1,59 +0,0 @@
import { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { ZodError } from 'zod';
import { appConfig } from '../config';
import { logger } from '../utils/logger';
export const errorHandler = (err: Error, c: Context) => {
logger.error('Error:', err);
// Handle Hono HTTP exceptions
if (err instanceof HTTPException) {
return c.json(
{ error: err.message },
err.status
);
}
// Handle Zod validation errors
if (err instanceof ZodError) {
return c.json(
{
error: 'Validation error',
details: err.errors.map(e => ({
path: e.path.join('.'),
message: e.message,
})),
},
400
);
}
// Handle Prisma errors
if (err.constructor.name === 'PrismaClientKnownRequestError') {
const prismaError = err as any;
if (prismaError.code === 'P2002') {
return c.json(
{ error: 'Duplicate entry' },
400
);
}
if (prismaError.code === 'P2025') {
return c.json(
{ error: 'Record not found' },
404
);
}
}
// Default error response
return c.json(
{
error: 'Internal server error',
message: appConfig.env === 'development' ? err.message : undefined,
},
500
);
};

View file

@ -1,75 +0,0 @@
import { Context, Next } from 'hono';
import Redis from 'ioredis';
import { config } from '../config';
import { logger } from '../utils/logger';
import { getWorkerConfig } from '@wcag-ada/config';
const workerConfig = getWorkerConfig();
const redis = new Redis({
host: workerConfig.redis.host,
port: workerConfig.redis.port,
password: workerConfig.redis.password,
db: workerConfig.redis.db,
});
interface RateLimitOptions {
limit?: number;
window?: number; // in milliseconds
keyGenerator?: (c: Context) => string;
}
export const rateLimiter = (options: RateLimitOptions = {}) => {
const {
limit = config.API_RATE_LIMIT,
window = config.API_RATE_WINDOW,
keyGenerator = (c) => {
const userId = c.get('userId');
const ip = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
return userId ? `rate:user:${userId}` : `rate:ip:${ip}`;
},
} = options;
return async (c: Context, next: Next) => {
const key = keyGenerator(c);
try {
// Get current count
const current = await redis.get(key);
const count = current ? parseInt(current) : 0;
// Check if limit exceeded
if (count >= limit) {
const ttl = await redis.pttl(key);
c.header('X-RateLimit-Limit', limit.toString());
c.header('X-RateLimit-Remaining', '0');
c.header('X-RateLimit-Reset', new Date(Date.now() + ttl).toISOString());
return c.json(
{
error: 'Rate limit exceeded',
retryAfter: Math.ceil(ttl / 1000),
},
429
);
}
// Increment counter
const pipeline = redis.pipeline();
pipeline.incr(key);
pipeline.pexpire(key, window);
await pipeline.exec();
// Set headers
c.header('X-RateLimit-Limit', limit.toString());
c.header('X-RateLimit-Remaining', (limit - count - 1).toString());
c.header('X-RateLimit-Reset', new Date(Date.now() + window).toISOString());
return next();
} catch (error) {
logger.error('Rate limiter error:', error);
// Continue on error - don't block requests due to rate limiter failure
return next();
}
};
};

View file

@ -1,177 +0,0 @@
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { sign } from 'hono/jwt';
import bcrypt from 'bcryptjs';
import { nanoid } from 'nanoid';
import { prisma } from '../utils/prisma';
import { config } from '../config';
const authRoutes = new Hono();
// Validation schemas
const registerSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
name: z.string().optional(),
company: z.string().optional(),
});
const loginSchema = z.object({
email: z.string().email(),
password: z.string(),
});
// Register
authRoutes.post('/register', zValidator('json', registerSchema), async (c) => {
const { email, password, name, company } = c.req.valid('json');
// Check if user exists
const existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
return c.json({ error: 'User already exists' }, 400);
}
// Hash password
const passwordHash = await bcrypt.hash(password, 10);
// Create user with API key
const user = await prisma.user.create({
data: {
email,
passwordHash,
name,
company,
apiKey: `wcag_${nanoid(32)}`,
},
select: {
id: true,
email: true,
name: true,
company: true,
apiKey: true,
role: true,
},
});
// Generate JWT
const token = await sign(
{
sub: user.id,
email: user.email,
role: user.role,
},
config.JWT_SECRET,
'HS256'
);
return c.json({
user,
token,
});
});
// Login
authRoutes.post('/login', zValidator('json', loginSchema), async (c) => {
const { email, password } = c.req.valid('json');
// Find user
const user = await prisma.user.findUnique({
where: { email },
select: {
id: true,
email: true,
passwordHash: true,
name: true,
company: true,
apiKey: true,
role: true,
isActive: true,
},
});
if (!user || !user.isActive) {
return c.json({ error: 'Invalid credentials' }, 401);
}
// Verify password
const validPassword = await bcrypt.compare(password, user.passwordHash);
if (!validPassword) {
return c.json({ error: 'Invalid credentials' }, 401);
}
// Generate JWT
const token = await sign(
{
sub: user.id,
email: user.email,
role: user.role,
},
config.JWT_SECRET,
'HS256'
);
// Remove passwordHash from response
const { passwordHash, ...userWithoutPassword } = user;
return c.json({
user: userWithoutPassword,
token,
});
});
// Refresh API key
authRoutes.post('/refresh-api-key', async (c) => {
const userId = c.get('userId');
if (!userId) {
return c.json({ error: 'Unauthorized' }, 401);
}
const newApiKey = `wcag_${nanoid(32)}`;
const user = await prisma.user.update({
where: { id: userId },
data: { apiKey: newApiKey },
select: {
id: true,
email: true,
apiKey: true,
},
});
return c.json({ apiKey: user.apiKey });
});
// Get current user
authRoutes.get('/me', async (c) => {
const userId = c.get('userId');
if (!userId) {
return c.json({ error: 'Unauthorized' }, 401);
}
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
email: true,
name: true,
company: true,
role: true,
apiKey: true,
createdAt: true,
},
});
if (!user) {
return c.json({ error: 'User not found' }, 404);
}
return c.json(user);
});
export { authRoutes };

View file

@ -1,118 +0,0 @@
import { Hono } from 'hono';
import { Queue } from 'bullmq';
import { prisma } from '../utils/prisma';
import Redis from 'ioredis';
import { appConfig } from '../config';
import { getWorkerConfig } from '@wcag-ada/config';
const healthRoutes = new Hono();
healthRoutes.get('/', async (c) => {
const checks = {
api: 'ok',
database: 'unknown',
redis: 'unknown',
queue: 'unknown',
};
// Check database
try {
await prisma.$queryRaw`SELECT 1`;
checks.database = 'ok';
} catch (error) {
checks.database = 'error';
}
// Check Redis
try {
const workerConfig = getWorkerConfig();
const redis = new Redis({
host: workerConfig.redis.host,
port: workerConfig.redis.port,
password: workerConfig.redis.password,
db: workerConfig.redis.db,
});
await redis.ping();
await redis.quit();
checks.redis = 'ok';
} catch (error) {
checks.redis = 'error';
}
// Check queue
try {
const workerConfig = getWorkerConfig();
const queue = new Queue(workerConfig.queueName, {
connection: new Redis({
host: workerConfig.redis.host,
port: workerConfig.redis.port,
password: workerConfig.redis.password,
db: workerConfig.redis.db,
}),
});
await queue.getJobCounts();
await queue.close();
checks.queue = 'ok';
} catch (error) {
checks.queue = 'error';
}
const allHealthy = Object.values(checks).every(status => status === 'ok');
return c.json(
{
status: allHealthy ? 'healthy' : 'unhealthy',
checks,
timestamp: new Date().toISOString(),
},
allHealthy ? 200 : 503
);
});
healthRoutes.get('/stats', async (c) => {
try {
// Get queue stats
const workerConfig = getWorkerConfig();
const queue = new Queue(workerConfig.queueName, {
connection: new Redis({
host: workerConfig.redis.host,
port: workerConfig.redis.port,
password: workerConfig.redis.password,
db: workerConfig.redis.db,
}),
});
const [waiting, active, completed, failed] = await Promise.all([
queue.getWaitingCount(),
queue.getActiveCount(),
queue.getCompletedCount(),
queue.getFailedCount(),
]);
const queueStats = { waiting, active, completed, failed };
const dbStats = await Promise.all([
prisma.user.count(),
prisma.website.count({ where: { active: true } }),
prisma.scanJob.count(),
prisma.scanResult.count(),
]);
await queue.close();
return c.json({
queue: queueStats,
database: {
users: dbStats[0],
websites: dbStats[1],
scanJobs: dbStats[2],
scanResults: dbStats[3],
},
timestamp: new Date().toISOString(),
});
} catch (error) {
return c.json({ error: 'Failed to get stats' }, 500);
}
});
export { healthRoutes };

View file

@ -1,244 +0,0 @@
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { prisma } from '../utils/prisma';
import { authenticate } from '../middleware/auth';
import { generateReport } from '../services/report-generator';
import type { ReportPeriod } from '@wcag-ada/shared';
const reportRoutes = new Hono();
// Apply authentication to all routes
reportRoutes.use('*', authenticate);
// Validation schemas
const generateReportSchema = z.object({
websiteId: z.string(),
type: z.enum(['COMPLIANCE', 'EXECUTIVE', 'TECHNICAL', 'TREND']),
format: z.enum(['PDF', 'HTML', 'JSON', 'CSV']),
period: z.object({
start: z.string().transform(s => new Date(s)),
end: z.string().transform(s => new Date(s)),
}),
});
// Generate a new report
reportRoutes.post('/generate', zValidator('json', generateReportSchema), async (c) => {
const userId = c.get('userId');
const { websiteId, type, format, period } = c.req.valid('json');
// Check website ownership
const website = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
active: true,
},
});
if (!website) {
return c.json({ error: 'Website not found' }, 404);
}
// Get scan results for the period
const scanResults = await prisma.scanResult.findMany({
where: {
websiteId,
createdAt: {
gte: period.start,
lte: period.end,
},
},
orderBy: { createdAt: 'asc' },
});
if (scanResults.length === 0) {
return c.json({ error: 'No scan data available for the specified period' }, 400);
}
// Generate report data
const reportData = await generateReport({
website,
scanResults,
type,
format,
period,
});
// Save report
const report = await prisma.report.create({
data: {
websiteId,
userId,
type,
format,
period: period as any,
summary: reportData.summary as any,
data: reportData.data as any,
fileUrl: reportData.fileUrl,
},
});
return c.json({
report: {
id: report.id,
type: report.type,
format: report.format,
period: report.period,
fileUrl: report.fileUrl,
generatedAt: report.generatedAt,
},
}, 201);
});
// Get user's reports
reportRoutes.get('/', async (c) => {
const userId = c.get('userId');
const { page = '1', limit = '20', websiteId, type } = c.req.query();
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
const where = {
userId,
...(websiteId && { websiteId }),
...(type && { type }),
};
const [reports, total] = await Promise.all([
prisma.report.findMany({
where,
skip,
take: limitNum,
orderBy: { generatedAt: 'desc' },
include: {
website: {
select: {
id: true,
name: true,
url: true,
},
},
},
}),
prisma.report.count({ where }),
]);
return c.json({
reports,
pagination: {
page: pageNum,
limit: limitNum,
total,
totalPages: Math.ceil(total / limitNum),
},
});
});
// Get report by ID
reportRoutes.get('/:id', async (c) => {
const userId = c.get('userId');
const reportId = c.req.param('id');
const report = await prisma.report.findFirst({
where: {
id: reportId,
userId,
},
include: {
website: {
select: {
id: true,
name: true,
url: true,
},
},
},
});
if (!report) {
return c.json({ error: 'Report not found' }, 404);
}
return c.json(report);
});
// Download report file
reportRoutes.get('/:id/download', async (c) => {
const userId = c.get('userId');
const reportId = c.req.param('id');
const report = await prisma.report.findFirst({
where: {
id: reportId,
userId,
},
});
if (!report || !report.fileUrl) {
return c.json({ error: 'Report file not found' }, 404);
}
// In production, this would redirect to a signed URL or serve from storage
// For now, we'll just return the file URL
return c.json({ downloadUrl: report.fileUrl });
});
// Get compliance trends
reportRoutes.get('/trends/:websiteId', async (c) => {
const userId = c.get('userId');
const websiteId = c.req.param('websiteId');
const { days = '30' } = c.req.query();
// Check website ownership
const website = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
},
});
if (!website) {
return c.json({ error: 'Website not found' }, 404);
}
const daysNum = parseInt(days);
const startDate = new Date();
startDate.setDate(startDate.getDate() - daysNum);
const scanResults = await prisma.scanResult.findMany({
where: {
websiteId,
createdAt: {
gte: startDate,
},
},
orderBy: { createdAt: 'asc' },
select: {
createdAt: true,
summary: true,
wcagCompliance: true,
},
});
const trends = scanResults.map(result => ({
date: result.createdAt,
score: (result.summary as any).score,
violationCount: (result.summary as any).violationCount,
passCount: (result.summary as any).passCount,
criticalIssues: (result.summary as any).criticalIssues,
seriousIssues: (result.summary as any).seriousIssues,
}));
return c.json({
websiteId,
period: {
start: startDate,
end: new Date(),
},
trends,
});
});
export { reportRoutes };

View file

@ -1,283 +0,0 @@
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { Queue } from 'bullmq';
import Redis from 'ioredis';
import { prisma } from '../utils/prisma';
import { authenticate } from '../middleware/auth';
import { getWorkerConfig } from '@wcag-ada/config';
import type { AccessibilityScanOptions } from '@wcag-ada/shared';
const scanRoutes = new Hono();
// Get worker config for queue connection
const workerConfig = getWorkerConfig();
// Create queue connection
const scanQueue = new Queue('accessibility-scans', {
connection: new Redis({
host: workerConfig.redis.host,
port: workerConfig.redis.port,
password: workerConfig.redis.password,
db: workerConfig.redis.db,
}),
});
// Apply authentication to all routes
scanRoutes.use('*', authenticate);
// Validation schemas
const createScanSchema = z.object({
websiteId: z.string(),
url: z.string().url().optional(),
options: z.object({
wcagLevel: z.object({
level: z.enum(['A', 'AA', 'AAA']),
version: z.enum(['2.0', '2.1', '2.2']),
}).optional(),
viewport: z.object({
width: z.number(),
height: z.number(),
deviceScaleFactor: z.number().optional(),
isMobile: z.boolean().optional(),
}).optional(),
includeScreenshots: z.boolean().optional(),
excludeSelectors: z.array(z.string()).optional(),
waitForSelector: z.string().optional(),
timeout: z.number().optional(),
}).optional(),
});
// Start a new scan
scanRoutes.post('/', zValidator('json', createScanSchema), async (c) => {
const userId = c.get('userId');
const { websiteId, url, options } = c.req.valid('json');
// Get website
const website = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
active: true,
},
});
if (!website) {
return c.json({ error: 'Website not found' }, 404);
}
// Merge options with website defaults
const scanOptions: AccessibilityScanOptions = {
url: url || website.url,
...website.scanOptions as any,
...options,
authenticate: website.authConfig as any,
};
// Create scan job
const job = await prisma.scanJob.create({
data: {
websiteId,
userId,
url: scanOptions.url,
options: scanOptions as any,
status: 'PENDING',
},
});
// Queue the scan
await scanQueue.add('scan', {
jobId: job.id,
websiteId,
userId,
options: scanOptions,
}, {
jobId: job.id,
});
return c.json({
job: {
id: job.id,
status: job.status,
url: job.url,
scheduledAt: job.scheduledAt,
},
message: 'Scan queued successfully',
}, 202);
});
// Get scan status
scanRoutes.get('/:id', async (c) => {
const userId = c.get('userId');
const scanId = c.req.param('id');
const job = await prisma.scanJob.findFirst({
where: {
id: scanId,
userId,
},
include: {
result: {
select: {
id: true,
summary: true,
wcagCompliance: true,
createdAt: true,
},
},
},
});
if (!job) {
return c.json({ error: 'Scan not found' }, 404);
}
return c.json(job);
});
// Get scan result
scanRoutes.get('/:id/result', async (c) => {
const userId = c.get('userId');
const scanId = c.req.param('id');
const result = await prisma.scanResult.findFirst({
where: {
jobId: scanId,
job: {
userId,
},
},
});
if (!result) {
return c.json({ error: 'Scan result not found' }, 404);
}
return c.json(result);
});
// Get scan violations
scanRoutes.get('/:id/violations', async (c) => {
const userId = c.get('userId');
const scanId = c.req.param('id');
const { impact, tag } = c.req.query();
const result = await prisma.scanResult.findFirst({
where: {
jobId: scanId,
job: {
userId,
},
},
select: {
violations: true,
},
});
if (!result) {
return c.json({ error: 'Scan result not found' }, 404);
}
let violations = result.violations as any[];
// Filter by impact if provided
if (impact) {
violations = violations.filter(v => v.impact === impact);
}
// Filter by tag if provided
if (tag) {
violations = violations.filter(v => v.tags.includes(tag));
}
return c.json({ violations });
});
// Cancel a pending scan
scanRoutes.delete('/:id', async (c) => {
const userId = c.get('userId');
const scanId = c.req.param('id');
const job = await prisma.scanJob.findFirst({
where: {
id: scanId,
userId,
status: 'PENDING',
},
});
if (!job) {
return c.json({ error: 'Scan not found or cannot be cancelled' }, 404);
}
// Update job status
await prisma.scanJob.update({
where: { id: scanId },
data: {
status: 'FAILED',
error: 'Cancelled by user',
completedAt: new Date(),
},
});
// Remove from queue if possible
const queueJob = await scanQueue.getJob(scanId);
if (queueJob) {
await queueJob.remove();
}
return c.json({ message: 'Scan cancelled successfully' });
});
// Get user's scan history
scanRoutes.get('/', async (c) => {
const userId = c.get('userId');
const { page = '1', limit = '20', status, websiteId } = c.req.query();
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
const where = {
userId,
...(status && { status }),
...(websiteId && { websiteId }),
};
const [jobs, total] = await Promise.all([
prisma.scanJob.findMany({
where,
skip,
take: limitNum,
orderBy: { createdAt: 'desc' },
include: {
website: {
select: {
id: true,
name: true,
url: true,
},
},
result: {
select: {
id: true,
summary: true,
},
},
},
}),
prisma.scanJob.count({ where }),
]);
return c.json({
scans: jobs,
pagination: {
page: pageNum,
limit: limitNum,
total,
totalPages: Math.ceil(total / limitNum),
},
});
});
export { scanRoutes };

View file

@ -1,245 +0,0 @@
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { prisma } from '../utils/prisma';
import { authenticate } from '../middleware/auth';
import type { Website, ScanSchedule } from '@wcag-ada/shared';
const websiteRoutes = new Hono();
// Apply authentication to all routes
websiteRoutes.use('*', authenticate);
// Validation schemas
const createWebsiteSchema = z.object({
name: z.string().min(1),
url: z.string().url(),
tags: z.array(z.string()).optional(),
scanSchedule: z.object({
frequency: z.enum(['manual', 'hourly', 'daily', 'weekly', 'monthly']),
dayOfWeek: z.number().min(0).max(6).optional(),
dayOfMonth: z.number().min(1).max(31).optional(),
hour: z.number().min(0).max(23).optional(),
timezone: z.string().optional(),
}).optional(),
authConfig: z.any().optional(),
scanOptions: z.any().optional(),
});
const updateWebsiteSchema = createWebsiteSchema.partial();
// List websites
websiteRoutes.get('/', async (c) => {
const userId = c.get('userId');
const { page = '1', limit = '20', search } = c.req.query();
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
const where = {
userId,
...(search && {
OR: [
{ name: { contains: search, mode: 'insensitive' } },
{ url: { contains: search, mode: 'insensitive' } },
],
}),
};
const [websites, total] = await Promise.all([
prisma.website.findMany({
where,
skip,
take: limitNum,
orderBy: { createdAt: 'desc' },
include: {
_count: {
select: { scanResults: true },
},
},
}),
prisma.website.count({ where }),
]);
return c.json({
websites,
pagination: {
page: pageNum,
limit: limitNum,
total,
totalPages: Math.ceil(total / limitNum),
},
});
});
// Get website by ID
websiteRoutes.get('/:id', async (c) => {
const userId = c.get('userId');
const websiteId = c.req.param('id');
const website = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
},
include: {
scanResults: {
take: 1,
orderBy: { createdAt: 'desc' },
},
_count: {
select: {
scanResults: true,
scanJobs: true,
},
},
},
});
if (!website) {
return c.json({ error: 'Website not found' }, 404);
}
return c.json(website);
});
// Create website
websiteRoutes.post('/', zValidator('json', createWebsiteSchema), async (c) => {
const userId = c.get('userId');
const data = c.req.valid('json');
// Check if website already exists for this user
const existing = await prisma.website.findFirst({
where: {
url: data.url,
userId,
},
});
if (existing) {
return c.json({ error: 'Website already exists' }, 400);
}
const website = await prisma.website.create({
data: {
...data,
userId,
scanSchedule: data.scanSchedule ? data.scanSchedule : undefined,
authConfig: data.authConfig ? data.authConfig : undefined,
scanOptions: data.scanOptions ? data.scanOptions : undefined,
},
});
return c.json(website, 201);
});
// Update website
websiteRoutes.patch('/:id', zValidator('json', updateWebsiteSchema), async (c) => {
const userId = c.get('userId');
const websiteId = c.req.param('id');
const data = c.req.valid('json');
// Check ownership
const existing = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
},
});
if (!existing) {
return c.json({ error: 'Website not found' }, 404);
}
const website = await prisma.website.update({
where: { id: websiteId },
data: {
...data,
scanSchedule: data.scanSchedule !== undefined ? data.scanSchedule : undefined,
authConfig: data.authConfig !== undefined ? data.authConfig : undefined,
scanOptions: data.scanOptions !== undefined ? data.scanOptions : undefined,
},
});
return c.json(website);
});
// Delete website
websiteRoutes.delete('/:id', async (c) => {
const userId = c.get('userId');
const websiteId = c.req.param('id');
// Check ownership
const existing = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
},
});
if (!existing) {
return c.json({ error: 'Website not found' }, 404);
}
// Soft delete by setting active to false
await prisma.website.update({
where: { id: websiteId },
data: { active: false },
});
return c.json({ message: 'Website deleted successfully' });
});
// Get website scan history
websiteRoutes.get('/:id/scans', async (c) => {
const userId = c.get('userId');
const websiteId = c.req.param('id');
const { page = '1', limit = '20' } = c.req.query();
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
// Check ownership
const website = await prisma.website.findFirst({
where: {
id: websiteId,
userId,
},
});
if (!website) {
return c.json({ error: 'Website not found' }, 404);
}
const [scans, total] = await Promise.all([
prisma.scanResult.findMany({
where: { websiteId },
skip,
take: limitNum,
orderBy: { createdAt: 'desc' },
select: {
id: true,
url: true,
scanDuration: true,
summary: true,
wcagCompliance: true,
createdAt: true,
},
}),
prisma.scanResult.count({ where: { websiteId } }),
]);
return c.json({
scans,
pagination: {
page: pageNum,
limit: limitNum,
total,
totalPages: Math.ceil(total / limitNum),
},
});
});
export { websiteRoutes };

View file

@ -1,271 +0,0 @@
import type { Website, ScanResult, Report } from '@prisma/client';
import type { ReportPeriod, ReportSummary } from '@wcag-ada/shared';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';
import { appConfig } from '../config';
import { getStorageConfig } from '@wcag-ada/config';
import { nanoid } from 'nanoid';
interface GenerateReportOptions {
website: Website;
scanResults: ScanResult[];
type: 'COMPLIANCE' | 'EXECUTIVE' | 'TECHNICAL' | 'TREND';
format: 'PDF' | 'HTML' | 'JSON' | 'CSV';
period: ReportPeriod;
}
interface GenerateReportResult {
summary: ReportSummary;
data: any;
fileUrl?: string;
}
export async function generateReport(
options: GenerateReportOptions
): Promise<GenerateReportResult> {
const { website, scanResults, type, format, period } = options;
// Calculate summary statistics
const summary = calculateReportSummary(scanResults, period);
// Generate report data based on type
let data: any;
switch (type) {
case 'COMPLIANCE':
data = generateComplianceData(website, scanResults, summary);
break;
case 'EXECUTIVE':
data = generateExecutiveData(website, scanResults, summary);
break;
case 'TECHNICAL':
data = generateTechnicalData(website, scanResults, summary);
break;
case 'TREND':
data = generateTrendData(website, scanResults, summary);
break;
}
// Generate file if not JSON format
let fileUrl: string | undefined;
if (format !== 'JSON') {
fileUrl = await generateReportFile(data, format, type);
}
return {
summary,
data,
fileUrl,
};
}
function calculateReportSummary(
scanResults: ScanResult[],
period: ReportPeriod
): ReportSummary {
if (scanResults.length === 0) {
return {
averageScore: 0,
totalScans: 0,
improvementRate: 0,
criticalIssuesFixed: 0,
newIssuesFound: 0,
complianceLevel: { level: 'AA', version: '2.1' },
};
}
// Calculate average score
const scores = scanResults.map(r => (r.summary as any).score || 0);
const averageScore = scores.reduce((a, b) => a + b, 0) / scores.length;
// Calculate improvement rate
const firstScore = scores[0];
const lastScore = scores[scores.length - 1];
const improvementRate = firstScore > 0 ? ((lastScore - firstScore) / firstScore) * 100 : 0;
// Count issues fixed and new issues
let criticalIssuesFixed = 0;
let newIssuesFound = 0;
if (scanResults.length >= 2) {
const firstScan = scanResults[0];
const lastScan = scanResults[scanResults.length - 1];
const firstCritical = (firstScan.summary as any).criticalIssues || 0;
const lastCritical = (lastScan.summary as any).criticalIssues || 0;
criticalIssuesFixed = Math.max(0, firstCritical - lastCritical);
newIssuesFound = Math.max(0, lastCritical - firstCritical);
}
// Get compliance level from last scan
const lastScan = scanResults[scanResults.length - 1];
const complianceLevel = (lastScan.wcagCompliance as any)?.level || { level: 'AA', version: '2.1' };
return {
averageScore: Math.round(averageScore * 100) / 100,
totalScans: scanResults.length,
improvementRate: Math.round(improvementRate * 100) / 100,
criticalIssuesFixed,
newIssuesFound,
complianceLevel,
};
}
function generateComplianceData(
website: Website,
scanResults: ScanResult[],
summary: ReportSummary
): any {
return {
website: {
name: website.name,
url: website.url,
},
summary,
latestScan: scanResults[scanResults.length - 1],
complianceHistory: scanResults.map(r => ({
date: r.createdAt,
score: (r.summary as any).score,
compliant: (r.wcagCompliance as any).isCompliant,
})),
};
}
function generateExecutiveData(
website: Website,
scanResults: ScanResult[],
summary: ReportSummary
): any {
return {
website: {
name: website.name,
url: website.url,
},
summary,
keyMetrics: {
currentScore: (scanResults[scanResults.length - 1].summary as any).score,
improvement: summary.improvementRate,
totalIssues: (scanResults[scanResults.length - 1].summary as any).violationCount,
criticalIssues: (scanResults[scanResults.length - 1].summary as any).criticalIssues,
},
recommendations: generateRecommendations(scanResults[scanResults.length - 1]),
};
}
function generateTechnicalData(
website: Website,
scanResults: ScanResult[],
summary: ReportSummary
): any {
const latestScan = scanResults[scanResults.length - 1];
return {
website: {
name: website.name,
url: website.url,
},
summary,
violations: latestScan.violations,
topIssues: getTopIssues(latestScan.violations as any[]),
fixPriority: generateFixPriority(latestScan.violations as any[]),
};
}
function generateTrendData(
website: Website,
scanResults: ScanResult[],
summary: ReportSummary
): any {
return {
website: {
name: website.name,
url: website.url,
},
summary,
trends: scanResults.map(r => ({
date: r.createdAt,
score: (r.summary as any).score,
violations: (r.summary as any).violationCount,
critical: (r.summary as any).criticalIssues,
serious: (r.summary as any).seriousIssues,
moderate: (r.summary as any).moderateIssues,
minor: (r.summary as any).minorIssues,
})),
};
}
function generateRecommendations(scanResult: ScanResult): string[] {
const violations = scanResult.violations as any[];
const recommendations: string[] = [];
// Group violations by type and generate recommendations
const criticalViolations = violations.filter(v => v.impact === 'critical');
if (criticalViolations.length > 0) {
recommendations.push('Address critical accessibility violations immediately to reduce legal risk');
}
// Add more intelligent recommendations based on violation patterns
return recommendations;
}
function getTopIssues(violations: any[]): any[] {
// Sort by impact and number of occurrences
return violations
.sort((a, b) => {
const impactOrder = { critical: 4, serious: 3, moderate: 2, minor: 1 };
const aScore = impactOrder[a.impact] * a.nodes.length;
const bScore = impactOrder[b.impact] * b.nodes.length;
return bScore - aScore;
})
.slice(0, 10);
}
function generateFixPriority(violations: any[]): any[] {
// Generate prioritized fix list
return violations
.map(v => ({
id: v.id,
impact: v.impact,
occurrences: v.nodes.length,
estimatedTime: estimateFixTime(v),
priority: calculatePriority(v),
}))
.sort((a, b) => b.priority - a.priority);
}
function estimateFixTime(violation: any): number {
const baseTime = {
critical: 30,
serious: 20,
moderate: 15,
minor: 10,
};
return (baseTime[violation.impact] || 15) * violation.nodes.length;
}
function calculatePriority(violation: any): number {
const impactScore = { critical: 100, serious: 75, moderate: 50, minor: 25 };
return (impactScore[violation.impact] || 50) * Math.log(violation.nodes.length + 1);
}
async function generateReportFile(
data: any,
format: 'PDF' | 'HTML' | 'CSV',
type: string
): Promise<string> {
const storageConfig = getStorageConfig();
const reportPath = join(storageConfig.local.basePath, storageConfig.local.reports);
// Create report directory if it doesn't exist
await mkdir(reportPath, { recursive: true });
const filename = `${type.toLowerCase()}_${nanoid()}.${format.toLowerCase()}`;
const filepath = join(reportPath, filename);
// For now, just save as JSON
// In production, you would generate actual PDF/HTML/CSV files
await writeFile(filepath, JSON.stringify(data, null, 2));
// Return relative URL (in production, this would be a CDN URL)
return `/reports/${filename}`;
}

View file

@ -1,12 +0,0 @@
import { PrismaClient } from '@prisma/client';
import { appConfig } from '../config';
const globalForPrisma = global as unknown as { prisma: PrismaClient };
export const prisma =
globalForPrisma.prisma ||
new PrismaClient({
log: appConfig.environment === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (appConfig.environment !== 'production') globalForPrisma.prisma = prisma;

View file

@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true,
"lib": ["ES2022"],
"types": ["bun-types"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../shared" },
{ "path": "../scanner" }
]
}

View file

@ -1,181 +0,0 @@
# WCAG-ADA Configuration
Centralized configuration management for the WCAG-ADA compliance platform, built on top of the core configuration system.
## Overview
This configuration system provides:
- Type-safe configuration with Zod schemas
- Multi-source configuration (JSON files + environment variables)
- Environment-specific overrides
- Service-specific configurations
- Feature flags management
## Usage
### Basic Usage
```typescript
import { initializeWcagConfig, getWcagConfig } from '@wcag-ada/config';
// Initialize configuration (do this once at app startup)
const config = initializeWcagConfig('api'); // 'api' | 'dashboard' | 'worker'
// Access configuration values
console.log(config.services.api.port); // 3001
console.log(config.scanner.concurrency); // 2
```
### Helper Functions
```typescript
import {
getScannerConfig,
getWorkerConfig,
isFeatureEnabled,
getServiceConfig
} from '@wcag-ada/config';
// Get specific configurations
const scannerConfig = getScannerConfig();
const workerConfig = getWorkerConfig();
// Check feature flags
if (isFeatureEnabled('screenshots')) {
// Screenshot feature is enabled
}
if (isFeatureEnabled('reports.pdf')) {
// PDF reports are enabled
}
// Get service configuration
const apiConfig = getServiceConfig('api');
```
## Configuration Structure
### Scanner Configuration
- `concurrency`: Number of concurrent scans (1-10)
- `timeout`: Maximum scan duration
- `headless`: Run browser in headless mode
- `blockResources`: Block images/fonts for faster scans
- `viewport`: Default viewport dimensions
### Worker Configuration
- `concurrency`: Number of concurrent jobs
- `queueName`: BullMQ queue name
- `redis`: Redis connection settings
- `jobs`: Job-specific configurations
- `scheduler`: Scheduled job settings
### Features Configuration
- `screenshots`: Screenshot capture settings
- `customRules`: Custom accessibility rules
- `multiPage`: Multi-page scanning
- `reports`: Report generation features
- `integrations`: External service integrations
- `enterprise`: Enterprise features (SSO, white-label)
### Providers Configuration
- `storage`: File storage (local, S3, GCS, Azure)
- `email`: Email providers (SMTP, SendGrid, SES)
- `auth`: Authentication settings (JWT, OAuth)
- `analytics`: Analytics providers
- `cdn`: CDN configuration
## Environment Variables
The system supports environment variable overrides with the `WCAG_` prefix:
```bash
# Scanner settings
WCAG_SCANNER_CONCURRENCY=5
WCAG_SCANNER_TIMEOUT=180000
WCAG_SCANNER_HEADLESS=true
# Worker settings
WCAG_WORKER_CONCURRENCY=3
WCAG_WORKER_REDIS_HOST=redis.example.com
WCAG_WORKER_REDIS_PORT=6379
# Service ports
WCAG_SERVICES_API_PORT=3001
WCAG_SERVICES_DASHBOARD_PORT=3000
# Storage
WCAG_PROVIDERS_STORAGE_TYPE=s3
WCAG_PROVIDERS_STORAGE_S3_BUCKET=wcag-ada-storage
WCAG_PROVIDERS_STORAGE_S3_REGION=us-east-1
# Authentication
WCAG_PROVIDERS_AUTH_JWT_SECRET=your-secret-key
```
## Configuration Files
Configuration files are loaded in this order (later files override earlier ones):
1. `config/default.json` - Base configuration
2. `config/{environment}.json` - Environment-specific (development, production, test)
3. Environment variables - Highest priority
## Service-Specific Configuration
Each service can have its own configuration:
```typescript
// API Service
initializeWcagConfig('api');
// Uses services.api configuration
// Dashboard
initializeWcagConfig('dashboard');
// Uses services.dashboard configuration
// Worker
initializeWcagConfig('worker');
// Uses services.worker configuration
```
## Adding New Configuration
1. Add schema definition in `src/schemas/`
2. Update `wcag-app.schema.ts` to include new schema
3. Add default values in `config/default.json`
4. Add environment-specific overrides as needed
5. Create helper functions in `src/index.ts` for easy access
## Examples
### Check Subscription Limits
```typescript
import { getSubscriptionConfig } from '@wcag-ada/config';
const starterLimits = getSubscriptionConfig('starter');
console.log(starterLimits.websites); // 5
console.log(starterLimits.scansPerMonth); // 500
```
### Get Compliance Settings
```typescript
import { getComplianceConfig } from '@wcag-ada/config';
const compliance = getComplianceConfig();
console.log(compliance.defaultLevel); // { standard: 'WCAG21', level: 'AA' }
console.log(compliance.criticalCriteria); // ['1.1.1', '1.3.1', ...]
```
### Storage Configuration
```typescript
import { getStorageConfig } from '@wcag-ada/config';
const storage = getStorageConfig();
if (storage.type === 's3') {
// Use S3 storage
} else {
// Use local storage
}
```

View file

@ -1,117 +0,0 @@
{
"appName": "wcag-ada",
"environment": "default",
"log": {
"level": "info",
"format": "json",
"pretty": false
},
"database": {
"postgres": {
"host": "localhost",
"port": 5432,
"database": "wcag_ada",
"connectionLimit": 10
},
"redis": {
"host": "localhost",
"port": 6379,
"db": 0
}
},
"scanner": {
"concurrency": 2,
"timeout": 120000,
"pageLoadTimeout": 30000,
"headless": true,
"blockResources": true,
"viewport": {
"width": 1280,
"height": 720,
"deviceScaleFactor": 1
}
},
"worker": {
"enabled": true,
"concurrency": 2,
"queueName": "accessibility-scans",
"redis": {
"host": "localhost",
"port": 6379,
"db": 2
}
},
"features": {
"screenshots": {
"enabled": true,
"quality": 80
},
"customRules": {
"enabled": true
},
"reports": {
"pdf": {
"enabled": true
}
}
},
"providers": {
"storage": {
"type": "local",
"local": {
"basePath": "/tmp/wcag-ada"
}
},
"email": {
"enabled": true,
"provider": "smtp"
},
"auth": {
"jwt": {
"expiresIn": "7d"
}
}
},
"services": {
"api": {
"name": "wcag-api",
"port": 3001,
"cors": {
"enabled": true,
"origin": "*"
},
"rateLimit": {
"enabled": true,
"windowMs": 900000,
"max": 100
}
},
"dashboard": {
"name": "wcag-dashboard",
"port": 3000,
"apiUrl": "http://localhost:3001"
},
"worker": {
"name": "wcag-worker",
"port": 3002
}
},
"compliance": {
"defaultLevel": {
"standard": "WCAG21",
"level": "AA"
}
},
"subscriptions": {
"enabled": true
}
}

View file

@ -1,51 +0,0 @@
{
"environment": "development",
"log": {
"level": "debug",
"pretty": true
},
"database": {
"postgres": {
"host": "localhost",
"database": "wcag_ada_dev"
}
},
"scanner": {
"headless": false,
"timeout": 300000
},
"worker": {
"concurrency": 1
},
"features": {
"reports": {
"pdf": {
"watermark": false
}
},
"enterprise": {
"audit": {
"enabled": false
}
}
},
"providers": {
"auth": {
"jwt": {
"secret": "dev-secret-change-me"
}
}
},
"services": {
"dashboard": {
"apiUrl": "http://localhost:3001"
}
}
}

View file

@ -1,64 +0,0 @@
{
"environment": "production",
"log": {
"level": "warn",
"pretty": false
},
"scanner": {
"concurrency": 5,
"headless": true
},
"worker": {
"concurrency": 4,
"redis": {
"maxRetriesPerRequest": 3
}
},
"features": {
"screenshots": {
"quality": 70
},
"reports": {
"pdf": {
"watermark": true
}
},
"enterprise": {
"audit": {
"enabled": true,
"retention": 365
}
}
},
"providers": {
"storage": {
"type": "s3"
},
"email": {
"provider": "sendgrid"
},
"cdn": {
"enabled": true
}
},
"services": {
"api": {
"cors": {
"origin": "https://app.wcag-ada.com"
},
"rateLimit": {
"max": 1000
}
},
"dashboard": {
"apiUrl": "https://api.wcag-ada.com",
"publicUrl": "https://app.wcag-ada.com"
}
}
}

View file

@ -1,53 +0,0 @@
{
"environment": "test",
"log": {
"level": "error",
"pretty": false
},
"database": {
"postgres": {
"database": "wcag_ada_test"
},
"redis": {
"db": 15
}
},
"scanner": {
"concurrency": 1,
"timeout": 10000,
"headless": true
},
"worker": {
"enabled": false
},
"features": {
"screenshots": {
"enabled": false
},
"webhooks": {
"enabled": false
}
},
"providers": {
"email": {
"enabled": false
},
"analytics": {
"enabled": false
}
},
"services": {
"api": {
"rateLimit": {
"enabled": false
}
}
}
}

View file

@ -1,19 +0,0 @@
{
"name": "@wcag-ada/config",
"version": "0.1.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -b",
"dev": "tsc -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@stock-bot/engine-config": "workspace:*",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/node": "^20.11.5",
"typescript": "^5.3.3"
}
}

View file

@ -1,67 +0,0 @@
import { ConfigManager, createAppConfig } from '@stock-bot/engine-config';
import * as path from 'path';
import { wcagAppConfigSchema, type WcagAppConfig } from './schemas/wcag-app.schema';
let configInstance: ConfigManager<WcagAppConfig> | null = null;
/**
* Initialize the WCAG-ADA configuration
* @param serviceName - Optional service name for service-specific overrides
*/
export function initializeWcagConfig(
serviceName?: 'api' | 'dashboard' | 'worker'
): WcagAppConfig {
if (!configInstance) {
configInstance = createAppConfig(wcagAppConfigSchema, {
configPath: path.join(__dirname, '../config'),
envPrefix: 'WCAG_',
});
}
const config = configInstance.initialize(wcagAppConfigSchema);
// Apply service-specific overrides if provided
if (serviceName && config.services[serviceName]) {
const serviceConfig = config.services[serviceName];
// Override port if specified for the service
if (serviceConfig.port && process.env.PORT) {
serviceConfig.port = parseInt(process.env.PORT, 10);
}
}
return config;
}
/**
* Get the current WCAG configuration instance
* @throws Error if configuration hasn't been initialized
*/
export function getWcagConfig(): WcagAppConfig {
if (!configInstance) {
throw new Error('WCAG configuration not initialized. Call initializeWcagConfig() first.');
}
return configInstance.get();
}
/**
* Get a specific configuration value by path
* @param path - Dot-notation path to the configuration value
*/
export function getConfigValue<T = unknown>(path: string): T {
if (!configInstance) {
throw new Error('WCAG configuration not initialized. Call initializeWcagConfig() first.');
}
return configInstance.getValue<T>(path);
}
/**
* Check if a configuration path exists
* @param path - Dot-notation path to check
*/
export function hasConfigValue(path: string): boolean {
if (!configInstance) {
return false;
}
return configInstance.has(path);
}

View file

@ -1,106 +0,0 @@
// Main configuration exports
export {
initializeWcagConfig,
getWcagConfig,
getConfigValue,
hasConfigValue,
} from './config-instance';
// Schema exports
export { wcagAppConfigSchema, type WcagAppConfig } from './schemas/wcag-app.schema';
export { scannerConfigSchema, type ScannerConfig } from './schemas/scanner.schema';
export { workerConfigSchema, type WorkerConfig } from './schemas/worker.schema';
export { featuresConfigSchema, type FeaturesConfig } from './schemas/features.schema';
export { providersConfigSchema, type ProvidersConfig } from './schemas/providers.schema';
// Helper functions
import { getWcagConfig } from './config-instance';
import type { ScannerConfig, WorkerConfig, FeaturesConfig, ProvidersConfig } from './schemas';
/**
* Get scanner configuration
*/
export function getScannerConfig(): ScannerConfig {
return getWcagConfig().scanner;
}
/**
* Get worker configuration
*/
export function getWorkerConfig(): WorkerConfig {
return getWcagConfig().worker;
}
/**
* Get features configuration
*/
export function getFeaturesConfig(): FeaturesConfig {
return getWcagConfig().features;
}
/**
* Get providers configuration
*/
export function getProvidersConfig(): ProvidersConfig {
return getWcagConfig().providers;
}
/**
* Get service configuration
*/
export function getServiceConfig(service: 'api' | 'dashboard' | 'worker') {
return getWcagConfig().services[service];
}
/**
* Check if a feature is enabled
*/
export function isFeatureEnabled(feature: string): boolean {
const features = getFeaturesConfig();
const parts = feature.split('.');
let current: any = features;
for (const part of parts) {
if (typeof current !== 'object' || !(part in current)) {
return false;
}
current = current[part];
}
return current === true || (typeof current === 'object' && current.enabled === true);
}
/**
* Get database configuration
*/
export function getDatabaseConfig() {
return getWcagConfig().database;
}
/**
* Get Redis configuration for queues
*/
export function getRedisConfig() {
return getWcagConfig().worker.redis;
}
/**
* Get storage configuration
*/
export function getStorageConfig() {
return getWcagConfig().providers.storage;
}
/**
* Get compliance configuration
*/
export function getComplianceConfig() {
return getWcagConfig().compliance;
}
/**
* Get subscription tier configuration
*/
export function getSubscriptionConfig(tier: 'starter' | 'professional' | 'enterprise') {
return getWcagConfig().subscriptions.tiers[tier];
}

View file

@ -1,89 +0,0 @@
import { z } from 'zod';
export const featuresConfigSchema = z.object({
// Scanner features
screenshots: z.object({
enabled: z.boolean().default(true),
quality: z.number().min(0).max(100).default(80),
fullPage: z.boolean().default(false),
}).default({}),
customRules: z.object({
enabled: z.boolean().default(true),
maxRules: z.number().default(50),
}).default({}),
multiPage: z.object({
enabled: z.boolean().default(true),
maxPages: z.number().default(10),
maxDepth: z.number().default(3),
}).default({}),
// API features
apiKeys: z.object({
enabled: z.boolean().default(true),
maxPerUser: z.number().default(5),
}).default({}),
webhooks: z.object({
enabled: z.boolean().default(true),
maxPerWebsite: z.number().default(3),
retryAttempts: z.number().default(3),
}).default({}),
// Report features
reports: z.object({
pdf: z.object({
enabled: z.boolean().default(true),
watermark: z.boolean().default(true),
}).default({}),
excel: z.object({
enabled: z.boolean().default(false),
}).default({}),
scheduling: z.object({
enabled: z.boolean().default(true),
}).default({}),
}).default({}),
// Compliance features
compliance: z.object({
wcag20: z.boolean().default(true),
wcag21: z.boolean().default(true),
wcag22: z.boolean().default(true),
section508: z.boolean().default(false),
ada: z.boolean().default(true),
}).default({}),
// Integration features
integrations: z.object({
github: z.object({
enabled: z.boolean().default(true),
}).default({}),
slack: z.object({
enabled: z.boolean().default(true),
}).default({}),
teams: z.object({
enabled: z.boolean().default(false),
}).default({}),
jira: z.object({
enabled: z.boolean().default(false),
}).default({}),
}).default({}),
// Enterprise features
enterprise: z.object({
sso: z.object({
enabled: z.boolean().default(false),
providers: z.array(z.enum(['saml', 'oauth', 'ldap'])).default([]),
}).default({}),
whiteLabel: z.object({
enabled: z.boolean().default(false),
}).default({}),
audit: z.object({
enabled: z.boolean().default(true),
retention: z.number().default(365), // days
}).default({}),
}).default({}),
});
export type FeaturesConfig = z.infer<typeof featuresConfigSchema>;

View file

@ -1,84 +0,0 @@
import { z } from 'zod';
export const providersConfigSchema = z.object({
// Storage providers
storage: z.object({
type: z.enum(['local', 's3', 'gcs', 'azure']).default('local'),
local: z.object({
basePath: z.string().default('/tmp/wcag-ada'),
reports: z.string().default('reports'),
screenshots: z.string().default('screenshots'),
exports: z.string().default('exports'),
}).default({}),
s3: z.object({
enabled: z.boolean().default(false),
bucket: z.string().optional(),
region: z.string().default('us-east-1'),
accessKeyId: z.string().optional(),
secretAccessKey: z.string().optional(),
endpoint: z.string().optional(),
}).default({}),
}).default({}),
// Email providers
email: z.object({
enabled: z.boolean().default(true),
provider: z.enum(['smtp', 'sendgrid', 'ses', 'postmark']).default('smtp'),
from: z.object({
name: z.string().default('WCAG-ADA Compliance'),
email: z.string().email().default('noreply@wcag-ada.com'),
}).default({}),
smtp: z.object({
host: z.string().default('localhost'),
port: z.number().default(587),
secure: z.boolean().default(false),
auth: z.object({
user: z.string().optional(),
pass: z.string().optional(),
}).default({}),
}).default({}),
sendgrid: z.object({
apiKey: z.string().optional(),
}).default({}),
}).default({}),
// Authentication providers
auth: z.object({
jwt: z.object({
secret: z.string().default('change-me-in-production'),
expiresIn: z.string().default('7d'),
refreshExpiresIn: z.string().default('30d'),
}).default({}),
oauth: z.object({
google: z.object({
enabled: z.boolean().default(false),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
}).default({}),
github: z.object({
enabled: z.boolean().default(false),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
}).default({}),
}).default({}),
}).default({}),
// Analytics providers
analytics: z.object({
enabled: z.boolean().default(true),
provider: z.enum(['posthog', 'mixpanel', 'amplitude', 'custom']).default('posthog'),
posthog: z.object({
apiKey: z.string().optional(),
host: z.string().default('https://app.posthog.com'),
}).default({}),
}).default({}),
// CDN providers
cdn: z.object({
enabled: z.boolean().default(false),
provider: z.enum(['cloudflare', 'cloudfront', 'fastly']).default('cloudflare'),
baseUrl: z.string().optional(),
}).default({}),
});
export type ProvidersConfig = z.infer<typeof providersConfigSchema>;

View file

@ -1,34 +0,0 @@
import { z } from 'zod';
export const scannerConfigSchema = z.object({
concurrency: z.number().min(1).max(10).default(2),
timeout: z.number().min(30000).default(120000), // 2 minutes default
pageLoadTimeout: z.number().min(10000).default(30000),
headless: z.boolean().default(true),
blockResources: z.boolean().default(true),
viewport: z.object({
width: z.number().default(1280),
height: z.number().default(720),
deviceScaleFactor: z.number().default(1),
}).default({}),
browsers: z.object({
chromium: z.object({
enabled: z.boolean().default(true),
args: z.array(z.string()).default(['--no-sandbox', '--disable-setuid-sandbox']),
}).default({}),
}).default({}),
axe: z.object({
tags: z.array(z.string()).default(['wcag2aa', 'wcag21aa']),
resultTypes: z.array(z.enum(['violations', 'passes', 'incomplete', 'inapplicable']))
.default(['violations', 'passes', 'incomplete', 'inapplicable']),
}).default({}),
retries: z.object({
maxAttempts: z.number().default(3),
backoff: z.object({
type: z.enum(['exponential', 'fixed']).default('exponential'),
delay: z.number().default(2000),
}).default({}),
}).default({}),
});
export type ScannerConfig = z.infer<typeof scannerConfigSchema>;

View file

@ -1,111 +0,0 @@
import {
baseAppConfigSchema,
databaseConfigSchema,
logConfigSchema,
serviceConfigSchema,
} from '@stock-bot/engine-config';
import { z } from 'zod';
import { featuresConfigSchema } from './features.schema';
import { providersConfigSchema } from './providers.schema';
import { scannerConfigSchema } from './scanner.schema';
import { workerConfigSchema } from './worker.schema';
// Service-specific configurations
const wcagServicesSchema = z.object({
api: serviceConfigSchema.extend({
port: z.number().default(3001),
cors: z.object({
enabled: z.boolean().default(true),
origin: z.string().default('*'),
credentials: z.boolean().default(true),
}).default({}),
rateLimit: z.object({
enabled: z.boolean().default(true),
windowMs: z.number().default(900000), // 15 minutes
max: z.number().default(100),
keyGenerator: z.enum(['ip', 'userId', 'apiKey']).default('userId'),
}).default({}),
pagination: z.object({
defaultLimit: z.number().default(20),
maxLimit: z.number().default(100),
}).default({}),
}),
dashboard: serviceConfigSchema.extend({
port: z.number().default(3000),
apiUrl: z.string().default('http://localhost:3001'),
publicUrl: z.string().default('http://localhost:3000'),
}),
worker: serviceConfigSchema.extend({
port: z.number().default(3002), // For health checks
}),
});
// Main WCAG application configuration schema
export const wcagAppConfigSchema = baseAppConfigSchema.extend({
appName: z.literal('wcag-ada').default('wcag-ada'),
// Core configurations
log: logConfigSchema,
database: databaseConfigSchema,
// WCAG-specific configurations
scanner: scannerConfigSchema,
worker: workerConfigSchema,
features: featuresConfigSchema,
providers: providersConfigSchema,
// Service configurations
services: wcagServicesSchema.default({}),
// Business logic configurations
compliance: z.object({
defaultLevel: z.object({
standard: z.enum(['WCAG20', 'WCAG21', 'WCAG22']).default('WCAG21'),
level: z.enum(['A', 'AA', 'AAA']).default('AA'),
}).default({}),
passingScore: z.object({
A: z.number().min(0).max(100).default(95),
AA: z.number().min(0).max(100).default(98),
AAA: z.number().min(0).max(100).default(100),
}).default({}),
criticalCriteria: z.array(z.string()).default([
'1.1.1', // Non-text Content
'1.3.1', // Info and Relationships
'1.4.3', // Contrast (Minimum)
'2.1.1', // Keyboard
'2.1.2', // No Keyboard Trap
'2.4.1', // Bypass Blocks
'2.4.2', // Page Titled
'4.1.2', // Name, Role, Value
]),
}).default({}),
// Subscription/pricing tiers
subscriptions: z.object({
enabled: z.boolean().default(true),
tiers: z.object({
starter: z.object({
websites: z.number().default(5),
scansPerMonth: z.number().default(500),
users: z.number().default(1),
price: z.number().default(49),
}).default({}),
professional: z.object({
websites: z.number().default(25),
scansPerMonth: z.number().default(5000),
users: z.number().default(5),
price: z.number().default(149),
}).default({}),
enterprise: z.object({
websites: z.number().default(-1), // Unlimited
scansPerMonth: z.number().default(-1),
users: z.number().default(-1),
price: z.number().default(499),
}).default({}),
}).default({}),
}).default({}),
});
export type WcagAppConfig = z.infer<typeof wcagAppConfigSchema>;

View file

@ -1,49 +0,0 @@
import { z } from 'zod';
export const workerConfigSchema = z.object({
enabled: z.boolean().default(true),
concurrency: z.number().min(1).max(10).default(2),
queueName: z.string().default('accessibility-scans'),
redis: z.object({
host: z.string().default('localhost'),
port: z.number().default(6379),
password: z.string().optional(),
db: z.number().default(2), // Different DB for WCAG
maxRetriesPerRequest: z.number().nullable().default(null),
}).default({}),
jobs: z.object({
scan: z.object({
priority: z.number().default(0),
attempts: z.number().default(3),
backoff: z.object({
type: z.enum(['exponential', 'fixed']).default('exponential'),
delay: z.number().default(2000),
}).default({}),
timeout: z.number().default(300000), // 5 minutes
removeOnComplete: z.object({
age: z.number().default(86400), // 24 hours
count: z.number().default(100),
}).default({}),
removeOnFail: z.object({
age: z.number().default(604800), // 7 days
count: z.number().default(500),
}).default({}),
}).default({}),
report: z.object({
priority: z.number().default(1),
attempts: z.number().default(2),
backoff: z.object({
type: z.enum(['exponential', 'fixed']).default('exponential'),
delay: z.number().default(5000),
}).default({}),
timeout: z.number().default(600000), // 10 minutes
}).default({}),
}).default({}),
scheduler: z.object({
enabled: z.boolean().default(true),
interval: z.number().default(60000), // Check every minute
timezone: z.string().default('UTC'),
}).default({}),
});
export type WorkerConfig = z.infer<typeof workerConfigSchema>;

View file

@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../../../libs/core/config" }
]
}

View file

@ -1,57 +0,0 @@
# Build stage
FROM oven/bun:1-alpine as builder
WORKDIR /app
# Copy workspace files
COPY package.json bun.lockb ./
COPY apps/wcag-ada/dashboard/package.json ./apps/wcag-ada/dashboard/
COPY apps/wcag-ada/shared/package.json ./apps/wcag-ada/shared/
# Install dependencies
RUN bun install --frozen-lockfile
# Copy source code
COPY apps/wcag-ada/dashboard ./apps/wcag-ada/dashboard
COPY apps/wcag-ada/shared ./apps/wcag-ada/shared
COPY tsconfig.json ./
# Build the application
WORKDIR /app/apps/wcag-ada/dashboard
RUN bun run build
# Production stage with nginx
FROM nginx:alpine
# Install runtime dependencies
RUN apk add --no-cache curl
# Copy nginx configuration
COPY apps/wcag-ada/dashboard/nginx.conf /etc/nginx/nginx.conf
# Copy built application
COPY --from=builder /app/apps/wcag-ada/dashboard/dist /usr/share/nginx/html
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Set ownership
RUN chown -R nodejs:nodejs /usr/share/nginx/html && \
chown -R nodejs:nodejs /var/cache/nginx && \
chown -R nodejs:nodejs /var/log/nginx && \
chown -R nodejs:nodejs /etc/nginx/conf.d && \
touch /var/run/nginx.pid && \
chown -R nodejs:nodejs /var/run/nginx.pid
USER nodejs
# Expose port
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/ || exit 1
# Start nginx
CMD ["nginx", "-g", "daemon off;"]

View file

@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WCAG-ADA Compliance Dashboard</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -1,79 +0,0 @@
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml application/atom+xml image/svg+xml;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline' 'unsafe-eval'" always;
server {
listen 8080;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Serve index.html for all routes (React Router)
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires "0";
}
# API proxy (if needed in production)
location /api {
proxy_pass http://wcag-ada-api:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Health check endpoint
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
}

View file

@ -1,61 +0,0 @@
{
"name": "@wcag-ada/dashboard",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"lint": "eslint src"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.1",
"@tanstack/react-query": "^5.17.0",
"axios": "^1.6.5",
"zustand": "^4.4.7",
"@wcag-ada/shared": "workspace:*",
"@wcag-ada/config": "workspace:*",
"recharts": "^2.10.3",
"date-fns": "^3.0.6",
"clsx": "^2.1.0",
"lucide-react": "^0.303.0",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-select": "^2.0.0",
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tooltip": "^1.0.7",
"tailwindcss-animate": "^1.0.7",
"react-hook-form": "^7.48.2",
"@hookform/resolvers": "^3.3.4",
"zod": "^3.22.4",
"class-variance-authority": "^0.7.0",
"tailwind-merge": "^2.2.0"
},
"devDependencies": {
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.18",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16",
"eslint": "^8.56.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"postcss": "^8.4.33",
"tailwindcss": "^3.4.0",
"typescript": "^5.3.3",
"vite": "^5.0.11"
}
}

View file

@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View file

@ -1,5 +0,0 @@
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="32" height="32" rx="8" fill="#3B82F6"/>
<path d="M16 6C10.4772 6 6 10.4772 6 16C6 21.5228 10.4772 26 16 26C21.5228 26 26 21.5228 26 16C26 10.4772 21.5228 6 16 6ZM16 8C20.4183 8 24 11.5817 24 16C24 20.4183 20.4183 24 16 24C11.5817 24 8 20.4183 8 16C8 11.5817 11.5817 8 16 8Z" fill="white"/>
<path d="M16 10C12.6863 10 10 12.6863 10 16C10 19.3137 12.6863 22 16 22C19.3137 22 22 19.3137 22 16C22 12.6863 19.3137 10 16 10ZM13 15H15V17H13V15ZM17 15H19V17H17V15Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 594 B

View file

@ -1,70 +0,0 @@
import { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuthStore } from '@/store/auth-store';
import { apiClient } from '@/lib/api-client';
import { MainLayout } from '@/components/layout/main-layout';
import { AuthLayout } from '@/components/layout/auth-layout';
import { ProtectedRoute } from '@/components/layout/protected-route';
// Pages
import { LoginPage } from '@/pages/auth/login';
import { RegisterPage } from '@/pages/auth/register';
import { DashboardPage } from '@/pages/dashboard';
import { WebsitesPage } from '@/pages/websites';
import { WebsiteDetailPage } from '@/pages/websites/[id]';
import { ScansPage } from '@/pages/scans';
import { ScanDetailPage } from '@/pages/scans/[id]';
import { ReportsPage } from '@/pages/reports';
import { SettingsPage } from '@/pages/settings';
function App() {
const { setAuth, setLoading, token } = useAuthStore();
useEffect(() => {
const initAuth = async () => {
if (!token) {
setLoading(false);
return;
}
try {
const user = await apiClient.getMe();
setAuth(user, token);
} catch (error) {
console.error('Auth check failed:', error);
setLoading(false);
}
};
initAuth();
}, [token, setAuth, setLoading]);
return (
<Routes>
{/* Auth routes */}
<Route element={<AuthLayout />}>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
</Route>
{/* Protected routes */}
<Route element={<ProtectedRoute />}>
<Route element={<MainLayout />}>
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/websites" element={<WebsitesPage />} />
<Route path="/websites/:id" element={<WebsiteDetailPage />} />
<Route path="/scans" element={<ScansPage />} />
<Route path="/scans/:id" element={<ScanDetailPage />} />
<Route path="/reports" element={<ReportsPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
</Route>
{/* 404 */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
}
export default App;

View file

@ -1,26 +0,0 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useAuthStore } from '@/store/auth-store';
export function AuthLayout() {
const { isAuthenticated } = useAuthStore();
if (isAuthenticated) {
return <Navigate to="/dashboard" replace />;
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div className="text-center">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">
WCAG-ADA Compliance
</h1>
<p className="mt-2 text-gray-600 dark:text-gray-400">
Automated accessibility testing and compliance monitoring
</p>
</div>
<Outlet />
</div>
</div>
);
}

View file

@ -1,189 +0,0 @@
import { Outlet, Link, useLocation } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { useAuthStore } from '@/store/auth-store';
import {
Home,
Globe,
Scan,
FileText,
Settings,
LogOut,
Menu,
X,
Shield,
} from 'lucide-react';
import { useState } from 'react';
const navigation = [
{ name: 'Dashboard', href: '/dashboard', icon: Home },
{ name: 'Websites', href: '/websites', icon: Globe },
{ name: 'Scans', href: '/scans', icon: Scan },
{ name: 'Reports', href: '/reports', icon: FileText },
{ name: 'Settings', href: '/settings', icon: Settings },
];
export function MainLayout() {
const location = useLocation();
const { user, logout } = useAuthStore();
const [sidebarOpen, setSidebarOpen] = useState(false);
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
{/* Mobile sidebar */}
<div
className={cn(
'fixed inset-0 z-50 lg:hidden',
sidebarOpen ? 'block' : 'hidden'
)}
>
<div
className="fixed inset-0 bg-gray-900/80"
onClick={() => setSidebarOpen(false)}
/>
<div className="fixed inset-y-0 left-0 flex w-64 flex-col bg-white dark:bg-gray-800">
<div className="flex h-16 items-center justify-between px-6">
<div className="flex items-center gap-2">
<Shield className="h-8 w-8 text-primary" />
<span className="text-xl font-semibold">WCAG-ADA</span>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => setSidebarOpen(false)}
>
<X className="h-5 w-5" />
</Button>
</div>
<nav className="flex-1 space-y-1 px-3 py-4">
{navigation.map((item) => {
const Icon = item.icon;
const isActive = location.pathname.startsWith(item.href);
return (
<Link
key={item.name}
to={item.href}
className={cn(
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
isActive
? 'bg-primary text-primary-foreground'
: 'text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700'
)}
onClick={() => setSidebarOpen(false)}
>
<Icon className="h-5 w-5" />
{item.name}
</Link>
);
})}
</nav>
<div className="border-t p-4">
<div className="flex items-center gap-3 mb-3">
<div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
<span className="text-sm font-medium">
{user?.name?.[0] || user?.email[0].toUpperCase()}
</span>
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{user?.name || user?.email}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
{user?.role}
</p>
</div>
</div>
<Button
variant="outline"
className="w-full justify-start"
onClick={logout}
>
<LogOut className="h-4 w-4 mr-2" />
Logout
</Button>
</div>
</div>
</div>
{/* Desktop sidebar */}
<div className="hidden lg:fixed lg:inset-y-0 lg:flex lg:w-64 lg:flex-col">
<div className="flex flex-1 flex-col bg-white dark:bg-gray-800 border-r">
<div className="flex h-16 items-center px-6">
<div className="flex items-center gap-2">
<Shield className="h-8 w-8 text-primary" />
<span className="text-xl font-semibold">WCAG-ADA</span>
</div>
</div>
<nav className="flex-1 space-y-1 px-3 py-4">
{navigation.map((item) => {
const Icon = item.icon;
const isActive = location.pathname.startsWith(item.href);
return (
<Link
key={item.name}
to={item.href}
className={cn(
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
isActive
? 'bg-primary text-primary-foreground'
: 'text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700'
)}
>
<Icon className="h-5 w-5" />
{item.name}
</Link>
);
})}
</nav>
<div className="border-t p-4">
<div className="flex items-center gap-3 mb-3">
<div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
<span className="text-sm font-medium">
{user?.name?.[0] || user?.email[0].toUpperCase()}
</span>
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{user?.name || user?.email}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
{user?.role}
</p>
</div>
</div>
<Button
variant="outline"
className="w-full justify-start"
onClick={logout}
>
<LogOut className="h-4 w-4 mr-2" />
Logout
</Button>
</div>
</div>
</div>
{/* Main content */}
<div className="lg:pl-64">
<div className="sticky top-0 z-40 flex h-16 items-center gap-4 border-b bg-white dark:bg-gray-800 px-4 sm:px-6 lg:px-8">
<Button
variant="ghost"
size="icon"
className="lg:hidden"
onClick={() => setSidebarOpen(true)}
>
<Menu className="h-5 w-5" />
</Button>
<h1 className="text-lg font-semibold">
{navigation.find((n) => location.pathname.startsWith(n.href))?.name || 'WCAG-ADA Compliance'}
</h1>
</div>
<main className="py-6">
<div className="px-4 sm:px-6 lg:px-8">
<Outlet />
</div>
</main>
</div>
</div>
);
}

View file

@ -1,21 +0,0 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useAuthStore } from '@/store/auth-store';
import { Loader2 } from 'lucide-react';
export function ProtectedRoute() {
const { isAuthenticated, isLoading } = useAuthStore();
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <Outlet />;
}

View file

@ -1,55 +0,0 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline:
'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };

View file

@ -1,78 +0,0 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-lg border bg-card text-card-foreground shadow-sm',
className
)}
{...props}
/>
));
Card.displayName = 'Card';
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex flex-col space-y-1.5 p-6', className)}
{...props}
/>
));
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
'text-2xl font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
));
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex items-center p-6 pt-0', className)}
{...props}
/>
));
CardFooter.displayName = 'CardFooter';
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };

View file

@ -1,167 +0,0 @@
import axios, { AxiosError, AxiosInstance } from 'axios';
import { useAuthStore } from '@/store/auth-store';
class ApiClient {
private client: AxiosInstance;
constructor() {
this.client = axios.create({
baseURL: '/api',
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor to add auth token
this.client.interceptors.request.use(
(config) => {
const token = useAuthStore.getState().token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor to handle errors
this.client.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
if (error.response?.status === 401) {
// Token expired or invalid
useAuthStore.getState().logout();
window.location.href = '/login';
}
return Promise.reject(error);
}
);
}
// Auth endpoints
async login(email: string, password: string) {
const response = await this.client.post('/auth/login', { email, password });
return response.data;
}
async register(data: { email: string; password: string; name?: string; company?: string }) {
const response = await this.client.post('/auth/register', data);
return response.data;
}
async getMe() {
const response = await this.client.get('/auth/me');
return response.data;
}
async refreshApiKey() {
const response = await this.client.post('/auth/refresh-api-key');
return response.data;
}
// Website endpoints
async getWebsites(params?: { page?: number; limit?: number; search?: string }) {
const response = await this.client.get('/websites', { params });
return response.data;
}
async getWebsite(id: string) {
const response = await this.client.get(`/websites/${id}`);
return response.data;
}
async createWebsite(data: any) {
const response = await this.client.post('/websites', data);
return response.data;
}
async updateWebsite(id: string, data: any) {
const response = await this.client.patch(`/websites/${id}`, data);
return response.data;
}
async deleteWebsite(id: string) {
const response = await this.client.delete(`/websites/${id}`);
return response.data;
}
async getWebsiteScans(id: string, params?: { page?: number; limit?: number }) {
const response = await this.client.get(`/websites/${id}/scans`, { params });
return response.data;
}
// Scan endpoints
async createScan(data: { websiteId: string; url?: string; options?: any }) {
const response = await this.client.post('/scans', data);
return response.data;
}
async getScan(id: string) {
const response = await this.client.get(`/scans/${id}`);
return response.data;
}
async getScanResult(id: string) {
const response = await this.client.get(`/scans/${id}/result`);
return response.data;
}
async getScanViolations(id: string, params?: { impact?: string; tag?: string }) {
const response = await this.client.get(`/scans/${id}/violations`, { params });
return response.data;
}
async cancelScan(id: string) {
const response = await this.client.delete(`/scans/${id}`);
return response.data;
}
async getScans(params?: { page?: number; limit?: number; status?: string; websiteId?: string }) {
const response = await this.client.get('/scans', { params });
return response.data;
}
// Report endpoints
async generateReport(data: {
websiteId: string;
type: 'COMPLIANCE' | 'EXECUTIVE' | 'TECHNICAL' | 'TREND';
format: 'PDF' | 'HTML' | 'JSON' | 'CSV';
period: { start: string; end: string };
}) {
const response = await this.client.post('/reports/generate', data);
return response.data;
}
async getReports(params?: { page?: number; limit?: number; websiteId?: string; type?: string }) {
const response = await this.client.get('/reports', { params });
return response.data;
}
async getReport(id: string) {
const response = await this.client.get(`/reports/${id}`);
return response.data;
}
async downloadReport(id: string) {
const response = await this.client.get(`/reports/${id}/download`);
return response.data;
}
async getComplianceTrends(websiteId: string, days: number = 30) {
const response = await this.client.get(`/reports/trends/${websiteId}`, { params: { days } });
return response.data;
}
// Health endpoints
async getHealth() {
const response = await this.client.get('/health');
return response.data;
}
async getStats() {
const response = await this.client.get('/health/stats');
return response.data;
}
}
export const apiClient = new ApiClient();

View file

@ -1,6 +0,0 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

View file

@ -1,27 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './styles/globals.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes
retry: 1,
},
},
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</React.StrictMode>
);

View file

@ -1,112 +0,0 @@
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { apiClient } from '@/lib/api-client';
import { useAuthStore } from '@/store/auth-store';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
const loginSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});
type LoginForm = z.infer<typeof loginSchema>;
export function LoginPage() {
const navigate = useNavigate();
const { setAuth } = useAuthStore();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginForm>({
resolver: zodResolver(loginSchema),
});
const onSubmit = async (data: LoginForm) => {
setIsLoading(true);
setError(null);
try {
const response = await apiClient.login(data.email, data.password);
setAuth(response.user, response.token);
navigate('/dashboard');
} catch (err: any) {
setError(err.response?.data?.error || 'Login failed. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
<form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
<div className="rounded-md shadow-sm -space-y-px">
<div>
<label htmlFor="email" className="sr-only">
Email address
</label>
<input
{...register('email')}
type="email"
autoComplete="email"
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Email address"
/>
{errors.email && (
<p className="mt-1 text-sm text-red-600">{errors.email.message}</p>
)}
</div>
<div>
<label htmlFor="password" className="sr-only">
Password
</label>
<input
{...register('password')}
type="password"
autoComplete="current-password"
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Password"
/>
{errors.password && (
<p className="mt-1 text-sm text-red-600">{errors.password.message}</p>
)}
</div>
</div>
{error && (
<div className="rounded-md bg-red-50 dark:bg-red-900/20 p-4">
<p className="text-sm text-red-800 dark:text-red-400">{error}</p>
</div>
)}
<div>
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Sign in
</Button>
</div>
<div className="text-center">
<span className="text-sm text-gray-600 dark:text-gray-400">
Don't have an account?{' '}
<Link
to="/register"
className="font-medium text-primary hover:text-primary/80"
>
Sign up
</Link>
</span>
</div>
</form>
);
}

View file

@ -1,141 +0,0 @@
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { apiClient } from '@/lib/api-client';
import { useAuthStore } from '@/store/auth-store';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
const registerSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
name: z.string().optional(),
company: z.string().optional(),
});
type RegisterForm = z.infer<typeof registerSchema>;
export function RegisterPage() {
const navigate = useNavigate();
const { setAuth } = useAuthStore();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegisterForm>({
resolver: zodResolver(registerSchema),
});
const onSubmit = async (data: RegisterForm) => {
setIsLoading(true);
setError(null);
try {
const response = await apiClient.register(data);
setAuth(response.user, response.token);
navigate('/dashboard');
} catch (err: any) {
setError(err.response?.data?.error || 'Registration failed. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
<form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-4">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Email address
</label>
<input
{...register('email')}
type="email"
autoComplete="email"
className="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Email address"
/>
{errors.email && (
<p className="mt-1 text-sm text-red-600">{errors.email.message}</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Password
</label>
<input
{...register('password')}
type="password"
autoComplete="new-password"
className="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Password"
/>
{errors.password && (
<p className="mt-1 text-sm text-red-600">{errors.password.message}</p>
)}
</div>
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Name (optional)
</label>
<input
{...register('name')}
type="text"
autoComplete="name"
className="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Your name"
/>
</div>
<div>
<label htmlFor="company" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Company (optional)
</label>
<input
{...register('company')}
type="text"
autoComplete="organization"
className="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
placeholder="Your company"
/>
</div>
</div>
{error && (
<div className="rounded-md bg-red-50 dark:bg-red-900/20 p-4">
<p className="text-sm text-red-800 dark:text-red-400">{error}</p>
</div>
)}
<div>
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create account
</Button>
</div>
<div className="text-center">
<span className="text-sm text-gray-600 dark:text-gray-400">
Already have an account?{' '}
<Link
to="/login"
className="font-medium text-primary hover:text-primary/80"
>
Sign in
</Link>
</span>
</div>
</form>
);
}

View file

@ -1,243 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Globe, Scan, AlertCircle, CheckCircle2, TrendingUp, TrendingDown } from 'lucide-react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { format } from 'date-fns';
export function DashboardPage() {
const { data: stats, isLoading: statsLoading } = useQuery({
queryKey: ['stats'],
queryFn: () => apiClient.getStats(),
});
const { data: recentScans } = useQuery({
queryKey: ['recent-scans'],
queryFn: () => apiClient.getScans({ limit: 5 }),
});
const { data: websites } = useQuery({
queryKey: ['websites-summary'],
queryFn: () => apiClient.getWebsites({ limit: 5 }),
});
if (statsLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
);
}
return (
<div className="space-y-6">
{/* Stats Grid */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Websites</CardTitle>
<Globe className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.database?.websites || 0}</div>
<p className="text-xs text-muted-foreground">
Active websites being monitored
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Scans</CardTitle>
<Scan className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.database?.scanResults || 0}</div>
<p className="text-xs text-muted-foreground">
Accessibility scans performed
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Queue Status</CardTitle>
<AlertCircle className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.queue?.active || 0}</div>
<p className="text-xs text-muted-foreground">
Active scans in progress
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Success Rate</CardTitle>
<CheckCircle2 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats?.queue?.completed && stats?.queue?.failed
? Math.round((stats.queue.completed / (stats.queue.completed + stats.queue.failed)) * 100)
: 100}%
</div>
<p className="text-xs text-muted-foreground">
Scan completion rate
</p>
</CardContent>
</Card>
</div>
{/* Charts Row */}
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Compliance Trends</CardTitle>
<CardDescription>Average compliance scores over time</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={[
{ date: 'Mon', score: 85 },
{ date: 'Tue', score: 87 },
{ date: 'Wed', score: 86 },
{ date: 'Thu', score: 89 },
{ date: 'Fri', score: 91 },
{ date: 'Sat', score: 90 },
{ date: 'Sun', score: 92 },
]}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis domain={[0, 100]} />
<Tooltip />
<Line
type="monotone"
dataKey="score"
stroke="hsl(var(--primary))"
strokeWidth={2}
/>
</LineChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Issue Distribution</CardTitle>
<CardDescription>Violations by severity level</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={[
{ severity: 'Critical', count: 5, fill: 'hsl(var(--destructive))' },
{ severity: 'Serious', count: 12, fill: 'hsl(var(--warning))' },
{ severity: 'Moderate', count: 25, fill: 'hsl(var(--primary))' },
{ severity: 'Minor', count: 45, fill: 'hsl(var(--muted))' },
]}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="severity" />
<YAxis />
<Tooltip />
<Bar dataKey="count" />
</BarChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
</div>
{/* Recent Activity */}
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<div>
<CardTitle>Recent Scans</CardTitle>
<CardDescription>Latest accessibility scan results</CardDescription>
</div>
<Button variant="outline" size="sm" asChild>
<Link to="/scans">View all</Link>
</Button>
</CardHeader>
<CardContent>
<div className="space-y-4">
{recentScans?.scans?.map((scan: any) => (
<div key={scan.id} className="flex items-center justify-between">
<div className="flex-1">
<p className="text-sm font-medium">{scan.website?.name}</p>
<p className="text-xs text-muted-foreground">
{format(new Date(scan.createdAt), 'MMM d, h:mm a')}
</p>
</div>
<div className="flex items-center gap-2">
{scan.status === 'COMPLETED' ? (
<div className="flex items-center gap-1">
<span className="text-sm font-medium">
{scan.result?.summary?.score || 0}%
</span>
{scan.result?.summary?.score > 90 ? (
<TrendingUp className="h-4 w-4 text-success" />
) : (
<TrendingDown className="h-4 w-4 text-destructive" />
)}
</div>
) : (
<span className="text-xs text-muted-foreground">
{scan.status}
</span>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<div>
<CardTitle>Websites</CardTitle>
<CardDescription>Your monitored websites</CardDescription>
</div>
<Button variant="outline" size="sm" asChild>
<Link to="/websites">Manage</Link>
</Button>
</CardHeader>
<CardContent>
<div className="space-y-4">
{websites?.websites?.map((website: any) => (
<div key={website.id} className="flex items-center justify-between">
<div className="flex-1">
<p className="text-sm font-medium">{website.name}</p>
<p className="text-xs text-muted-foreground">{website.url}</p>
</div>
<div className="flex items-center gap-2">
{website.complianceScore !== null ? (
<span className="text-sm font-medium">
{Math.round(website.complianceScore)}%
</span>
) : (
<span className="text-xs text-muted-foreground">
No scans yet
</span>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View file

@ -1,8 +0,0 @@
export function ReportsPage() {
return (
<div>
<h1 className="text-2xl font-bold">Reports</h1>
<p className="text-muted-foreground">Compliance reports and analytics coming soon...</p>
</div>
);
}

View file

@ -1,8 +0,0 @@
export function ScanDetailPage() {
return (
<div>
<h1 className="text-2xl font-bold">Scan Results</h1>
<p className="text-muted-foreground">Scan detail page coming soon...</p>
</div>
);
}

View file

@ -1,8 +0,0 @@
export function ScansPage() {
return (
<div>
<h1 className="text-2xl font-bold">Scans</h1>
<p className="text-muted-foreground">Scan history and management coming soon...</p>
</div>
);
}

View file

@ -1,8 +0,0 @@
export function SettingsPage() {
return (
<div>
<h1 className="text-2xl font-bold">Settings</h1>
<p className="text-muted-foreground">Account settings and preferences coming soon...</p>
</div>
);
}

View file

@ -1,8 +0,0 @@
export function WebsiteDetailPage() {
return (
<div>
<h1 className="text-2xl font-bold">Website Details</h1>
<p className="text-muted-foreground">Website detail page coming soon...</p>
</div>
);
}

View file

@ -1,88 +0,0 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Plus, Globe, ExternalLink, MoreVertical } from 'lucide-react';
import { Link } from 'react-router-dom';
import { format } from 'date-fns';
export function WebsitesPage() {
const [page, setPage] = useState(1);
const { data, isLoading } = useQuery({
queryKey: ['websites', page],
queryFn: () => apiClient.getWebsites({ page, limit: 12 }),
});
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Websites</h1>
<p className="text-muted-foreground">
Manage your monitored websites and their scan schedules
</p>
</div>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Website
</Button>
</div>
{isLoading ? (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{[...Array(6)].map((_, i) => (
<Card key={i} className="h-48 animate-pulse bg-muted" />
))}
</div>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{data?.websites?.map((website: any) => (
<Card key={website.id} className="p-6">
<div className="flex items-start justify-between">
<Globe className="h-5 w-5 text-muted-foreground" />
<Button variant="ghost" size="icon">
<MoreVertical className="h-4 w-4" />
</Button>
</div>
<div className="mt-4">
<h3 className="font-semibold">{website.name}</h3>
<a
href={website.url}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-muted-foreground hover:text-primary flex items-center gap-1 mt-1"
>
{website.url}
<ExternalLink className="h-3 w-3" />
</a>
</div>
<div className="mt-4 flex items-center justify-between">
<div>
{website.complianceScore !== null ? (
<div>
<span className="text-2xl font-bold">
{Math.round(website.complianceScore)}%
</span>
<p className="text-xs text-muted-foreground">Compliance</p>
</div>
) : (
<p className="text-sm text-muted-foreground">No scans yet</p>
)}
</div>
<Button variant="outline" size="sm" asChild>
<Link to={`/websites/${website.id}`}>View Details</Link>
</Button>
</div>
{website.lastScanAt && (
<p className="text-xs text-muted-foreground mt-2">
Last scan: {format(new Date(website.lastScanAt), 'MMM d, h:mm a')}
</p>
)}
</Card>
))}
</div>
)}
</div>
);
}

View file

@ -1,55 +0,0 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface User {
id: string;
email: string;
name?: string;
company?: string;
role: string;
apiKey?: string;
}
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
isLoading: boolean;
setAuth: (user: User, token: string) => void;
setUser: (user: User) => void;
setLoading: (loading: boolean) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
token: null,
isAuthenticated: false,
isLoading: true,
setAuth: (user, token) =>
set({
user,
token,
isAuthenticated: true,
isLoading: false,
}),
setUser: (user) => set({ user }),
setLoading: (loading) => set({ isLoading: loading }),
logout: () =>
set({
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
}),
}),
{
name: 'wcag-auth',
partialize: (state) => ({
token: state.token,
}),
}
)
);

View file

@ -1,67 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--success: 142.1 76.2% 36.3%;
--success-foreground: 355.7 100% 97.3%;
--warning: 47.9 95.8% 53.1%;
--warning-foreground: 26 83.3% 14.1%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--success: 142.1 70.6% 45.3%;
--success-foreground: 144.9 80.4% 10%;
--warning: 47.9 80% 60%;
--warning-foreground: 47.5 90% 10%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View file

@ -1,85 +0,0 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
success: {
DEFAULT: "hsl(var(--success))",
foreground: "hsl(var(--success-foreground))",
},
warning: {
DEFAULT: "hsl(var(--warning))",
foreground: "hsl(var(--warning-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
}

View file

@ -1,34 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Path aliases */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"references": [
{ "path": "../shared" },
{ "path": "../config" }
]
}

View file

@ -1,22 +0,0 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:3001',
changeOrigin: true,
},
},
},
});

View file

@ -1,47 +0,0 @@
version: '3.8'
services:
# PostgreSQL Database (for local development)
postgres:
image: postgres:16-alpine
container_name: wcag-ada-postgres-dev
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: wcag_ada_dev
volumes:
- postgres_dev_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d wcag_ada_dev"]
interval: 10s
timeout: 5s
retries: 5
networks:
- wcag-ada-dev-network
# Redis (for local development)
redis:
image: redis:7-alpine
container_name: wcag-ada-redis-dev
command: redis-server --appendonly yes
volumes:
- redis_dev_data:/data
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
networks:
- wcag-ada-dev-network
networks:
wcag-ada-dev-network:
driver: bridge
volumes:
postgres_dev_data:
redis_dev_data:

View file

@ -1,28 +0,0 @@
version: '3.8'
services:
# Test databases for CI/CD
postgres-test:
image: postgres:16-alpine
environment:
POSTGRES_USER: test_user
POSTGRES_PASSWORD: test_password
POSTGRES_DB: wcag_ada_test
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U test_user -d wcag_ada_test"]
interval: 5s
timeout: 5s
retries: 5
redis-test:
image: redis:7-alpine
command: redis-server --appendonly yes
ports:
- "6380:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 5s
retries: 5

View file

@ -1,153 +0,0 @@
version: '3.8'
services:
# PostgreSQL Database
postgres:
image: postgres:16-alpine
container_name: wcag-ada-postgres
environment:
POSTGRES_USER: wcag_user
POSTGRES_PASSWORD: wcag_password
POSTGRES_DB: wcag_ada
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U wcag_user -d wcag_ada"]
interval: 10s
timeout: 5s
retries: 5
networks:
- wcag-ada-network
# Redis
redis:
image: redis:7-alpine
container_name: wcag-ada-redis
command: redis-server --appendonly yes
volumes:
- redis_data:/data
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
networks:
- wcag-ada-network
# API Service
api:
build:
context: ../..
dockerfile: apps/wcag-ada/api/Dockerfile
container_name: wcag-ada-api
environment:
NODE_ENV: production
DATABASE_URL: postgresql://wcag_user:wcag_password@postgres:5432/wcag_ada
REDIS_HOST: redis
REDIS_PORT: 6379
API_PORT: 3001
API_JWT_SECRET: ${API_JWT_SECRET:-change-this-in-production}
API_CORS_ORIGIN: ${API_CORS_ORIGIN:-http://localhost:8080}
ports:
- "3001:3001"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3001/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- wcag-ada-network
restart: unless-stopped
# Worker Service
worker:
build:
context: ../..
dockerfile: apps/wcag-ada/worker/Dockerfile
container_name: wcag-ada-worker
environment:
NODE_ENV: production
DATABASE_URL: postgresql://wcag_user:wcag_password@postgres:5432/wcag_ada
REDIS_HOST: redis
REDIS_PORT: 6379
WORKER_PORT: 3002
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-5}
SCANNER_HEADLESS: "true"
ports:
- "3002:3002"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
api:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3002/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- wcag-ada-network
restart: unless-stopped
# Additional security options for Chromium
security_opt:
- seccomp:unconfined
cap_add:
- SYS_ADMIN
# Dashboard
dashboard:
build:
context: ../..
dockerfile: apps/wcag-ada/dashboard/Dockerfile
container_name: wcag-ada-dashboard
ports:
- "8080:8080"
depends_on:
api:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- wcag-ada-network
restart: unless-stopped
# Database migrations (one-time job)
migrate:
build:
context: ../..
dockerfile: apps/wcag-ada/api/Dockerfile
container_name: wcag-ada-migrate
command: ["bunx", "prisma", "migrate", "deploy"]
environment:
DATABASE_URL: postgresql://wcag_user:wcag_password@postgres:5432/wcag_ada
depends_on:
postgres:
condition: service_healthy
networks:
- wcag-ada-network
restart: "no"
networks:
wcag-ada-network:
driver: bridge
volumes:
postgres_data:
redis_data:

View file

@ -1,69 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: wcag-ada-api
namespace: wcag-ada
spec:
replicas: 3
selector:
matchLabels:
app: wcag-ada-api
template:
metadata:
labels:
app: wcag-ada-api
spec:
initContainers:
- name: wait-for-postgres
image: busybox:1.36
command: ['sh', '-c', 'until nc -z postgres-service 5432; do echo waiting for postgres; sleep 2; done']
- name: run-migrations
image: wcag-ada/api:latest
command: ["bunx", "prisma", "migrate", "deploy"]
envFrom:
- configMapRef:
name: wcag-ada-config
- secretRef:
name: wcag-ada-secrets
containers:
- name: api
image: wcag-ada/api:latest
ports:
- containerPort: 3001
envFrom:
- configMapRef:
name: wcag-ada-config
- secretRef:
name: wcag-ada-secrets
livenessProbe:
httpGet:
path: /health
port: 3001
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 3001
initialDelaySeconds: 5
periodSeconds: 5
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
name: wcag-ada-api-service
namespace: wcag-ada
spec:
selector:
app: wcag-ada-api
ports:
- port: 3001
targetPort: 3001
type: ClusterIP

View file

@ -1,47 +0,0 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: wcag-ada-config
namespace: wcag-ada
data:
NODE_ENV: "production"
APP_NAME: "wcag-ada"
# API Configuration
API_PORT: "3001"
API_CORS_ORIGIN: "https://wcag-ada.example.com"
API_JWT_EXPIRES_IN: "7d"
API_RATE_LIMIT: "100"
API_RATE_WINDOW: "60000"
# Worker Configuration
WORKER_PORT: "3002"
WORKER_CONCURRENCY: "5"
WORKER_QUEUE_NAME: "accessibility-scans"
# Redis Configuration
REDIS_HOST: "redis-service"
REDIS_PORT: "6379"
REDIS_DB: "0"
# Scanner Configuration
SCANNER_HEADLESS: "true"
SCANNER_TIMEOUT: "30000"
SCANNER_VIEWPORT_WIDTH: "1920"
SCANNER_VIEWPORT_HEIGHT: "1080"
SCANNER_BLOCK_RESOURCES: "true"
SCANNER_BLOCK_PATTERNS: "font,image"
# Features
FEATURES_SCREENSHOTS: "true"
FEATURES_FIX_SUGGESTIONS: "true"
FEATURES_CUSTOM_RULES: "true"
FEATURES_SCHEDULED_SCANS: "true"
FEATURES_BULK_SCANNING: "false"
FEATURES_API_ACCESS: "true"
# Scheduler
SCHEDULER_TIMEZONE: "America/New_York"
SCHEDULER_MAX_CONCURRENT_SCANS: "3"
SCHEDULER_RETRY_ATTEMPTS: "3"
SCHEDULER_RETRY_DELAY: "5000"

View file

@ -1,52 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: wcag-ada-dashboard
namespace: wcag-ada
spec:
replicas: 2
selector:
matchLabels:
app: wcag-ada-dashboard
template:
metadata:
labels:
app: wcag-ada-dashboard
spec:
containers:
- name: dashboard
image: wcag-ada/dashboard:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
resources:
requests:
memory: "64Mi"
cpu: "50m"
limits:
memory: "128Mi"
cpu: "100m"
---
apiVersion: v1
kind: Service
metadata:
name: wcag-ada-dashboard-service
namespace: wcag-ada
spec:
selector:
app: wcag-ada-dashboard
ports:
- port: 80
targetPort: 8080
type: ClusterIP

View file

@ -1,38 +0,0 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: wcag-ada-ingress
namespace: wcag-ada
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/proxy-body-size: "10m"
spec:
ingressClassName: nginx
tls:
- hosts:
- wcag-ada.example.com
- api.wcag-ada.example.com
secretName: wcag-ada-tls
rules:
- host: wcag-ada.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: wcag-ada-dashboard-service
port:
number: 80
- host: api.wcag-ada.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: wcag-ada-api-service
port:
number: 3001

View file

@ -1,6 +0,0 @@
apiVersion: v1
kind: Namespace
metadata:
name: wcag-ada
labels:
name: wcag-ada

View file

@ -1,84 +0,0 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-pvc
namespace: wcag-ada
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
namespace: wcag-ada
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_USER
value: wcag_user
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: wcag-ada-secrets
key: DATABASE_URL
- name: POSTGRES_DB
value: wcag_ada
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
volumeMounts:
- name: postgres-storage
mountPath: /var/lib/postgresql/data
livenessProbe:
exec:
command:
- pg_isready
- -U
- wcag_user
- -d
- wcag_ada
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- pg_isready
- -U
- wcag_user
- -d
- wcag_ada
initialDelaySeconds: 5
periodSeconds: 5
volumes:
- name: postgres-storage
persistentVolumeClaim:
claimName: postgres-pvc
---
apiVersion: v1
kind: Service
metadata:
name: postgres-service
namespace: wcag-ada
spec:
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
type: ClusterIP

View file

@ -1,77 +0,0 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: redis-pvc
namespace: wcag-ada
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
namespace: wcag-ada
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:7-alpine
command:
- redis-server
- --appendonly
- "yes"
ports:
- containerPort: 6379
volumeMounts:
- name: redis-storage
mountPath: /data
livenessProbe:
exec:
command:
- redis-cli
- ping
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- redis-cli
- ping
initialDelaySeconds: 5
periodSeconds: 5
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "200m"
volumes:
- name: redis-storage
persistentVolumeClaim:
claimName: redis-pvc
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
namespace: wcag-ada
spec:
selector:
app: redis
ports:
- port: 6379
targetPort: 6379
type: ClusterIP

View file

@ -1,26 +0,0 @@
apiVersion: v1
kind: Secret
metadata:
name: wcag-ada-secrets
namespace: wcag-ada
type: Opaque
stringData:
# Database
DATABASE_URL: "postgresql://wcag_user:wcag_password@postgres-service:5432/wcag_ada"
# Redis
REDIS_PASSWORD: ""
# API
API_JWT_SECRET: "your-super-secret-jwt-key-change-in-production"
# Email (optional)
SMTP_HOST: ""
SMTP_PORT: "587"
SMTP_USER: ""
SMTP_PASS: ""
SMTP_FROM: "noreply@wcag-ada.com"
# Slack (optional)
SLACK_WEBHOOK_URL: ""
SLACK_CHANNEL: "#wcag-alerts"

Some files were not shown because too many files have changed in this diff Show more