Spaces:
Sleeping
Sleeping
Sam Cole Claude Opus 4.8 (1M context) commited on
Commit ·
887650c
1
Parent(s): 40aab9f
Self-improving dev/test/deploy loop: frozen tests, diff-based evolution engine, CI
Browse filesMigrates InsightsEngine into the WorldDigest-style self-evolving process:
- tests/: frozen fitness suite (reliability, analysis correctness, performance,
coverage ratchet) + frontend gate (node --check + index.html structure)
- evolution/: diff-based mutation engine on the HF Inference router, goal prompts,
metrics + attempts logs
- .github/workflows/: nightly evolve (mutate->test->merge/revert->deploy to live
Space) + daily health metrics
- scripts/collect_metrics.py, requirements-dev.txt (CI-only), CLAUDE.md, .gitignore
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- .github/workflows/evolve.yml +87 -0
- .github/workflows/health.yml +33 -0
- .gitignore +15 -0
- CLAUDE.md +90 -0
- evolution/attempts.log +0 -0
- evolution/evolve.py +226 -0
- evolution/metrics.json +1 -0
- evolution/prompts.md +44 -0
- fetch_datasets.py +252 -0
- requirements-dev.txt +4 -0
- scripts/collect_metrics.py +76 -0
- tests/__init__.py +0 -0
- tests/conftest.py +53 -0
- tests/test_app.py +259 -0
- tests/test_frontend.py +83 -0
.github/workflows/evolve.yml
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Nightly Evolution
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: "0 3 * * *" # 03:00 UTC nightly
|
| 6 |
+
workflow_dispatch: # manual trigger button
|
| 7 |
+
|
| 8 |
+
# Needs write access to push merged mutations back to the GitHub repo.
|
| 9 |
+
permissions:
|
| 10 |
+
contents: write
|
| 11 |
+
|
| 12 |
+
jobs:
|
| 13 |
+
evolve:
|
| 14 |
+
runs-on: ubuntu-latest
|
| 15 |
+
timeout-minutes: 25
|
| 16 |
+
steps:
|
| 17 |
+
- uses: actions/checkout@v4
|
| 18 |
+
with:
|
| 19 |
+
fetch-depth: 0
|
| 20 |
+
|
| 21 |
+
- name: Kill switch
|
| 22 |
+
run: |
|
| 23 |
+
if [ -f EVOLUTION_PAUSED ]; then
|
| 24 |
+
echo "Evolution paused by kill-switch file. Exiting cleanly."
|
| 25 |
+
exit 0
|
| 26 |
+
fi
|
| 27 |
+
|
| 28 |
+
- uses: actions/setup-python@v5
|
| 29 |
+
with:
|
| 30 |
+
python-version: "3.12"
|
| 31 |
+
- uses: actions/setup-node@v4
|
| 32 |
+
with:
|
| 33 |
+
node-version: "20"
|
| 34 |
+
|
| 35 |
+
- run: pip install -r requirements.txt -r requirements-dev.txt
|
| 36 |
+
|
| 37 |
+
- name: Baseline - frozen suite must pass before evolving
|
| 38 |
+
run: |
|
| 39 |
+
pytest tests/ -q
|
| 40 |
+
for f in dataset_embed.js app_v30.js globe_patch.js mapping_canvas.js; do
|
| 41 |
+
node --check "static/$f"
|
| 42 |
+
done
|
| 43 |
+
|
| 44 |
+
- name: Propose mutation (one diff)
|
| 45 |
+
env:
|
| 46 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 47 |
+
run: python evolution/evolve.py
|
| 48 |
+
|
| 49 |
+
- name: Guard - frozen files untouched
|
| 50 |
+
run: |
|
| 51 |
+
if ! git diff --quiet -- tests/ .github/ requirements.txt requirements-dev.txt Dockerfile; then
|
| 52 |
+
echo "VIOLATION: mutation touched frozen files. Reverting."
|
| 53 |
+
git checkout -- tests/ .github/ requirements.txt requirements-dev.txt Dockerfile
|
| 54 |
+
exit 1
|
| 55 |
+
fi
|
| 56 |
+
|
| 57 |
+
- name: Validate mutation
|
| 58 |
+
id: validate
|
| 59 |
+
continue-on-error: true
|
| 60 |
+
run: |
|
| 61 |
+
pytest tests/ -q
|
| 62 |
+
for f in dataset_embed.js app_v30.js globe_patch.js mapping_canvas.js; do
|
| 63 |
+
node --check "static/$f"
|
| 64 |
+
done
|
| 65 |
+
|
| 66 |
+
- name: Merge or revert
|
| 67 |
+
run: |
|
| 68 |
+
git config user.name "evolution-bot"
|
| 69 |
+
git config user.email "bot@users.noreply.github.com"
|
| 70 |
+
if [ "${{ steps.validate.outcome }}" = "success" ]; then
|
| 71 |
+
echo "$(date -u --iso-8601=seconds) | MERGED | tests passed" >> evolution/attempts.log
|
| 72 |
+
git add main.py static/ evolution/attempts.log
|
| 73 |
+
git commit -m "evolve: mutation accepted $(date -u +%F)"
|
| 74 |
+
else
|
| 75 |
+
git checkout -- main.py static/
|
| 76 |
+
echo "$(date -u --iso-8601=seconds) | REVERTED | tests failed" >> evolution/attempts.log
|
| 77 |
+
git add evolution/attempts.log
|
| 78 |
+
git commit -m "evolve: mutation reverted $(date -u +%F)"
|
| 79 |
+
fi
|
| 80 |
+
git push origin HEAD:main
|
| 81 |
+
|
| 82 |
+
- name: Deploy to HuggingFace Space (live) on accepted mutation
|
| 83 |
+
if: steps.validate.outcome == 'success'
|
| 84 |
+
env:
|
| 85 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 86 |
+
run: |
|
| 87 |
+
git push "https://colesr:${HF_TOKEN}@huggingface.co/spaces/colesr/insight-engine-docker" HEAD:main
|
.github/workflows/health.yml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Daily Health
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: "0 7 * * *" # 07:00 UTC daily
|
| 6 |
+
workflow_dispatch:
|
| 7 |
+
|
| 8 |
+
permissions:
|
| 9 |
+
contents: write
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
health:
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
timeout-minutes: 15
|
| 15 |
+
steps:
|
| 16 |
+
- uses: actions/checkout@v4
|
| 17 |
+
|
| 18 |
+
- uses: actions/setup-python@v5
|
| 19 |
+
with:
|
| 20 |
+
python-version: "3.12"
|
| 21 |
+
|
| 22 |
+
- run: pip install -r requirements.txt -r requirements-dev.txt
|
| 23 |
+
|
| 24 |
+
- name: Collect metrics
|
| 25 |
+
run: python scripts/collect_metrics.py
|
| 26 |
+
|
| 27 |
+
- name: Commit metrics
|
| 28 |
+
run: |
|
| 29 |
+
git config user.name "health-bot"
|
| 30 |
+
git config user.email "bot@users.noreply.github.com"
|
| 31 |
+
git add evolution/metrics.json
|
| 32 |
+
git commit -m "metrics: daily health $(date -u +%F)" || echo "no changes"
|
| 33 |
+
git push origin HEAD:main
|
.gitignore
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local Claude Code settings (machine-specific)
|
| 2 |
+
.claude/
|
| 3 |
+
|
| 4 |
+
# Python
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.pyc
|
| 7 |
+
.venv/
|
| 8 |
+
.pytest_cache/
|
| 9 |
+
|
| 10 |
+
# Dead / local-only artifacts (not part of the canonical app)
|
| 11 |
+
app.js
|
| 12 |
+
index
|
| 13 |
+
|
| 14 |
+
# Playwright browsers (if the optional render smoke test is enabled locally)
|
| 15 |
+
node_modules/
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md
|
| 2 |
+
|
| 3 |
+
This file guides Claude Code (claude.ai/code) when working in this repository.
|
| 4 |
+
|
| 5 |
+
## What this is
|
| 6 |
+
|
| 7 |
+
**Global Insight Engine** is a self-evolving FastAPI + vanilla-JS data-analytics web app
|
| 8 |
+
(3D news globe, correlation/outlier/decision tools over global development indicators),
|
| 9 |
+
deployed as a Docker Space on HuggingFace at `colesr/insight-engine-docker`.
|
| 10 |
+
|
| 11 |
+
The code lives on **GitHub** (`colesr/insight-engine`, remote `origin`) where two scheduled
|
| 12 |
+
GitHub Actions form a cyclical, minimal-supervision dev/test/deploy loop. The HF Space
|
| 13 |
+
(remote `hf`) is the **deploy target** — accepted mutations are pushed to it and it rebuilds.
|
| 14 |
+
|
| 15 |
+
- **Daily** (`.github/workflows/health.yml`, 07:00 UTC): `scripts/collect_metrics.py` boots
|
| 16 |
+
the app, records coverage + latency signals, and commits `evolution/metrics.json`.
|
| 17 |
+
- **Nightly** (`.github/workflows/evolve.yml`, 03:00 UTC): `evolution/evolve.py` asks a code
|
| 18 |
+
LLM to rewrite ONE evolvable file as a unified diff. CI runs the frozen suite + frontend
|
| 19 |
+
gate; on pass it commits, pushes to GitHub, **and deploys to the live HF Space**; on fail
|
| 20 |
+
it `git checkout`-reverts.
|
| 21 |
+
|
| 22 |
+
## Commands
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
pip install -r requirements.txt -r requirements-dev.txt
|
| 26 |
+
pytest tests/ -q # the fitness gate
|
| 27 |
+
node --check static/app_v30.js # frontend syntax gate (also v_embed/globe/mapping)
|
| 28 |
+
.venv/bin/uvicorn main:app --host 0.0.0.0 --port 7860 --reload # run locally
|
| 29 |
+
python scripts/collect_metrics.py # write one metrics.json entry
|
| 30 |
+
python evolution/evolve.py # propose one mutation (needs HF_TOKEN)
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
## The core invariant
|
| 34 |
+
|
| 35 |
+
`tests/test_app.py` + `tests/test_frontend.py` are the **frozen fitness definition** and the
|
| 36 |
+
user's encoded intent. The loop is only correct because these files (and `.github/`,
|
| 37 |
+
`requirements.txt`, `Dockerfile`) can never be modified by the system. Three layers enforce it:
|
| 38 |
+
|
| 39 |
+
1. `evolve.yml` runs `git diff --quiet -- tests/ .github/ requirements*.txt Dockerfile` and
|
| 40 |
+
reverts + fails if any changed.
|
| 41 |
+
2. `evolve.py` rejects any diff whose hunk headers target a frozen path, or whose added lines
|
| 42 |
+
contain forbidden tokens (`import tests`, `pytest.skip`, `sys.exit(0)`, `os.remove`, …),
|
| 43 |
+
*before* applying — and re-checks `git diff --name-only` after applying.
|
| 44 |
+
3. `tests/test_app.py` asserts `main.py` never imports from `tests/` and contains no
|
| 45 |
+
fitness-gaming calls.
|
| 46 |
+
|
| 47 |
+
**To change the system's behavior or goals, edit the tests** — that is the steering
|
| 48 |
+
mechanism. Auto-deploy goes straight to live users, so the gate must stay strong; never
|
| 49 |
+
weaken a test to make a mutation pass.
|
| 50 |
+
|
| 51 |
+
Fitness priority order (encoded in tests + `evolution/prompts.md`):
|
| 52 |
+
**Reliability > Analysis correctness > Performance > Coverage/features.**
|
| 53 |
+
|
| 54 |
+
## Evolvable surface
|
| 55 |
+
|
| 56 |
+
The engine edits ONE file per nightly run, chosen by rotation (weighted toward `main.py`):
|
| 57 |
+
`main.py`, `static/app_v30.js`, `static/globe_patch.js`, `static/mapping_canvas.js`,
|
| 58 |
+
`static/index.html`. The live frontend load order is
|
| 59 |
+
`dataset_embed.js → app_v30.js → init() → globe_patch.js → mapping_canvas.js`.
|
| 60 |
+
|
| 61 |
+
> ⚠️ `static/app.js` and `static/app_v35.js` are **DEAD** (referenced nowhere) — do not edit
|
| 62 |
+
> or resurrect them. The real application is `app_v30.js`.
|
| 63 |
+
|
| 64 |
+
Coverage floors the engine must never breach (asserted in tests): ≥269 World Bank indicators,
|
| 65 |
+
≥12 built-in datasets, exactly 9 WB presets, ≥40 globe countries, ≥10 RSS feeds. Counts may
|
| 66 |
+
grow, never shrink.
|
| 67 |
+
|
| 68 |
+
## Steering the evolution engine
|
| 69 |
+
|
| 70 |
+
- `evolution/prompts.md` is the goal hierarchy + constraints handed to the mutation LLM. Edit
|
| 71 |
+
it to redirect what mutations optimize for.
|
| 72 |
+
- The engine is shown recent `metrics.json` trends and recent `attempts.log` entries so it
|
| 73 |
+
doesn't repeat reverted/rejected/skipped approaches.
|
| 74 |
+
- **Kill switch:** create an empty `EVOLUTION_PAUSED` file in the repo root to halt the
|
| 75 |
+
nightly evolution (the daily health run keeps going). Delete it to resume.
|
| 76 |
+
- LLM: Hugging Face Inference Providers router (`Qwen/Qwen3-Coder-480B-A35B-Instruct:cheapest`)
|
| 77 |
+
via `HF_TOKEN`, OpenAI-compatible shape — same infra as the sibling WorldDigest system.
|
| 78 |
+
|
| 79 |
+
## Secrets (GitHub repo → Settings → Secrets and variables → Actions)
|
| 80 |
+
|
| 81 |
+
- `HF_TOKEN` — a HuggingFace token with BOTH "Make calls to Inference Providers" (for the
|
| 82 |
+
mutation LLM) AND "Write access to repos you can contribute to" (so CI can `git push` the
|
| 83 |
+
accepted mutation to the live Space). One fine-grained token can hold both permissions.
|
| 84 |
+
|
| 85 |
+
## Deploy
|
| 86 |
+
|
| 87 |
+
The HF Space is a Docker Space built from `Dockerfile` + `requirements.txt` + `main.py`;
|
| 88 |
+
pushing `main` triggers a rebuild. CI pushes to it ONLY on the validate-success branch, so the
|
| 89 |
+
live app only ever receives test-passing mutations. `requirements-dev.txt` (pytest/httpx) is
|
| 90 |
+
CI-only and is never installed into the runtime image.
|
evolution/attempts.log
ADDED
|
File without changes
|
evolution/evolve.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Evolution engine: proposes ONE diff-based mutation per run.
|
| 3 |
+
|
| 4 |
+
Cycle:
|
| 5 |
+
1. Pick ONE target file (rotation, weighted toward main.py where the top
|
| 6 |
+
priorities live), and gather metrics history + recent attempts + goals.
|
| 7 |
+
2. Ask a code LLM for ONE targeted improvement as a unified diff.
|
| 8 |
+
3. Validate the diff (no frozen paths, no forbidden tokens) and `git apply` it.
|
| 9 |
+
4. CI runs the frozen tests + frontend gate and decides merge-or-revert.
|
| 10 |
+
|
| 11 |
+
Hard rules (defense in depth; the CI `git diff` guard is the real wall):
|
| 12 |
+
- Never touches tests/, .github/, requirements.txt, Dockerfile.
|
| 13 |
+
- One file, one mutation per run.
|
| 14 |
+
- Logs every attempt (PROPOSED / SKIPPED / REJECTED) to evolution/attempts.log.
|
| 15 |
+
|
| 16 |
+
This deliberately reuses the working WorldDigest setup: the Hugging Face Inference
|
| 17 |
+
Providers OpenAI-compatible router, authed with an `hf_...` HF_TOKEN. (Non-Anthropic
|
| 18 |
+
by design — mirrors the sibling system; no Claude SDK is involved here.)
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import subprocess
|
| 25 |
+
import sys
|
| 26 |
+
import tempfile
|
| 27 |
+
from datetime import datetime, timezone
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import requests
|
| 31 |
+
|
| 32 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 33 |
+
METRICS = ROOT / "evolution" / "metrics.json"
|
| 34 |
+
ATTEMPTS = ROOT / "evolution" / "attempts.log"
|
| 35 |
+
PROMPTS = ROOT / "evolution" / "prompts.md"
|
| 36 |
+
|
| 37 |
+
MAX_TOKENS = 6000 # a diff is small; full files are only sent as INPUT context
|
| 38 |
+
|
| 39 |
+
LLM_ENDPOINT = "https://router.huggingface.co/v1/chat/completions"
|
| 40 |
+
LLM_MODEL = "Qwen/Qwen3-Coder-480B-A35B-Instruct:cheapest"
|
| 41 |
+
|
| 42 |
+
# Files the engine may edit (relative to repo root). main.py is weighted heavily
|
| 43 |
+
# because Reliability + Analysis-correctness (priorities 1-2) live there. The dead
|
| 44 |
+
# files static/app.js and static/app_v35.js are intentionally absent.
|
| 45 |
+
EVOLVABLE = [
|
| 46 |
+
"main.py", "main.py", "main.py", # weight: ~50% of runs target the backend
|
| 47 |
+
"static/app_v30.js",
|
| 48 |
+
"static/globe_patch.js",
|
| 49 |
+
"static/mapping_canvas.js",
|
| 50 |
+
"static/index.html",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
# Never let a hunk header point at these (also enforced by CI git-diff guard).
|
| 54 |
+
FROZEN_PREFIXES = ("tests/", ".github/", "requirements.txt", "Dockerfile", "requirements-dev.txt")
|
| 55 |
+
FORBIDDEN_TOKENS = ["import tests", "from tests", "pytest.skip", "sys.exit(0)", "os.remove(", "shutil.rmtree"]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _git(*args) -> str:
|
| 59 |
+
return subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True, text=True)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def pick_target() -> str:
|
| 63 |
+
"""Deterministic rotation (no Math.random / Date.now available in CI determinism
|
| 64 |
+
concerns here, but we key off the commit count so successive runs rotate)."""
|
| 65 |
+
count = _git("rev-list", "--count", "HEAD").stdout.strip()
|
| 66 |
+
idx = (int(count) if count.isdigit() else 0) % len(EVOLVABLE)
|
| 67 |
+
return EVOLVABLE[idx]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def recent_metrics(n=7) -> str:
|
| 71 |
+
if not METRICS.exists():
|
| 72 |
+
return "No metrics yet."
|
| 73 |
+
try:
|
| 74 |
+
history = json.loads(METRICS.read_text() or "[]")
|
| 75 |
+
except json.JSONDecodeError:
|
| 76 |
+
return "No metrics yet."
|
| 77 |
+
return json.dumps(history[-n:], indent=2) if history else "No metrics yet."
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def recent_attempts(n=8) -> str:
|
| 81 |
+
if not ATTEMPTS.exists():
|
| 82 |
+
return "No previous attempts."
|
| 83 |
+
lines = ATTEMPTS.read_text().strip().splitlines()
|
| 84 |
+
return "\n".join(lines[-n:]) if lines else "No previous attempts."
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def log_attempt(status: str, note: str = ""):
|
| 88 |
+
ATTEMPTS.parent.mkdir(exist_ok=True)
|
| 89 |
+
with ATTEMPTS.open("a") as f:
|
| 90 |
+
f.write(f"{datetime.now(timezone.utc).isoformat()} | {status} | {note}\n")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def propose_diff(target: str) -> str | None:
|
| 94 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 95 |
+
if not hf_token:
|
| 96 |
+
print("[error] HF_TOKEN not set; cannot evolve.")
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
goals = PROMPTS.read_text() if PROMPTS.exists() else ""
|
| 100 |
+
tree = _git("ls-files", "main.py", "static").stdout.strip()
|
| 101 |
+
target_src = (ROOT / target).read_text()
|
| 102 |
+
|
| 103 |
+
prompt = f"""{goals}
|
| 104 |
+
|
| 105 |
+
REPO FILES YOU MAY REFERENCE (you may ONLY edit the target file below):
|
| 106 |
+
{tree}
|
| 107 |
+
|
| 108 |
+
TARGET FILE THIS RUN: {target}
|
| 109 |
+
```
|
| 110 |
+
{target_src}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
RECENT METRICS (last 7 health runs):
|
| 114 |
+
{recent_metrics()}
|
| 115 |
+
|
| 116 |
+
RECENT ATTEMPTS (do NOT repeat reverted/rejected/skipped approaches):
|
| 117 |
+
{recent_attempts()}
|
| 118 |
+
|
| 119 |
+
Propose exactly ONE improvement to `{target}`, consistent with the priority order and
|
| 120 |
+
constraints above. Output ONLY a single unified diff, git-apply compatible, inside one
|
| 121 |
+
```diff fenced block, and nothing else. The diff must:
|
| 122 |
+
- modify ONLY `{target}` (correct `--- a/{target}` / `+++ b/{target}` headers),
|
| 123 |
+
- keep all existing route paths and JSON keys (add, don't rename/remove),
|
| 124 |
+
- never touch tests/, .github/, requirements.txt, or Dockerfile.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
resp = requests.post(
|
| 128 |
+
LLM_ENDPOINT,
|
| 129 |
+
headers={"Authorization": f"Bearer {hf_token}"},
|
| 130 |
+
json={
|
| 131 |
+
"model": LLM_MODEL,
|
| 132 |
+
"max_tokens": MAX_TOKENS,
|
| 133 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 134 |
+
},
|
| 135 |
+
timeout=300,
|
| 136 |
+
)
|
| 137 |
+
resp.raise_for_status()
|
| 138 |
+
text = resp.json()["choices"][0]["message"]["content"]
|
| 139 |
+
|
| 140 |
+
match = re.search(r"```(?:diff|patch)?\s*\n(.*?)```", text, re.DOTALL)
|
| 141 |
+
if match:
|
| 142 |
+
return match.group(1).strip() + "\n"
|
| 143 |
+
stripped = text.strip()
|
| 144 |
+
if stripped.startswith(("diff --git", "--- ")):
|
| 145 |
+
return stripped + "\n"
|
| 146 |
+
print(f"[error] no diff block in {len(text)}-char response. Preview:\n{text[:600]}")
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def diff_targets_frozen(diff: str) -> str | None:
|
| 151 |
+
"""Return the first frozen path a hunk header points at, else None."""
|
| 152 |
+
for line in diff.splitlines():
|
| 153 |
+
if line.startswith(("+++ ", "--- ", "diff --git")):
|
| 154 |
+
for prefix in FROZEN_PREFIXES:
|
| 155 |
+
# strip a/ b/ and quoting before matching
|
| 156 |
+
norm = line.replace("+++ ", "").replace("--- ", "").replace("diff --git ", "")
|
| 157 |
+
norm = norm.replace("a/", "").replace("b/", "").strip()
|
| 158 |
+
if prefix in norm:
|
| 159 |
+
return prefix
|
| 160 |
+
return None
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def added_lines(diff: str) -> str:
|
| 164 |
+
return "\n".join(l[1:] for l in diff.splitlines() if l.startswith("+") and not l.startswith("+++"))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def apply_diff(diff: str) -> bool:
|
| 168 |
+
"""Atomic pre-flight then real apply. Returns True on success."""
|
| 169 |
+
with tempfile.NamedTemporaryFile("w", suffix=".diff", delete=False) as fh:
|
| 170 |
+
fh.write(diff)
|
| 171 |
+
patch_path = fh.name
|
| 172 |
+
for extra in ([], ["--3way"]):
|
| 173 |
+
check = subprocess.run(
|
| 174 |
+
["git", "-C", str(ROOT), "apply", "--check", *extra, patch_path],
|
| 175 |
+
capture_output=True, text=True,
|
| 176 |
+
)
|
| 177 |
+
if check.returncode == 0:
|
| 178 |
+
real = subprocess.run(
|
| 179 |
+
["git", "-C", str(ROOT), "apply", *extra, patch_path],
|
| 180 |
+
capture_output=True, text=True,
|
| 181 |
+
)
|
| 182 |
+
os.unlink(patch_path)
|
| 183 |
+
return real.returncode == 0
|
| 184 |
+
print(f"[error] git apply failed: {check.stderr.strip()[:400]}")
|
| 185 |
+
os.unlink(patch_path)
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main():
|
| 190 |
+
target = pick_target()
|
| 191 |
+
print(f"[evolve] target this run: {target}")
|
| 192 |
+
|
| 193 |
+
diff = propose_diff(target)
|
| 194 |
+
if not diff:
|
| 195 |
+
log_attempt("SKIPPED", f"{target}: no usable diff returned")
|
| 196 |
+
sys.exit(1)
|
| 197 |
+
|
| 198 |
+
frozen = diff_targets_frozen(diff)
|
| 199 |
+
if frozen:
|
| 200 |
+
log_attempt("REJECTED", f"{target}: diff touches frozen path {frozen}")
|
| 201 |
+
sys.exit(1)
|
| 202 |
+
|
| 203 |
+
adds = added_lines(diff)
|
| 204 |
+
for tok in FORBIDDEN_TOKENS:
|
| 205 |
+
if tok in adds:
|
| 206 |
+
log_attempt("REJECTED", f"{target}: forbidden token {tok!r}")
|
| 207 |
+
sys.exit(1)
|
| 208 |
+
|
| 209 |
+
if not apply_diff(diff):
|
| 210 |
+
log_attempt("SKIPPED", f"{target}: git apply failed (context drift)")
|
| 211 |
+
sys.exit(1)
|
| 212 |
+
|
| 213 |
+
# Belt-and-suspenders: confirm nothing outside the allowed set actually changed.
|
| 214 |
+
changed = [l for l in _git("diff", "--name-only").stdout.splitlines() if l.strip()]
|
| 215 |
+
bad = [c for c in changed if any(p in c for p in FROZEN_PREFIXES)]
|
| 216 |
+
if bad:
|
| 217 |
+
_git("checkout", "--", *bad)
|
| 218 |
+
log_attempt("REJECTED", f"{target}: post-apply touched frozen {bad}")
|
| 219 |
+
sys.exit(1)
|
| 220 |
+
|
| 221 |
+
log_attempt("PROPOSED", f"{target}: {len(diff)} char diff applied; CI will validate")
|
| 222 |
+
print(f"Mutation applied to {target}. CI will test and merge or revert.")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
main()
|
evolution/metrics.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[]
|
evolution/prompts.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evolution Goals
|
| 2 |
+
|
| 3 |
+
You are the mutation engine for **Global Insight Engine**, a FastAPI + vanilla-JS
|
| 4 |
+
data-analytics web app (a 3D news globe, correlation/outlier/decision tools over
|
| 5 |
+
global development indicators). It auto-deploys to a live public HuggingFace Space
|
| 6 |
+
on every accepted mutation. You may propose **exactly ONE** improvement per cycle.
|
| 7 |
+
|
| 8 |
+
Improvements should target, in strict priority order:
|
| 9 |
+
|
| 10 |
+
1. **Reliability** — the app boots, every API contract in `tests/test_app.py` holds,
|
| 11 |
+
no endpoint regresses to an error, the frontend never white-screens.
|
| 12 |
+
2. **Analysis correctness** — correlation / outlier / decision math stays valid and
|
| 13 |
+
stable; never trade accuracy for cleverness.
|
| 14 |
+
3. **Performance** — keep endpoints responsive; preserve the in-memory cache layer
|
| 15 |
+
(`_cache_get` / `_cache_set`); don't add slow synchronous network calls to hot paths.
|
| 16 |
+
4. **Coverage / features** — breadth of indicators, built-in datasets, data sources,
|
| 17 |
+
and globe countries may only GROW. Adding indicators/datasets or a genuinely useful
|
| 18 |
+
UI capability is the main way to make forward progress once 1–3 are solid.
|
| 19 |
+
|
| 20 |
+
## Constraints (non-negotiable)
|
| 21 |
+
|
| 22 |
+
- Touch ONLY the file you are given. Output a single unified diff against repo root.
|
| 23 |
+
- NEVER modify `tests/`, `.github/`, `requirements.txt`, or `Dockerfile` — CI auto-reverts
|
| 24 |
+
and fails the run if you do. To change what the system optimizes for, the human edits
|
| 25 |
+
the tests; you do not.
|
| 26 |
+
- Keep every existing API route path and JSON response key intact (the tests and the
|
| 27 |
+
frontend both depend on them). You may ADD fields/endpoints, not rename/remove.
|
| 28 |
+
- Keep the coverage floors: ≥269 indicators, ≥12 built-in datasets, 9 World Bank presets,
|
| 29 |
+
≥40 globe countries, ≥10 RSS feeds. Never delete entries.
|
| 30 |
+
- Runtime stays within the current `requirements.txt` (FastAPI, uvicorn, requests, aiohttp,
|
| 31 |
+
pandas, numpy, feedparser, vaderSentiment). Do NOT introduce new runtime dependencies.
|
| 32 |
+
- Never import from or reference `tests/`. Never call `pytest.skip`, `sys.exit(0)`,
|
| 33 |
+
`os.remove`, or `shutil.rmtree`.
|
| 34 |
+
- The frontend's live load order is `dataset_embed.js → app_v30.js → init() → globe_patch.js
|
| 35 |
+
→ mapping_canvas.js`. `static/app.js` and `static/app_v35.js` are DEAD — do not edit them.
|
| 36 |
+
- Keep all JS syntactically valid (`node --check` gates it) and `init()` callable.
|
| 37 |
+
|
| 38 |
+
## Signals to use
|
| 39 |
+
|
| 40 |
+
- `metrics.json` trends: a dropping indicator/dataset/country count means coverage is
|
| 41 |
+
eroding; rising endpoint latency means a performance regression crept in.
|
| 42 |
+
- `attempts.log`: do NOT repeat an approach already logged as REVERTED, REJECTED, or SKIPPED.
|
| 43 |
+
- Prefer small, surgical, obviously-correct diffs. A tiny improvement that passes is worth
|
| 44 |
+
far more than an ambitious rewrite that gets reverted.
|
fetch_datasets.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Insight Engine Dataset Fetcher — Run: python fetch_datasets.py"""
|
| 3 |
+
|
| 4 |
+
import json, time, sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import requests, pandas as pd, numpy as np
|
| 7 |
+
from io import StringIO
|
| 8 |
+
import datetime
|
| 9 |
+
|
| 10 |
+
OUTPUT = Path(".")
|
| 11 |
+
COUNTRY_MAP = {
|
| 12 |
+
"United States of America": "United States",
|
| 13 |
+
"Russian Federation": "Russia",
|
| 14 |
+
"Korea, Republic of": "South Korea", "Korea, Rep.": "South Korea",
|
| 15 |
+
"Iran, Islamic Republic of": "Iran", "Iran, Islamic Rep.": "Iran",
|
| 16 |
+
"Viet Nam": "Vietnam",
|
| 17 |
+
"Venezuela, Bolivarian Republic of": "Venezuela", "Venezuela, RB": "Venezuela",
|
| 18 |
+
"Egypt, Arab Republic of": "Egypt", "Egypt, Arab Rep.": "Egypt",
|
| 19 |
+
"Syrian Arab Republic": "Syria", "Yemen, Republic of": "Yemen",
|
| 20 |
+
"Tanzania, United Republic of": "Tanzania",
|
| 21 |
+
"Congo, Democratic Republic of the": "Democratic Republic of the Congo", "Congo, Dem. Rep.": "Democratic Republic of the Congo",
|
| 22 |
+
"Congo, Republic of": "Republic of the Congo", "Congo, Rep.": "Republic of the Congo",
|
| 23 |
+
"Lao People's Democratic Republic": "Laos", "Lao PDR": "Laos",
|
| 24 |
+
"Libyan Arab Jamahiriya": "Libya", "Moldova, Republic of": "Moldova",
|
| 25 |
+
"Macedonia, the former Yugoslav Republic of": "North Macedonia", "North Macedonia, Republic of": "North Macedonia",
|
| 26 |
+
"Czechia": "Czech Republic", "Brunei Darussalam": "Brunei",
|
| 27 |
+
"Cabo Verde": "Cape Verde", "Eswatini": "Swaziland",
|
| 28 |
+
"Gambia, The": "Gambia", "Bahamas, The": "Bahamas",
|
| 29 |
+
}
|
| 30 |
+
def norm(name):
|
| 31 |
+
return COUNTRY_MAP.get(name.strip(), name.strip()) if name else ""
|
| 32 |
+
|
| 33 |
+
print("[1/5] Building country lookup...")
|
| 34 |
+
rc = {}
|
| 35 |
+
try:
|
| 36 |
+
r = requests.get("https://restcountries.com/v3.1/all?fields=name,cca3,population,area,region", timeout=30)
|
| 37 |
+
for c in r.json():
|
| 38 |
+
for k in [c.get("name",{}).get("common",""), c.get("name",{}).get("official","")]:
|
| 39 |
+
if k: rc[norm(k)] = c
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f" REST Countries failed: {e}")
|
| 42 |
+
|
| 43 |
+
def iso3(name):
|
| 44 |
+
name = norm(name)
|
| 45 |
+
if name in rc: return rc[name].get("cca3", name)
|
| 46 |
+
for c in rc.values():
|
| 47 |
+
if c.get("cca3","").upper() == name.upper(): return name
|
| 48 |
+
return name
|
| 49 |
+
|
| 50 |
+
def w(name, unit, cat, icon, hib):
|
| 51 |
+
return {"key":None,"name":name,"unit":unit,"category":cat,"desc":"","icon":icon,"higherIsBetter":hib}
|
| 52 |
+
|
| 53 |
+
def write(name, source, desc, vars, data, fname):
|
| 54 |
+
js = f"""// {name} Dataset
|
| 55 |
+
// Source: {source}
|
| 56 |
+
// Variables: {len(vars)} | Countries: {len(data)}
|
| 57 |
+
const DATASET_{name.upper().replace(' ','_').replace('-','_')} = {json.dumps(data, ensure_ascii=False, indent=2)};
|
| 58 |
+
const VARIABLE_DEFS_{name.upper().replace(' ','_').replace('-','_')} = {json.dumps(vars, ensure_ascii=False, indent=2)};
|
| 59 |
+
const DATASET_PACK_{name.upper().replace(' ','_').replace('-','_')} = {{
|
| 60 |
+
name: "{name}", source: "{source}", description: "{desc}",
|
| 61 |
+
variableCount: {len(vars)}, countryCount: {len(data)},
|
| 62 |
+
lastUpdated: "{time.strftime('%Y-%m-%d')}", requiresKey: false,
|
| 63 |
+
dataset: DATASET_{name.upper().replace(' ','_').replace('-','_')},
|
| 64 |
+
variables: VARIABLE_DEFS_{name.upper().replace(' ','_').replace('-','_')}
|
| 65 |
+
}};
|
| 66 |
+
"""
|
| 67 |
+
(OUTPUT / fname).write_text(js, encoding="utf-8")
|
| 68 |
+
print(f" ✓ {fname} ({len(data)} rows, {len(vars)} vars)")
|
| 69 |
+
|
| 70 |
+
# ===== WORLD BANK =====
|
| 71 |
+
print("\n[2/5] Fetching World Bank indicators...")
|
| 72 |
+
inds = {
|
| 73 |
+
"NY.GDP.PCAP.CD":w("GDP per Capita","USD","Economy","trending-up",None),
|
| 74 |
+
"NY.GDP.MKTP.KD.ZG":w("GDP Growth","%","Economy","trending-up",True),
|
| 75 |
+
"NE.TRD.GNFS.ZS":w("Trade (% of GDP)","%","Economy","globe",None),
|
| 76 |
+
"SL.UEM.TOTL.ZS":w("Unemployment","%","Economy","users",False),
|
| 77 |
+
"SP.DYN.LE00.IN":w("Life Expectancy","years","Health","heart",True),
|
| 78 |
+
"SH.DYN.MORT":w("Mortality (under 5 per 1k)","per 1k","Health","skull",False),
|
| 79 |
+
"SH.XPD.CHEX.GD.ZS":w("Health Expenditure (% GDP)","%","Health","activity",None),
|
| 80 |
+
"SE.PRM.CMPT.ZS":w("Primary Completion","%","Education","graduation-cap",True),
|
| 81 |
+
"SE.TER.ENRR":w("Tertiary Enrollment","%","Education","book-open",True),
|
| 82 |
+
"IT.NET.USER.ZS":w("Internet Users","%","Infrastructure","wifi",True),
|
| 83 |
+
"EG.ELC.ACCS.ZS":w("Electricity Access","%","Infrastructure","zap",True),
|
| 84 |
+
"EN.ATM.CO2E.PC":w("CO2 per Capita","tonnes","Environment","cloud",False),
|
| 85 |
+
"AG.LND.FRST.ZS":w("Forest Cover","%","Environment","trees",None),
|
| 86 |
+
"EG.FEC.RNEW.ZS":w("Renewable Energy","%","Environment","sun",True),
|
| 87 |
+
"SP.POP.TOTL":w("Population","people","Demographics","users",None),
|
| 88 |
+
"SP.POP.GROW":w("Population Growth","%","Demographics","baby",None),
|
| 89 |
+
"SP.DYN.TFRT.IN":w("Fertility Rate","births/woman","Demographics","baby",None),
|
| 90 |
+
"SI.POV.GINI":w("Gini Index","index","Social","bar-chart",False),
|
| 91 |
+
"SG.GEN.PARL.ZS":w("Women in Parliament","%","Social","user-check",True),
|
| 92 |
+
"VC.IHR.PSRC.P5":w("Intentional Homicides","per 100k","Social","alert-triangle",False),
|
| 93 |
+
}
|
| 94 |
+
wb_data = {}
|
| 95 |
+
for code, v in inds.items():
|
| 96 |
+
v["key"] = code
|
| 97 |
+
try:
|
| 98 |
+
r = requests.get(f"https://api.worldbank.org/v2/country/all/indicator/{code}?format=json&per_page=10000&mrnev=1&date=2018:2023", timeout=30)
|
| 99 |
+
d = r.json()
|
| 100 |
+
if len(d)>1 and isinstance(d[1], list):
|
| 101 |
+
for e in d[1]:
|
| 102 |
+
val = e.get("value")
|
| 103 |
+
if val is not None:
|
| 104 |
+
c = norm(e.get("country",{}).get("value",""))
|
| 105 |
+
if c:
|
| 106 |
+
if c not in wb_data: wb_data[c] = {"country": c}
|
| 107 |
+
wb_data[c][code] = val
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f" {code} failed: {e}")
|
| 110 |
+
time.sleep(0.2)
|
| 111 |
+
write("World Bank Extended","api.worldbank.org/v2","Economy, health, education, infrastructure, environment, demographics and social",list(inds.values()),list(wb_data.values()),"dataset_worldbank.js")
|
| 112 |
+
|
| 113 |
+
# ===== REST COUNTRIES =====
|
| 114 |
+
print("\n[3/5] Fetching REST Countries...")
|
| 115 |
+
try:
|
| 116 |
+
r = requests.get("https://restcountries.com/v3.1/all?fields=name,cca3,population,area,region,subregion,capital,languages,currencies,independent,unMember,landlocked,gini", timeout=60)
|
| 117 |
+
rc_data = r.json()
|
| 118 |
+
rc_vars = [
|
| 119 |
+
{"key":"population","name":"Population","unit":"people","category":"Demographics","desc":"Total population","icon":"users","higherIsBetter":None},
|
| 120 |
+
{"key":"area","name":"Land Area","unit":"km2","category":"Demographics","desc":"Total land area","icon":"map","higherIsBetter":None},
|
| 121 |
+
{"key":"independent","name":"Independent","unit":"boolean","category":"Politics","desc":"Recognized independent","icon":"flag","higherIsBetter":True},
|
| 122 |
+
{"key":"unMember","name":"UN Member","unit":"boolean","category":"Politics","desc":"UN membership","icon":"globe","higherIsBetter":None},
|
| 123 |
+
{"key":"landlocked","name":"Landlocked","unit":"boolean","category":"Geography","desc":"No ocean coastline","icon":"map-pin","higherIsBetter":False},
|
| 124 |
+
{"key":"num_languages","name":"Official Languages","unit":"count","category":"Culture","desc":"Number of official languages","icon":"languages","higherIsBetter":None},
|
| 125 |
+
{"key":"num_currencies","name":"Currencies","unit":"count","category":"Economy","desc":"Number of official currencies","icon":"coins","higherIsBetter":None},
|
| 126 |
+
]
|
| 127 |
+
rc_rows = []
|
| 128 |
+
for c in rc_data:
|
| 129 |
+
country = norm(c.get("name",{}).get("common",""))
|
| 130 |
+
rc_rows.append({
|
| 131 |
+
"country": country, "iso3": c.get("cca3",""),
|
| 132 |
+
"population": c.get("population"), "area": c.get("area"),
|
| 133 |
+
"independent": 1 if c.get("independent") else 0,
|
| 134 |
+
"unMember": 1 if c.get("unMember") else 0,
|
| 135 |
+
"landlocked": 1 if c.get("landlocked") else 0,
|
| 136 |
+
"num_languages": len(c.get("languages",{})),
|
| 137 |
+
"num_currencies": len(c.get("currencies",{})),
|
| 138 |
+
})
|
| 139 |
+
write("REST Countries","restcountries.com/v3.1","Geography, demographics, politics and cultural",rc_vars,rc_rows,"dataset_countries.js")
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print(f" Failed: {e}")
|
| 142 |
+
|
| 143 |
+
# ===== OWID =====
|
| 144 |
+
print("\n[4/5] Fetching Our World in Data...")
|
| 145 |
+
try:
|
| 146 |
+
r = requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv", timeout=60)
|
| 147 |
+
df = pd.read_csv(StringIO(r.text))
|
| 148 |
+
latest = df.sort_values("date").groupby("location").last().reset_index()
|
| 149 |
+
owid_cols = {
|
| 150 |
+
"total_cases_per_million":w("Total Cases per Million","per million","Health","virus",False),
|
| 151 |
+
"total_deaths_per_million":w("Total Deaths per Million","per million","Health","skull",False),
|
| 152 |
+
"people_vaccinated_per_hundred":w("People Vaccinated","%","Health","syringe",True),
|
| 153 |
+
"hospital_beds_per_thousand":w("Hospital Beds per 1k","per 1000","Health","bed",True),
|
| 154 |
+
"human_development_index":w("Human Development Index","0-1","Social","award",True),
|
| 155 |
+
"extreme_poverty":w("Extreme Poverty Rate","%","Social","frown",False),
|
| 156 |
+
"median_age":w("Median Age","years","Demographics","calendar",None),
|
| 157 |
+
"gdp_per_capita":w("GDP per Capita","USD","Economy","trending-up",True),
|
| 158 |
+
"life_expectancy":w("Life Expectancy","years","Health","heart",True),
|
| 159 |
+
}
|
| 160 |
+
for col,v in owid_cols.items(): v["key"] = col
|
| 161 |
+
owid_rows = []
|
| 162 |
+
for _, row in latest.iterrows():
|
| 163 |
+
c = norm(row.get("location",""))
|
| 164 |
+
if not c or c in ["World","International","High income","Low income","Upper middle income","Lower middle income","European Union"]:
|
| 165 |
+
continue
|
| 166 |
+
rec = {"country": c, "iso3": row.get("iso_code","")}
|
| 167 |
+
for col in owid_cols.keys():
|
| 168 |
+
v = row.get(col)
|
| 169 |
+
if pd.notna(v): rec[col] = float(v)
|
| 170 |
+
if len(rec)>2: owid_rows.append(rec)
|
| 171 |
+
write("OWID Health & COVID","github.com/owid/covid-19-data","COVID-19 outcomes, vaccination, HDI, demographics",list(owid_cols.values()),owid_rows,"dataset_owid.js")
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print(f" Failed: {e}")
|
| 174 |
+
|
| 175 |
+
# ===== CLIMATE =====
|
| 176 |
+
print("\n[5/5] Fetching Open-Meteo climate data...")
|
| 177 |
+
caps = {
|
| 178 |
+
"United States":(38.9072,-77.0369),"China":(39.9042,116.4074),"India":(28.6139,77.2090),
|
| 179 |
+
"Russia":(55.7558,37.6173),"Japan":(35.6762,139.6503),"Germany":(52.5200,13.4050),
|
| 180 |
+
"United Kingdom":(51.5074,-0.1278),"France":(48.8566,2.3522),"Brazil":(-15.7975,-47.8919),
|
| 181 |
+
"Italy":(41.9028,12.4964),"Canada":(45.4215,-75.6972),"Australia":(-35.2809,149.1300),
|
| 182 |
+
"South Korea":(37.5665,126.9780),"Spain":(40.4168,-3.7038),"Mexico":(19.4326,-99.1332),
|
| 183 |
+
"Indonesia":(-6.2088,106.8456),"Turkey":(39.9334,32.8597),"Saudi Arabia":(24.7136,46.6753),
|
| 184 |
+
"South Africa":(-25.7479,28.2293),"Egypt":(30.0444,31.2357),"Argentina":(-34.6037,-58.3816),
|
| 185 |
+
"Nigeria":(9.0765,7.3986),"Pakistan":(33.6844,73.0479),"Bangladesh":(23.8103,90.4125),
|
| 186 |
+
"Vietnam":(21.0278,105.8342),"Thailand":(13.7563,100.5018),"Poland":(52.2297,21.0122),
|
| 187 |
+
"Ukraine":(50.4501,30.5234),"Malaysia":(3.1390,101.6869),"Philippines":(14.5995,120.9842),
|
| 188 |
+
"Chile":(-33.4489,-70.6693),"Singapore":(1.3521,103.8198),"Sweden":(59.3293,18.0686),
|
| 189 |
+
"Norway":(59.9139,10.7522),"Netherlands":(52.3676,4.9041),"Belgium":(50.8503,4.3517),
|
| 190 |
+
"Switzerland":(46.9480,7.4474),"Austria":(48.2082,16.3738),"Israel":(31.7683,35.2137),
|
| 191 |
+
"UAE":(24.4539,54.3773),"Czech Republic":(50.0755,14.4378),"Portugal":(38.7223,-9.1393),
|
| 192 |
+
"Greece":(37.9838,23.7275),"Finland":(60.1699,24.9384),"Denmark":(55.6761,12.5683),
|
| 193 |
+
"Ireland":(53.3498,-6.2603),"New Zealand":(-41.2865,174.7762),"Colombia":(4.7110,-74.0721),
|
| 194 |
+
"Peru":(-12.0464,-77.0428),"Morocco":(34.0209,-6.8416),"Kenya":(-1.2921,36.8219),
|
| 195 |
+
"Ethiopia":(9.0054,38.7636),"Ghana":(5.6037,-0.1870),
|
| 196 |
+
}
|
| 197 |
+
om_vars = [
|
| 198 |
+
{"key":"temp_mean_annual","name":"Mean Annual Temperature","unit":"°C","category":"Climate","desc":"Average temperature","icon":"thermometer","higherIsBetter":None},
|
| 199 |
+
{"key":"temp_max_annual","name":"Max Annual Temperature","unit":"°C","category":"Climate","desc":"Maximum temperature","icon":"flame","higherIsBetter":None},
|
| 200 |
+
{"key":"temp_min_annual","name":"Min Annual Temperature","unit":"°C","category":"Climate","desc":"Minimum temperature","icon":"snowflake","higherIsBetter":None},
|
| 201 |
+
{"key":"precipitation_annual","name":"Annual Precipitation","unit":"mm","category":"Climate","desc":"Total annual rainfall","icon":"cloud-rain","higherIsBetter":None},
|
| 202 |
+
{"key":"rain_days","name":"Rain Days","unit":"days","category":"Climate","desc":"Days with precipitation","icon":"umbrella","higherIsBetter":None},
|
| 203 |
+
]
|
| 204 |
+
ed = datetime.datetime.now().strftime("%Y-%m-%d")
|
| 205 |
+
sd = (datetime.datetime.now()-datetime.timedelta(days=365)).strftime("%Y-%m-%d")
|
| 206 |
+
om_rows = []
|
| 207 |
+
for country,(lat,lon) in caps.items():
|
| 208 |
+
try:
|
| 209 |
+
url = f"https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date={sd}&end_date={ed}&daily=temperature_2m_mean,temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto"
|
| 210 |
+
r = requests.get(url, timeout=15)
|
| 211 |
+
if r.status_code!=200: continue
|
| 212 |
+
d = r.json().get("daily",{})
|
| 213 |
+
t,m,n,p = d.get("temperature_2m_mean",[]),d.get("temperature_2m_max",[]),d.get("temperature_2m_min",[]),d.get("precipitation_sum",[])
|
| 214 |
+
if t:
|
| 215 |
+
om_rows.append({"country":country,"temp_mean_annual":round(np.mean(t),1) if t else None,"temp_max_annual":round(np.max(m),1) if m else None,"temp_min_annual":round(np.min(n),1) if n else None,"precipitation_annual":round(np.sum(p),1) if p else None,"rain_days":sum(1 for x in p if x and x>0.1) if p else None})
|
| 216 |
+
time.sleep(0.05)
|
| 217 |
+
except: continue
|
| 218 |
+
write("Open-Meteo Climate","archive-api.open-meteo.com/v1","Historical climate: temperature ranges and precipitation",om_vars,om_rows,"dataset_climate.js")
|
| 219 |
+
|
| 220 |
+
# ===== INDEX =====
|
| 221 |
+
print("\n[Generating dataset index...]")
|
| 222 |
+
packs = []
|
| 223 |
+
for f in sorted(OUTPUT.glob("dataset_*.js")):
|
| 224 |
+
if f.name == "dataset_index.js": continue
|
| 225 |
+
content = f.read_text()
|
| 226 |
+
import re
|
| 227 |
+
m = re.search(r'const DATASET_PACK_(\\w+) =', content)
|
| 228 |
+
if m:
|
| 229 |
+
key = f"DATASET_PACK_{m.group(1)}"
|
| 230 |
+
nm = re.search(r'name: "([^"]+)"', content)
|
| 231 |
+
src = re.search(r'source: "([^"]+)"', content)
|
| 232 |
+
desc = re.search(r'description: "([^"]+)"', content)
|
| 233 |
+
vc = re.search(r'variableCount: (\\d+)', content)
|
| 234 |
+
cc = re.search(r'countryCount: (\\d+)', content)
|
| 235 |
+
if nm:
|
| 236 |
+
packs.append({"name":nm.group(1),"source":src.group(1) if src else "","description":desc.group(1) if desc else "","variableCount":int(vc.group(1)) if vc else 0,"countryCount":int(cc.group(1)) if cc else 0,"lastUpdated":time.strftime("%Y-%m-%d"),"requiresKey":False,"jsFile":f.name,"key":key})
|
| 237 |
+
|
| 238 |
+
idx = f"""// Insight Engine Dataset Index
|
| 239 |
+
const DATASET_INDEX = {json.dumps({"packs":packs}, ensure_ascii=False, indent=2)};
|
| 240 |
+
function listAvailableDatasets(){{ return DATASET_INDEX.packs; }}
|
| 241 |
+
function loadDataset(packKey){{ const p=DATASET_INDEX.packs.find(x=>x.key===packKey); return p?window[p.key]:null; }}
|
| 242 |
+
"""
|
| 243 |
+
(OUTPUT / "dataset_index.js").write_text(idx, encoding="utf-8")
|
| 244 |
+
print(f" ✓ dataset_index.js ({len(packs)} packs)")
|
| 245 |
+
|
| 246 |
+
print("\n" + "="*50 + "\nDONE\n" + "="*50)
|
| 247 |
+
for p in packs:
|
| 248 |
+
print(f" {p['name']:25s} | {p['variableCount']:3d} vars | {p['countryCount']:3d} countries")
|
| 249 |
+
print(f"\nNext steps:")
|
| 250 |
+
print(f" 1. cd ~/insight-engine-v3")
|
| 251 |
+
print(f" 2. cp ~/CodingProjects/Insights\\ Engine/dataset_*.js .")
|
| 252 |
+
print(f" 3. git add . && git commit -m 'multi-dataset support' && git push")
|
requirements-dev.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CI / test-only dependencies. NOT installed into the HF Docker image
|
| 2 |
+
# (the Dockerfile uses requirements.txt only), so the runtime image stays lean.
|
| 3 |
+
pytest>=8.0
|
| 4 |
+
httpx>=0.27 # required by fastapi.testclient.TestClient
|
scripts/collect_metrics.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Daily health probe. Boots the app in-process, records coverage + latency signals,
|
| 3 |
+
appends one entry to evolution/metrics.json (capped at the last 90 runs).
|
| 4 |
+
|
| 5 |
+
This file is CI-only and is NOT frozen, but nothing in the evolution loop edits it.
|
| 6 |
+
Its output is the fitness signal the mutation engine reads each night.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
from datetime import datetime, timezone
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 16 |
+
sys.path.insert(0, str(ROOT)) # so `import main` works when run from scripts/
|
| 17 |
+
|
| 18 |
+
from fastapi.testclient import TestClient # noqa: E402
|
| 19 |
+
|
| 20 |
+
import main # noqa: E402
|
| 21 |
+
|
| 22 |
+
METRICS = ROOT / "evolution" / "metrics.json"
|
| 23 |
+
CAP = 90
|
| 24 |
+
|
| 25 |
+
client = TestClient(main.app)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _latency_ms(method, path, **kw):
|
| 29 |
+
start = time.perf_counter()
|
| 30 |
+
method(path, **kw)
|
| 31 |
+
return round((time.perf_counter() - start) * 1000, 1)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def collect() -> dict:
|
| 35 |
+
indicators = client.get("/api/worldbank/indicators").json()
|
| 36 |
+
builtin = client.get("/api/datasets/builtin").json()
|
| 37 |
+
sources = client.get("/api/sources/list").json()
|
| 38 |
+
|
| 39 |
+
# A representative offline compute, for the latency trend.
|
| 40 |
+
inds = [{"key": f"v{j}", "name": f"V{j}", "category": "Economy"} for j in range(6)]
|
| 41 |
+
recs = [{"country": f"C{i}", **{f"v{j}": float(i * (j + 1)) for j in range(6)}} for i in range(50)]
|
| 42 |
+
up = client.post("/api/dataset/upload", json={"name": "metrics", "indicators": inds, "records": recs})
|
| 43 |
+
ds_id = up.json()["dataset_id"]
|
| 44 |
+
corr_ms = _latency_ms(client.post, "/api/analyze/correlations", json={"dataset_id": ds_id})
|
| 45 |
+
client.delete(f"/api/dataset/{ds_id}")
|
| 46 |
+
|
| 47 |
+
globe = main._build_globe_response({})
|
| 48 |
+
|
| 49 |
+
return {
|
| 50 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 51 |
+
"health_ms": _latency_ms(client.get, "/api/health"),
|
| 52 |
+
"indicator_count": indicators["count"],
|
| 53 |
+
"builtin_dataset_count": builtin["count"],
|
| 54 |
+
"wb_preset_count": sources["total_wb_presets"],
|
| 55 |
+
"globe_country_count": len(globe["countries"]),
|
| 56 |
+
"rss_feed_count": len(main.RSS_FEEDS),
|
| 57 |
+
"correlation_ms_50x6": corr_ms,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def main_():
|
| 62 |
+
entry = collect()
|
| 63 |
+
history = []
|
| 64 |
+
if METRICS.exists():
|
| 65 |
+
try:
|
| 66 |
+
history = json.loads(METRICS.read_text() or "[]")
|
| 67 |
+
except json.JSONDecodeError:
|
| 68 |
+
history = []
|
| 69 |
+
history.append(entry)
|
| 70 |
+
history = history[-CAP:]
|
| 71 |
+
METRICS.write_text(json.dumps(history, indent=2) + "\n")
|
| 72 |
+
print(json.dumps(entry, indent=2))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
main_()
|
tests/__init__.py
ADDED
|
File without changes
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared fixtures for the FROZEN fitness suite.
|
| 3 |
+
|
| 4 |
+
The app is imported and driven black-box via FastAPI's TestClient so the tests
|
| 5 |
+
survive internal refactors (a mutation may rename functions freely as long as the
|
| 6 |
+
HTTP contracts hold). We deliberately build the client WITHOUT the `with` context
|
| 7 |
+
manager: that skips the app's startup event (an 8s globe prewarm that would hit the
|
| 8 |
+
network), keeping the suite offline, fast, and deterministic.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
from fastapi.testclient import TestClient
|
| 16 |
+
|
| 17 |
+
# Repo root on sys.path so `import main` works when pytest runs from anywhere.
|
| 18 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 19 |
+
sys.path.insert(0, str(ROOT))
|
| 20 |
+
|
| 21 |
+
from main import app # noqa: E402
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture(scope="session")
|
| 25 |
+
def client():
|
| 26 |
+
# No context manager -> startup/shutdown events do not fire (no network prewarm).
|
| 27 |
+
return TestClient(app)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _upload(client, indicators, records, name="fixture"):
|
| 31 |
+
"""Upload a dataset and return its id. Caller is responsible for shape."""
|
| 32 |
+
resp = client.post(
|
| 33 |
+
"/api/dataset/upload",
|
| 34 |
+
json={"name": name, "indicators": indicators, "records": records},
|
| 35 |
+
)
|
| 36 |
+
assert resp.status_code == 200, resp.text
|
| 37 |
+
return resp.json()["dataset_id"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.fixture
|
| 41 |
+
def uploaded(client):
|
| 42 |
+
"""Factory that uploads a dataset and cleans it up afterwards."""
|
| 43 |
+
created = []
|
| 44 |
+
|
| 45 |
+
def _make(indicators, records, name="fixture"):
|
| 46 |
+
ds_id = _upload(client, indicators, records, name)
|
| 47 |
+
created.append(ds_id)
|
| 48 |
+
return ds_id
|
| 49 |
+
|
| 50 |
+
yield _make
|
| 51 |
+
|
| 52 |
+
for ds_id in created:
|
| 53 |
+
client.delete(f"/api/dataset/{ds_id}")
|
tests/test_app.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FROZEN FITNESS DEFINITION (backend).
|
| 3 |
+
|
| 4 |
+
The evolution engine must NEVER modify this file or anything under .github/
|
| 5 |
+
(enforced by the CI git-diff guard). These tests encode the user's intent: any
|
| 6 |
+
mutation of main.py / the frontend must keep them green or it is auto-reverted.
|
| 7 |
+
|
| 8 |
+
Priority order baked in here mirrors evolution/prompts.md:
|
| 9 |
+
Reliability > Analysis correctness > Performance > Coverage/features.
|
| 10 |
+
|
| 11 |
+
All tests are offline and deterministic — no live World Bank / RSS calls — so CI
|
| 12 |
+
noise can never trigger a spurious revert of a good mutation.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import main
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ===========================================================================
|
| 22 |
+
# 1. RELIABILITY — the app boots and its core HTTP contracts hold
|
| 23 |
+
# ===========================================================================
|
| 24 |
+
|
| 25 |
+
def test_health_contract(client):
|
| 26 |
+
r = client.get("/api/health")
|
| 27 |
+
assert r.status_code == 200
|
| 28 |
+
body = r.json()
|
| 29 |
+
assert body["status"] == "ok"
|
| 30 |
+
assert isinstance(body["datasets_loaded"], int)
|
| 31 |
+
assert isinstance(body["cache_entries"], int)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_spa_shell_served(client):
|
| 35 |
+
r = client.get("/")
|
| 36 |
+
assert r.status_code == 200
|
| 37 |
+
# The single-page shell the frontend mounts into.
|
| 38 |
+
assert 'id="globeContainer"' in r.text
|
| 39 |
+
assert 'id="categoryGrid"' in r.text
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_indicators_catalog(client):
|
| 43 |
+
r = client.get("/api/worldbank/indicators")
|
| 44 |
+
assert r.status_code == 200
|
| 45 |
+
body = r.json()
|
| 46 |
+
assert body["count"] == len(body["indicators"])
|
| 47 |
+
first = body["indicators"][0]
|
| 48 |
+
for key in ("id", "wb_code", "name", "source", "category"):
|
| 49 |
+
assert key in first
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_sources_list_contract(client):
|
| 53 |
+
r = client.get("/api/sources/list")
|
| 54 |
+
assert r.status_code == 200
|
| 55 |
+
body = r.json()
|
| 56 |
+
assert body["sources"]["builtin_datasets"]
|
| 57 |
+
assert body["sources"]["worldbank_presets"]
|
| 58 |
+
assert body["total_builtin"] >= 1
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_builtin_list_and_detail(client):
|
| 62 |
+
r = client.get("/api/datasets/builtin")
|
| 63 |
+
assert r.status_code == 200
|
| 64 |
+
body = r.json()
|
| 65 |
+
assert body["count"] == len(body["datasets"])
|
| 66 |
+
for ds in body["datasets"]:
|
| 67 |
+
for key in ("id", "name", "record_count", "variable_count"):
|
| 68 |
+
assert key in ds
|
| 69 |
+
|
| 70 |
+
detail = client.get("/api/datasets/builtin/happiness_2023")
|
| 71 |
+
assert detail.status_code == 200
|
| 72 |
+
dbody = detail.json()
|
| 73 |
+
assert dbody["record_count"] > 0
|
| 74 |
+
assert isinstance(dbody["data"], list)
|
| 75 |
+
assert "country" in dbody["data"][0] and "happiness_score" in dbody["data"][0]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_builtin_unknown_returns_404(client):
|
| 79 |
+
assert client.get("/api/datasets/builtin/does_not_exist").status_code == 404
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_dataset_crud_roundtrip(client):
|
| 83 |
+
indicators = [{"key": "a", "name": "A", "category": "Economy"}]
|
| 84 |
+
records = [{"country": "X", "a": 1.0}, {"country": "Y", "a": 2.0}]
|
| 85 |
+
up = client.post(
|
| 86 |
+
"/api/dataset/upload",
|
| 87 |
+
json={"name": "crud", "indicators": indicators, "records": records},
|
| 88 |
+
)
|
| 89 |
+
assert up.status_code == 200
|
| 90 |
+
ds_id = up.json()["dataset_id"]
|
| 91 |
+
assert up.json()["record_count"] == 2
|
| 92 |
+
assert up.json()["indicators_count"] == 1
|
| 93 |
+
|
| 94 |
+
listed = client.get("/api/dataset/list").json()["datasets"]
|
| 95 |
+
assert any(d["id"] == ds_id for d in listed)
|
| 96 |
+
|
| 97 |
+
got = client.get(f"/api/dataset/{ds_id}")
|
| 98 |
+
assert got.status_code == 200 and got.json()["record_count"] == 2
|
| 99 |
+
|
| 100 |
+
assert client.get("/api/dataset/nope-nope").status_code == 404
|
| 101 |
+
|
| 102 |
+
deleted = client.delete(f"/api/dataset/{ds_id}")
|
| 103 |
+
assert deleted.status_code == 200 and deleted.json()["deleted"] == ds_id
|
| 104 |
+
assert client.get(f"/api/dataset/{ds_id}").status_code == 404
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_globe_response_builder_shape():
|
| 108 |
+
"""Synthesized globe payload (offline path) must keep its full contract."""
|
| 109 |
+
resp = main._build_globe_response({})
|
| 110 |
+
for key in (
|
| 111 |
+
"countries", "total_articles", "avg_sentiment", "most_active",
|
| 112 |
+
"live_count", "total_count", "source", "updated_at",
|
| 113 |
+
):
|
| 114 |
+
assert key in resp
|
| 115 |
+
assert isinstance(resp["countries"], list)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_globe_route_registered(client):
|
| 119 |
+
paths = {getattr(r, "path", None) for r in client.app.routes}
|
| 120 |
+
assert "/api/news/globe" in paths
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ===========================================================================
|
| 124 |
+
# 2. ANALYSIS CORRECTNESS — known-answer fixtures
|
| 125 |
+
# ===========================================================================
|
| 126 |
+
|
| 127 |
+
def test_perfect_positive_correlation(uploaded, client):
|
| 128 |
+
inds = [
|
| 129 |
+
{"key": "x", "name": "X", "category": "Economy"},
|
| 130 |
+
{"key": "y", "name": "Y", "category": "Economy"},
|
| 131 |
+
]
|
| 132 |
+
recs = [{"country": f"C{i}", "x": float(i), "y": float(2 * i)} for i in range(1, 11)]
|
| 133 |
+
ds_id = uploaded(inds, recs, "pos")
|
| 134 |
+
r = client.post("/api/analyze/correlations", json={"dataset_id": ds_id})
|
| 135 |
+
assert r.status_code == 200
|
| 136 |
+
corr = r.json()["correlations"]
|
| 137 |
+
assert corr, "expected at least one correlation"
|
| 138 |
+
top = corr[0]
|
| 139 |
+
assert abs(top["r"] - 1.0) < 0.001
|
| 140 |
+
assert top["n"] == 10
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_perfect_negative_correlation(uploaded, client):
|
| 144 |
+
inds = [
|
| 145 |
+
{"key": "x", "name": "X", "category": "Economy"},
|
| 146 |
+
{"key": "y", "name": "Y", "category": "Economy"},
|
| 147 |
+
]
|
| 148 |
+
recs = [{"country": f"C{i}", "x": float(i), "y": float(-i)} for i in range(1, 11)]
|
| 149 |
+
ds_id = uploaded(inds, recs, "neg")
|
| 150 |
+
r = client.post("/api/analyze/correlations", json={"dataset_id": ds_id})
|
| 151 |
+
top = r.json()["correlations"][0]
|
| 152 |
+
assert abs(top["r"] + 1.0) < 0.001
|
| 153 |
+
assert abs(top["abs_r"] - 1.0) < 0.001
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_correlations_sorted_by_abs_r(uploaded, client):
|
| 157 |
+
inds = [
|
| 158 |
+
{"key": "a", "name": "A", "category": "Economy"},
|
| 159 |
+
{"key": "b", "name": "B", "category": "Economy"},
|
| 160 |
+
{"key": "c", "name": "C", "category": "Economy"},
|
| 161 |
+
]
|
| 162 |
+
recs = [
|
| 163 |
+
{"country": f"C{i}", "a": float(i), "b": float(2 * i), "c": float((i * 7) % 5)}
|
| 164 |
+
for i in range(1, 13)
|
| 165 |
+
]
|
| 166 |
+
ds_id = uploaded(inds, recs, "sorted")
|
| 167 |
+
corr = client.post("/api/analyze/correlations", json={"dataset_id": ds_id}).json()["correlations"]
|
| 168 |
+
abs_rs = [c["abs_r"] for c in corr]
|
| 169 |
+
assert abs_rs == sorted(abs_rs, reverse=True)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_correlations_bad_dataset_id(client):
|
| 173 |
+
assert client.post("/api/analyze/correlations", json={"dataset_id": "nope"}).status_code == 400
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_outlier_is_flagged(uploaded, client):
|
| 177 |
+
inds = [{"key": "val", "name": "Value", "category": "Economy"}]
|
| 178 |
+
normal = [10, 10, 11, 9, 10, 12, 10, 9, 11, 10, 10]
|
| 179 |
+
recs = [{"country": f"N{i}", "val": float(v)} for i, v in enumerate(normal)]
|
| 180 |
+
recs.append({"country": "Spikeland", "val": 500.0})
|
| 181 |
+
ds_id = uploaded(inds, recs, "outliers")
|
| 182 |
+
body = client.post("/api/analyze/outliers", json={"dataset_id": ds_id, "threshold": 2.0}).json()
|
| 183 |
+
assert body["total_deviations"] >= 1
|
| 184 |
+
top = body["outliers"][0]
|
| 185 |
+
assert top["country"] == "Spikeland"
|
| 186 |
+
assert top["top_deviation"]["direction"] == "high"
|
| 187 |
+
assert top["top_deviation"]["z_score"] > 2.0
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_no_false_positive_outliers(uploaded, client):
|
| 191 |
+
inds = [{"key": "val", "name": "Value", "category": "Economy"}]
|
| 192 |
+
recs = [{"country": f"N{i}", "val": v} for i, v in enumerate([10.0, 10.0, 10.1, 9.9, 10.0, 10.0])]
|
| 193 |
+
ds_id = uploaded(inds, recs, "flat")
|
| 194 |
+
body = client.post("/api/analyze/outliers", json={"dataset_id": ds_id, "threshold": 2.0}).json()
|
| 195 |
+
assert body["total_deviations"] == 0
|
| 196 |
+
assert body["country_count"] == 0
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# ===========================================================================
|
| 200 |
+
# 3. PERFORMANCE — noise-robust (generous ceiling + cache primitive), no tight timing
|
| 201 |
+
# ===========================================================================
|
| 202 |
+
|
| 203 |
+
def test_correlation_latency_ceiling(uploaded, client):
|
| 204 |
+
"""Catches only catastrophic algorithmic regressions, not a slow runner."""
|
| 205 |
+
keys = [f"v{j}" for j in range(6)]
|
| 206 |
+
inds = [{"key": k, "name": k.upper(), "category": "Economy"} for k in keys]
|
| 207 |
+
recs = [{"country": f"C{i}", **{k: float(i * (j + 1)) for j, k in enumerate(keys)}} for i in range(50)]
|
| 208 |
+
ds_id = uploaded(inds, recs, "perf")
|
| 209 |
+
start = time.perf_counter()
|
| 210 |
+
r = client.post("/api/analyze/correlations", json={"dataset_id": ds_id})
|
| 211 |
+
assert r.status_code == 200
|
| 212 |
+
assert time.perf_counter() - start < 5.0
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_cache_primitive_roundtrip():
|
| 216 |
+
"""The in-memory cache (perf infra) must set/get and miss correctly."""
|
| 217 |
+
main._cache_set("frozen_test_key", {"hello": "world"}, ttl=60)
|
| 218 |
+
assert main._cache_get("frozen_test_key") == {"hello": "world"}
|
| 219 |
+
assert main._cache_get("frozen_test_missing_key_xyz") in (None, False)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ===========================================================================
|
| 223 |
+
# 4. COVERAGE RATCHET — locks current breadth; `>=` lets it grow, never shrink
|
| 224 |
+
# ===========================================================================
|
| 225 |
+
|
| 226 |
+
def test_indicator_coverage_floor(client):
|
| 227 |
+
body = client.get("/api/worldbank/indicators").json()
|
| 228 |
+
assert body["count"] >= 269
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_builtin_dataset_floor(client):
|
| 232 |
+
assert client.get("/api/datasets/builtin").json()["count"] >= 12
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_worldbank_preset_count(client):
|
| 236 |
+
assert client.get("/api/sources/list").json()["total_wb_presets"] == 9
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def test_globe_country_floor():
|
| 240 |
+
assert len(main.GLOBE_COUNTRIES) >= 40
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_rss_feed_floor():
|
| 244 |
+
assert len(main.RSS_FEEDS) >= 10
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# ===========================================================================
|
| 248 |
+
# 5. FROZEN-GUARD — fast pre-check against fitness gaming (CI git-diff is the wall)
|
| 249 |
+
# ===========================================================================
|
| 250 |
+
|
| 251 |
+
def test_main_does_not_import_tests():
|
| 252 |
+
src = inspect.getsource(main)
|
| 253 |
+
assert "from tests" not in src and "import tests" not in src
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def test_main_has_no_fitness_gaming_calls():
|
| 257 |
+
src = inspect.getsource(main)
|
| 258 |
+
for bad in ["pytest.skip", "sys.exit(0)", "os.remove(", "shutil.rmtree"]:
|
| 259 |
+
assert bad not in src, f"main.py must not contain {bad!r}"
|
tests/test_frontend.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FROZEN FITNESS DEFINITION (frontend).
|
| 3 |
+
|
| 4 |
+
Backend pytest cannot catch a white-screened UI, and mutations auto-deploy to the
|
| 5 |
+
LIVE public Space. This gate is the safety net:
|
| 6 |
+
|
| 7 |
+
1. Every live JS file must pass `node --check` (a syntax error would blank the app).
|
| 8 |
+
2. index.html must keep its structural anchors — required <script> includes, the
|
| 9 |
+
element IDs the app mounts into, all 8 tabs, and the init() bootstrap.
|
| 10 |
+
|
| 11 |
+
The live frontend load order (index.html) is dataset_embed.js -> app_v30.js ->
|
| 12 |
+
inline init() -> globe_patch.js -> mapping_canvas.js. NOTE: static/app.js and
|
| 13 |
+
static/app_v35.js are dead (referenced nowhere) and are intentionally NOT gated here.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pytest
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
+
STATIC = ROOT / "static"
|
| 24 |
+
INDEX = STATIC / "index.html"
|
| 25 |
+
|
| 26 |
+
LIVE_JS = ["dataset_embed.js", "app_v30.js", "globe_patch.js", "mapping_canvas.js"]
|
| 27 |
+
|
| 28 |
+
REQUIRED_SCRIPT_SRCS = [
|
| 29 |
+
"/static/dataset_embed.js",
|
| 30 |
+
"/static/app_v30.js",
|
| 31 |
+
"/static/globe_patch.js",
|
| 32 |
+
"/static/mapping_canvas.js",
|
| 33 |
+
"cdn.tailwindcss.com",
|
| 34 |
+
"chart.js",
|
| 35 |
+
"three.min.js",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
REQUIRED_IDS = [
|
| 39 |
+
"categoryGrid", "variableList", "datasetTbody", "globeContainer",
|
| 40 |
+
"correlationBars", "scatterChart", "distributionChart", "emptyState", "resultsArea",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
REQUIRED_TABS = [
|
| 44 |
+
"explorer", "simulator", "discover", "compare",
|
| 45 |
+
"decisions", "benchmark", "outliers", "mapping",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
_NODE = shutil.which("node")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.mark.skipif(_NODE is None, reason="node not installed (CI installs it via setup-node)")
|
| 52 |
+
@pytest.mark.parametrize("js_file", LIVE_JS)
|
| 53 |
+
def test_live_js_passes_node_check(js_file):
|
| 54 |
+
path = STATIC / js_file
|
| 55 |
+
assert path.exists(), f"{js_file} missing"
|
| 56 |
+
result = subprocess.run(
|
| 57 |
+
[_NODE, "--check", str(path)],
|
| 58 |
+
capture_output=True, text=True,
|
| 59 |
+
)
|
| 60 |
+
assert result.returncode == 0, f"{js_file} failed node --check:\n{result.stderr}"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_index_has_required_script_includes():
|
| 64 |
+
html = INDEX.read_text()
|
| 65 |
+
for src in REQUIRED_SCRIPT_SRCS:
|
| 66 |
+
assert src in html, f"index.html missing required script reference: {src}"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_index_has_required_element_ids():
|
| 70 |
+
html = INDEX.read_text()
|
| 71 |
+
for el_id in REQUIRED_IDS:
|
| 72 |
+
assert f'id="{el_id}"' in html, f"index.html missing element id: {el_id}"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_index_has_all_tabs():
|
| 76 |
+
html = INDEX.read_text()
|
| 77 |
+
for tab in REQUIRED_TABS:
|
| 78 |
+
assert f'data-tab="{tab}"' in html, f"index.html missing tab: {tab}"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_index_bootstraps_init():
|
| 82 |
+
html = INDEX.read_text()
|
| 83 |
+
assert "init()" in html
|