diff --git a/CLAUDE.md b/CLAUDE.md index b3130fb..d2f87fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ docs/restart/LESSONS.md. `otel`), `project.py` (the cell format: `spec.morphogen` on the catalog's entities, default deny), `backstage.py` (the catalog: `catalog-info.yaml` and its Location targets, read into cells, interfaces and settings), `status.py` (where a project stands and the next step), - `documents.py` (the project's settings, from the System's `spec.morphogen`, and the target spec a cell compiles to), `request.py` (one document in, one verdict out), `pullrequest.py` (`morphogen pr`: a pull request as the GitHub judge, `.github/workflows/judge.yml`, hands it to the judge as a request), `intake.py` (the judge held by another user: a candidate arrives as a git bundle), `research.py` (the research loop's deterministic half: arXiv watch, paper text, quote checks, claim files, steering, the queue; never imported by the judge), `cli.py`, `mcp_server.py`, `ui.py` and `ui.html` (the read-only web UI). + `documents.py` (the project's settings, from the System's `spec.morphogen`, and the target spec a cell compiles to), `request.py` (one document in, one verdict out), `pullrequest.py` (`morphogen pr`: a pull request as the GitHub judge, `.github/workflows/judge.yml`, hands it to the judge as a request), `intake.py` (the judge held by another user: a candidate arrives as a git bundle), `research.py` (the research loop's deterministic half: arXiv watch, paper text, quote checks, claim files, steering, the queue; never imported by the judge), `site.py` (`morphogen site init` and `build`: the research site for any system), `cli.py`, `mcp_server.py`, `ui.py` and `ui.html` (the read-only web UI). - `.claude-plugin/`, `skills/`, `agents/`: the Claude Code plugin around the MCP server. Skills (the kit): `morphogen` (improve a cell), `map` (take a system apart into Backstage entity files and draft cells), `catalog` and `research` (options for a role, as `lifecycle: candidate` Components), `research-loop` (one session of @@ -20,7 +20,8 @@ docs/restart/LESSONS.md. 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 with Astro (`site/src/`) from the evidence claims, the map and the - options (`site/README.md`); `.github/workflows/site.yml` deploys it to Pages when started by hand. + options named in a config file (`site/README.md`): `site/config.toml` for the demo, anyone's own through + `morphogen site build`. `.github/workflows/site.yml` deploys the demo 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/README.md b/README.md index 57378a8..4f1cf30 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ directory, so it can only answer. The cell's `description` is its objective. | Optimizers | `optimize.py` | a catalog behind one contract: grid, random, hill-climb (with `restarts`) and simulated annealing (`anneal`), built in; Optuna and GEPA adapters (optional extras); and the `selector`, whose bandit policy (primed by earlier verdicts, with a stagnation signal) chooses which proposes next. A model-based policy is planned; packages add more through the `morphogen.optimizers` entry point. `tune` checks, writes and probes each proposal and judges the best | | Interfaces | `cli.py`, `mcp_server.py`, `ui.py` | the command line, an MCP server with 13 tools, and a local read-only web UI | | Plugin | `.claude-plugin/`, `skills/`, `agents/` | the Claude Code plugin around the MCP server; the skills (`map`, `catalog`, `research`, `morphogen`) are plain Agent Skills any harness can load | +| Research site | `site/`, `site.py` | a static site for any system's research loop, from its claims, map and options: a page per claim, paper, trial, model, option and role with links both ways, the queue, predictions and calibration, and steering links into its own repository. `morphogen site init` writes a starter `site.toml` into a research project, `morphogen site build --config site.toml --out _site [--base /research]` builds it, and `skills/research-loop/research-site.yml` deploys it to GitHub Pages ([site/README.md](site/README.md)) | | Schemas | `schemas/` | the evidence record (v1); the `spec.morphogen` fields of the catalog entities the code loads (v1; a test keeps them equal); the research loop's evidence claim (v1, draft) | ### The system guard diff --git a/morphogen/cli.py b/morphogen/cli.py index 787e424..c58f323 100644 --- a/morphogen/cli.py +++ b/morphogen/cli.py @@ -10,6 +10,8 @@ morphogen optimizers morphogen evidence [--verify] [--limit N] [--by judge] morphogen ui [--host 127.0.0.1] [--port 8765] + morphogen site init [ROOT] [--repo OWNER/NAME] [--system system:default/NAME] # a starter research site config + morphogen site build --config FILE --out DIR [--base /prefix] # the static research site TARGET is `cell:NAME` for a cell with a `run` in the catalog (`spec.morphogen.run` on its entity) (or the cell's name, or its `dir`). """ @@ -178,6 +180,23 @@ def cmd_ui(a) -> int: return 0 +def cmd_site(a) -> int: + from . import site + try: + if a.action == "init": + _print(site.init(a.root, repo=a.repo, system=a.system, title=a.title, owner=a.owner, config=a.config_name, + content=a.content, force=a.force)) + else: + if not a.config or not a.out: + print("morphogen: site build needs --config and --out", file=sys.stderr) + return 2 + print(f"Built {site.build(a.config, a.out, a.base or '', install=a.install)}") + except site.SiteError as e: + print(f"morphogen: {e}", file=sys.stderr) + return 2 + return 0 + + def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="morphogen", description=__doc__.split("\n\n")[0]) sub = ap.add_subparsers(dest="command", required=True) @@ -264,6 +283,25 @@ def main(argv: list[str] | None = None) -> int: ui.add_argument("--port", type=int, default=8765) ui.set_defaults(fn=cmd_ui) + si = sub.add_parser("site", help="the research site: init writes a starter config and content folder into a " + "research project; build makes the static site from a config (site/README.md)") + si.add_argument("action", choices=["init", "build"]) + si.add_argument("root", nargs="?", default=".", help="for init: the research project (catalog-info.yaml, " + "claims/, research/); default: here") + si.add_argument("--config", help="for build: the site's config file") + si.add_argument("--out", help="for build: the folder to write the HTML into") + si.add_argument("--base", help="for build: the path the site is served under, e.g. /research (default: " + "relative links, which work under any path)") + si.add_argument("--install", action="store_true", help="for build: run npm ci in site/ first if needed") + si.add_argument("--repo", help="for init: OWNER/NAME for steering issues (default: the origin remote)") + si.add_argument("--system", help="for init: the System to assess against (default: catalog-info.yaml's)") + si.add_argument("--title", help="for init: the site's title") + si.add_argument("--owner", help="for init: whose research it is (default: the repo's owner)") + si.add_argument("--config-name", default="site.toml", help="for init: the config file, in ROOT") + si.add_argument("--content", default="site", help="for init: the content folder, in ROOT") + si.add_argument("--force", action="store_true", help="for init: replace existing files") + si.set_defaults(fn=cmd_site) + a = ap.parse_args(argv) try: return a.fn(a) diff --git a/morphogen/site.py b/morphogen/site.py new file mode 100644 index 0000000..f6f3710 --- /dev/null +++ b/morphogen/site.py @@ -0,0 +1,168 @@ +"""The research site for any system (site/README.md): `morphogen site init` writes a starter config and content +folder into a research project, and `morphogen site build` builds the static site from it with the Astro sources in +Morphogen's `site/` folder. The build itself is `npm run build` there, given the config, the output folder and the +base path in MORPHOGEN_SITE_CONFIG, MORPHOGEN_SITE_OUT and MORPHOGEN_SITE_BASE; this module only sets them.""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import tomllib +from pathlib import Path + +import yaml + +SITE = Path(__file__).resolve().parent.parent / "site" +LABELS = {"prioritise": ["research:prioritise"], "reject": ["research:reject"], "dispute": ["research:question"], + "question": ["research:question"], "propose-role": ["research:question"], + "propose-option": ["research:question"]} + + +class SiteError(Exception): + pass + + +def site_dir() -> Path: + d = Path(os.environ.get("MORPHOGEN_SITE_SRC") or SITE) + if not (d / "package.json").is_file(): + raise SiteError(f"the site's sources are not at {d}: run Morphogen from a clone or the Claude Code plugin " + "(the Python package alone does not carry site/), or set MORPHOGEN_SITE_SRC") + return d + + +def build(config: str | Path, out: str | Path, base: str = "", install: bool = False) -> Path: + """Build the site from `config` into `out`. Returns the output folder.""" + d = site_dir() + config, out = Path(config).resolve(), Path(out).resolve() + if not config.is_file(): + raise SiteError(f"no config file at {config} (morphogen site init writes one)") + try: + tomllib.loads(config.read_text(encoding="utf-8")) + except tomllib.TOMLDecodeError as e: + raise SiteError(f"{config} is not valid TOML: {e}") from e + npm = shutil.which("npm") + if npm is None: + raise SiteError("the site needs Node 22.23.4 or later and npm") + if not (d / "node_modules" / "astro").is_dir(): + if not install: + raise SiteError(f"the site's packages are not installed: run `npm ci --ignore-scripts` in {d}, " + "or pass --install") + subprocess.run([npm, "ci", "--ignore-scripts", "--no-fund", "--no-audit"], cwd=d, check=True) + env = dict(os.environ, MORPHOGEN_SITE_CONFIG=str(config), MORPHOGEN_SITE_OUT=str(out), + MORPHOGEN_SITE_BASE=base or "", ASTRO_TELEMETRY_DISABLED="1") + r = subprocess.run([npm, "run", "--silent", "build", "--", "--force"], cwd=d, env=env) + if r.returncode: + raise SiteError(f"the build failed (exit {r.returncode}); its errors are above") + return out + + +def _git_repo(root: Path) -> str | None: + """owner/name of the GitHub remote `origin`, if there is one.""" + try: + url = subprocess.run(["git", "-C", str(root), "remote", "get-url", "origin"], capture_output=True, + text=True, timeout=10).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + m = re.search(r"github\.com[:/]([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+?)(?:\.git)?/?$", url) + return f"{m[1]}/{m[2]}" if m else None + + +def _system(root: Path) -> str | None: + """system:default/NAME of the first System in the project's catalog-info.yaml.""" + f = root / "catalog-info.yaml" + if not f.is_file(): + return None + for doc in yaml.safe_load_all(f.read_text(encoding="utf-8")): + if isinstance(doc, dict) and doc.get("kind") == "System" and (doc.get("metadata") or {}).get("name"): + ns = doc["metadata"].get("namespace", "default") + return f"system:{ns}/{doc['metadata']['name']}" + return None + + +def _q(s: str) -> str: + return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +CONFIG = """\ +# The research site for {title_plain} (Morphogen's site/README.md, "The config file"). Paths are relative to this +# file. Build it: morphogen site build --config {config_rel} --out _site [--base /research] + +[site] +title = {title} +description = {description} +owner = {owner} +# Steering issues open here, and claim files are linked here on GitHub. +repo = {repo} +branch = "main" +# The System each claim's status is shown for: the `system` of its assessments. +system = {system} + +[sources] +claims = ["claims"] # searched recursively for EvidenceClaim files +catalog = ["catalog-info.yaml", "catalog"] # Backstage entity files, or folders of them; a missing one is skipped +research = "research" # queue.json, watch.yaml, seen.jsonl, index.json (each optional) +content = {content} # Markdown pages + +# The labels on each steering link (the agent reads the `research-action:` line in the body first). +[labels] +{labels} + +[theme] +# css = "site-theme.css" # loaded after the default style; override its custom properties (--accent, --bg...) +# logo = "logo.svg" # in the header, and the icon + +[nav] +# Any of: claims, queue, predictions, roles, map, notes, search. Pages with `nav: N` in front matter come after. +pages = ["claims", "queue", "predictions", "roles", "map", "notes"] +""" + +ABOUT = """\ +--- +title: About this site +description: What {title_plain} shows, and how to steer it. +kind: page +nav: 90 +blocks: [statuses, steering, files] +--- +This site lists claims from papers about options for the parts of {owner_plain}'s system, whether each is +expected to carry over to it, and what our own trials found. It is rebuilt from the files in the repository. + +Edit this page in `{content_rel}/about.md`. Every `.md` file in that folder becomes a page; give one +`kind: note` and a `date` to list it on the notes page, and `refs: [claim:NAME, resource:NAME]` to link it from +those pages. +""" + + +def init(root: str | Path, *, repo: str | None = None, system: str | None = None, title: str | None = None, + owner: str | None = None, config: str = "site.toml", content: str = "site", force: bool = False) -> dict: + """Write a starter config and content folder into the research project `root`. Returns what was written.""" + root = Path(root).resolve() + repo = repo or _git_repo(root) + system = system or _system(root) + if not repo: + raise SiteError("pass --repo OWNER/NAME (no GitHub remote named origin was found)") + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo): + raise SiteError(f"--repo must be OWNER/NAME, not {repo}") + if not system: + raise SiteError("pass --system system:default/NAME (no System in catalog-info.yaml)") + if not system.startswith("system:"): + system = f"system:default/{system}" + owner = owner or repo.split("/")[0] + title = title or f"{repo.split('/')[1]} research" + cfg, about = root / config, root / content / "about.md" + for f in (cfg, about): + if f.exists() and not force: + raise SiteError(f"{f} exists; pass --force to replace it") + labels = "\n".join(f"{k} = [{', '.join(_q(x) for x in v)}]" for k, v in LABELS.items()) + cfg.parent.mkdir(parents=True, exist_ok=True) + cfg.write_text(CONFIG.format( + title_plain=title, title=_q(title), config_rel=config, + description=_q(f"Claims from papers about options for {owner}'s system, with transfer predictions and outcomes."), + owner=_q(owner), repo=_q(repo), system=_q(system), content=_q(content), labels=labels), encoding="utf-8") + about.parent.mkdir(parents=True, exist_ok=True) + about.write_text(ABOUT.format(title_plain=title, owner_plain=owner, content_rel=content), encoding="utf-8") + return {"config": str(cfg), "content": str(about.parent), "repo": repo, "system": system, + "workflow_template": str(Path(__file__).resolve().parent.parent / "skills" / "research-loop" / "research-site.yml"), + "next": f"morphogen site build --config {cfg} --out _site"} diff --git a/site/README.md b/site/README.md index cb7beaa..332ddd2 100644 --- a/site/README.md +++ b/site/README.md @@ -1,33 +1,100 @@ # 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, with a page for every claim, paper, trial, model, option and role and the links between them. Built -with [Astro](https://astro.build) 7 into plain HTML in `_build/`; the interactive parts use +A static site for the research loop ([docs/research-loop.md](../docs/research-loop.md)), for any system running +Morphogen: the claims the research agent has catalogued, their status for that system, its transfer predictions +against outcomes, and the roles it watches for, with a page for every claim, paper, trial, model, option and role and +the links between them. Built with [Astro](https://astro.build) 7 into plain HTML; the interactive parts use [Alpine.js](https://alpinejs.dev)'s CSP build, served from the site itself. No server, no database, no tracking, -nothing loaded from another host. +nothing loaded from another host. Everything specific to one system (its sources, name, owner, repository, labels, +theme and navigation) comes from a config file; this folder holds only the templates. -## Build and preview +## Your own site -Needs Node 22.23.4 or later (the workflow uses 24.5.0). +```sh +uv run morphogen site init ROOT # writes ROOT/site.toml and ROOT/site/about.md +uv run morphogen site build --config ROOT/site.toml --out _site [--base /research] [--install] +``` + +`ROOT` is a research project (`catalog-info.yaml`, `catalog/`, `claims/`, `research/`). `init` takes the repository +from the `origin` remote and the System from `catalog-info.yaml` (or `--repo`, `--system`, `--title`, `--owner`) and +never overwrites without `--force`. `build` runs `npm run build` here with these variables, which can also be set by +hand: + +| Variable | Meaning | Default | +| --- | --- | --- | +| `MORPHOGEN_SITE_CONFIG` | the config file | `site/config.toml` (Morphogen's own demo) | +| `MORPHOGEN_SITE_OUT` | the folder to write | `site/_build` | +| `MORPHOGEN_SITE_BASE` | the path the site is served under, e.g. `/research`: every link and asset then starts with it | none: links are relative, which works under any path | + +To deploy on GitHub Pages, copy [skills/research-loop/research-site.yml](../skills/research-loop/research-site.yml) +to `.github/workflows/` in your repository and follow the steps at its top (set `SITE_CONFIG`, pin `MORPHOGEN_REF`, +set Pages to "GitHub Actions"). The research-loop skill has the same steps ("Set up your research site"). + +## The config file + +TOML; every path is relative to the file. `[site] repo` and `[site] system` are required; everything else has a +default. Unknown label actions or navigation pages, or a theme file that does not exist, stop the build. + +```toml +[site] +title = "Grove research" # header, page titles (default "Research") +description = "One sentence" # meta description of pages that have none of their own +owner = "The Growers" # whose research it is, in the footer (default: the repo's owner) +repo = "Growers/grove" # steering issues open here; claim files are linked here +branch = "main" +system = "system:default/orchard" # the System each claim's status is shown for (an assessment's `system`) +# repo_dir = ".." # the repository root, for claim-file links (default: found from .git) + +[sources] +claims = ["claims"] # searched recursively for EvidenceClaim files +catalog = ["catalog-info.yaml", "catalog"] # Backstage entity files or folders of them; a missing one is skipped +research = "research" # queue.json, watch.yaml, seen.jsonl, index.json (each optional) +content = "site" # Markdown pages (optional) +# schema = "evidence-claim.v1.json" # default: Morphogen's schemas/evidence-claim.v1.json + +[labels] # per steering action; the body's `research-action:` line comes first +prioritise = ["research:prioritise"] +reject = ["research:reject"] +dispute = ["research:question"] +question = ["research:question"] +propose-role = ["research:question"] +propose-option = ["research:question"] + +[theme] +css = "brand/theme.css" # served as assets/user/theme.css, after style.css: override its custom properties +logo = "brand/logo.svg" # .svg, .png, .webp or .jpg; in the header and as the icon + +[nav] +# The header's pages, in order, from: claims, queue, predictions, roles, map, notes (shown once a note exists), +# search; `{ page = "search", text = "Find" }` renames one. Markdown pages with `nav: N` follow. Every page is +# built either way. +pages = ["claims", "queue", "predictions", "roles", "map", "notes"] +``` + +Morphogen's own demo builds from [config.toml](config.toml), which points at [demos/research-loop](../demos/research-loop). + +## Working on the templates + +Needs Node 22.23.4 or later (the workflows use 24.5.0). ```sh cd site -npm ci # the exact versions in package-lock.json +npm ci --ignore-scripts # the exact versions in package-lock.json npm run dev # http://localhost:4321/index.html, rebuilt as you edit (YAML too, on reload) -npm run build # writes _build/ +npm run build # writes _build/ (or MORPHOGEN_SITE_OUT) from config.toml (or MORPHOGEN_SITE_CONFIG) npm run preview # serves _build/ npm test # the data layer's unit tests (node --test) cd .. && MORPHOGEN_SITE_TESTS=1 uv run python -m unittest tests.test_site -v # builds and checks real and hostile input ``` -`SITE_CONFIG`, `SITE_ROOT`, `SITE_CONTENT` and `SITE_OUT` point a build at another config, checkout, content folder or -output directory (the tests use them). The scripts set `ASTRO_TELEMETRY_DISABLED=1`. Without `npm ci` in `site/`, -`tests/test_site.py` is skipped (and fails instead when `MORPHOGEN_SITE_TESTS=1`). +The scripts set `ASTRO_TELEMETRY_DISABLED=1`. Without `npm ci` in `site/`, `tests/test_site.py` is skipped (and +fails instead when `MORPHOGEN_SITE_TESTS=1`). It builds the demo, a hostile fixture, and a made-up second system +through `morphogen site init` and `morphogen site build --base /lab` (another repository, other labels, a theme and +a shorter header), and checks that every link there resolves under `/lab/`. -## Adding a page: drop Markdown into `content/` +## Adding a page: drop Markdown into the content folder -Every `.md` file under `site/content/` becomes a page with the shared layout: `content/how.md` is `how.html`, +Every `.md` file under the config's `content` folder (`site/content/` for the demo) becomes a page with the shared layout: `content/how.md` is `how.html`, `content/notes/2026-11-27-inkling.md` is `notes/2026-11-27-inkling.html`. Front matter (checked by `src/content.config.mjs`; a page that breaks it stops the build): @@ -56,10 +123,9 @@ the content security policy still blocks any inline script. ## Where the data comes from -`config.toml` points at [demos/research-loop](../demos/research-loop): the claims under `claims/` (searched -recursively), the map, `options.yaml` and the agent's `found.yaml` (a missing catalog file is skipped), and the -agent's own files in `research/`: `queue.json`, `watch.yaml`, `seen.jsonl`, and `index.json`, which the build checks -against the claim files. `src/lib/data.mjs` reads them all, validates every claim against +The config's sources: the claims (searched recursively), the catalog files (the map, the options and the agent's +`found.yaml`), and the agent's own files in `research`: `queue.json`, `watch.yaml`, `seen.jsonl`, and `index.json`, +which the build checks against the claim files. `src/lib/config.mjs` reads the config; `src/lib/data.mjs` reads them all, validates every claim against [schemas/evidence-claim.v1.json](../schemas/evidence-claim.v1.json) (Ajv, draft 2020-12; an invalid claim or a name used twice stops the build), and joins them into one graph: entities, typed references, and the backlinks of each. @@ -109,7 +175,7 @@ The buttons open a prefilled GitHub new-issue page (title, body, labels); nothin it. Each body ends with a `research-action:` line (`prioritise`, `reject`, `dispute`, `question`, `propose-role`, `propose-option`), with `research-claim:`, `claim-file:` and `status:` for a claim and `role:` for an option proposed for a role; the agent reads those lines first (`morphogen/research.py`, `parse_issue`). They are written by -`src/lib/steer.mjs`. The labels in `config.toml` are the fallback. Text from papers never goes into an issue body, +`src/lib/steer.mjs`. The labels in the config's `[labels]` are the fallback. Text from papers never goes into an issue body, since it is rendered as Markdown. ## Safety @@ -125,6 +191,7 @@ markup and a `javascript:` link and checks that none of it comes through. ## Deploying `.github/workflows/site.yml` installs the locked packages, runs the 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. +Pages: Morphogen's own demo. 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; `MORPHOGEN_SITE_BASE` makes them absolute under a path. +For your own repository, use the template in [skills/research-loop/research-site.yml](../skills/research-loop/research-site.yml). diff --git a/site/astro.config.mjs b/site/astro.config.mjs index f40f4be..7dbf09d 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -1,12 +1,44 @@ -// The research site (site/README.md). Static output only; every page is a file such as claims/.html, and -// every link is relative, so the site works under https://.github.io/Morphogen/ or on its own domain. +// The research site (site/README.md), built from the config file in MORPHOGEN_SITE_CONFIG (src/lib/config.mjs). +// Static output only; every page is a file such as claims/.html. Links are relative, so the site works under +// any path, unless MORPHOGEN_SITE_BASE (`morphogen site build --base /research`) makes them start with that path. import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { defineConfig } from "astro/config"; +import { loadConfig, themeFiles } from "./src/lib/config.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); -process.env.SITE_DIR ||= HERE; // read by src/lib/data.mjs +process.env.SITE_DIR ||= HERE; // read by src/lib/config.mjs +const CFG = loadConfig(); + +// The config's theme (themeFiles, in src/lib/config.mjs): written into the output after a build as assets/user/; +// served from the config's own files by the dev server. +const TYPES = { ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp", ".jpg": "image/jpeg", ".jpeg": "image/jpeg" }; + +function userTheme() { + const files = themeFiles(CFG.theme); + return { + name: "user-theme", + hooks: { + "astro:config:setup": ({ updateConfig }) => { + updateConfig({ vite: { plugins: [{ name: "user-theme-dev", configureServer(server) { + server.middlewares.use((req, res, next) => { + const m = /\/assets\/user\/([^/?#]+)/.exec(req.url || ""); + if (!m || !files[m[1]]) return next(); + res.setHeader("Content-Type", TYPES[path.extname(m[1])] || "application/octet-stream"); + res.end(fs.readFileSync(files[m[1]])); + }); + } }] } }); + }, + "astro:build:done": ({ dir }) => { + const out = path.join(fileURLToPath(dir), "assets", "user"); + if (!Object.keys(files).length) return; + fs.mkdirSync(out, { recursive: true }); + for (const [name, from] of Object.entries(files)) fs.copyFileSync(from, path.join(out, name)); + }, + }, + }; +} // Alpine's CSP build (no `new Function`, so the content security policy needs no 'unsafe-eval'), served from the // site itself: copied from the pinned package into public/assets/vendor before every build and dev start. @@ -29,9 +61,10 @@ function alpineCsp() { export default defineConfig({ output: "static", - outDir: process.env.SITE_OUT || "./_build", + outDir: process.env.MORPHOGEN_SITE_OUT ? path.resolve(process.env.MORPHOGEN_SITE_OUT) : "./_build", + base: CFG.base || undefined, build: { format: "file" }, compressHTML: true, devToolbar: { enabled: false }, - integrations: [alpineCsp()], + integrations: [alpineCsp(), userTheme()], }); diff --git a/site/config.toml b/site/config.toml index 217efb4..062c2fa 100644 --- a/site/config.toml +++ b/site/config.toml @@ -1,6 +1,12 @@ -# What the site reads (site/src/lib/data.mjs). Paths are relative to the repository root. +# Morphogen's own research site: the research-loop demo (site/README.md, "The config file"). Paths are relative to +# this file. Build it with `npm run build` here, or `morphogen site build --config site/config.toml --out site/_build`. + +[site] title = "Morphogen research" -# Where steering issues go, and where claim files are linked on GitHub. +description = "Claims from papers about options for the system's roles, with conditions, transfer predictions and outcomes." +owner = "OpenReplicant" +# Where steering issues go, and where claim files are linked on GitHub (by their path from the repository root, +# found from .git above this file; `repo_dir` sets it instead). repo = "OpenReplicant/Morphogen" branch = "main" # The System whose status each claim is shown with (an assessment's `system`). @@ -8,18 +14,20 @@ 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. +claims = ["../demos/research-loop/claims"] +# Backstage entity files: the map (roles, this system's conditions) and the options. A missing one is skipped. catalog = [ - "demos/research-loop/catalog-info.yaml", - "demos/research-loop/catalog/map.yaml", - "demos/research-loop/catalog/options.yaml", - "demos/research-loop/catalog/found.yaml", + "../demos/research-loop/catalog-info.yaml", + "../demos/research-loop/catalog/map.yaml", + "../demos/research-loop/catalog/options.yaml", + "../demos/research-loop/catalog/found.yaml", ] # The research agent's own files (morphogen.research): queue.json (next to test), watch.yaml (what it watches), # seen.jsonl (papers seen) and index.json (every claim's path). Each is optional; a missing file leaves its view empty. -research = "demos/research-loop/research" -schema = "schemas/evidence-claim.v1.json" +research = "../demos/research-loop/research" +# Markdown pages: every .md file under it becomes a page. +content = "content" +# schema = "../schemas/evidence-claim.v1.json" # the default: the one next to this site # 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 @@ -32,3 +40,12 @@ dispute = ["research:question"] question = ["research:question"] propose-role = ["research:question"] propose-option = ["research:question"] + +# [theme] +# css = "theme.css" # loaded after the default style.css; override its custom properties +# logo = "logo.svg" # shown in the header and used as the icon + +[nav] +# The header's pages, in order: claims, queue, predictions, roles, map, notes (shown once there is a note), search. +# A Markdown page with `nav: ` in its front matter is added after these. +pages = ["claims", "queue", "predictions", "roles", "map", "notes"] diff --git a/site/public/assets/style.css b/site/public/assets/style.css index a1b7a3d..03027a1 100644 --- a/site/public/assets/style.css +++ b/site/public/assets/style.css @@ -1,4 +1,5 @@ -/* Morphogen research. Loosely after openreplicant.com: near-black panels, cyan and magenta, mono labels. +/* The research site's default theme: near-black panels, cyan and magenta, mono labels. A config's [theme] css is + loaded after this file, so it can override any of the custom properties below. Light is a paper theme with darker inks so every pairing keeps 4.5:1 contrast. */ :root { @@ -125,6 +126,7 @@ p { margin: 0 0 0.9em; } .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-logo { height: 1.6rem; width: auto; } .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; } diff --git a/site/src/components/Assessment.astro b/site/src/components/Assessment.astro index e3414b0..0f87627 100644 --- a/site/src/components/Assessment.astro +++ b/site/src/components/Assessment.astro @@ -4,7 +4,7 @@ import ClaimRef from "./ClaimRef.astro"; import ExtLink from "./ExtLink.astro"; import Meter from "./Meter.astro"; import StatusBadge from "./StatusBadge.astro"; -import { refName } from "../lib/text.mjs"; +import { refName, up } from "../lib/text.mjs"; const { site, c, a } = Astro.props; const label = site.configLabel(a); const pr = a.prediction; @@ -17,7 +17,7 @@ const v = out?.verdict || {}; const by = { morphogen: "the judge", falsifier: "a falsifier registered before the outcome", operator: "the operator", none: "nobody yet" }[v.by] || v.by || ""; ---

