Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions morphogen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
"""
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
168 changes: 168 additions & 0 deletions morphogen/site.py
Original file line number Diff line number Diff line change
@@ -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"}
Loading