Spaces:
Sleeping
Engine: SEARCH/REPLACE mutations + graceful no-op; wire World Digest sibling bridge
Browse filesEvolution engine:
- Replace fragile line-numbered diffs with exact-text SEARCH/REPLACE edits
(models hallucinate hunk line numbers on a 2k-line file). A block matches
verbatim or the cycle is a clean SKIP. Only the target file is ever written.
- evolve.yml uses an evolution/.mutation_applied marker so an unusable-edit cycle
is a green no-op (logs + pushes the skip) instead of a failed run; only an
applied + test-passing mutation commits and deploys to the live Space.
Sibling integration (co-developed):
- main.py: /api/news/world-digest bridge (never-500 fallback, schema
world-digest/news-exchange@1) reading contract/news_exchange.md.
- static/globe_patch.js: globe "Digest view" calls the bridge.
- tests/: 3 frozen tests pin the bridge route, fallback shape, and globe wiring.
- evolution/prompts.md: priority #5 (sibling integration) + contract/ as a
read-only shared interface.
- scripts/sibling_dashboard.py + health.yml co-evolution dashboard step.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- .github/workflows/evolve.yml +34 -14
- .github/workflows/health.yml +4 -0
- .gitignore +3 -0
- contract/country_aliases.json +42 -0
- contract/news_exchange.md +49 -0
- evolution/evolve.py +91 -106
- evolution/prompts.md +5 -0
- main.py +38 -0
- scripts/sibling_dashboard.py +103 -0
- static/globe_patch.js +111 -0
- tests/test_app.py +26 -0
- tests/test_frontend.py +7 -0
|
@@ -5,9 +5,8 @@ on:
|
|
| 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:
|
|
@@ -41,12 +40,24 @@ jobs:
|
|
| 41 |
node --check "static/$f"
|
| 42 |
done
|
| 43 |
|
| 44 |
-
- name: Propose mutation (one
|
| 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."
|
|
@@ -56,6 +67,7 @@ jobs:
|
|
| 56 |
|
| 57 |
- name: Validate mutation
|
| 58 |
id: validate
|
|
|
|
| 59 |
continue-on-error: true
|
| 60 |
run: |
|
| 61 |
pytest tests/ -q
|
|
@@ -63,25 +75,33 @@ jobs:
|
|
| 63 |
node --check "static/$f"
|
| 64 |
done
|
| 65 |
|
| 66 |
-
- name:
|
|
|
|
|
|
|
| 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 "$
|
| 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 "$
|
| 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
|
|
|
|
| 5 |
- cron: "0 3 * * *" # 03:00 UTC nightly
|
| 6 |
workflow_dispatch: # manual trigger button
|
| 7 |
|
|
|
|
| 8 |
permissions:
|
| 9 |
+
contents: write # push merged mutations / attempt logs
|
| 10 |
|
| 11 |
jobs:
|
| 12 |
evolve:
|
|
|
|
| 40 |
node --check "static/$f"
|
| 41 |
done
|
| 42 |
|
| 43 |
+
- name: Propose mutation (one SEARCH/REPLACE edit)
|
| 44 |
env:
|
| 45 |
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 46 |
run: python evolution/evolve.py
|
| 47 |
|
| 48 |
+
- name: Detect mutation
|
| 49 |
+
id: detect
|
| 50 |
+
run: |
|
| 51 |
+
if [ -f evolution/.mutation_applied ]; then
|
| 52 |
+
echo "applied=true" >> "$GITHUB_OUTPUT"
|
| 53 |
+
echo "Mutation applied to $(cat evolution/.mutation_applied)"
|
| 54 |
+
else
|
| 55 |
+
echo "applied=false" >> "$GITHUB_OUTPUT"
|
| 56 |
+
echo "No usable mutation this cycle — clean no-op."
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
- name: Guard - frozen files untouched
|
| 60 |
+
if: steps.detect.outputs.applied == 'true'
|
| 61 |
run: |
|
| 62 |
if ! git diff --quiet -- tests/ .github/ requirements.txt requirements-dev.txt Dockerfile; then
|
| 63 |
echo "VIOLATION: mutation touched frozen files. Reverting."
|
|
|
|
| 67 |
|
| 68 |
- name: Validate mutation
|
| 69 |
id: validate
|
| 70 |
+
if: steps.detect.outputs.applied == 'true'
|
| 71 |
continue-on-error: true
|
| 72 |
run: |
|
| 73 |
pytest tests/ -q
|
|
|
|
| 75 |
node --check "static/$f"
|
| 76 |
done
|
| 77 |
|
| 78 |
+
- name: Finalize — merge / revert / no-op, then push (+deploy on accept)
|
| 79 |
+
env:
|
| 80 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 81 |
run: |
|
| 82 |
git config user.name "evolution-bot"
|
| 83 |
git config user.email "bot@users.noreply.github.com"
|
| 84 |
+
rm -f evolution/.mutation_applied
|
| 85 |
+
ts="$(date -u --iso-8601=seconds)"
|
| 86 |
+
|
| 87 |
+
if [ "${{ steps.detect.outputs.applied }}" != "true" ]; then
|
| 88 |
+
git add evolution/attempts.log
|
| 89 |
+
git commit -m "evolve: no-op $(date -u +%F)" || echo "nothing to commit"
|
| 90 |
+
git push origin HEAD:main || true
|
| 91 |
+
exit 0
|
| 92 |
+
fi
|
| 93 |
+
|
| 94 |
if [ "${{ steps.validate.outcome }}" = "success" ]; then
|
| 95 |
+
echo "$ts | MERGED | tests passed" >> evolution/attempts.log
|
| 96 |
git add main.py static/ evolution/attempts.log
|
| 97 |
git commit -m "evolve: mutation accepted $(date -u +%F)"
|
| 98 |
+
git push origin HEAD:main
|
| 99 |
+
echo "Deploying to live HuggingFace Space..."
|
| 100 |
+
git push "https://colesr:${HF_TOKEN}@huggingface.co/spaces/colesr/insight-engine-docker" HEAD:main
|
| 101 |
else
|
| 102 |
git checkout -- main.py static/
|
| 103 |
+
echo "$ts | REVERTED | tests failed" >> evolution/attempts.log
|
| 104 |
git add evolution/attempts.log
|
| 105 |
git commit -m "evolve: mutation reverted $(date -u +%F)"
|
| 106 |
+
git push origin HEAD:main
|
| 107 |
fi
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -31,3 +31,7 @@ jobs:
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 34 |
+
|
| 35 |
+
- name: Co-evolution dashboard
|
| 36 |
+
if: always()
|
| 37 |
+
run: python scripts/sibling_dashboard.py
|
|
@@ -13,3 +13,6 @@ index
|
|
| 13 |
|
| 14 |
# Playwright browsers (if the optional render smoke test is enabled locally)
|
| 15 |
node_modules/
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Playwright browsers (if the optional render smoke test is enabled locally)
|
| 15 |
node_modules/
|
| 16 |
+
|
| 17 |
+
# Evolution engine working marker (never committed)
|
| 18 |
+
evolution/.mutation_applied
|
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"United States": ["united states", "u.s.", "usa", "american", "americans", "washington d.c.", "biden", "trump"],
|
| 3 |
+
"China": ["china", "chinese", "beijing", "xi jinping"],
|
| 4 |
+
"India": ["india", "indian", "indians", "new delhi", "modi"],
|
| 5 |
+
"Russia": ["russia", "russian", "russians", "moscow", "kremlin", "putin"],
|
| 6 |
+
"United Kingdom": ["united kingdom", "u.k.", "britain", "british", "london", "downing street"],
|
| 7 |
+
"Germany": ["germany", "german", "germans", "berlin"],
|
| 8 |
+
"France": ["france", "french", "paris", "macron"],
|
| 9 |
+
"Brazil": ["brazil", "brazilian", "sao paulo", "rio de janeiro", "lula"],
|
| 10 |
+
"Japan": ["japan", "japanese", "tokyo"],
|
| 11 |
+
"Canada": ["canada", "canadian", "canadians", "ottawa", "toronto", "trudeau"],
|
| 12 |
+
"Australia": ["australia", "australian", "australians", "sydney", "canberra"],
|
| 13 |
+
"South Korea": ["south korea", "south korean", "seoul"],
|
| 14 |
+
"Mexico": ["mexico", "mexican", "mexicans", "mexico city"],
|
| 15 |
+
"Italy": ["italy", "italian", "italians", "rome", "meloni"],
|
| 16 |
+
"Spain": ["spain", "spanish", "madrid"],
|
| 17 |
+
"Indonesia": ["indonesia", "indonesian", "jakarta"],
|
| 18 |
+
"Saudi Arabia": ["saudi arabia", "saudis", "riyadh", "mohammed bin salman"],
|
| 19 |
+
"Turkey": ["turkey", "turkish", "ankara", "istanbul", "erdogan"],
|
| 20 |
+
"Nigeria": ["nigeria", "nigerian", "lagos", "abuja"],
|
| 21 |
+
"South Africa": ["south africa", "south african", "johannesburg", "cape town"],
|
| 22 |
+
"Argentina": ["argentina", "argentinian", "argentine", "buenos aires", "milei"],
|
| 23 |
+
"Egypt": ["egypt", "egyptian", "cairo", "sisi"],
|
| 24 |
+
"Thailand": ["thailand", "thai", "bangkok"],
|
| 25 |
+
"Vietnam": ["vietnam", "vietnamese", "hanoi"],
|
| 26 |
+
"Israel": ["israel", "israeli", "tel aviv", "jerusalem", "netanyahu"],
|
| 27 |
+
"Ukraine": ["ukraine", "ukrainian", "ukrainians", "kyiv", "kiev", "zelensky"],
|
| 28 |
+
"Iran": ["iran", "iranian", "iranians", "tehran"],
|
| 29 |
+
"Pakistan": ["pakistan", "pakistani", "islamabad", "karachi"],
|
| 30 |
+
"Philippines": ["philippines", "filipino", "manila", "marcos"],
|
| 31 |
+
"Ethiopia": ["ethiopia", "ethiopian", "addis ababa", "tigray"],
|
| 32 |
+
"Kenya": ["kenya", "kenyan", "nairobi"],
|
| 33 |
+
"Chile": ["chile", "chilean", "santiago", "boric"],
|
| 34 |
+
"Sweden": ["sweden", "swedish", "stockholm"],
|
| 35 |
+
"Norway": ["norway", "norwegian", "oslo"],
|
| 36 |
+
"Finland": ["finland", "finnish", "helsinki"],
|
| 37 |
+
"Singapore": ["singapore", "singaporean"],
|
| 38 |
+
"UAE": ["uae", "united arab emirates", "dubai", "abu dhabi"],
|
| 39 |
+
"Poland": ["poland", "polish", "warsaw"],
|
| 40 |
+
"Netherlands": ["netherlands", "dutch", "amsterdam", "the hague"],
|
| 41 |
+
"Switzerland": ["switzerland", "swiss", "zurich", "geneva", "bern"]
|
| 42 |
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# News Exchange Contract — `world-digest/news-exchange@1`
|
| 2 |
+
|
| 3 |
+
The stable interface between two self-evolving siblings:
|
| 4 |
+
|
| 5 |
+
- **World Digest** — batch RSS digest pipeline (GitHub Actions, no server). *Publishes* Artifact B; *consumes* Artifact A.
|
| 6 |
+
- **InsightsEngine** — live FastAPI app on a Hugging Face Space. *Publishes* Artifact A; *consumes* Artifact B.
|
| 7 |
+
|
| 8 |
+
Both apps rewrite their own source nightly. This contract is **vendored identically into both repos** (`contract/`) and **pinned by a frozen test on each side**, so it lives outside every evolvable file and no mutation loop can drift it. The schema id (`world-digest/news-exchange@1`) is the version handle — bump it only by editing the frozen tests in both repos.
|
| 9 |
+
|
| 10 |
+
The cardinal rule on both sides: **the coupling is additive and best-effort.** Each app must fully function with the sibling offline. Enrichment when the sibling is reachable; silent degradation when it is not.
|
| 11 |
+
|
| 12 |
+
## `contract/country_aliases.json`
|
| 13 |
+
|
| 14 |
+
Canonical `{ "Country Name": ["lowercased", "alias", ...] }` map (≥40 countries), the shared vocabulary for tagging articles to countries. Matching rule (mirrors InsightsEngine `_match_country_for`): build a lowercased haystack from an article's title (+ summary); a multi-word or punctuated alias matches as a substring, a single-word alias matches on `\b…\b` word boundaries.
|
| 15 |
+
|
| 16 |
+
## Artifact A — globe sentiment (InsightsEngine → World Digest)
|
| 17 |
+
|
| 18 |
+
Already produced by `GET /api/news/globe`. World Digest reads it best-effort (env `SIBLING_GLOBE_URL`, default the live Space) to borrow sentiment without computing its own. Consumed fields:
|
| 19 |
+
|
| 20 |
+
```
|
| 21 |
+
countries: [ { name: str, sentiment: float (-80..80), articles: int, ... }, ... ]
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
World Digest normalizes `sentiment / 80` → `-1..1` per country.
|
| 25 |
+
|
| 26 |
+
## Artifact B — digest narrative (World Digest → InsightsEngine)
|
| 27 |
+
|
| 28 |
+
World Digest writes `public/digest.json` and commits it; InsightsEngine reads it best-effort (env `DIGEST_JSON_URL`, default `https://raw.githubusercontent.com/colesr/World.alive/main/public/digest.json`).
|
| 29 |
+
|
| 30 |
+
```json
|
| 31 |
+
{
|
| 32 |
+
"schema": "world-digest/news-exchange@1",
|
| 33 |
+
"generated_at": "<ISO-8601 UTC>",
|
| 34 |
+
"digest_words": 0,
|
| 35 |
+
"clusters": [
|
| 36 |
+
{
|
| 37 |
+
"headline": "string — top story title in the cluster",
|
| 38 |
+
"countries": ["United States"],
|
| 39 |
+
"regions": ["Americas"],
|
| 40 |
+
"outlets": 3,
|
| 41 |
+
"summary": "string — short gloss of the cluster",
|
| 42 |
+
"links": ["https://..."]
|
| 43 |
+
}
|
| 44 |
+
],
|
| 45 |
+
"narrative": "string — the full LLM digest text"
|
| 46 |
+
}
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
`countries[]` uses the canonical names from `country_aliases.json`. On any fetch failure InsightsEngine returns the same shape with `clusters: []`, `narrative: ""`, and `stale: true`.
|
|
@@ -1,21 +1,28 @@
|
|
| 1 |
"""
|
| 2 |
-
Evolution engine: proposes ONE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
Cycle:
|
| 5 |
-
1. Pick ONE target file (rotation, weighted toward main.py
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 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 |
-
-
|
| 13 |
-
-
|
| 14 |
- Logs every attempt (PROPOSED / SKIPPED / REJECTED) to evolution/attempts.log.
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
"""
|
| 20 |
|
| 21 |
import json
|
|
@@ -23,7 +30,6 @@ 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 |
|
|
@@ -33,8 +39,9 @@ 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 #
|
| 38 |
|
| 39 |
LLM_ENDPOINT = "https://router.huggingface.co/v1/chat/completions"
|
| 40 |
LLM_MODEL = "Qwen/Qwen3-Coder-480B-A35B-Instruct:cheapest"
|
|
@@ -43,25 +50,23 @@ LLM_MODEL = "Qwen/Qwen3-Coder-480B-A35B-Instruct:cheapest"
|
|
| 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", #
|
| 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)
|
| 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]
|
|
@@ -90,7 +95,7 @@ def log_attempt(status: str, note: str = ""):
|
|
| 90 |
f.write(f"{datetime.now(timezone.utc).isoformat()} | {status} | {note}\n")
|
| 91 |
|
| 92 |
|
| 93 |
-
def
|
| 94 |
hf_token = os.environ.get("HF_TOKEN")
|
| 95 |
if not hf_token:
|
| 96 |
print("[error] HF_TOKEN not set; cannot evolve.")
|
|
@@ -102,7 +107,7 @@ def propose_diff(target: str) -> str | None:
|
|
| 102 |
|
| 103 |
prompt = f"""{goals}
|
| 104 |
|
| 105 |
-
REPO FILES
|
| 106 |
{tree}
|
| 107 |
|
| 108 |
TARGET FILE THIS RUN: {target}
|
|
@@ -116,12 +121,21 @@ RECENT METRICS (last 7 health runs):
|
|
| 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
|
| 120 |
-
constraints above.
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
"""
|
| 126 |
|
| 127 |
resp = requests.post(
|
|
@@ -135,91 +149,62 @@ constraints above. Output ONLY a single unified diff, git-apply compatible, insi
|
|
| 135 |
timeout=300,
|
| 136 |
)
|
| 137 |
resp.raise_for_status()
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 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 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
if
|
| 200 |
-
log_attempt("
|
| 201 |
-
sys.exit(
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
|
| 225 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
+
Evolution engine: proposes ONE mutation per run to a single target file.
|
| 3 |
+
|
| 4 |
+
Mutations are expressed as SEARCH/REPLACE blocks (exact-text edits, Aider-style)
|
| 5 |
+
rather than line-numbered unified diffs — code models reliably hallucinate diff
|
| 6 |
+
line numbers on a 2k-line file, but a verbatim SEARCH block either matches or it
|
| 7 |
+
doesn't. Each block's SEARCH text must be an exact copy of consecutive lines in
|
| 8 |
+
the target; the engine replaces the first occurrence. If any block fails to match,
|
| 9 |
+
the whole mutation is a clean SKIP (no file change, exit 0) — the nightly run is a
|
| 10 |
+
no-op that cycle, not a failure.
|
| 11 |
|
| 12 |
Cycle:
|
| 13 |
+
1. Pick ONE target file (rotation, weighted toward main.py).
|
| 14 |
+
2. Ask a code LLM for SEARCH/REPLACE edits to that file only.
|
| 15 |
+
3. Apply them in-process; on success drop evolution/.mutation_applied so CI
|
| 16 |
+
knows to validate + (on pass) deploy. CI decides merge-or-revert.
|
|
|
|
| 17 |
|
| 18 |
Hard rules (defense in depth; the CI `git diff` guard is the real wall):
|
| 19 |
+
- Only the single target file is ever written.
|
| 20 |
+
- Never produce forbidden tokens (import tests, pytest.skip, sys.exit(0), ...).
|
| 21 |
- Logs every attempt (PROPOSED / SKIPPED / REJECTED) to evolution/attempts.log.
|
| 22 |
|
| 23 |
+
Reuses the working WorldDigest setup: the Hugging Face Inference Providers
|
| 24 |
+
OpenAI-compatible router, authed with an `hf_...` HF_TOKEN. (Non-Anthropic by
|
| 25 |
+
design — mirrors the sibling system; no Claude SDK is involved here.)
|
| 26 |
"""
|
| 27 |
|
| 28 |
import json
|
|
|
|
| 30 |
import re
|
| 31 |
import subprocess
|
| 32 |
import sys
|
|
|
|
| 33 |
from datetime import datetime, timezone
|
| 34 |
from pathlib import Path
|
| 35 |
|
|
|
|
| 39 |
METRICS = ROOT / "evolution" / "metrics.json"
|
| 40 |
ATTEMPTS = ROOT / "evolution" / "attempts.log"
|
| 41 |
PROMPTS = ROOT / "evolution" / "prompts.md"
|
| 42 |
+
MARKER = ROOT / "evolution" / ".mutation_applied"
|
| 43 |
|
| 44 |
+
MAX_TOKENS = 6000 # edits are small; full file is INPUT context only
|
| 45 |
|
| 46 |
LLM_ENDPOINT = "https://router.huggingface.co/v1/chat/completions"
|
| 47 |
LLM_MODEL = "Qwen/Qwen3-Coder-480B-A35B-Instruct:cheapest"
|
|
|
|
| 50 |
# because Reliability + Analysis-correctness (priorities 1-2) live there. The dead
|
| 51 |
# files static/app.js and static/app_v35.js are intentionally absent.
|
| 52 |
EVOLVABLE = [
|
| 53 |
+
"main.py", "main.py", "main.py", # ~50% of runs target the backend
|
| 54 |
"static/app_v30.js",
|
| 55 |
"static/globe_patch.js",
|
| 56 |
"static/mapping_canvas.js",
|
| 57 |
"static/index.html",
|
| 58 |
]
|
| 59 |
|
|
|
|
|
|
|
| 60 |
FORBIDDEN_TOKENS = ["import tests", "from tests", "pytest.skip", "sys.exit(0)", "os.remove(", "shutil.rmtree"]
|
| 61 |
|
| 62 |
+
EDIT_RE = re.compile(r"<{5,}\s*SEARCH\s*\n(.*?)\n={5,}\s*\n(.*?)\n>{5,}\s*REPLACE", re.DOTALL)
|
| 63 |
+
|
| 64 |
|
| 65 |
+
def _git(*args):
|
| 66 |
return subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True, text=True)
|
| 67 |
|
| 68 |
|
| 69 |
def pick_target() -> str:
|
|
|
|
|
|
|
| 70 |
count = _git("rev-list", "--count", "HEAD").stdout.strip()
|
| 71 |
idx = (int(count) if count.isdigit() else 0) % len(EVOLVABLE)
|
| 72 |
return EVOLVABLE[idx]
|
|
|
|
| 95 |
f.write(f"{datetime.now(timezone.utc).isoformat()} | {status} | {note}\n")
|
| 96 |
|
| 97 |
|
| 98 |
+
def propose(target: str) -> str | None:
|
| 99 |
hf_token = os.environ.get("HF_TOKEN")
|
| 100 |
if not hf_token:
|
| 101 |
print("[error] HF_TOKEN not set; cannot evolve.")
|
|
|
|
| 107 |
|
| 108 |
prompt = f"""{goals}
|
| 109 |
|
| 110 |
+
REPO FILES (you may ONLY edit the target file below):
|
| 111 |
{tree}
|
| 112 |
|
| 113 |
TARGET FILE THIS RUN: {target}
|
|
|
|
| 121 |
RECENT ATTEMPTS (do NOT repeat reverted/rejected/skipped approaches):
|
| 122 |
{recent_attempts()}
|
| 123 |
|
| 124 |
+
Propose exactly ONE improvement to `{target}`, consistent with the priority order
|
| 125 |
+
and constraints above. Express it as one or more SEARCH/REPLACE edits in EXACTLY
|
| 126 |
+
this format (you may output several blocks):
|
| 127 |
+
|
| 128 |
+
<<<<<<< SEARCH
|
| 129 |
+
<verbatim consecutive lines that currently exist in {target}>
|
| 130 |
+
=======
|
| 131 |
+
<the replacement lines>
|
| 132 |
+
>>>>>>> REPLACE
|
| 133 |
+
|
| 134 |
+
Rules:
|
| 135 |
+
- The SEARCH text MUST be copied EXACTLY (whitespace included) from the current
|
| 136 |
+
{target} above, long enough to be unique.
|
| 137 |
+
- Edit ONLY {target}. Keep all existing route paths and JSON keys (add, don't
|
| 138 |
+
rename/remove). Output the SEARCH/REPLACE blocks and nothing else.
|
| 139 |
"""
|
| 140 |
|
| 141 |
resp = requests.post(
|
|
|
|
| 149 |
timeout=300,
|
| 150 |
)
|
| 151 |
resp.raise_for_status()
|
| 152 |
+
return resp.json()["choices"][0]["message"]["content"]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def parse_edits(text: str):
|
| 156 |
+
return [(m.group(1), m.group(2)) for m in EDIT_RE.finditer(text)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
|
| 159 |
def main():
|
| 160 |
+
if MARKER.exists():
|
| 161 |
+
MARKER.unlink()
|
| 162 |
+
|
| 163 |
target = pick_target()
|
| 164 |
print(f"[evolve] target this run: {target}")
|
| 165 |
|
| 166 |
+
try:
|
| 167 |
+
text = propose(target)
|
| 168 |
+
except requests.HTTPError as e:
|
| 169 |
+
log_attempt("SKIPPED", f"{target}: LLM HTTP error {e.response.status_code}")
|
| 170 |
+
print(f"[skip] LLM error: {e}")
|
| 171 |
+
sys.exit(0)
|
| 172 |
+
if not text:
|
| 173 |
+
log_attempt("SKIPPED", f"{target}: no response")
|
| 174 |
+
sys.exit(0)
|
| 175 |
+
|
| 176 |
+
edits = parse_edits(text)
|
| 177 |
+
if not edits:
|
| 178 |
+
log_attempt("SKIPPED", f"{target}: no SEARCH/REPLACE blocks in response")
|
| 179 |
+
print("[skip] model returned no usable edit blocks")
|
| 180 |
+
sys.exit(0)
|
| 181 |
+
|
| 182 |
+
# Forbidden-token pre-check on replacement text.
|
| 183 |
+
for _, replace in edits:
|
| 184 |
+
for tok in FORBIDDEN_TOKENS:
|
| 185 |
+
if tok in replace:
|
| 186 |
+
log_attempt("REJECTED", f"{target}: forbidden token {tok!r}")
|
| 187 |
+
print(f"[reject] forbidden token {tok!r}")
|
| 188 |
+
sys.exit(0)
|
| 189 |
+
|
| 190 |
+
path = ROOT / target
|
| 191 |
+
src = path.read_text()
|
| 192 |
+
new = src
|
| 193 |
+
for search, replace in edits:
|
| 194 |
+
if search not in new:
|
| 195 |
+
log_attempt("SKIPPED", f"{target}: SEARCH block not found (drift)")
|
| 196 |
+
print("[skip] a SEARCH block did not match the current file")
|
| 197 |
+
sys.exit(0)
|
| 198 |
+
new = new.replace(search, replace, 1)
|
| 199 |
+
|
| 200 |
+
if new == src:
|
| 201 |
+
log_attempt("SKIPPED", f"{target}: edits were a no-op")
|
| 202 |
+
sys.exit(0)
|
| 203 |
+
|
| 204 |
+
path.write_text(new)
|
| 205 |
+
MARKER.write_text(target + "\n")
|
| 206 |
+
log_attempt("PROPOSED", f"{target}: {len(edits)} edit(s) applied; CI will validate")
|
| 207 |
+
print(f"Mutation applied to {target} ({len(edits)} edit(s)). CI will test and merge or revert.")
|
| 208 |
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
|
@@ -16,6 +16,9 @@ Improvements should target, in strict priority order:
|
|
| 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 |
|
|
@@ -33,6 +36,8 @@ Improvements should target, in strict priority order:
|
|
| 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
|
|
|
|
| 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 |
+
5. **Sibling integration** — the `/api/news/world-digest` bridge and the globe's
|
| 20 |
+
"Digest view" surface World Digest's published narrative (`world-digest/news-exchange@1`).
|
| 21 |
+
Keep both intact and best-effort; the bridge must never 500 when the sibling is down.
|
| 22 |
|
| 23 |
## Constraints (non-negotiable)
|
| 24 |
|
|
|
|
| 36 |
`os.remove`, or `shutil.rmtree`.
|
| 37 |
- The frontend's live load order is `dataset_embed.js → app_v30.js → init() → globe_patch.js
|
| 38 |
→ mapping_canvas.js`. `static/app.js` and `static/app_v35.js` are DEAD — do not edit them.
|
| 39 |
+
- Treat `contract/` as a read-only shared interface with the World Digest sibling. Never
|
| 40 |
+
rename/remove `/api/news/world-digest` or the globe "Digest view" wiring (`tests/` pins both).
|
| 41 |
- Keep all JS syntactically valid (`node --check` gates it) and `init()` callable.
|
| 42 |
|
| 43 |
## Signals to use
|
|
@@ -2371,6 +2371,44 @@ async def news_globe():
|
|
| 2371 |
# Last resort — synthesized.
|
| 2372 |
return _build_globe_response({})
|
| 2373 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2374 |
# ============================================================================
|
| 2375 |
# HEALTH CHECK
|
| 2376 |
# ============================================================================
|
|
|
|
| 2371 |
# Last resort — synthesized.
|
| 2372 |
return _build_globe_response({})
|
| 2373 |
|
| 2374 |
+
|
| 2375 |
+
# ----------------------------------------------------------------------------
|
| 2376 |
+
# Sibling bridge: World Digest's published digest (contract/news_exchange.md).
|
| 2377 |
+
# Best-effort + cached; surfaces the sibling's clustered LLM narrative for the
|
| 2378 |
+
# globe's "Digest view". Never 500s — a sibling outage degrades to an empty,
|
| 2379 |
+
# stale-flagged payload so the globe keeps rendering.
|
| 2380 |
+
# ----------------------------------------------------------------------------
|
| 2381 |
+
DIGEST_JSON_URL = os.environ.get(
|
| 2382 |
+
"DIGEST_JSON_URL",
|
| 2383 |
+
"https://raw.githubusercontent.com/colesr/World.alive/main/public/digest.json",
|
| 2384 |
+
)
|
| 2385 |
+
|
| 2386 |
+
@app.get("/api/news/world-digest")
|
| 2387 |
+
def news_world_digest():
|
| 2388 |
+
cache_key = "world_digest_v1"
|
| 2389 |
+
cached = _cache_get(cache_key)
|
| 2390 |
+
if cached:
|
| 2391 |
+
return cached
|
| 2392 |
+
fallback = {
|
| 2393 |
+
"schema": "world-digest/news-exchange@1",
|
| 2394 |
+
"clusters": [],
|
| 2395 |
+
"narrative": "",
|
| 2396 |
+
"stale": True,
|
| 2397 |
+
}
|
| 2398 |
+
try:
|
| 2399 |
+
resp = requests.get(DIGEST_JSON_URL, timeout=8)
|
| 2400 |
+
if not resp.ok:
|
| 2401 |
+
return fallback
|
| 2402 |
+
data = resp.json()
|
| 2403 |
+
if not isinstance(data, dict) or "clusters" not in data:
|
| 2404 |
+
return fallback
|
| 2405 |
+
data.setdefault("stale", False)
|
| 2406 |
+
_cache_set(cache_key, data, ttl=1800)
|
| 2407 |
+
return data
|
| 2408 |
+
except Exception as e:
|
| 2409 |
+
print(f"world-digest bridge failed: {e}")
|
| 2410 |
+
return fallback
|
| 2411 |
+
|
| 2412 |
# ============================================================================
|
| 2413 |
# HEALTH CHECK
|
| 2414 |
# ============================================================================
|
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Co-evolution dashboard. Renders a merged GitHub Step Summary showing the health of
|
| 3 |
+
BOTH self-evolving siblings — this InsightsEngine and World Digest — so the two
|
| 4 |
+
organisms can be watched in one place.
|
| 5 |
+
|
| 6 |
+
CI-only and NOT frozen; nothing in the evolution loop edits it. Best-effort: a
|
| 7 |
+
failed sibling fetch degrades to a notice and never fails the job. Writes markdown
|
| 8 |
+
to $GITHUB_STEP_SUMMARY when set (GitHub Actions), otherwise to stdout.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import requests
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 18 |
+
LOCAL_METRICS = ROOT / "evolution" / "metrics.json"
|
| 19 |
+
|
| 20 |
+
SIBLING_METRICS_URL = os.environ.get(
|
| 21 |
+
"SIBLING_METRICS_URL",
|
| 22 |
+
"https://raw.githubusercontent.com/colesr/World.alive/main/evolution/metrics.json",
|
| 23 |
+
)
|
| 24 |
+
SIBLING_DIGEST_URL = os.environ.get(
|
| 25 |
+
"DIGEST_JSON_URL",
|
| 26 |
+
"https://raw.githubusercontent.com/colesr/World.alive/main/public/digest.json",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def out(line: str = "") -> None:
|
| 31 |
+
target = os.environ.get("GITHUB_STEP_SUMMARY")
|
| 32 |
+
if target:
|
| 33 |
+
with open(target, "a", encoding="utf-8") as f:
|
| 34 |
+
f.write(line + "\n")
|
| 35 |
+
else:
|
| 36 |
+
print(line)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _load_local() -> list:
|
| 40 |
+
try:
|
| 41 |
+
return json.loads(LOCAL_METRICS.read_text() or "[]")
|
| 42 |
+
except Exception:
|
| 43 |
+
return []
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _fetch_json(url: str):
|
| 47 |
+
try:
|
| 48 |
+
resp = requests.get(url, timeout=10)
|
| 49 |
+
if resp.ok:
|
| 50 |
+
return resp.json()
|
| 51 |
+
except Exception as exc: # noqa: BLE001 - dashboard must never fail the job
|
| 52 |
+
print(f"[warn] fetch failed {url}: {exc}")
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main() -> None:
|
| 57 |
+
out("## 🌐 Co-evolution dashboard\n")
|
| 58 |
+
|
| 59 |
+
local = _load_local()
|
| 60 |
+
out("### InsightsEngine (this repo)\n")
|
| 61 |
+
if local:
|
| 62 |
+
m = local[-1]
|
| 63 |
+
out(
|
| 64 |
+
f"- {m.get('indicator_count', '—')} indicators · {m.get('builtin_dataset_count', '—')} datasets · "
|
| 65 |
+
f"{m.get('globe_country_count', '—')} globe countries · {m.get('rss_feed_count', '—')} feeds"
|
| 66 |
+
)
|
| 67 |
+
out(
|
| 68 |
+
f"- health {m.get('health_ms', '—')}ms · correlation {m.get('correlation_ms_50x6', '—')}ms · "
|
| 69 |
+
f"{len(local)} runs logged"
|
| 70 |
+
)
|
| 71 |
+
else:
|
| 72 |
+
out("_No metrics logged yet._")
|
| 73 |
+
|
| 74 |
+
out("\n### World Digest (sibling)\n")
|
| 75 |
+
sib = _fetch_json(SIBLING_METRICS_URL)
|
| 76 |
+
if isinstance(sib, list) and sib:
|
| 77 |
+
m = sib[-1]
|
| 78 |
+
out(
|
| 79 |
+
f"- {m.get('items_fetched', '—')} items · {m.get('clusters', '—')} clusters · "
|
| 80 |
+
f"{len(m.get('regions_covered', []))} regions · digest {m.get('digest_words', '—')} words"
|
| 81 |
+
)
|
| 82 |
+
out(
|
| 83 |
+
f"- does World Digest see *us*? reachable={m.get('sibling_reachable', '—')}, "
|
| 84 |
+
f"enriched={m.get('sentiment_enriched', '—')}"
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
out("_Sibling metrics unreachable — World Digest may not have run yet._")
|
| 88 |
+
|
| 89 |
+
out("\n### Exchange (`world-digest/news-exchange@1`)\n")
|
| 90 |
+
digest = _fetch_json(SIBLING_DIGEST_URL)
|
| 91 |
+
if isinstance(digest, dict):
|
| 92 |
+
n = len(digest.get("clusters", []))
|
| 93 |
+
out(
|
| 94 |
+
f"- World Digest is publishing: {n} clusters, {digest.get('digest_words', '—')} words, "
|
| 95 |
+
f"generated {digest.get('generated_at', '—')}"
|
| 96 |
+
)
|
| 97 |
+
out("- InsightsEngine surfaces this via `/api/news/world-digest` + the globe Digest view.")
|
| 98 |
+
else:
|
| 99 |
+
out("- World Digest's `public/digest.json` not reachable yet — the globe Digest view shows its quiet fallback.")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|
|
@@ -1215,3 +1215,114 @@
|
|
| 1215 |
|
| 1216 |
console.log('globe_standalone: loaded');
|
| 1217 |
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1215 |
|
| 1216 |
console.log('globe_standalone: loaded');
|
| 1217 |
})();
|
| 1218 |
+
|
| 1219 |
+
// === Digest View: sibling bridge to World Digest (contract/news_exchange.md) ===
|
| 1220 |
+
// Adds a "Digest" toggle to the globe that slides in World Digest's clustered,
|
| 1221 |
+
// LLM-written narrative fetched from /api/news/world-digest. Fully self-contained
|
| 1222 |
+
// and best-effort: if the sibling hasn't published or is unreachable it shows a
|
| 1223 |
+
// quiet notice and the globe is otherwise untouched.
|
| 1224 |
+
(function() {
|
| 1225 |
+
'use strict';
|
| 1226 |
+
var PANEL_ID = 'worldDigestPanel';
|
| 1227 |
+
var injected = false;
|
| 1228 |
+
|
| 1229 |
+
function ensureUI() {
|
| 1230 |
+
if (injected) return true;
|
| 1231 |
+
var overlay = document.getElementById('globeOverlay');
|
| 1232 |
+
if (!overlay) return false;
|
| 1233 |
+
var bar = overlay.querySelector('.globe-top-bar');
|
| 1234 |
+
if (!bar) return false;
|
| 1235 |
+
|
| 1236 |
+
var btn = document.createElement('button');
|
| 1237 |
+
btn.id = 'worldDigestToggle';
|
| 1238 |
+
btn.textContent = 'Digest';
|
| 1239 |
+
btn.style.cssText = 'pointer-events:auto;cursor:pointer;font-size:11px;font-weight:600;color:#94a3b8;background:rgba(15,23,42,0.7);border:1px solid rgba(34,211,238,0.15);border-radius:999px;padding:6px 14px;margin-right:8px;transition:all .2s';
|
| 1240 |
+
btn.onmouseenter = function() { btn.style.color = '#22d3ee'; btn.style.borderColor = 'rgba(34,211,238,0.4)'; };
|
| 1241 |
+
btn.onmouseleave = function() { btn.style.color = '#94a3b8'; btn.style.borderColor = 'rgba(34,211,238,0.15)'; };
|
| 1242 |
+
btn.onclick = toggleDigest;
|
| 1243 |
+
var closeBtn = bar.querySelector('.globe-close');
|
| 1244 |
+
if (closeBtn && closeBtn.parentNode) closeBtn.parentNode.insertBefore(btn, closeBtn);
|
| 1245 |
+
else bar.appendChild(btn);
|
| 1246 |
+
|
| 1247 |
+
var panel = document.createElement('div');
|
| 1248 |
+
panel.id = PANEL_ID;
|
| 1249 |
+
panel.className = 'globe-detail-panel'; // reuse the slide-in panel styling
|
| 1250 |
+
panel.style.left = '0';
|
| 1251 |
+
panel.style.right = 'auto';
|
| 1252 |
+
panel.style.borderLeft = 'none';
|
| 1253 |
+
panel.style.borderRight = '1px solid rgba(34,211,238,0.1)';
|
| 1254 |
+
panel.style.transform = 'translateX(-100%)';
|
| 1255 |
+
panel.setAttribute('data-open', '0');
|
| 1256 |
+
panel.innerHTML = '<div class="globe-detail-header"><div><div class="text-base font-bold text-white">World Digest</div><div class="text-xs mt-0.5 text-slate-400">State of the World — clustered narrative</div></div><button id="worldDigestClose" class="globe-close" style="width:30px;height:30px">×</button></div><div id="worldDigestBody" class="globe-detail-body"><div class="text-xs text-slate-500">Loading…</div></div>';
|
| 1257 |
+
overlay.appendChild(panel);
|
| 1258 |
+
var pc = panel.querySelector('#worldDigestClose');
|
| 1259 |
+
if (pc) pc.onclick = function() { panel.style.transform = 'translateX(-100%)'; panel.setAttribute('data-open', '0'); };
|
| 1260 |
+
|
| 1261 |
+
injected = true;
|
| 1262 |
+
return true;
|
| 1263 |
+
}
|
| 1264 |
+
|
| 1265 |
+
function toggleDigest() {
|
| 1266 |
+
if (!ensureUI()) return;
|
| 1267 |
+
var panel = document.getElementById(PANEL_ID);
|
| 1268 |
+
if (!panel) return;
|
| 1269 |
+
if (panel.getAttribute('data-open') === '1') {
|
| 1270 |
+
panel.style.transform = 'translateX(-100%)';
|
| 1271 |
+
panel.setAttribute('data-open', '0');
|
| 1272 |
+
} else {
|
| 1273 |
+
panel.style.transform = 'translateX(0)';
|
| 1274 |
+
panel.setAttribute('data-open', '1');
|
| 1275 |
+
loadDigest();
|
| 1276 |
+
}
|
| 1277 |
+
}
|
| 1278 |
+
|
| 1279 |
+
function esc(s) {
|
| 1280 |
+
return String(s == null ? '' : s).replace(/[&<>"]/g, function(c) {
|
| 1281 |
+
return { '&': '&', '<': '<', '>': '>', '"': '"' }[c];
|
| 1282 |
+
});
|
| 1283 |
+
}
|
| 1284 |
+
|
| 1285 |
+
function render(data) {
|
| 1286 |
+
var body = document.getElementById('worldDigestBody');
|
| 1287 |
+
if (!body) return;
|
| 1288 |
+
if (!data || data.stale || !data.clusters || !data.clusters.length) {
|
| 1289 |
+
body.innerHTML = '<div class="text-xs text-slate-500">World Digest hasn\'t published yet, or is unreachable. The globe is unaffected.</div>';
|
| 1290 |
+
return;
|
| 1291 |
+
}
|
| 1292 |
+
var html = '';
|
| 1293 |
+
if (data.narrative) {
|
| 1294 |
+
html += '<div class="globe-detail-section"><div class="globe-detail-title">Narrative</div>' +
|
| 1295 |
+
'<div class="text-xs text-slate-300" style="white-space:pre-wrap;line-height:1.5">' + esc(data.narrative).slice(0, 4000) + '</div></div>';
|
| 1296 |
+
}
|
| 1297 |
+
html += '<div class="globe-detail-section"><div class="globe-detail-title">Top stories</div><div class="flex flex-col gap-2">';
|
| 1298 |
+
data.clusters.slice(0, 12).forEach(function(c) {
|
| 1299 |
+
var src = (c.countries && c.countries.length ? c.countries : (c.regions || [])).join(', ');
|
| 1300 |
+
html += '<div class="globe-headline-item"><div class="globe-headline-title">' + esc(c.headline) + '</div>' +
|
| 1301 |
+
'<div class="globe-headline-meta"><span class="globe-headline-source">' + esc(src) + '</span>' +
|
| 1302 |
+
'<span>' + esc(c.outlets || 0) + ' outlets</span></div></div>';
|
| 1303 |
+
});
|
| 1304 |
+
html += '</div></div>';
|
| 1305 |
+
body.innerHTML = html;
|
| 1306 |
+
}
|
| 1307 |
+
|
| 1308 |
+
function loadDigest() {
|
| 1309 |
+
var body = document.getElementById('worldDigestBody');
|
| 1310 |
+
if (body) body.innerHTML = '<div class="text-xs text-slate-500">Loading…</div>';
|
| 1311 |
+
fetch('/api/news/world-digest', { cache: 'no-store' })
|
| 1312 |
+
.then(function(r) { return r.json(); })
|
| 1313 |
+
.then(render)
|
| 1314 |
+
.catch(function() { render(null); });
|
| 1315 |
+
}
|
| 1316 |
+
|
| 1317 |
+
window.toggleWorldDigest = toggleDigest;
|
| 1318 |
+
|
| 1319 |
+
// The overlay ships in index.html, but the bar may settle after load; retry a
|
| 1320 |
+
// few times then give up quietly.
|
| 1321 |
+
var tries = 0;
|
| 1322 |
+
var t = setInterval(function() {
|
| 1323 |
+
tries++;
|
| 1324 |
+
if (ensureUI() || tries > 20) clearInterval(t);
|
| 1325 |
+
}, 500);
|
| 1326 |
+
|
| 1327 |
+
console.log('globe_digest_view: loaded');
|
| 1328 |
+
})();
|
|
@@ -257,3 +257,29 @@ 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}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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}"
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# ===========================================================================
|
| 263 |
+
# 6. SIBLING BRIDGE — the news-exchange contract (contract/news_exchange.md)
|
| 264 |
+
# ===========================================================================
|
| 265 |
+
|
| 266 |
+
def test_world_digest_route_registered(client):
|
| 267 |
+
paths = {getattr(r, "path", None) for r in client.app.routes}
|
| 268 |
+
assert "/api/news/world-digest" in paths
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_world_digest_fallback_shape(client, monkeypatch):
|
| 272 |
+
"""When the sibling artifact is unreachable, the bridge must degrade to a
|
| 273 |
+
stale-flagged empty payload — never 500, never raise."""
|
| 274 |
+
main._cache.pop("world_digest_v1", None)
|
| 275 |
+
|
| 276 |
+
def boom(*args, **kwargs):
|
| 277 |
+
raise RuntimeError("sibling unreachable")
|
| 278 |
+
|
| 279 |
+
monkeypatch.setattr(main.requests, "get", boom)
|
| 280 |
+
resp = client.get("/api/news/world-digest")
|
| 281 |
+
assert resp.status_code == 200
|
| 282 |
+
body = resp.json()
|
| 283 |
+
assert body["stale"] is True
|
| 284 |
+
assert body["clusters"] == []
|
| 285 |
+
assert body["schema"] == "world-digest/news-exchange@1"
|
|
@@ -81,3 +81,10 @@ def test_index_has_all_tabs():
|
|
| 81 |
def test_index_bootstraps_init():
|
| 82 |
html = INDEX.read_text()
|
| 83 |
assert "init()" in html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def test_index_bootstraps_init():
|
| 82 |
html = INDEX.read_text()
|
| 83 |
assert "init()" in html
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_globe_digest_view_wired():
|
| 87 |
+
"""The globe's 'Digest view' must keep calling the sibling bridge endpoint
|
| 88 |
+
(contract/news_exchange.md). A mutation may restyle it but not unwire it."""
|
| 89 |
+
src = (STATIC / "globe_patch.js").read_text()
|
| 90 |
+
assert "/api/news/world-digest" in src
|