{label && <> on {label}} for {a.system}{a.date && <> on {a.date}}

-{(a.against || []).length > 0 &&

Compared with: {a.against.map((r, i) => { const e = site.catalogRef(r); return <>{i > 0 && ", "}{e ? {refName(r)} : {refName(r)}}; })}

} +{(a.against || []).length > 0 &&

Compared with: {a.against.map((r, i) => { const e = site.catalogRef(r); return <>{i > 0 && ", "}{e ? {refName(r)} : {refName(r)}}; })}

} {pr &&

Transfer prediction

{pr.reason || ""}

@@ -25,9 +25,9 @@ const by = { morphogen: "the judge", falsifier: "a falsifier registered before t {plan &&

The cheapest trial that would settle it

{plan.plan || ""}

Cost
about {plan.cost_hours} hours, setting up included
{(plan.needs || []).length > 0 && <>
Needs
    {plan.needs.map((n) =>
  • {n}
  • )}
}{plan.code && <>
Code
}
-{ranked &&

Number {ranked[0]} of {site.queue().length} in the queue.

}
} +{ranked &&

Number {ranked[0]} of {site.queue().length} in the queue.

}
} {out &&

Outcome

-

Trial {trialEnt ? {t.id} : {t.id || ""}}{t.url && <> ()}{out.date && <> · {out.date}} · {out.comparison === "our-setup" ? "a transfer test on our setup" : "the source's own setup reproduced"}

+

Trial {trialEnt ? {t.id} : {t.id || ""}}{t.url && <> ()}{out.date && <> · {out.date}} · {out.comparison === "our-setup" ? "a transfer test on our setup" : "the source's own setup reproduced"}

{out.summary || ""}

Verdict
{v.decision || ""}, decided by {by}{v.ref && <> {v.ref}}{v.note && <>
{v.note}}
Observed
    {(out.observed || []).map((n) =>
  • )}
} diff --git a/site/src/components/Blocks.astro b/site/src/components/Blocks.astro index f87a51d..bb53d68 100644 --- a/site/src/components/Blocks.astro +++ b/site/src/components/Blocks.astro @@ -2,9 +2,11 @@ // Generated sections a Markdown page can ask for in its front matter (`blocks: [statuses, steering, files]`). import StatusBadge from "./StatusBadge.astro"; import ExtLink from "./ExtLink.astro"; -import { OBSERVATION, STATUSES, STATUS_HELP } from "../lib/text.mjs"; +import { OBSERVATION, STATUSES, STATUS_HELP, up } from "../lib/text.mjs"; +// Morphogen's claim format, wherever this site's own files live. +const SCHEMA_URL = "https://github.com/OpenReplicant/Morphogen/blob/main/schemas/evidence-claim.v1.json"; const { site, blocks = [], depth = 0 } = Astro.props; -const u = "../".repeat(depth); +const u = up(depth); const actions = [["prioritise", "test this claim sooner; it counts double in the queue"], ["reject", "drop it from the queue"], ["dispute", "the transfer prediction is wrong; the next session reassesses it"], ["question", "a question to watch"], ["propose-role", "a role to read papers for"], ["propose-option", "an option or paper for a role"]]; @@ -16,4 +18,4 @@ const actions = [["prioritise", "test this claim sooner; it counts double in the
    {actions.map(([k, t]) =>
  • research-action: {k} {t}{(site.labels[k] || []).length > 0 && <> (label {site.labels[k].join(", ")})}
  • )}

