From bf6b2705b1e9f2590b3298ad07e755d6ff87f6f6 Mon Sep 17 00:00:00 2001 From: OpenReplicant <122761100+OpenReplicant@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:53:07 -0800 Subject: [PATCH 1/4] Research site: a static catalog of the research agent's claims, with steering by GitHub issue site/build.py reads the EvidenceClaim files and the map and options (site/config.toml; phase 0's demos/research-loop until the agent writes its own) and writes plain HTML: a feed filtered in the page by search, role, source and status; a page per claim (quote and its check, measure and effect, conditions and what is unstated, the transfer prediction and its reason, the outcome, trial and verdict); predictions against outcomes with a calibration chart and Brier score once outcomes exist; the roles from the map; how the loop works. Buttons open prefilled new-issue pages labelled research:prioritise, research:reject or research:question. Text from papers is escaped, links from files must be http(s), each page has a CSP, and nothing loads from another host. PyYAML only (already pinned); claims validated with jsonschema. .github/workflows/site.yml tests, builds and deploys to Pages, started by hand only. tests/test_site.py: the real input renders, issue URLs round-trip, hostile markup and javascript: links do not come through, an invalid claim stops the build, a scored prediction reaches the chart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KhsqyyPmp7iKCkTFcXs6sh --- .github/workflows/site.yml | 49 ++ CLAUDE.md | 2 + site/.gitignore | 1 + site/README.md | 52 +++ site/build.py | 934 +++++++++++++++++++++++++++++++++++++ site/config.toml | 27 ++ site/static/app.js | 50 ++ site/static/icon.svg | 1 + site/static/style.css | 275 +++++++++++ site/static/theme.js | 30 ++ tests/test_site.py | 214 +++++++++ 11 files changed, 1635 insertions(+) create mode 100644 .github/workflows/site.yml create mode 100644 site/.gitignore create mode 100644 site/README.md create mode 100644 site/build.py create mode 100644 site/config.toml create mode 100644 site/static/app.js create mode 100644 site/static/icon.svg create mode 100644 site/static/style.css create mode 100644 site/static/theme.js create mode 100644 tests/test_site.py diff --git a/.github/workflows/site.yml b/.github/workflows/site.yml new file mode 100644 index 0000000..0816085 --- /dev/null +++ b/.github/workflows/site.yml @@ -0,0 +1,49 @@ +# The research site (site/): build it from the claim, role and option files and deploy it to GitHub Pages. +# Not enabled: it runs only when started by hand, and deploying needs Pages turned on with "GitHub Actions" as its +# source (Settings > Pages). To deploy on every change to main, add the `push` trigger below. +name: research-site +on: + workflow_dispatch: + # push: + # branches: [main] + # paths: [site/**, demos/research-loop/**, schemas/evidence-claim.v1.json, .github/workflows/site.yml] + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install PyYAML and jsonschema (a venv; hash-locked wheels only) + run: | + python3 -m venv "$RUNNER_TEMP/site" + "$RUNNER_TEMP/site/bin/pip" install --quiet --only-binary=:all: --require-hashes -r requirements.lock + - name: Test the build + run: '"$RUNNER_TEMP/site/bin/python" -m unittest tests.test_site -v' + - name: Build + run: '"$RUNNER_TEMP/site/bin/python" site/build.py --out site/_build' + - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: site/_build + + deploy: + needs: build + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + steps: + - id: deploy + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/CLAUDE.md b/CLAUDE.md index ffb1ce4..cd68732 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,6 +18,8 @@ docs/restart/LESSONS.md. - `tests/`: the core's tests and red team; fixture projects in `tests/fixture*.py`, the timed sample's files in `tests/fixtures`. - `demos/`: projects Morphogen can build and drive. The core never imports from them. +- `site/`: the research site, static HTML built by `site/build.py` from the evidence claims, the map and the + options (`site/README.md`); `.github/workflows/site.yml` deploys it to Pages when started by hand. ## Rules - Look it up before relying on it: read a tool's or library's current docs before designing diff --git a/site/.gitignore b/site/.gitignore new file mode 100644 index 0000000..69fa449 --- /dev/null +++ b/site/.gitignore @@ -0,0 +1 @@ +_build/ diff --git a/site/README.md b/site/README.md new file mode 100644 index 0000000..16b261b --- /dev/null +++ b/site/README.md @@ -0,0 +1,52 @@ +# The research site + +A static site for the research loop ([docs/research-loop.md](../docs/research-loop.md)): the claims the research +agent has catalogued, their status for this system, its transfer predictions against outcomes, and the roles it +watches for. `build.py` reads the files named in `config.toml` (EvidenceClaim files, +[schemas/evidence-claim.v1.json](../schemas/evidence-claim.v1.json); the map and options as Backstage entity files) +and writes plain HTML into `_build/`. No server, no database, no tracking, nothing loaded from another host. + +Until the research agent writes its own claims, `config.toml` points at phase 0's records in +[demos/research-loop](../demos/research-loop). + +## Build and preview + +```sh +uv run python site/build.py # or: python3 site/build.py (needs PyYAML; validates with jsonschema if installed) +python3 -m http.server 8000 -d site/_build # then open http://localhost:8000 +uv run python -m unittest tests.test_site -v +``` + +Every claim is validated against the schema first; an invalid file stops the build. + +## Pages + +| Page | What it shows | +| --- | --- | +| `index.html` | the feed, newest first, filtered in the page by search, role, source and status (kept in the address, so a view can be shared); works without JavaScript, unfiltered | +| `claims/.html` | one claim: the quote and whether it was checked, the measure and effect, the conditions and what the source left unstated, the transfer prediction and its reason, the outcome with its trial and verdict | +| `predictions.html` | predictions waiting for a trial, and a calibration chart with the Brier score once predictions written before an outcome have one | +| `roles.html` | the roles in the map, the options catalogued for each, and this system's conditions | +| `how.html` | the loop: watch, read, catalogue, predict, test behind the judge, score the prediction | +| `data/claims.json` | the same records, for other tools | + +## Steering + +The buttons open a prefilled GitHub new-issue page (title, body, labels); nothing is sent until the person submits +it. The labels are in `config.toml`: `research:prioritise`, `research:reject`, and `research:question` for a +disputed prediction or a question, role or option to watch. GitHub applies labels from the link only for people +who can triage the repository, so each body also carries `research-action:`, `research-claim:` and `claim-file:` +lines. Text from papers never goes into an issue body, since it is rendered as Markdown. + +## Safety + +Claim text comes from papers. Every string from a file is HTML-escaped where it is written, a link from a file is +written only if it is http or https, and each page sets a content security policy that allows only its own +scripts and styles. `tests/test_site.py` builds a claim full of markup and a `javascript:` link and checks that +none of it comes through. + +## Deploying + +`.github/workflows/site.yml` tests, builds and deploys `_build/` to GitHub Pages. It runs only when started by hand +until its `push` trigger is uncommented, and it needs Pages set to "GitHub Actions" in the repository's settings. +Links are relative, so the site works at `https://.github.io/Morphogen/` or on a custom domain. diff --git a/site/build.py b/site/build.py new file mode 100644 index 0000000..9a46cdf --- /dev/null +++ b/site/build.py @@ -0,0 +1,934 @@ +"""Build the research agent's static site from the claim, role and option files. + + python3 site/build.py # site/config.toml in, site/_build out + python3 site/build.py --out /tmp/site --config other.toml + +Reads EvidenceClaim files (schemas/evidence-claim.v1.json) and the catalog's Backstage entity files, and writes +plain HTML, one CSS file, two small scripts and data/claims.json. No server, no database, nothing fetched at +runtime. Needs Python 3.11 and PyYAML; with jsonschema installed (it is in requirements.lock), every claim is +validated first and an invalid one stops the build. + +Claim text comes from papers, so every string from a file is HTML-escaped where it is written (`e()`), and a link +from a file is written only when it is http or https (`safe_url()`). +""" + +from __future__ import annotations + +import argparse +import html +import json +import shutil +import sys +import tomllib +from dataclasses import dataclass, field +from pathlib import Path +from urllib.parse import quote, urlencode, urlsplit + +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent + +STATUSES = ["untested", "predicted", "replicated", "did-not-transfer", "not-testable"] +OBSERVATION = "observation" # a claim of this system's own (source.kind trial or probe): it has no status +STATUS_TEXT = { + "untested": "Untested", + "predicted": "Predicted", + "replicated": "Replicated", + "did-not-transfer": "Did not transfer", + "not-testable": "Not testable", + OBSERVATION: "Our observation", +} +STATUS_HELP = { + "untested": "Catalogued, with the reason it has not been tried here.", + "predicted": "A probability that it holds here was written before any outcome.", + "replicated": "Tried on this system's setup, and the finding held.", + "did-not-transfer": "Tried on this system's setup, and the finding did not hold.", + "not-testable": "Cannot be tried here, and why.", + OBSERVATION: "A measurement this system ran itself, which a paper's outcome links to.", +} +QUOTE_SHORT = {"checked": "quote checked", "unchecked": "quote unchecked", "none": "no quote"} +QUOTE_TEXT = { + "checked": "Quote checked against the source", + "unchecked": "Quote copied, not yet checked", + "none": "No verbatim quote taken", +} + + +# ---------------------------------------------------------------- escaping and links + + +def e(value) -> str: + """Escape any value for HTML text or a quoted attribute.""" + return html.escape("" if value is None else str(value), quote=True) + + +def safe_url(url) -> str | None: + """The URL if it is http(s) with a host, else None: a file must not be able to write a javascript: link.""" + if not isinstance(url, str): + return None + url = url.strip() + try: + parts = urlsplit(url) + except ValueError: + return None + if parts.scheme not in ("http", "https") or not parts.netloc: + return None + return url + + +def link(url, text, cls: str = "") -> str: + """An external link when the URL is safe, plain text when it is not.""" + good = safe_url(url) + if not good: + return e(text) + c = f' class="{e(cls)}"' if cls else "" + return f'{e(text)}' + + +def issue_url(repo: str, title: str, body: str, labels: list[str]) -> str: + """A prefilled new-issue URL. GitHub reads `title`, `body` and comma-separated `labels` from the query.""" + query = {"title": title, "body": body} + if labels: + query["labels"] = ",".join(labels) + return f"https://github.com/{quote(repo, safe='/')}/issues/new?" + urlencode(query, quote_via=quote) + + +# ---------------------------------------------------------------- loading + + +def ref_name(ref: str | None) -> str: + """`component:default/decision-backend` -> `decision-backend`.""" + if not ref: + return "" + return ref.split(":", 1)[-1].split("/", 1)[-1] + + +@dataclass +class Claim: + doc: dict + path: str # relative to the repository root + + @property + def name(self) -> str: + return self.doc["metadata"]["name"] + + @property + def spec(self) -> dict: + return self.doc["spec"] + + @property + def source(self) -> dict: + return self.spec["source"] + + @property + def ours(self) -> bool: + return self.source.get("kind") in ("trial", "probe") + + def assessment(self, system: str) -> dict | None: + for a in self.spec.get("assessments") or []: + if a.get("system") == system: + return a + return None + + def status(self, system: str) -> str: + if self.ours: + return OBSERVATION + a = self.assessment(system) + return a["status"] if a else "untested" + + def date(self) -> str: + dates = [] + for a in self.spec.get("assessments") or []: + dates += [a.get("date"), (a.get("prediction") or {}).get("date"), (a.get("outcome") or {}).get("date")] + return max((str(d) for d in dates if d), default="") + + +@dataclass +class Catalog: + entities: list[dict] = field(default_factory=list) + + def of(self, kind: str) -> list[dict]: + return [x for x in self.entities if x.get("kind") == kind] + + def get(self, ref: str) -> dict | None: + name = ref_name(ref) + for x in self.entities: + if x.get("metadata", {}).get("name") == name and x.get("kind") != "Location": + return x + return None + + @property + def roles(self) -> list[dict]: + return [x for x in self.of("Component") if (x.get("spec") or {}).get("type") == "role"] + + @property + def options(self) -> list[dict]: + return [x for x in self.of("Component") if (x.get("spec") or {}).get("lifecycle") == "candidate"] + + @property + def conditions(self) -> list[dict]: + return self.of("Resource") + + @property + def system(self) -> dict | None: + systems = self.of("System") + return systems[0] if systems else None + + +def load_yaml_docs(path: Path) -> list[dict]: + with path.open(encoding="utf-8") as f: + return [d for d in yaml.safe_load_all(f) if isinstance(d, dict)] + + +def load_claims(dirs: list[Path], root: Path, schema: dict | None) -> list[Claim]: + validator = None + if schema is not None: + try: + import jsonschema # noqa: PLC0415 + except ImportError: + print("build: jsonschema is not installed; claims are not validated", file=sys.stderr) + else: + cls = jsonschema.validators.validator_for(schema) + validator = cls(schema, format_checker=cls.FORMAT_CHECKER) + claims, seen = [], {} + for d in dirs: + for path in sorted(list(d.rglob("*.yaml")) + list(d.rglob("*.yml"))): + for doc in load_yaml_docs(path): + if doc.get("kind") != "EvidenceClaim": + continue + rel = path.resolve().relative_to(root).as_posix() if path.resolve().is_relative_to(root) else path.name + if validator is not None: + errors = sorted(validator.iter_errors(_jsonable(doc)), key=lambda x: list(x.path)) + if errors: + where = "/".join(str(p) for p in errors[0].path) + raise SystemExit(f"build: {rel} is not a valid EvidenceClaim: {where}: {errors[0].message}") + claim = Claim(doc, rel) + if claim.name in seen: + raise SystemExit(f"build: claim name {claim.name} is in both {seen[claim.name]} and {rel}") + seen[claim.name] = rel + claims.append(claim) + return claims + + +def _jsonable(value): + """YAML gives dates as date objects; the schema and JSON want strings.""" + if isinstance(value, dict): + return {str(k): _jsonable(v) for k, v in value.items()} + if isinstance(value, list): + return [_jsonable(v) for v in value] + if hasattr(value, "isoformat"): + return value.isoformat() + return value + + +def sort_claims(claims: list[Claim]) -> list[Claim]: + """Newest first: the latest assessment, prediction or outcome date; then the source id (arXiv ids grow).""" + return sorted(claims, key=lambda c: (c.date(), str(c.source.get("id", "")), c.name), reverse=True) + + +# ---------------------------------------------------------------- formatting values + + +def fmt_number(value) -> str: + if value is None: + return "not stated" + if isinstance(value, dict): + over = f" over {value['over']}" if value.get("over") else "" + return f"{value.get('min')} to {value.get('max')}{over}" + return str(value) + + +def fmt_interval(iv: dict | None) -> str: + if not iv: + return "" + how = [f"{round(iv['level'] * 100)}%" if iv.get("level") else "", iv.get("method", "")] + how = ", ".join(x for x in how if x) + return f"[{iv.get('low')}, {iv.get('high')}]" + (f" ({how})" if how else "") + + +def measure_html(m: dict) -> str: + """One measure as a definition list row group.""" + better = {"higher": "higher is better", "lower": "lower is better"}.get(m.get("better", ""), "") + unit = f" {m['unit']}" if m.get("unit") else "" + value = fmt_number(m.get("value")) + (unit if m.get("value") is not None else "") + rows = [("Metric", m.get("metric", "") + (f" ({better})" if better else ""))] + rows.append(("Value", value + (" " + fmt_interval(m.get("interval")) if m.get("interval") else ""))) + if m.get("where"): + rows.append(("Where", m["where"])) + b = m.get("baseline") + if b: + bv = b.get("value") + bval = "" if bv is None else f": {fmt_number(bv)}" + rows.append(("Against", f"{b.get('name', '')}{bval}" + (" " + fmt_interval(b.get("interval")) if b.get( + "interval") else ""))) + return "".join(f"
{e(k)}
{e(v)}
" for k, v in rows) + + +def status_badge(status: str) -> str: + return f'{e(STATUS_TEXT.get(status, status))}' + + +def meter(p: float, label: bool = True) -> str: + """The transfer probability as a bar, with the number beside it (never the bar alone).""" + pct = max(0.0, min(1.0, float(p))) * 100 + bar = (f'') + text = f'p {float(p):.2f}' if label else "" + return f'{bar}{text}' + + +def source_short(src: dict) -> str: + return src.get("id") or src.get("title", "") + + +def truncate(text: str, n: int) -> str: + text = " ".join(str(text).split()) + return text if len(text) <= n else text[: n - 1].rstrip() + "…" + + +# ---------------------------------------------------------------- page frame + + +@dataclass +class Site: + title: str + repo: str + branch: str + system: str + labels: dict + claims: list[Claim] + catalog: Catalog + + def by_name(self) -> dict[str, Claim]: + return {c.name: c for c in self.claims} + + def file_url(self, path: str) -> str: + return f"https://github.com/{self.repo}/blob/{self.branch}/{path}" + + def issue(self, action: str, title: str, body: str) -> str: + return issue_url(self.repo, title, body, list(self.labels.get(action, []))) + + +NAV = [("index.html", "Claims"), ("predictions.html", "Predictions"), ("roles.html", "Roles"), ("how.html", "How it works")] + + +def page(site: Site, title: str, body: str, current: str, depth: int = 0, description: str = "") -> str: + up = "../" * depth + nav = "".join( + f'
  • {e(text)}
  • ' + for href, text in NAV) + full_title = f"{title} · {site.title}" if title != site.title else site.title + desc = description or "Claims from papers about options for the system's roles, with conditions, transfer predictions and outcomes." + return f""" + + + + + + + + +{e(full_title)} + + + + + + +
    +
    + Morphogen research + + +
    +
    +
    +{body} +
    +
    +

    Built from the claim, role and option files in {link(f"https://github.com/{site.repo}", site.repo)}. Static files only: no tracking, no cookies, nothing loaded from elsewhere. Steering happens in GitHub issues.

    +
    + + +""" + + +# ---------------------------------------------------------------- the feed + + +def feed_item(site: Site, c: Claim) -> str: + status = c.status(site.system) + a = c.assessment(site.system) or {} + src, cl = c.source, c.spec["claim"] + role, option = ref_name(c.spec.get("role")), ref_name(c.spec.get("about")) + p = (a.get("prediction") or {}).get("p_transfer") + search = " ".join(str(x) for x in [c.name, c.doc["metadata"].get("description", ""), cl.get("statement", ""), + src.get("title", ""), src.get("id", ""), role, option, cl.get("metric", "")]) + quote_cls = "q-" + src.get("quote_status", "none") + meta = [f'{e(source_short(src))}', f'{e(role)}', + f'option {e(option)}'] + if c.date(): + meta.append(f'') + right = meter(p) if p is not None else "" + return f"""
  • + +
  • """ + + +def render_index(site: Site) -> str: + claims = sort_claims(site.claims) + counts = {s: 0 for s in STATUSES + [OBSERVATION]} + for c in claims: + counts[c.status(site.system)] = counts.get(c.status(site.system), 0) + 1 + roles = sorted({ref_name(c.spec.get("role")) for c in claims}) + sources = {} + for c in claims: + sources.setdefault(source_short(c.source), c.source.get("title", "")) + stat = "".join( + f'
  • {counts[s]} {status_badge(s)}
  • ' for s in STATUSES + [OBSERVATION] + if counts.get(s)) + status_boxes = "".join( + f'' + for s in STATUSES + [OBSERVATION]) + role_opts = "".join(f'' for r in roles) + src_opts = "".join( + f'' + for k, v in sorted(sources.items(), reverse=True)) + items = "\n".join(feed_item(site, c) for c in claims) + paper_n = sum(1 for c in claims if not c.ours) + question = site.issue("question", "Question to watch: ", issue_body("question", site, None, extra=[ + "What should the research agent look for? A method, a role, an open question from the system's docs.", "", + "Question:", "", "Why it matters here:", ""])) + body = f""" +
    +

    The research agent's catalog

    +

    Claims from papers, checked against this system

    +

    The agent reads new papers for the roles in the map, writes down each claimed gain with the conditions it was measured under, and predicts whether it will hold here. Trials behind the judge then score the prediction. {paper_n} claims from papers so far, for {e(ref_name(site.system))}.

    +
      {stat}
    +

    Propose a question to watch How it works

    +
    + + +

    +
      +{items} +
    + + +""" + return page(site, site.title, body, "index.html") + + +# ---------------------------------------------------------------- one claim + + +def issue_body(action: str, site: Site, c: Claim | None, extra: list[str] | None = None) -> str: + """The body of a steering issue. Only the claim's name and path go in, never text from the paper: an issue + body is rendered as Markdown, and a paper's words could mention people or carry links.""" + lines = [] + lines += extra or [] + lines += ["", "---", f"research-action: {action}", f"system: {site.system}"] + if c is not None: + lines += [f"research-claim: {c.name}", f"claim-file: {site.file_url(c.path)}", + f"status: {c.status(site.system)}"] + p = ((c.assessment(site.system) or {}).get("prediction") or {}).get("p_transfer") + if p is not None: + lines.append(f"p_transfer: {p}") + return "\n".join(lines).strip() + "\n" + + +def claim_actions(site: Site, c: Claim) -> str: + if c.ours: + return "" + a = c.assessment(site.system) or {} + btns = [ + ("prioritise", f"Prioritise: {c.name}", "Test this claim next", + ["Please test this claim sooner.", "", "Why it is worth a trial now:", ""]), + ("reject", f"Reject: {c.name}", "Reject it", + ["Please drop this claim from the queue.", "", "Why (does not apply here, already known, not a real gain):", + ""]), + ] + if a.get("prediction"): + btns.append(("dispute", f"Dispute prediction: {c.name}", "Dispute the prediction", + ["I think the transfer prediction is wrong.", "", "My probability that it holds here:", "", + "Which conditions it gets wrong:", ""])) + out = [] + for action, title, text, extra in btns: + url = site.issue(action, title, issue_body(action, site, c, extra)) + cls = "btn" if action == "prioritise" else "btn ghost" + out.append(f'{e(text)}') + labels = ", ".join(sorted({lab for k in ("prioritise", "reject", "dispute") for lab in site.labels.get(k, [])})) + return f"""
    +

    Steer the agent

    +

    Each button opens a new GitHub issue, filled in, for you to edit and submit. The agent reads issues labelled {e(labels)}.

    +

    {" ".join(out)}

    +
    """ + + +def quote_html(src: dict) -> str: + status = src.get("quote_status", "none") + head = f'

    {e(QUOTE_TEXT.get(status, status))}' + if src.get("quote_location"): + head += f' {e(src["quote_location"])}' + head += "

    " + parts = [head] + if src.get("quote"): + parts.append(f'

    {e(src["quote"])}

    ') + if src.get("quote_note"): + parts.append(f'

    {e(src["quote_note"])}

    ') + via = src.get("via") + if via: + where = f", {via['location']}" if via.get("location") else "" + parts.append(f'

    Via a secondary source ' + f'{link(via.get("url"), via.get("title", ""))}{e(where)}

    ') + parts.append(f'

    {e(via.get("quote", ""))}

    ') + return "".join(parts) + + +def conditions_html(cond: dict) -> str: + rows = [] + models = cond.get("models") or [] + if models: + items = [] + for m in models: + bits = [m.get(k) for k in ("size", "precision", "tuned") if m.get(k)] + items.append(f'
  • {e(m.get("name", ""))}' + + (f' {e(", ".join(bits))}' if bits else "") + + (f'
    {e(m["capability"])}' if m.get("capability") else "") + + "
  • ") + rows.append(("Models", f'
      {"".join(items)}
    ')) + for key, label in (("engine", "Engine"), ("dataset", "Dataset"), ("hardware", "Hardware")): + v = cond.get(key) + if isinstance(v, dict): + text = ", ".join(str(v[k]) for k in ("name", "version", "split", "size", "memory") if v.get(k)) + rows.append((label, e(text))) + for key, label in (("method", "Method"), ("thinking", "Thinking"), ("labels", "Labels")): + if cond.get(key): + rows.append((label, e(cond[key]))) + known = {"models", "engine", "dataset", "hardware", "method", "thinking", "labels", "unstated"} + for key, v in cond.items(): + if key not in known and v not in (None, "", [], {}): + rows.append((key.replace("_", " ").capitalize(), e(v if isinstance(v, str) else json.dumps(_jsonable(v))))) + if cond.get("unstated"): + rows.append(("Not stated", '
      ' + "".join( + f"
    • {e(u)}
    • " for u in cond["unstated"]) + "
    ")) + return '
    ' + "".join(f"
    {e(k)}
    {v}
    " for k, v in rows) + "
    " + + +def claim_ref(site: Site, name: str, depth: int) -> str: + c = site.by_name().get(name) + up = "../" * depth + if not c: + return f'{e(name)}' + return (f'{e(name)}' + f' {e(truncate(c.doc["metadata"].get("description", ""), 110))}') + + +def assessment_html(site: Site, c: Claim, a: dict) -> str: + parts = [f'

    {status_badge(a["status"])} for {e(a.get("system"))}' + + (f' on {e(a["date"])}' if a.get("date") else "") + "

    "] + if a.get("against"): + parts.append('

    Compared with: ' + ", ".join( + f'{e(ref_name(r))}' for r in a["against"]) + "

    ") + pr = a.get("prediction") + if pr: + parts.append(f"""

    Transfer prediction

    +

    {meter(pr["p_transfer"])}

    +

    {e(pr.get("reason", ""))}

    +

    By {e(pr.get("by", ""))}, {e(pr.get("date", ""))}. {"Written before any outcome, so it counts towards calibration." if pr.get("before_outcome") else "Written after an outcome was seen, so it does not count towards calibration."}

    """) + out = a.get("outcome") + if out: + t = out.get("trial") or {} + v = out.get("verdict") or {} + observed = "".join(f"
  • {claim_ref(site, n, 1)}
  • " for n in out.get("observed") or []) + by = {"morphogen": "the judge", "falsifier": "a falsifier registered before the outcome", + "operator": "the operator", "none": "nobody yet"}.get(v.get("by"), v.get("by", "")) + parts.append(f"""

    Outcome

    +

    Trial {link(t.get("url"), t.get("id", ""), "mono")}{(" · " + e(out["date"])) if out.get("date") else ""} · {e("a transfer test on our setup" if out.get("comparison") == "our-setup" else "the source's own setup reproduced")}

    +

    {e(out.get("summary", ""))}

    +
    Verdict
    {e(v.get("decision", ""))}, decided by {e(by)}{(" " + e(v["ref"]) + "") if v.get("ref") else ""}{("
    " + e(v["note"]) + "") if v.get("note") else ""}
    +
    Observed
      {observed}
    """) + if a.get("reason"): + parts.append(f'

    Note
    {e(a["reason"])}

    ') + if a.get("see_also"): + parts.append('

    See also

      ' + "".join( + f"
    • {claim_ref(site, n, 1)}
    • " for n in a["see_also"]) + "
    ") + parts.append("
    ") + return "".join(parts) + + +def render_claim(site: Site, c: Claim) -> str: + md, src, cl, cond = c.doc["metadata"], c.source, c.spec["claim"], c.spec.get("conditions") or {} + status = c.status(site.system) + option = site.catalog.get(c.spec.get("about", "")) + role = site.catalog.get(c.spec.get("role", "")) + reporting = {"self": "the source measures its own method", "independent": "the source measures methods it did not make", + "ours": "this system's own trial", "unknown": "not stated who measured it"}.get(cl.get("reporting"), "") + effect = cl.get("effect_size") + effect_html = (f"
    Effect
    {e(fmt_number(effect.get('value')))} ({e(effect.get('kind'))})" + f"{(' · ' + e(effect['note'])) if effect.get('note') else ''}
    ") if effect else ( + "
    Effect
    No effect size stated (a difference of two stated numbers is not one)
    ") + strength = [f"
    Finding
    {e(cl.get('finding'))} against the baseline
    ", effect_html] + if cl.get("significance"): + strength.append(f"
    Significance
    {e(cl['significance'])}
    ") + strength.append(f"
    Runs · cases
    {e(cl.get('runs') if cl.get('runs') is not None else 'not stated')} · " + f"{e(cl.get('cases') if cl.get('cases') is not None else 'not stated')}
    ") + strength.append(f"
    Reported by
    {e(cl.get('reporting'))}: {e(reporting)}
    ") + also = "".join(f'
    {measure_html(m)}
    ' for m in cl.get("also") or []) + if also: + also = "

    Also measured

    " + also + if cl.get("note"): + also += f'

    {e(cl["note"])}

    ' + src_bits = [x for x in (src.get("id"), src.get("version") and f"version {src['version']}") if x] + assessments = "".join(assessment_html(site, c, a) for a in c.spec.get("assessments") or []) + if not assessments and c.ours: + linked = [o for o in site.claims for a in o.spec.get("assessments") or [] + for n in ((a.get("outcome") or {}).get("observed") or []) + (a.get("see_also") or []) if n == c.name] + names = sorted({o.name for o in linked}) + assessments = ('

    This is a measurement this system ran. Claims from papers that it bears on:

      ' + + "".join(f"
    • {claim_ref(site, n, 1)}
    • " for n in names) + "
    ") if names else ( + "

    This is a measurement this system ran. No paper's claim links to it yet.

    ") + body = f""" +

    Claims {e(c.name)}

    +
    +
    +
    {status_badge(status)}{e(ref_name(c.spec.get("role")))} · option {e(ref_name(c.spec.get("about")))}
    +

    {e(md.get("description") or c.name)}

    +

    {e(cl.get("statement", ""))}

    +
    + +
    +

    Source

    +

    {link(src.get("url"), src.get("title", ""))}
    {e(" · ".join(src_bits))} ({e(src.get("kind"))})

    +
    Where
    {e(src.get("location", ""))}
    Read
    {e(src.get("read", ""))}
    + {quote_html(src)} +
    + +
    +
    +

    Measure and effect

    +
    {measure_html(cl)}{"".join(strength)}
    + {also} +
    +
    +

    Conditions

    + {conditions_html(cond)} +
    +
    + +
    +

    {"Status here" if not c.ours else "Where it is used"}

    + {assessments} +
    + + {option_panel(option, role)} + {claim_actions(site, c)} +

    The record: {link(site.file_url(c.path), c.path, "mono")}

    +
    +""" + return page(site, md.get("description") or c.name, body, "", depth=1, description=truncate(cl.get("statement", ""), 160)) + + +def option_panel(option: dict | None, role: dict | None) -> str: + if not option: + return "" + ev = ((option.get("spec") or {}).get("morphogen") or {}).get("evaluation") or {} + rows = "".join(f"
    {e(k)}
    {e(ev[key])}
    " for key, k in (("need", "What would count"), + ("method", "How it is measured"), + ("result", "Result so far")) if ev.get(key)) + rname = (role or {}).get("metadata", {}).get("name", "") + name = option["metadata"]["name"] + return f"""

    The option

    +

    {e(name)}, a candidate for the role {e(rname)}.

    +

    {e(option["metadata"].get("description", ""))}

    {f'
    {rows}
    ' if rows else ""}
    """ + + +# ---------------------------------------------------------------- roles + + +def fills(option: dict) -> list[str]: + """The roles an option fills: `spec.morphogen.fills`, one ref or a list.""" + f = ((option.get("spec") or {}).get("morphogen") or {}).get("fills") or [] + return [ref_name(r) for r in ([f] if isinstance(f, str) else f)] + + +def parse_evidence(annotation: str | None) -> list[tuple[str, str]]: + """`stated | repo@commit:path | "quote"` lines -> (source, quote).""" + out = [] + for line in (annotation or "").splitlines(): + parts = [p.strip() for p in line.split("|", 2)] + if len(parts) == 3: + out.append((parts[1], parts[2].strip('"'))) + return out + + +def render_roles(site: Site) -> str: + cat = site.catalog + claims_by_option: dict[str, list[Claim]] = {} + for c in site.claims: + if not c.ours: + claims_by_option.setdefault(ref_name(c.spec.get("about")), []).append(c) + blocks = [] + for r in cat.roles: + name = r["metadata"]["name"] + parent = (r.get("spec") or {}).get("subcomponentOf") + ev = parse_evidence((r["metadata"].get("annotations") or {}).get("morphogen.dev/evidence")) + ev_html = "".join(f'

    {e(q)}

    {e(s)}
    ' + for s, q in ev) + opts = [o for o in cat.options if name in fills(o)] + rows = [] + for o in opts: + oname = o["metadata"]["name"] + cs = claims_by_option.get(oname, []) + counts = {} + for c in cs: + counts[c.status(site.system)] = counts.get(c.status(site.system), 0) + 1 + badges = " ".join(f"{status_badge(s)}×{n}" for s, n in counts.items()) + result = (((o.get("spec") or {}).get("morphogen") or {}).get("evaluation") or {}).get("result") + links = "".join(f'
  • {e(truncate(c.doc["metadata"].get("description", c.name), 120))}
  • ' for c in cs) + rows.append(f"""
  • {e(oname)}

    {e(o["metadata"].get("description", ""))}

    +

    {badges or "No claims from papers yet"}

    {f'

    Result so far {e(result)}

    ' if result else ""} +{f'
    {len(cs)} claim{"s" if len(cs) != 1 else ""}
      {links}
    ' if cs else ""}
  • """) + propose = site.issue("question", f"Option to watch for {name}: ", issue_body("question", site, None, extra=[ + f"An option, paper or method the research agent should look at for the role `{name}`.", "", + "Option or paper:", "", "Why it might help here:", "", f"role: {name}"])) + blocks.append(f"""
    +

    Role{f' · part of {e(parent)}' if parent else ""}

    +

    {e(name)}

    +

    {e(r["metadata"].get("description", ""))}

    {ev_html} +

    Options the agent is tracking ({len(opts)})

    +
      {"".join(rows) or "
    • None yet.
    • "}
    +

    Suggest an option for this role

    +
    """) + conds = [] + for res in cat.conditions: + n = res["metadata"]["name"] + conds.append(f'
  • {e(n)} {e((res.get("spec") or {}).get("type", ""))}
    {e(res["metadata"].get("description", ""))}
  • ') + system = cat.system + sysdesc = e(system["metadata"].get("description", "")) if system else "" + new_role = site.issue("question", "Role to watch: ", issue_body("question", site, None, extra=[ + "A part of the system the research agent should read papers for.", "", "The part, and what it does:", "", + "What a better option would improve:", ""])) + body = f""" +
    +

    What the agent watches for

    +

    Roles, from the map

    +

    The agent does not read a general feed. It looks for papers about the roles in the system's map, and every option it catalogues is a candidate for one of them. {sysdesc}

    +

    Propose a role to watch

    +
    +{"".join(blocks)} +

    This system's conditions

    +

    Every claim's conditions are compared with these when its transfer is predicted.

    +
      {"".join(conds)}
    +""" + return page(site, "Roles", body, "roles.html") + + +# ---------------------------------------------------------------- predictions and calibration + + +def calibration_pairs(site: Site) -> list[tuple[float, int, Claim]]: + """(p, held, claim) for each prediction written before an outcome that now has one.""" + out = [] + for c in site.claims: + a = c.assessment(site.system) or {} + pr, status = a.get("prediction") or {}, a.get("status") + if pr.get("before_outcome") and a.get("outcome") and status in ("replicated", "did-not-transfer"): + out.append((float(pr["p_transfer"]), 1 if status == "replicated" else 0, c)) + return out + + +def brier(pairs) -> float | None: + return sum((p - o) ** 2 for p, o, _ in pairs) / len(pairs) if pairs else None + + +def calibration_svg(pairs, waiting: list[float]) -> str: + """A reliability diagram: predicted probability against the share that held, in five bins, with the diagonal + of perfect calibration; predictions still waiting, one per claim.are ticks under the axis. Attributes only (no inline style), + so the page's content security policy holds.""" + w, h, m = 360, 300, 44 + pw, ph = w - m - 16, h - m - 30 + + def x(p): + return m + p * pw + + def y(v): + return 16 + (1 - v) * ph + + grid = "".join(f'' + f'' + f'{t:.1f}' + f'{t:.1f}' + for t in (0, 0.2, 0.4, 0.6, 0.8, 1.0)) + diag = f'' + bins = [] + for i in range(5): + lo, hi = i / 5, (i + 1) / 5 + inside = [(p, o) for p, o, _ in pairs if lo <= p < hi or (i == 4 and p == 1.0)] + if inside: + mp = sum(p for p, _ in inside) / len(inside) + rate = sum(o for _, o in inside) / len(inside) + bins.append((mp, rate, len(inside))) + dots = "".join( + f'' + f'Predicted {mp:.2f} on average, {r:.2f} held ({n} claim{"s" if n != 1 else ""})' + for mp, r, n in bins) + stacked, seen = [], {} + for p in sorted(waiting): + k = round(p, 2) + stacked.append((p, seen.get(k, 0))) + seen[k] = seen.get(k, 0) + 1 + ticks = "".join(f'Waiting: p {p:.2f}' + for p, i in stacked) + h += 7 * max(seen.values(), default=1) + return f""" +Predicted probability against the share that held +{len(pairs)} predictions with outcomes in {len(bins)} bins; {len(waiting)} waiting. The diagonal is perfect calibration. +{grid}{diag}{dots}{ticks} +predicted probability it holds here +share that held +""" + + +def render_predictions(site: Site) -> str: + pairs = calibration_pairs(site) + waiting, unscored = [], [] + for c in sort_claims(site.claims): + a = c.assessment(site.system) or {} + if a.get("status") == "predicted" and a.get("prediction"): + waiting.append(c) + elif a.get("status") in ("replicated", "did-not-transfer") and not (a.get("prediction") or {}).get("before_outcome"): + unscored.append(c) + b = brier(pairs) + if pairs: + summary = (f"

    {len(pairs)} predictions written before their outcome now have one. " + f"Brier score {b:.3f} (0 is perfect; always saying 0.5 scores 0.250).

    ") + else: + summary = ("

    No prediction has an outcome yet, so there is nothing to score. The chart fills in as trials " + "report: each dot is a group of predictions, placed at their average probability and at the share " + "that held. The small dots under the axis are predictions still waiting, one per claim.

    ") + rows = "".join( + f'{e(truncate(c.doc["metadata"].get("description", c.name), 90))}' + f'{meter(p)}{status_badge(c.status(site.system))}' for p, _, c in pairs) + wait_rows = "".join( + f'{e(truncate(c.doc["metadata"].get("description", c.name), 90))}' + f'{meter(c.assessment(site.system)["prediction"]["p_transfer"])}' + for c in sorted(waiting, key=lambda c: -c.assessment(site.system)["prediction"]["p_transfer"])) + unscored_items = "".join(f"
  • {status_badge(c.status(site.system))} {e(truncate(c.doc['metadata'].get('description', c.name), 110))}
  • " for c in unscored) + svg = calibration_svg(pairs, [c.assessment(site.system)["prediction"]["p_transfer"] for c in waiting]) + body = f""" +
    +

    Scoring the agent

    +

    Predictions against outcomes

    +

    Before a claim is tried, the agent writes the probability that its finding holds on this system. When the trial reports, the prediction is scored. Over time this shows which kinds of claims carry over, and how far to trust the agent's guesses.

    +
    +
    +

    Calibration

    {summary}{svg}
    +

    Waiting for a trial ({len(waiting)})

    + {wait_rows or ""}
    ClaimPrediction
    None.
    +

    Who wrote each one is on its page. To argue with one, open the claim and use "Dispute the prediction".

    +
    +{f'

    Scored

    {rows}
    ClaimPredictionOutcome
    ' if pairs else ""} +{f'

    Outcomes that do not count

    These were tried before anyone wrote a probability, so they say nothing about the agent's calibration.

      {unscored_items}
    ' if unscored else ""} +""" + return page(site, "Predictions", body, "predictions.html") + + +# ---------------------------------------------------------------- how it works + + +def render_how(site: Site) -> str: + steps = [ + ("Watch", "New papers are read for the roles in the system's map and the open questions in its docs. Nothing else."), + ("Read", "Each paper is read far enough to find what it measured, on what, and how. How much was read is recorded with every claim."), + ("Catalogue", "A method becomes an option for a role. Each claimed gain becomes a claim: one measure, the baseline, the effect if the paper states one, the conditions (models, precision, engine, dataset, runs, who measured it), and a verbatim quote that a verifier matches against the source."), + ("Predict", "The claim's conditions are compared with this system's own. The agent writes the probability that the finding holds here, and why, before anything is tried."), + ("Test behind the judge", "The cheapest informative trial goes first. An implementer turns the method into a change, and Morphogen's judge decides on cases the implementer never saw. A paper's number never decides anything."), + ("Score the prediction", "The outcome is recorded against the claim: replicated, did not transfer, or not testable here. Predictions written before the outcome are scored, which calibrates the next ones."), + ] + ol = "".join(f'
  • {i:02d}

    {e(t)}

    {e(d)}

  • ' + for i, (t, d) in enumerate(steps, 1)) + labs = "".join(f"
  • {e(', '.join(v))} {e(t)}
  • " for k, t in ( + ("prioritise", "test this claim sooner"), ("reject", "drop it from the queue"), + ("dispute", "the transfer prediction is wrong"), ("question", "a question, role or option to watch")) + for v in [site.labels.get(k, [])] if v) + statuses = "".join(f"
  • {status_badge(s)} {e(STATUS_HELP[s])}
  • " for s in STATUSES + [OBSERVATION]) + body = f""" +
    +

    How it works

    +

    A research loop with a judge at the end

    +

    Papers report far more gains than anyone tests, mostly once, on setups unlike yours. The research agent keeps a catalog of those claims for this system and tests the promising ones, so that only measured gains reach the code.

    +
    +
      {ol}
    +
    +

    What a status means

      {statuses}
    +

    "Replicated" means the finding held on this system's setup. It is a transfer test of the method, not a reproduction of the paper, and "did not transfer" is not a refutation of it.

    +

    Steering it

    +

    The agent takes direction from GitHub issues. The buttons on this site open one, filled in, for you to edit and submit; nothing is sent until you do. Labels:

    +
      {labs}
    +

    GitHub applies labels from a link only for people who can triage the repository. For anyone else, the research-action: line in the issue says what is asked.

    +
    +

    Files, not a service

    +

    Every claim is a YAML file in the repository ({link(site.file_url("schemas/evidence-claim.v1.json"), "schemas/evidence-claim.v1.json")}), and the roles and options are Backstage entity files. This site is built from them by site/build.py; data/claims.json holds the same records for other tools. The judge never reads the claims: what decides a change is only what it measures.

    +""" + return page(site, "How it works", body, "how.html") + + +# ---------------------------------------------------------------- build + + +def build(config_path: Path, out: Path, root: Path = ROOT) -> Site: + with config_path.open("rb") as f: + cfg = tomllib.load(f) + srcs = cfg.get("sources", {}) + schema_path = srcs.get("schema") + schema = json.loads((root / schema_path).read_text(encoding="utf-8")) if schema_path else None + claims = load_claims([root / d for d in srcs.get("claims", [])], root.resolve(), schema) + catalog = Catalog([d for p in srcs.get("catalog", []) for d in load_yaml_docs(root / p)]) + site = Site(cfg.get("title", "Morphogen research"), cfg["repo"], cfg.get("branch", "main"), cfg["system"], + cfg.get("labels", {}), claims, catalog) + + if out.exists(): + shutil.rmtree(out) + (out / "claims").mkdir(parents=True) + (out / "data").mkdir() + shutil.copytree(HERE / "static", out / "assets") + write = lambda rel, text: (out / rel).write_text(text, encoding="utf-8") # noqa: E731 + write("index.html", render_index(site)) + write("roles.html", render_roles(site)) + write("predictions.html", render_predictions(site)) + write("how.html", render_how(site)) + for c in claims: + write(f"claims/{c.name}.html", render_claim(site, c)) + data = [{"name": c.name, "path": c.path, "status": c.status(site.system), "date": c.date(), + "record": _jsonable(c.doc)} for c in sort_claims(claims)] + write("data/claims.json", json.dumps({"system": site.system, "claims": data}, indent=1, ensure_ascii=False)) + write(".nojekyll", "") + return site + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--config", type=Path, default=HERE / "config.toml") + ap.add_argument("--out", type=Path, default=HERE / "_build") + args = ap.parse_args(argv) + site = build(args.config, args.out) + print(f"build: {len(site.claims)} claims, {len(site.catalog.roles)} roles, {len(site.catalog.options)} options -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/site/config.toml b/site/config.toml new file mode 100644 index 0000000..5cf92b6 --- /dev/null +++ b/site/config.toml @@ -0,0 +1,27 @@ +# What site/build.py reads. Paths are relative to the repository root. +title = "Morphogen research" +# Where steering issues go, and where claim files are linked on GitHub. +repo = "OpenReplicant/Morphogen" +branch = "main" +# The System whose status each claim is shown with (an assessment's `system`). +system = "system:default/metasoar" + +[sources] +# Directories searched recursively for EvidenceClaim files (*.yaml, *.yml). +claims = ["demos/research-loop/claims"] +# Backstage entity files: the map (roles, this system's conditions) and the options. +catalog = [ + "demos/research-loop/catalog-info.yaml", + "demos/research-loop/catalog/map.yaml", + "demos/research-loop/catalog/options.yaml", +] +schema = "schemas/evidence-claim.v1.json" + +# The labels the research agent reads its steering from. A label is applied only when the person opening the issue +# can triage the repository; for anyone else GitHub drops it, and the `research-action:` line in the body still says +# what is asked. +[labels] +prioritise = ["research:prioritise"] +reject = ["research:reject"] +dispute = ["research:question"] +question = ["research:question"] diff --git a/site/static/app.js b/site/static/app.js new file mode 100644 index 0000000..91ade71 --- /dev/null +++ b/site/static/app.js @@ -0,0 +1,50 @@ +// The feed's filters: search, role, source and status, all in the page (no requests). The filters are kept in the +// address (?q=&role=&source=&status=) so a filtered view can be shared. Without JavaScript every claim is listed. +(function () { + var form = document.getElementById("filters"); + var list = document.getElementById("claims"); + if (!form || !list) return; + var items = Array.prototype.slice.call(list.querySelectorAll("li[data-name]")); + var count = document.getElementById("count"); + var empty = document.getElementById("empty"); + var boxes = Array.prototype.slice.call(form.querySelectorAll("input[name=status]")); + form.hidden = false; + + var params = new URLSearchParams(location.search); + if (params.has("q")) form.q.value = params.get("q"); + if (params.has("role")) form.role.value = params.get("role"); + if (params.has("source")) form.source.value = params.get("source"); + if (params.has("status")) { + var want = params.get("status").split(","); + boxes.forEach(function (b) { b.checked = want.indexOf(b.value) !== -1; }); + } + + function apply() { + var words = form.q.value.toLowerCase().split(/\s+/).filter(Boolean); + var role = form.role.value, source = form.source.value; + var statuses = boxes.filter(function (b) { return b.checked; }).map(function (b) { return b.value; }); + var shown = 0; + items.forEach(function (li) { + var d = li.dataset; + var ok = (!role || d.role === role) && (!source || d.source === source) && + statuses.indexOf(d.status) !== -1 && + words.every(function (w) { return d.search.indexOf(w) !== -1; }); + li.hidden = !ok; + if (ok) shown++; + }); + count.textContent = shown + " of " + items.length + " claims"; + empty.hidden = shown !== 0; + var p = new URLSearchParams(); + if (form.q.value) p.set("q", form.q.value); + if (role) p.set("role", role); + if (source) p.set("source", source); + var defaults = boxes.every(function (b) { return b.checked === b.defaultChecked; }); + if (!defaults) p.set("status", statuses.join(",")); + var qs = p.toString(); + history.replaceState(null, "", qs ? "?" + qs : location.pathname); + } + form.addEventListener("input", apply); + form.addEventListener("change", apply); + form.addEventListener("submit", function (ev) { ev.preventDefault(); }); + apply(); +})(); diff --git a/site/static/icon.svg b/site/static/icon.svg new file mode 100644 index 0000000..d08e915 --- /dev/null +++ b/site/static/icon.svg @@ -0,0 +1 @@ + diff --git a/site/static/style.css b/site/static/style.css new file mode 100644 index 0000000..fa2bd03 --- /dev/null +++ b/site/static/style.css @@ -0,0 +1,275 @@ +/* Morphogen research. Loosely after openreplicant.com: near-black panels, cyan and magenta, mono labels. + Light is a paper theme with darker inks so every pairing keeps 4.5:1 contrast. */ + +:root { + --bg: #f5f5f0; + --panel: #ffffff; + --panel-2: #ecece6; + --border: #d6d6cf; + --text: #14141c; + --muted: #55556a; + --accent: #006e78; + --accent-2: #7a10a8; + --accent-soft: rgba(0, 110, 120, 0.09); + --ring: #006e78; + --good: #1d6b3a; + --good-bg: #e2f2e7; + --bad: #9d1a4f; + --bad-bg: #f8e3ec; + --pred: #005f80; + --pred-bg: #e0f0f6; + --idle: #4d4d5c; + --idle-bg: #ebebef; + --warn: #7a4b00; + --warn-bg: #f7ecd9; + --ours: #5f1d8a; + --ours-bg: #f0e6f7; + --grid: rgba(20, 20, 28, 0.045); + --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --mono: ui-monospace, "SFMono-Regular", "Cascadia Mono", Menlo, Consolas, monospace; + --radius: 10px; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #0a0a0f; + --panel: #111118; + --panel-2: #161620; + --border: #2a2a3a; + --text: #e8e8f0; + --muted: #9a9ab0; + --accent: #00f2ff; + --accent-2: #d25cff; + --accent-soft: rgba(0, 242, 255, 0.08); + --ring: #00f2ff; + --good: #6ee39a; + --good-bg: rgba(110, 227, 154, 0.1); + --bad: #ff7aa8; + --bad-bg: rgba(255, 122, 168, 0.1); + --pred: #5fd8f5; + --pred-bg: rgba(95, 216, 245, 0.1); + --idle: #b4b4c6; + --idle-bg: rgba(180, 180, 198, 0.1); + --warn: #f3c46b; + --warn-bg: rgba(243, 196, 107, 0.1); + --ours: #d9a3ff; + --ours-bg: rgba(217, 163, 255, 0.1); + --grid: rgba(0, 242, 255, 0.035); + color-scheme: dark; + } +} + +:root[data-theme="dark"] { + --bg: #0a0a0f; + --panel: #111118; + --panel-2: #161620; + --border: #2a2a3a; + --text: #e8e8f0; + --muted: #9a9ab0; + --accent: #00f2ff; + --accent-2: #d25cff; + --accent-soft: rgba(0, 242, 255, 0.08); + --ring: #00f2ff; + --good: #6ee39a; + --good-bg: rgba(110, 227, 154, 0.1); + --bad: #ff7aa8; + --bad-bg: rgba(255, 122, 168, 0.1); + --pred: #5fd8f5; + --pred-bg: rgba(95, 216, 245, 0.1); + --idle: #b4b4c6; + --idle-bg: rgba(180, 180, 198, 0.1); + --warn: #f3c46b; + --warn-bg: rgba(243, 196, 107, 0.1); + --ours: #d9a3ff; + --ours-bg: rgba(217, 163, 255, 0.1); + --grid: rgba(0, 242, 255, 0.035); + color-scheme: dark; +} + +*, *::before, *::after { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + background: var(--bg); + background-image: linear-gradient(var(--grid) 1px, transparent 1px), linear-gradient(90deg, var(--grid) 1px, transparent 1px); + background-size: 28px 28px; + color: var(--text); + font: 16px/1.55 var(--font); + overflow-wrap: anywhere; +} + +a { color: var(--accent); text-decoration-thickness: 1px; text-underline-offset: 3px; } +a:hover { color: var(--accent-2); } +:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; border-radius: 4px; } + +h1, h2, h3, h4 { line-height: 1.2; margin: 0 0 0.5em; letter-spacing: -0.01em; } +h1 { font-size: clamp(1.7rem, 1.2rem + 2.2vw, 2.6rem); font-weight: 750; } +h2 { font-size: 1.15rem; } +h3 { font-size: 1rem; } +p { margin: 0 0 0.9em; } + +.wrap { max-width: 1040px; margin: 0 auto; padding: 0 16px; } +.mono { font-family: var(--mono); font-size: 0.92em; } +.muted { color: var(--muted); } +.small { font-size: 0.875rem; } +.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } +.skip { position: absolute; left: -999px; top: 8px; background: var(--panel); padding: 8px 12px; z-index: 10; } +.skip:focus { left: 8px; } + +/* Header */ +.top { border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--panel) 88%, transparent); position: sticky; top: 0; z-index: 5; backdrop-filter: blur(8px); } +.top-in { max-width: 1040px; margin: 0 auto; padding: 10px 16px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } +.brand { color: var(--text); text-decoration: none; font-weight: 750; letter-spacing: 0.04em; display: inline-flex; align-items: center; gap: 8px; } +.brand:hover { color: var(--text); } +.brand-mark { color: var(--accent); font-size: 1.2rem; } +.brand-sub { font-family: var(--mono); font-weight: 500; color: var(--accent-2); font-size: 0.85rem; letter-spacing: 0.08em; text-transform: uppercase; } +.top nav { margin-left: auto; } +.top nav ul { list-style: none; display: flex; gap: 4px; margin: 0; padding: 0; flex-wrap: wrap; } +.top nav a { color: var(--muted); text-decoration: none; padding: 6px 10px; border-radius: 8px; font-size: 0.92rem; } +.top nav a:hover { color: var(--text); background: var(--accent-soft); } +.top nav a[aria-current] { color: var(--text); box-shadow: inset 0 -2px 0 var(--accent); border-radius: 0; } +.theme { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); border-radius: 8px; height: 34px; padding: 0 10px; font: 600 0.75rem var(--mono); text-transform: uppercase; letter-spacing: 0.06em; cursor: pointer; } +.theme:hover { border-color: var(--accent); } +@media (max-width: 640px) { + .top nav { order: 3; margin-left: 0; width: 100%; } + .top-in { gap: 8px; } + .theme { margin-left: auto; } +} + +/* Hero */ +.hero { padding: 48px 0 24px; max-width: 760px; } +.small-hero { padding-top: 40px; } +.eyebrow { font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.12em; font-size: 0.75rem; color: var(--accent-2); margin-bottom: 0.6em; } +.lede { font-size: 1.08rem; color: var(--muted); } +.stats { list-style: none; padding: 0; margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px 18px; } +.stats li { display: inline-flex; align-items: center; gap: 8px; } +.stat-n { font-family: var(--mono); font-size: 1.4rem; font-weight: 700; } +.actions { display: flex; flex-wrap: wrap; gap: 10px; } + +.btn { display: inline-block; padding: 9px 14px; border-radius: 8px; background: var(--accent); color: var(--bg); text-decoration: none; font-weight: 650; font-size: 0.92rem; border: 1px solid var(--accent); } +.btn:hover { color: var(--bg); background: var(--accent-2); border-color: var(--accent-2); } +.btn.ghost { background: transparent; color: var(--accent); } +.btn.ghost:hover { color: var(--accent-2); border-color: var(--accent-2); background: var(--accent-soft); } + +/* Badges */ +.badge { display: inline-block; font-family: var(--mono); font-size: 0.75rem; font-weight: 650; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; white-space: nowrap; } +.s-replicated { color: var(--good); background: var(--good-bg); } +.s-did-not-transfer { color: var(--bad); background: var(--bad-bg); } +.s-predicted { color: var(--pred); background: var(--pred-bg); } +.s-untested { color: var(--idle); background: var(--idle-bg); border-style: dashed; } +.s-not-testable { color: var(--warn); background: var(--warn-bg); border-style: dotted; } +.s-observation { color: var(--ours); background: var(--ours-bg); } +.qs { font-family: var(--mono); font-size: 0.72rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; } +.q-checked { color: var(--good); } +.q-checked::before { content: "✓ "; } +.q-unchecked::before { content: "? "; } +.q-none::before { content: ""; } +.q-via { color: var(--warn); } +.tag { font-family: var(--mono); font-size: 0.75rem; padding: 1px 6px; border-radius: 5px; background: var(--panel-2); border: 1px solid var(--border); color: var(--muted); } +.n { font-family: var(--mono); font-size: 0.8rem; color: var(--muted); margin-left: 2px; } + +/* Meter */ +.meter-wrap { display: inline-flex; align-items: center; gap: 8px; } +.meter { width: 72px; height: 8px; } +.meter-track { fill: var(--panel-2); stroke: var(--border); stroke-width: 0.5; } +.meter-fill { fill: var(--accent); } +.meter-num { white-space: nowrap; font-family: var(--mono); font-size: 0.85rem; font-weight: 650; } + +/* Filters */ +.filters { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px; margin: 8px 0 12px; display: grid; gap: 12px; } +.f-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: end; border: 0; margin: 0; padding: 0; min-width: 0; } +.f-row label { display: grid; gap: 4px; } +.f-search { flex: 1 1 260px; } +.f-lab { font-family: var(--mono); font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); } +.f-status legend { margin-bottom: 6px; float: left; width: 100%; } +input[type=search], select { font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; min-width: 0; max-width: 100%; } +input[type=search] { width: 100%; } +select { max-width: 320px; } +input[type=search]:focus, select:focus { border-color: var(--accent); } +.chk { display: inline-flex !important; grid-auto-flow: column; align-items: center; gap: 6px; font-size: 0.9rem; padding: 4px 10px; border: 1px solid var(--border); border-radius: 999px; cursor: pointer; background: var(--bg); } +.chk:has(input:checked) { border-color: var(--accent); background: var(--accent-soft); } +.chk input { accent-color: var(--accent); margin: 0; } +.count { font-family: var(--mono); font-size: 0.85rem; color: var(--muted); min-height: 1.3em; } + +/* Feed */ +.feed { list-style: none; padding: 0; margin: 0 0 40px; display: grid; gap: 10px; } +.card { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; position: relative; transition: border-color 0.15s, transform 0.15s; } +.item:hover .card { border-color: var(--accent); } +.card h3 { font-size: 1.02rem; font-weight: 620; margin: 8px 0 6px; } +.card h3 a { color: var(--text); text-decoration: none; } +.card h3 a::after { content: ""; position: absolute; inset: 0; border-radius: var(--radius); } +.card h3 a:hover { color: var(--accent); } +.card-top { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; } +.card-top .meter-wrap { margin-left: auto; } +.meta { color: var(--muted); font-size: 0.85rem; margin: 0; } +.empty { color: var(--muted); padding: 24px 0; } + +/* Panels and claim page */ +.panel { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 18px 20px; margin: 0 0 16px; } +.panel h2 { font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.8rem; color: var(--accent-2); } +.panel h3 { margin-top: 1em; } +.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 16px; align-items: start; } +.cols > .panel { margin: 0; } +.cols + .panel, .cols + section { margin-top: 16px; } +.crumbs { margin: 24px 0 8px; font-size: 0.9rem; color: var(--muted); } +.claim-head { padding: 8px 0 20px; max-width: 820px; } +.claim-head h1 { font-size: clamp(1.4rem, 1.1rem + 1.4vw, 2rem); margin-top: 12px; } +.statement { font-size: 1.05rem; color: var(--muted); } +.kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0 0 12px; } +.kv dt { font-family: var(--mono); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); padding-top: 3px; } +.kv dd { margin: 0; } +@media (max-width: 520px) { .kv { grid-template-columns: 1fr; } .kv dd { margin-bottom: 6px; } } +.also { border-top: 1px dashed var(--border); padding-top: 10px; } +.plain { list-style: none; padding: 0; margin: 0 0 8px; display: grid; gap: 6px; } +.unstated li::before { content: "? "; color: var(--warn); font-family: var(--mono); } +.verbatim { margin: 8px 0 12px; padding: 10px 14px; border-left: 3px solid var(--accent); background: var(--accent-soft); border-radius: 0 8px 8px 0; font-family: var(--mono); font-size: 0.88rem; white-space: pre-wrap; } +.verbatim p { margin: 0; } +.verbatim.via { border-left-color: var(--warn); background: var(--warn-bg); font-family: var(--font); font-size: 0.95rem; } +.verbatim footer { margin-top: 6px; font-size: 0.75rem; white-space: normal; } +.qhead { margin: 12px 0 4px; display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: baseline; } +.assess + .assess { border-top: 1px solid var(--border); margin-top: 14px; padding-top: 14px; } +.assess-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.pred, .outcome { border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; margin: 12px 0; background: var(--bg); } +.pred-p .meter { width: 160px; height: 10px; } +.steer { border: 1px solid var(--accent); background: var(--accent-soft); border-radius: var(--radius); padding: 18px 20px; margin: 0 0 16px; } +.steer h2 { font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.8rem; color: var(--accent); } + +/* Roles */ +.role h2 { font-family: var(--mono); text-transform: none; letter-spacing: 0; font-size: 1.3rem; color: var(--text); } +.opts { list-style: none; padding: 0; margin: 0 0 12px; display: grid; gap: 10px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); } +.opt { border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; background: var(--bg); } +.opt:target, .role:target, .conds li:target { outline: 2px solid var(--accent); outline-offset: 2px; } +.opt h4 { margin: 0 0 6px; color: var(--accent); } +.opt p { font-size: 0.9rem; } +details summary { cursor: pointer; color: var(--accent); font-size: 0.9rem; } +details ul { margin-top: 8px; font-size: 0.88rem; } +.conds li { padding: 8px 0; border-top: 1px solid var(--border); } + +/* Predictions */ +.calib { width: 100%; max-width: 440px; height: auto; display: block; margin: 8px auto 0; } +.calib .grid { stroke: var(--border); stroke-width: 1; } +.calib .diag { stroke: var(--muted); stroke-width: 1.5; stroke-dasharray: 4 4; } +.calib .dot circle { fill: var(--accent); fill-opacity: 0.85; stroke: var(--panel); stroke-width: 2; } +.calib .wait { fill: var(--accent-2); } +.calib .tick, .calib .axis { fill: var(--muted); font: 11px var(--mono); } +.tbl { width: 100%; border-collapse: collapse; font-size: 0.92rem; } +.tbl th { text-align: left; font-family: var(--mono); font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); font-weight: 500; padding: 6px 8px 6px 0; border-bottom: 1px solid var(--border); } +.tbl td:last-child { white-space: nowrap; } +.tbl td { padding: 8px 8px 8px 0; border-bottom: 1px solid var(--border); vertical-align: top; } + +/* How it works */ +.loop { list-style: none; padding: 0; margin: 8px 0 24px; display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); counter-reset: none; } +.loop li { display: flex; gap: 14px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; } +.loop li:last-child { border-color: var(--accent); } +.step-n { color: var(--accent); font-size: 1.3rem; font-weight: 700; line-height: 1; padding-top: 2px; } +.loop h3 { margin-bottom: 4px; } +.loop p { margin: 0; color: var(--muted); font-size: 0.93rem; } +.statuses li { display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; } + +.foot { color: var(--muted); font-size: 0.85rem; padding-top: 24px; padding-bottom: 40px; border-top: 1px solid var(--border); margin-top: 32px; } + +@media (prefers-reduced-motion: reduce) { * { transition: none !important; } } +@media (forced-colors: active) { .badge, .btn, .card, .panel { border: 1px solid CanvasText; } .meter-fill { fill: Highlight; } } diff --git a/site/static/theme.js b/site/static/theme.js new file mode 100644 index 0000000..0e66425 --- /dev/null +++ b/site/static/theme.js @@ -0,0 +1,30 @@ +// Colour theme: the system's by default; the button cycles system, light, dark and remembers the choice in this +// browser only. Loaded in so the page never flashes the wrong theme. +(function () { + var root = document.documentElement; + var order = ["system", "light", "dark"]; + function read() { + try { return localStorage.getItem("theme") || "system"; } catch (err) { return "system"; } + } + function apply(choice) { + if (choice === "light" || choice === "dark") root.setAttribute("data-theme", choice); + else root.removeAttribute("data-theme"); + var btn = document.querySelector("[data-theme-toggle]"); + if (btn) { + btn.setAttribute("aria-label", "Colour theme: " + choice); + btn.title = "Colour theme: " + choice; + btn.textContent = choice === "light" ? "Light" : choice === "dark" ? "Dark" : "Auto"; + } + } + apply(read()); + document.addEventListener("DOMContentLoaded", function () { + apply(read()); + var btn = document.querySelector("[data-theme-toggle]"); + if (!btn) return; + btn.addEventListener("click", function () { + var next = order[(order.indexOf(read()) + 1) % order.length]; + try { localStorage.setItem("theme", next); } catch (err) { /* private mode: not remembered */ } + apply(next); + }); + }); +})(); diff --git a/tests/test_site.py b/tests/test_site.py new file mode 100644 index 0000000..698a959 --- /dev/null +++ b/tests/test_site.py @@ -0,0 +1,214 @@ +"""The research site's build (site/build.py): real input renders, issue links are well formed, and text from papers +is escaped.""" + +import copy +import html +import importlib.util +import json +import re +import shutil +import sys +import tempfile +import unittest +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import yaml + +ROOT = Path(__file__).resolve().parent.parent +_spec = importlib.util.spec_from_file_location("site_build", ROOT / "site" / "build.py") +build = importlib.util.module_from_spec(_spec) +sys.modules["site_build"] = build # dataclasses look their module up here +_spec.loader.exec_module(build) + +HOSTILE = '' + +CLAIM = { + "apiVersion": "morphogen.dev/v1alpha1", + "kind": "EvidenceClaim", + "metadata": {"name": "hostile-claim", "description": "Method X wins " + HOSTILE}, + "spec": { + "about": "component:default/opt-x", + "role": "component:default/role-x", + "source": { + "kind": "preprint", "title": "A paper " + HOSTILE, "id": "arXiv:2611.00001", + "url": "javascript:alert(1)", "version": "v1", "location": "Table 1 " + HOSTILE, + "read": "in full", "quote": 'It "wins" & beats ' + HOSTILE, "quote_status": "unchecked", + }, + "claim": {"statement": "X beats Y " + HOSTILE, "finding": "better", "reporting": "self", + "metric": "accuracy " + HOSTILE, "value": 0.9, "baseline": {"name": "Y", "value": 0.8}}, + "conditions": {"models": [{"name": "M " + HOSTILE}], "unstated": ["hardware " + HOSTILE]}, + "assessments": [{ + "system": "system:default/sys", "status": "predicted", "date": "2026-11-27", + "prediction": {"p_transfer": 0.4, "reason": "Different model " + HOSTILE, "by": "test " + HOSTILE, + "date": "2026-11-27", "before_outcome": True}, + }], + }, +} + +CATALOG = [ + {"apiVersion": "backstage.io/v1alpha1", "kind": "System", "metadata": {"name": "sys", "description": "S " + HOSTILE}, + "spec": {"owner": "group:default/g"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", + "metadata": {"name": "role-x", "description": "The role " + HOSTILE}, + "spec": {"type": "role", "lifecycle": "experimental", "owner": "group:default/g"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", + "metadata": {"name": "opt-x", "description": "Option " + HOSTILE}, + "spec": {"type": "method", "lifecycle": "candidate", "owner": "group:default/g", + "morphogen": {"fills": "component:default/role-x", "evaluation": {"result": "R " + HOSTILE}}}}, +] + + +def make_project(root: Path, claims: list[dict]) -> Path: + (root / "claims").mkdir(parents=True) + (root / "schemas").mkdir() + shutil.copy(ROOT / "schemas" / "evidence-claim.v1.json", root / "schemas") + for c in claims: + (root / "claims" / f"{c['metadata']['name']}.yaml").write_text(yaml.safe_dump(c), encoding="utf-8") + (root / "catalog.yaml").write_text(yaml.safe_dump_all(CATALOG), encoding="utf-8") + cfg = root / "config.toml" + cfg.write_text('repo = "Owner/Repo"\nsystem = "system:default/sys"\n[sources]\nclaims = ["claims"]\n' + 'catalog = ["catalog.yaml"]\nschema = "schemas/evidence-claim.v1.json"\n' + '[labels]\nprioritise = ["research:prioritise"]\nreject = ["research:reject"]\n' + 'dispute = ["research:question"]\nquestion = ["research:question"]\n', encoding="utf-8") + return cfg + + +def all_html(out: Path) -> str: + return "\n".join(p.read_text(encoding="utf-8") for p in sorted(out.rglob("*.html"))) + + +class RealInput(unittest.TestCase): + """The phase-0 claims in demos/research-loop, through site/config.toml.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.out = Path(cls.tmp.name) / "out" + cls.site = build.build(ROOT / "site" / "config.toml", cls.out) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_every_claim_has_a_page_and_a_feed_entry(self): + names = {c.name for c in self.site.claims} + self.assertEqual(len(names), 25) + self.assertEqual({p.stem for p in (self.out / "claims").glob("*.html")}, names) + index = (self.out / "index.html").read_text(encoding="utf-8") + self.assertEqual(set(re.findall(r'
  • ]+(src|href)="https?://') + self.assertNotIn("