GitHub applies labels from a link only for people who can triage the repository, which is why the body line comes first. The agent records every issue but acts only on those from the repository's owner, members and collaborators.

} {blocks.includes("files") &&

Files, not a service

-

Every claim is a YAML file in the repository (), and the roles and options are Backstage entity files. This site is built from them by Astro (site/); data/claims.json holds the same records and data/graph.json every reference between them, for other tools. The judge never reads the claims: what decides a change is only what it measures.

} +

Every claim is a YAML file in the repository (), and the roles and options are Backstage entity files. This site is built from them by morphogen site build; data/claims.json holds the same records and data/graph.json every reference between them, for other tools. The judge never reads the claims: what decides a change is only what it measures.

} diff --git a/site/src/components/Watch.astro b/site/src/components/Watch.astro index cba7641..103a4f4 100644 --- a/site/src/components/Watch.astro +++ b/site/src/components/Watch.astro @@ -1,4 +1,5 @@ --- +import { up } from "../lib/text.mjs"; // What the agent watches (watch.yaml) and what became of the papers it saw (seen.jsonl). import ExtLink from "./ExtLink.astro"; const { site, depth = 0 } = Astro.props; @@ -13,8 +14,8 @@ const paperFor = (id) => site.of("paper").find((p) => String(p.source?.id || "") {(Object.keys(w).length > 0 || seen.length > 0) &&

Watching

{w.conditions &&

{w.conditions}

} {(w.topics || []).length > 0 &&
    {w.topics.map((t) =>
  • {t.name || ""}

    {t.question || ""}

    -

    {(t.roles || []).map((r) => { const e = site.catalogRef(r); return <>{e ? {r} : {r}} ; })}{(t.categories || []).length > 0 && · {t.categories.join(", ")}}

    +

    {(t.roles || []).map((r) => { const e = site.catalogRef(r); return <>{e ? {r} : {r}} ; })}{(t.categories || []).length > 0 && · {t.categories.join(", ")}}

    {(t.terms || []).length ? t.terms.map((x) => {x}) : terms still to be filled in by the next session}

  • )}
} {seen.length > 0 &&

Papers seen {seen.length}: {countText}.

} -{cataloged.length > 0 &&
{cataloged.length} papers catalogued
    {cataloged.map((x) => { const p = paperFor(x.id); return
  • {p ? {x.title || ""} : } {x.id || ""}
  • ; })}
} +{cataloged.length > 0 &&
{cataloged.length} papers catalogued
    {cataloged.map((x) => { const p = paperFor(x.id); return
  • {p ? {x.title || ""} : } {x.id || ""}
  • ; })}
}
} diff --git a/site/src/content.config.mjs b/site/src/content.config.mjs index 5922391..966ce1e 100644 --- a/site/src/content.config.mjs +++ b/site/src/content.config.mjs @@ -1,12 +1,13 @@ -// The file-based pages: every Markdown file under site/content (or SITE_CONTENT) becomes a page with the shared +// The file-based pages: every Markdown file under the config's content folder ([sources] content) becomes a page with the shared // layout (src/pages/[...slug].astro). Front matter is checked here; a page that breaks it stops the build. import { defineCollection, z } from "astro:content"; import { glob } from "astro/loaders"; +import { loadConfig } from "./lib/config.mjs"; const day = z.union([z.string(), z.date()]).transform((d) => (typeof d === "string" ? d : d.toISOString().slice(0, 10))); const pages = defineCollection({ - loader: glob({ pattern: "**/*.md", base: process.env.SITE_CONTENT || "./content" }), + loader: glob({ pattern: "**/*.md", base: loadConfig().sources.content || "./src/no-content" }), schema: z.object({ title: z.string(), description: z.string().optional(), diff --git a/site/src/layouts/Base.astro b/site/src/layouts/Base.astro index 97ae093..d45d084 100644 --- a/site/src/layouts/Base.astro +++ b/site/src/layouts/Base.astro @@ -1,17 +1,23 @@ --- -// The frame of every page: the content security policy, the header and its navigation, the footer. Links are -// relative (`depth` directories below the site root), so the site works under any path. +// The frame of every page: the content security policy, the header and its navigation, the footer. The title, the +// description, the owner, the navigation and the theme all come from the config file (src/lib/config.mjs). Links +// are relative (`depth` directories below the site root), or start with the base path when there is one. +import path from "node:path"; +import { themeFiles } from "../lib/config.mjs"; import { safeUrl, up } from "../lib/text.mjs"; const { site, title, description = "", depth = 0, current = "" } = Astro.props; const u = up(depth); -const fixed = [["index.html", "Claims"], ["queue.html", "Next to test"], ["predictions.html", "Predictions"], - ["roles.html", "Roles"], ["map.html", "Map"]]; const listed = site.pages.filter((p) => p.kind !== "page"); +const fixed = site.nav.filter((n) => n.id !== "notes" || listed.length).map((n) => [n.href, n.text]); const extra = site.pages.filter((p) => typeof p.nav === "number").sort((a, b) => a.nav - b.nav).map((p) => [`${p.slug}.html`, p.title]); -const nav = [...fixed, ...(listed.length ? [["notes.html", "Notes"]] : []), ...extra]; +const nav = [...fixed, ...extra]; const fullTitle = title && title !== site.title ? `${title} · ${site.title}` : site.title; -const desc = description || "Claims from papers about options for the system's roles, with conditions, transfer predictions and outcomes."; +const desc = description || site.description; const repoUrl = safeUrl(`https://github.com/${site.repo}`); +const theme = Object.keys(themeFiles(site.theme)); +const logo = theme.find((f) => f.startsWith("logo")); +const icon = logo ? `assets/user/${logo}` : "assets/icon.svg"; +const iconType = { ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp" }[path.extname(icon)] || "image/jpeg"; --- @@ -23,8 +29,9 @@ const repoUrl = safeUrl(`https://github.com/${site.repo}`); {fullTitle} - + +{theme.includes("theme.css") && } @@ -33,7 +40,7 @@ const repoUrl = safeUrl(`https://github.com/${site.repo}`);
- Morphogen research + {logo ? : } {site.title}

Reading it

-

Claims are coloured by their status here: green replicated, red did not transfer, amber mixed, blue predicted, grey untested, purple our own observation. A link from a claim to a model means the claim was measured on it, or tested on it with a result. data/graph.json has every entity and reference, for other tools; search lists everything by kind.

+

Claims are coloured by their status here: green replicated, red did not transfer, amber mixed, blue predicted, grey untested, purple our own observation. A link from a claim to a model means the claim was measured on it, or tested on it with a result. data/graph.json has every entity and reference, for other tools; search lists everything by kind.

diff --git a/site/src/pages/notes.astro b/site/src/pages/notes.astro index 689dbc1..29aab59 100644 --- a/site/src/pages/notes.astro +++ b/site/src/pages/notes.astro @@ -1,4 +1,5 @@ --- +import { link } from "../lib/text.mjs"; // Notes and announcements: the Markdown files in site/content with kind note or announcement, newest first. import Base from "../layouts/Base.astro"; import { getSite } from "../lib/site.mjs"; @@ -7,6 +8,6 @@ const listed = site.of("page").filter((p) => p.kind !== "page").sort((a, b) => S ---

From the people running it

Notes and announcements

-{listed.length ?
    {listed.map((p) =>
  1. {p.kind}{p.date && }

    {p.title}

    {p.summary &&

    {p.summary}

    }
  2. )}
+{listed.length ?
    {listed.map((p) =>
  1. {p.kind}{p.date && }

    {p.title}

    {p.summary &&

    {p.summary}

    }
  2. )}
:

None yet. A Markdown file in site/content/notes becomes one (site/README.md).

} diff --git a/site/src/pages/options/[name].astro b/site/src/pages/options/[name].astro index 3596f8f..37b79b6 100644 --- a/site/src/pages/options/[name].astro +++ b/site/src/pages/options/[name].astro @@ -11,7 +11,7 @@ import References from "../../components/References.astro"; import ResultsTable from "../../components/ResultsTable.astro"; import StatusCounts from "../../components/StatusCounts.astro"; import { getSite } from "../../lib/site.mjs"; -import { truncate } from "../../lib/text.mjs"; +import { truncate, up } from "../../lib/text.mjs"; export async function getStaticPaths() { const site = await getSite(); @@ -26,8 +26,8 @@ const docs = o.spec?.morphogen?.docs; const tested = site.results(claims).filter((x) => x.a.outcome); --- - -

A candidate for {roles.length ? roles.map((r, i) => <>{i > 0 && ", "}the role {r.name}) : "no role named"}.{docs?.url && <> Described at .}

+ +

A candidate for {roles.length ? roles.map((r, i) => <>{i > 0 && ", "}the role {r.name}) : "no role named"}.{docs?.url && <> Described at .}

diff --git a/site/src/pages/papers/[id].astro b/site/src/pages/papers/[id].astro index a9e1526..52d0708 100644 --- a/site/src/pages/papers/[id].astro +++ b/site/src/pages/papers/[id].astro @@ -1,4 +1,5 @@ --- +import { up } from "../../lib/text.mjs"; // One paper (or other outside source): its claims with their status here, the options and roles they bear on, // what the agent saw of it, and every reference to and from it. import Base from "../../layouts/Base.astro"; @@ -25,14 +26,14 @@ const src = p.source || {}; const seen = p.seen; --- - +

{[src.id, src.version && `version ${src.version}`].filter(Boolean).join(" · ")} · {seen?.published && <> · published {seen.published}}{seen?.category && <> · {seen.category}}{seen?.seen && <> · seen by the agent {seen.seen}}

Options and roles

-

Options

-

Roles

+

Options

+

Roles

{seen?.abstract &&

Abstract

{seen.abstract}

}
diff --git a/site/src/pages/predictions.astro b/site/src/pages/predictions.astro index 18a71d0..dca3a2b 100644 --- a/site/src/pages/predictions.astro +++ b/site/src/pages/predictions.astro @@ -6,7 +6,7 @@ import Meter from "../components/Meter.astro"; import StatusBadge from "../components/StatusBadge.astro"; import { brier } from "../lib/data.mjs"; import { getSite } from "../lib/site.mjs"; -import { truncate } from "../lib/text.mjs"; +import { truncate, link } from "../lib/text.mjs"; const site = await getSite(); const pairs = site.calibrationPairs(); const waiting = [], unscored = []; @@ -31,9 +31,9 @@ const cfg = (a) => site.configLabel(a); x.a.prediction.p_transfer)} />

Waiting for a trial ({waiting.length})

-
{waiting.length ? waiting.map(({ c, a }) => ) : }
ClaimPrediction
{truncate(c.title, 90)}{cfg(a) && <> on {cfg(a)}}
None.
+
{waiting.length ? waiting.map(({ c, a }) => ) : }
ClaimPrediction
{truncate(c.title, 90)}{cfg(a) && <> on {cfg(a)}}
None.

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

-{pairs.length > 0 &&

Scored

{pairs.map(({ p, claim, a }) => )}
ClaimPredictionOutcome
{truncate(claim.title, 90)}{cfg(a) && <> on {cfg(a)}}
} -{unscored.length > 0 &&

Outcomes that do not count

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

} +{pairs.length > 0 &&

Scored

{pairs.map(({ p, claim, a }) => )}
ClaimPredictionOutcome
{truncate(claim.title, 90)}{cfg(a) && <> on {cfg(a)}}
} +{unscored.length > 0 &&

Outcomes that do not count

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

} diff --git a/site/src/pages/queue.astro b/site/src/pages/queue.astro index 3f854e7..99eefed 100644 --- a/site/src/pages/queue.astro +++ b/site/src/pages/queue.astro @@ -4,7 +4,7 @@ import Base from "../layouts/Base.astro"; import Meter from "../components/Meter.astro"; import { getSite } from "../lib/site.mjs"; import { issue, issueBody } from "../lib/steer.mjs"; -import { refName } from "../lib/text.mjs"; +import { refName, link } from "../lib/text.mjs"; const site = await getSite(); const q = site.research.queue || {}; const items = site.queue().map((it, i) => { @@ -27,8 +27,8 @@ const items = site.queue().map((it, i) => { {q.how &&

{q.how}

} {items.length ?
    {items.map((x) =>
  1. {String(x.i).padStart(2, "0")}
    -
    {x.role ? {refName(x.it.role)} : refName(x.it.role)} · option {x.about ? {refName(x.it.about)} : refName(x.it.about)}{typeof x.it.p_transfer === "number" && }
    -

    {x.c ? {x.c.title} : x.it.claim}

    +
    {x.role ? {refName(x.it.role)} : refName(x.it.role)} · option {x.about ? {refName(x.it.about)} : refName(x.it.about)}{typeof x.it.p_transfer === "number" && }
    +

    {x.c ? {x.c.title} : x.it.claim}

    {x.nums.map(([k, v]) => {k} {v})}{x.steer.map((s) => {s})}

    {x.it.plan &&

    Plan
    {x.it.plan}

    } {x.it.reason &&
    Why this probability

    {x.it.reason}

    } diff --git a/site/src/pages/resources/[name].astro b/site/src/pages/resources/[name].astro index f148947..f8046fd 100644 --- a/site/src/pages/resources/[name].astro +++ b/site/src/pages/resources/[name].astro @@ -9,7 +9,7 @@ import Mentions from "../../components/Mentions.astro"; import References from "../../components/References.astro"; import ResultsTable from "../../components/ResultsTable.astro"; import { getSite } from "../../lib/site.mjs"; -import { truncate } from "../../lib/text.mjs"; +import { truncate, up } from "../../lib/text.mjs"; export async function getStaticPaths() { const site = await getSite(); @@ -27,15 +27,15 @@ const trials = [...new Set([...measured.flatMap((c) => site.outs(c, "from")), .. const kindText = { model: "Model", engine: "Engine", hardware: "Hardware", dataset: "Dataset" }[res.kind] || "Resource"; --- - -

    {res.name}{site.outs(res, "in-system").map((s) => <> · in {s.name})}

    + +

    {res.name}{site.outs(res, "in-system").map((s) => <> · in {s.name})}

    {results.length} result{results.length === 1 ? "" : "s"} from papers' claims tested with it · {pending.length} predicted or untested · {measured.length} of our own measurements on it · {trials.length} trial{trials.length === 1 ? "" : "s"}

    Papers' claims tested with it ({results.length})

    {results.length ? :

    No claim from a paper has been tested with it yet.

    }
    -{trials.length > 0 &&

    Trials it was used in

      {trials.map((t) =>
    • {t.key} {t.summary}
    • )}
    } +{trials.length > 0 &&

    Trials it was used in

      {trials.map((t) =>
    • {t.key} {t.summary}
    • )}
    } {measured.length > 0 &&

    Measurements on it ({measured.length})

    } {pending.length > 0 &&

    Predicted or not yet tried with it ({pending.length})

    } diff --git a/site/src/pages/roles.astro b/site/src/pages/roles.astro index ce3e518..9fea961 100644 --- a/site/src/pages/roles.astro +++ b/site/src/pages/roles.astro @@ -6,7 +6,7 @@ import StatusCounts from "../components/StatusCounts.astro"; import Watch from "../components/Watch.astro"; import { getSite } from "../lib/site.mjs"; import { proposeOptionUrl, proposeRoleUrl } from "../lib/steer.mjs"; -import { truncate } from "../lib/text.mjs"; +import { truncate, link } from "../lib/text.mjs"; const site = await getSite(); const system = site.of("system")[0]; --- @@ -23,22 +23,22 @@ const system = site.of("system")[0]; const opts = site.ins(r, "fills"); return

    Role{parent && <> · part of {parent.name}}

    -

    {r.name}

    +

    {r.name}

    {r.summary}

    -

    · its page: questions, tests, claims

    +

    · its page: questions, tests, claims

    Options the agent is tracking ({opts.length})

      {opts.length ? opts.map((o) => { const cs = site.ins(o, "about").filter((c) => !c.ours); const result = o.spec?.morphogen?.evaluation?.result; - return
    • {o.name}

      {o.summary}

      + return
    • {o.name}

      {o.summary}

      {cs.length ? : No claims from papers yet}

      {result &&

      Result so far {result}

      } - {cs.length > 0 &&
      {cs.length} claim{cs.length !== 1 ? "s" : ""}
      }
    • ; + {cs.length > 0 &&
      {cs.length} claim{cs.length !== 1 ? "s" : ""}
      }; }) :
    • None yet.
    • }

    Suggest an option for this role

    ; })}

    This system's conditions

    Every claim's conditions are compared with these when its transfer is predicted. Each one's page lists the claims tested with it.

    -
      {site.of("resource").map((res) =>
    • {res.name} {res.kind}
      {res.summary}
    • )}
    +
      {site.of("resource").map((res) =>
    • {res.name} {res.kind}
      {res.summary}
    • )}
    diff --git a/site/src/pages/roles/[name].astro b/site/src/pages/roles/[name].astro index 25ec1bb..e384b0d 100644 --- a/site/src/pages/roles/[name].astro +++ b/site/src/pages/roles/[name].astro @@ -12,7 +12,7 @@ import ResultsTable from "../../components/ResultsTable.astro"; import StatusCounts from "../../components/StatusCounts.astro"; import { getSite } from "../../lib/site.mjs"; import { proposeOptionUrl } from "../../lib/steer.mjs"; -import { refName, truncate } from "../../lib/text.mjs"; +import { refName, truncate, up } from "../../lib/text.mjs"; export async function getStaticPaths() { const site = await getSite(); @@ -30,8 +30,8 @@ const topics = site.topicsFor(r.name); const queue = site.queue().map((q, i) => ({ ...q, rank: i + 1 })).filter((q) => refName(q.role) === r.name); --- - -

    {parent.map((p) => <>Part of {p.name}. )}{parts.length > 0 && <>Its parts: {parts.map((p, i) => <>{i > 0 && ", "}{p.name})}. }{site.outs(r, "in-system").map((s) => <>In the system {s.name}.)}

    + +

    {parent.map((p) => <>Part of {p.name}. )}{parts.length > 0 && <>Its parts: {parts.map((p, i) => <>{i > 0 && ", "}{p.name})}. }{site.outs(r, "in-system").map((s) => <>In the system {s.name}.)}

    @@ -42,8 +42,8 @@ const queue = site.queue().map((q, i) => ({ ...q, rank: i + 1 })).filter((q) => :

    No watch topic names this role yet (research/watch.yaml).

    }

    Next to test ({queue.length})

    - {queue.length ?
      {queue.map((q) =>
    1. #{q.rank} {site.claim(q.claim)?.title || q.claim} {typeof q.p_transfer === "number" && }
    2. )}
    - :

    Nothing for this role in the queue.

    } + {queue.length ?
      {queue.map((q) =>
    1. #{q.rank} {site.claim(q.claim)?.title || q.claim} {typeof q.p_transfer === "number" && }
    2. )}
    + :

    Nothing for this role in the queue.

    }
    @@ -51,14 +51,14 @@ const queue = site.queue().map((q, i) => ({ ...q, rank: i + 1 })).filter((q) =>
      {options.length ? options.map((o) => { const cs = site.ins(o, "about"); const result = o.spec?.morphogen?.evaluation?.result; - return
    • {o.name}

      {o.summary}

      {result &&

      Result so far {result}

      }
    • ; + return
    • {o.name}

      {o.summary}

      {result &&

      Result so far {result}

      }
    • ; }) :
    • None yet.
    • }

    Suggest an option for this role

    What has been tested ({tested.length})

    {tested.length ? :

    No claim for this role has an outcome yet.

    } - {waiting.length > 0 &&

    {waiting.length} more predicted and waiting for a trial; see the claims below or the predictions.

    } + {waiting.length > 0 &&

    {waiting.length} more predicted and waiting for a trial; see the claims below or the predictions.

    }

    Every claim for this role ({claims.length})

    diff --git a/site/src/pages/search.astro b/site/src/pages/search.astro index 2b8473f..35d536b 100644 --- a/site/src/pages/search.astro +++ b/site/src/pages/search.astro @@ -4,7 +4,7 @@ import Base from "../layouts/Base.astro"; import { TYPES } from "../lib/data.mjs"; import { getSite } from "../lib/site.mjs"; -import { truncate } from "../lib/text.mjs"; +import { truncate, up, link } from "../lib/text.mjs"; const site = await getSite(); const order = ["claim", "paper", "trial", "resource", "option", "role", "component", "system", "page"]; const groups = order.map((t) => [t, [...site.of(t)].sort((a, b) => a.title.localeCompare(b.title))]).filter(([, l]) => l.length); @@ -14,7 +14,7 @@ const groups = order.map((t) => [t, [...site.of(t)].sort((a, b) => a.title.local

    Everything on the site

    Search

    -
    +
    @@ -25,7 +25,7 @@ const groups = order.map((t) => [t, [...site.of(t)].sort((a, b) => a.title.local
-{groups.map(([t, list]) =>

{TYPES[t].many} ({list.length})

)} +{groups.map(([t, list]) =>

{TYPES[t].many} ({list.length})

)}
diff --git a/site/src/pages/systems/[name].astro b/site/src/pages/systems/[name].astro index a9eb31a..bb38361 100644 --- a/site/src/pages/systems/[name].astro +++ b/site/src/pages/systems/[name].astro @@ -1,4 +1,5 @@ --- +import { up } from "../../lib/text.mjs"; // The system: its roles, its conditions (the models, engine, GPU and datasets every prediction is made against). import Base from "../../layouts/Base.astro"; import EntityHead from "../../components/EntityHead.astro"; @@ -17,12 +18,12 @@ const members = site.ins(s, "in-system"); const links = s.doc?.metadata?.links || []; --- - + {links.length > 0 &&

{links.map((l) => )}

}
-

Roles

    {members.filter((m) => m.type === "role").map((m) =>
  • {m.name} {m.summary}
  • )}
-

Conditions

    {members.filter((m) => m.type === "resource").map((m) =>
  • {m.kind} {m.title}
  • )}
+

Roles

    {members.filter((m) => m.type === "role").map((m) =>
  • {m.name} {m.summary}
  • )}
+

Conditions

    {members.filter((m) => m.type === "resource").map((m) =>
  • {m.kind} {m.title}
  • )}
diff --git a/site/src/pages/trials/[id].astro b/site/src/pages/trials/[id].astro index d0d5f3a..7cd90e7 100644 --- a/site/src/pages/trials/[id].astro +++ b/site/src/pages/trials/[id].astro @@ -1,4 +1,5 @@ --- +import { up } from "../../lib/text.mjs"; // One trial (E-04a, E-17b...): the claims it produced, every claim it gave an outcome for and on which models, the // models it measured, related trials of the same family, and every reference to and from it. import Base from "../../layouts/Base.astro"; @@ -23,14 +24,14 @@ const models = [...new Set([...produced.flatMap((c) => site.outs(c, "measured-on const family = site.of("trial").filter((x) => x !== t && x.family === t.family); --- - -

{t.url_ext && <> · }{produced.length} claim{produced.length === 1 ? "" : "s"} recorded from it · outcomes for {tested.length} claim{tested.length === 1 ? "" : "s"} from papers{models.length > 0 && <> · on {models.map((m, i) => <>{i > 0 && ", "}{m.title})}}

+ +

{t.url_ext && <> · }{produced.length} claim{produced.length === 1 ? "" : "s"} recorded from it · outcomes for {tested.length} claim{tested.length === 1 ? "" : "s"} from papers{models.length > 0 && <> · on {models.map((m, i) => <>{i > 0 && ", "}{m.title})}}

Outcomes it produced for papers' claims ({rows.length})

{rows.length ? :

No paper's claim records an outcome from this trial.

}

What it measured ({produced.length})

-{family.length > 0 &&

Related trials ({t.family})

    {family.map((x) =>
  • {x.key} {x.summary}
  • )}
} +{family.length > 0 &&

Related trials ({t.family})

    {family.map((x) =>
  • {x.key} {x.summary}
  • )}
} diff --git a/skills/research-loop/SKILL.md b/skills/research-loop/SKILL.md index 22cf205..b39fde1 100644 --- a/skills/research-loop/SKILL.md +++ b/skills/research-loop/SKILL.md @@ -169,3 +169,21 @@ On a branch `research/DATE`, commit `ROOT/research/`, `ROOT/claims/` and `ROOT/c pull request into main. Its description: papers seen, read and skipped; claims written and refused; the top five of the queue with their p and cost; the steering events recorded and whether each was applied; any topic still waiting for terms. Plain sentences, no claims stronger than the files. + +## Set up your research site + +Once a project has claims, anyone running Morphogen can publish its own research site: every claim, paper, trial, +model, option and role as a page with links both ways, the queue, the predictions and their calibration, and steering +buttons that open prefilled issues in their repository. Do this once, when the owner asks (it is not part of a session). + +1. `uv run morphogen site init ROOT` writes `ROOT/site.toml` and `ROOT/site/about.md`. It reads the repository from + the `origin` remote and the System from `ROOT/catalog-info.yaml`; pass `--repo OWNER/NAME`, `--system + system:default/NAME`, `--title` and `--owner` when they are missing or wrong. It never overwrites without `--force`. +2. Edit `site.toml` if needed: the sources (paths relative to it), the labels the agent reads (the same ones as for + steering, step 1), `[theme] css` and `logo`, and `[nav] pages`. Add pages as Markdown files under `ROOT/site/`. +3. Build and look: `uv run morphogen site build --config ROOT/site.toml --out _site --install` (Node 22.23.4 or + later; `--install` runs `npm ci` in Morphogen's `site/` the first time), then open `_site/index.html`. Add + `--base /research` only for a host that needs absolute links under that path. An invalid claim stops the build. +4. To deploy on GitHub Pages, copy `skills/research-loop/research-site.yml` to `.github/workflows/` in that + repository, set `SITE_CONFIG`, pin `MORPHOGEN_REF`, and tell the owner to set Pages to "GitHub Actions" (a + setting: never change it yourself) and run the workflow once by hand. diff --git a/skills/research-loop/research-site.yml b/skills/research-loop/research-site.yml new file mode 100644 index 0000000..52c95a0 --- /dev/null +++ b/skills/research-loop/research-site.yml @@ -0,0 +1,72 @@ +# A template for YOUR repository, not an active workflow here: GitHub never runs it from skills/. +# It builds your research site (Morphogen's site/README.md) from the config `morphogen site init` wrote, and deploys +# it to GitHub Pages. To turn it on: +# 1. copy it to .github/workflows/research-site.yml in your repository; +# 2. set SITE_CONFIG below to your config file (the path from the repository root); +# 3. pin MORPHOGEN_REF to a Morphogen commit or tag you have read (the site's code comes from there); +# 4. in Settings > Pages, set the source to "GitHub Actions"; +# 5. run it once by hand (Actions > research-site > Run workflow), then uncomment `push` if wanted. +# Links are relative, so the site works at https://OWNER.github.io/REPO/ as it is. SITE_BASE is only for a host that +# needs absolute links under a subpath, e.g. /research. +name: research-site +on: + workflow_dispatch: + # push: + # branches: [main] + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +env: + SITE_CONFIG: site.toml + SITE_BASE: "" + MORPHOGEN_REF: main # pin a commit SHA + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Morphogen's site sources + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: OpenReplicant/Morphogen + ref: ${{ env.MORPHOGEN_REF }} + path: .morphogen + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24.5.0 + - name: Install the site's packages (exact versions from its package-lock.json) + working-directory: .morphogen/site + run: npm ci --ignore-scripts --no-fund + - name: Build (the same as `morphogen site build --config $SITE_CONFIG --out _site --base $SITE_BASE`) + working-directory: .morphogen/site + env: + MORPHOGEN_SITE_CONFIG: ${{ github.workspace }}/${{ env.SITE_CONFIG }} + MORPHOGEN_SITE_OUT: ${{ github.workspace }}/_site + MORPHOGEN_SITE_BASE: ${{ env.SITE_BASE }} + run: npm run build + - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: _site + + 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/tests/test_site.py b/tests/test_site.py index 18c6a5a..66b0c18 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -12,10 +12,11 @@ import re import shutil import subprocess +import sys import tempfile import unittest from pathlib import Path -from urllib.parse import parse_qs, urlsplit +from urllib.parse import parse_qs, urljoin, urlsplit import yaml @@ -105,9 +106,9 @@ def make_project(root: Path, claims: list[dict]) -> None: (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") (root / "config.toml").write_text( - 'repo = "Owner/Repo"\nsystem = "system:default/sys"\n[sources]\nclaims = ["claims"]\n' - 'catalog = ["catalog.yaml"]\nresearch = "research"\nschema = "schemas/evidence-claim.v1.json"\n' - '[labels]\nprioritise = ["research:prioritise"]\nreject = ["research:reject"]\n' + '[site]\nrepo = "Owner/Repo"\nsystem = "system:default/sys"\n[sources]\nclaims = ["claims"]\n' + 'catalog = ["catalog.yaml"]\nresearch = "research"\ncontent = "content"\n' + 'schema = "schemas/evidence-claim.v1.json"\n[labels]\nprioritise = ["research:prioritise"]\nreject = ["research:reject"]\n' 'dispute = ["research:question"]\nquestion = ["research:question"]\n', encoding="utf-8") research = root / "research" research.mkdir() @@ -128,12 +129,12 @@ def make_project(root: Path, claims: list[dict]) -> None: "Some *text*.\n", encoding="utf-8") -def run_build(out: Path, root: Path | None = None, content: Path | None = None) -> subprocess.CompletedProcess: - env = dict(os.environ, SITE_OUT=str(out), ASTRO_TELEMETRY_DISABLED="1") - if root is not None: - env.update(SITE_ROOT=str(root), SITE_CONFIG=str(root / "config.toml")) - if content is not None: - env["SITE_CONTENT"] = str(content) +def run_build(out: Path, config: Path | None = None, base: str = "") -> subprocess.CompletedProcess: + """`npm run build` with the contract's variables (site/README.md); `morphogen site build` sets the same.""" + env = dict(os.environ, MORPHOGEN_SITE_OUT=str(out), MORPHOGEN_SITE_BASE=base, ASTRO_TELEMETRY_DISABLED="1") + env.pop("MORPHOGEN_SITE_CONFIG", None) + if config is not None: + env["MORPHOGEN_SITE_CONFIG"] = str(config) return subprocess.run(["npm", "run", "--silent", "build", "--", "--force"], cwd=SITE, env=env, capture_output=True, text=True, timeout=600) @@ -284,7 +285,7 @@ def setUpClass(cls): cls.root = Path(cls.tmp.name) make_project(cls.root, [CLAIM, two_setups(), scored()]) cls.out = cls.root / "out" - built(cls.out, root=cls.root, content=cls.root / "content") + built(cls.out, config=cls.root / "config.toml") cls.graph = json.loads(read(cls.out, "data/graph.json")) @classmethod @@ -373,7 +374,7 @@ def test_invalid_claim_stops_the_build(self): bad = copy.deepcopy(CLAIM) bad["spec"]["assessments"][0]["status"] = "probably-fine" make_project(root, [bad]) - r = run_build(root / "out", root=root, content=root / "content") + r = run_build(root / "out", config=root / "config.toml") self.assertNotEqual(r.returncode, 0) self.assertIn("not a valid EvidenceClaim", r.stdout + r.stderr) @@ -382,10 +383,140 @@ def test_a_page_naming_a_missing_entity_stops_the_build(self): root = Path(tmp) make_project(root, [CLAIM]) (root / "content" / "bad.md").write_text("---\ntitle: Bad\nrefs: [resource:nowhere]\n---\nx\n", encoding="utf-8") - r = run_build(root / "out", root=root, content=root / "content") + r = run_build(root / "out", config=root / "config.toml") self.assertNotEqual(r.returncode, 0) self.assertIn("refers to resource:nowhere", r.stdout + r.stderr) +ORCHARD_CLAIM = { + "apiVersion": "morphogen.dev/v1alpha1", + "kind": "EvidenceClaim", + "metadata": {"name": "pruning-raises-yield", "description": "Summer pruning raises yield"}, + "spec": { + "about": "component:default/summer-pruning", + "role": "component:default/canopy", + "source": {"kind": "preprint", "title": "Pruning and yield", "id": "arXiv:2611.00042", + "url": "https://arxiv.org/abs/2611.00042", "version": "v1", "location": "Table 2", + "read": "in full", "quote": "yield rose", "quote_status": "checked"}, + "claim": {"statement": "Summer pruning raises yield", "finding": "better", "reporting": "self", + "metric": "kg per tree", "value": 41, "baseline": {"name": "no pruning", "value": 35}}, + "conditions": {"unstated": ["rootstock"]}, + "assessments": [{"system": "system:default/orchard", "status": "predicted", "date": "2026-11-27", + "prediction": {"p_transfer": 0.6, "reason": "Same climate", "by": "test", + "date": "2026-11-27", "before_outcome": True}}], + }, +} +ORCHARD_CATALOG = [ + {"apiVersion": "backstage.io/v1alpha1", "kind": "System", "metadata": {"name": "orchard"}, + "spec": {"owner": "group:default/growers"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "canopy"}, + "spec": {"type": "role", "lifecycle": "production", "owner": "group:default/growers", "system": "system:default/orchard"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "summer-pruning"}, + "spec": {"type": "method", "lifecycle": "candidate", "owner": "group:default/growers", + "morphogen": {"fills": "component:default/canopy"}}}, +] + + +class AnotherSystem(_Toolchain): + """Anyone's system: `morphogen site init` in a made-up project (another system, other labels, a theme, fewer + pages in the header), built with `morphogen site build --base /lab`. Nothing of Morphogen's demo may show.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + from morphogen import site + cls.tmp = tempfile.TemporaryDirectory() + root = cls.root = Path(cls.tmp.name) / "grove" + (root / "claims").mkdir(parents=True) + (root / "claims" / "pruning.yaml").write_text(yaml.safe_dump(ORCHARD_CLAIM), encoding="utf-8") + (root / "catalog-info.yaml").write_text(yaml.safe_dump(ORCHARD_CATALOG[0]), encoding="utf-8") + (root / "catalog").mkdir() + (root / "catalog" / "map.yaml").write_text(yaml.safe_dump_all(ORCHARD_CATALOG[1:]), encoding="utf-8") + made = site.init(root, repo="Growers/grove", title="Grove lab", owner="The Growers") + assert made["system"] == "system:default/orchard", made # read from catalog-info.yaml + cfg = Path(made["config"]) + text = cfg.read_text(encoding="utf-8") + for old, new in (('"research:prioritise"', '"grove:boost"'), ('"research:reject"', '"grove:drop"'), + ('# css = "site-theme.css"', 'css = "brand/theme.css"'), ('# logo = "logo.svg"', 'logo = "brand/logo.svg"'), + ('pages = ["claims", "queue", "predictions", "roles", "map", "notes"]', 'pages = ["claims", "roles", {page = "search", text = "Find"}]')): + assert old in text, old + text = text.replace(old, new) + cfg.write_text(text, encoding="utf-8") + (root / "brand").mkdir() + (root / "brand" / "theme.css").write_text(":root { --accent: #2a7; }\n", encoding="utf-8") + (root / "brand" / "logo.svg").write_text('', encoding="utf-8") + cls.out = Path(cls.tmp.name) / "public" + r = subprocess.run([sys.executable, "-m", "morphogen", "site", "build", "--config", str(cfg), "--out", + str(cls.out), "--base", "/lab"], cwd=cls.tmp.name, capture_output=True, text=True, timeout=600) + if r.returncode: + raise AssertionError(f"morphogen site build failed:\n{r.stdout[-3000:]}\n{r.stderr[-3000:]}") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_it_is_their_site(self): + text = all_html(self.out) + self.assertNotIn("Morphogen research", text) + self.assertNotIn("metasoar", text.lower()) + self.assertNotIn("demos/research-loop", text) + index = read(self.out, "index.html") + self.assertIn("Grove lab", index) + self.assertIn("The Growers", index) + self.assertTrue((self.out / "claims" / "pruning-raises-yield.html").is_file()) + self.assertTrue((self.out / "about.html").is_file()) # the starter content folder + + def test_steering_goes_to_their_repo_with_their_labels(self): + links = issue_links(read(self.out, "claims/pruning-raises-yield.html")) + self.assertEqual(len(links), 3) + labels = set() + for url in links: + parts = urlsplit(url) + self.assertEqual(parts.path, "/Growers/grove/issues/new") + q = parse_qs(parts.query, strict_parsing=True) + self.assertIn("\nsystem: system:default/orchard", q["body"][0]) + self.assertIn("\nclaim-file: https://github.com/Growers/grove/blob/main/claims/pruning.yaml", q["body"][0]) + labels.add(q["labels"][0]) + self.assertEqual(labels, {"grove:boost", "grove:drop", "research:question"}) + + def test_every_link_and_asset_is_under_the_base(self): + n = 0 + for f in self.out.rglob("*.html"): + page = "/lab/" + f.relative_to(self.out).as_posix() + for u in re.findall(r'\s(?:href|src)="([^"]*)"', f.read_text(encoding="utf-8")): + if u.startswith(("https://", "http://", "#")): + continue + n += 1 + target = urlsplit(urljoin("http://host" + page, html.unescape(u))).path + self.assertTrue(target.startswith("/lab/"), f"{page}: {u}") + self.assertTrue((self.out / target[len("/lab/"):]).is_file(), f"{page}: {u} -> {target}") + self.assertGreater(n, 50) + self.assertIn('href="/lab/claims/pruning-raises-yield.html"', read(self.out, "index.html")) + self.assertIn('data-index="/lab/data/search.json"', read(self.out, "search.html")) + + def test_theme_and_navigation(self): + index = read(self.out, "index.html") + self.assertIn('', index) + self.assertIn('src="/lab/assets/user/logo.svg"', index) + self.assertEqual(read(self.out, "assets/user/theme.css"), ":root { --accent: #2a7; }\n") + nav = re.search(r'', index).group(1) + self.assertEqual(re.findall(r">([^<]+)", nav), ["Claims", "Roles", "Find", "About this site"]) + self.assertTrue((self.out / "queue.html").is_file()) # left out of the header, still built + + +class Init(unittest.TestCase): + def test_init_refuses_to_overwrite_and_needs_a_system(self): + from morphogen import site + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaisesRegex(site.SiteError, "--system"): + site.init(tmp, repo="A/b") + site.init(tmp, repo="A/b", system="mine") + self.assertIn('system = "system:default/mine"', (Path(tmp) / "site.toml").read_text(encoding="utf-8")) + with self.assertRaisesRegex(site.SiteError, "exists"): + site.init(tmp, repo="A/b", system="mine") + with self.assertRaisesRegex(site.SiteError, "OWNER/NAME"): + site.init(tmp, repo="not a repo", system="mine", force=True) + + if __name__ == "__main__": unittest.main()