From c4517d00f6d1d216a6ac496df690c60a8b89a032 Mon Sep 17 00:00:00 2001 From: OpenReplicant <122761100+OpenReplicant@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:03:04 -0800 Subject: [PATCH] Site: map, catalog, research and optimise in one UI; Fernhill as a second site Entities with interfaces (APIs, owners, dependencies) on the map; a catalog page per role with a compare table; an Optimise page with the cells, the judge's verdict log and its evidence chain; [sources] map, options and verdicts; catalog and optimise nav ids that hide when empty; demos/fernhill/site.toml. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01KhsqyyPmp7iKCkTFcXs6sh --- CLAUDE.md | 4 +- demos/fernhill/README.md | 10 + demos/fernhill/site.toml | 26 +++ morphogen/site.py | 8 +- site/README.md | 66 +++++- site/public/assets/site.js | 2 +- site/public/assets/style.css | 26 +++ site/src/components/EntityList.astro | 6 + site/src/components/Interfaces.astro | 24 ++ site/src/layouts/Base.astro | 5 +- site/src/lib/catalog.mjs | 31 +++ site/src/lib/config.mjs | 11 +- site/src/lib/data.mjs | 94 +++++++- site/src/lib/layout.mjs | 31 ++- site/src/lib/optimise.mjs | 288 ++++++++++++++++++++++++ site/src/lib/site.mjs | 2 +- site/src/pages/apis/[name].astro | 35 +++ site/src/pages/catalog.astro | 74 +++++++ site/src/pages/components/[name].astro | 2 + site/src/pages/index.astro | 15 ++ site/src/pages/map.astro | 59 +++-- site/src/pages/optimise.astro | 80 +++++++ site/src/pages/options/[name].astro | 2 + site/src/pages/owners/[name].astro | 26 +++ site/src/pages/resources/[name].astro | 2 + site/src/pages/roles/[name].astro | 2 + site/src/pages/search.astro | 2 +- site/src/pages/systems/[name].astro | 2 + site/test/lib.test.mjs | 27 +++ tests/test_site.py | 294 ++++++++++++++++++++++++- 30 files changed, 1202 insertions(+), 54 deletions(-) create mode 100644 demos/fernhill/site.toml create mode 100644 site/src/components/EntityList.astro create mode 100644 site/src/components/Interfaces.astro create mode 100644 site/src/lib/catalog.mjs create mode 100644 site/src/lib/optimise.mjs create mode 100644 site/src/pages/apis/[name].astro create mode 100644 site/src/pages/catalog.astro create mode 100644 site/src/pages/optimise.astro create mode 100644 site/src/pages/owners/[name].astro diff --git a/CLAUDE.md b/CLAUDE.md index d2f87fc..c31272b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,8 +19,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 with Astro (`site/src/`) from the evidence claims, the map and the - options named in a config file (`site/README.md`): `site/config.toml` for the demo, anyone's own through +- `site/`: the Morphogen site (map, catalog, research, optimise), static HTML built with Astro (`site/src/`) from the evidence claims, the map, the + options and the judge's verdict log 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 diff --git a/demos/fernhill/README.md b/demos/fernhill/README.md index 90d3155..4d423f4 100644 --- a/demos/fernhill/README.md +++ b/demos/fernhill/README.md @@ -13,6 +13,16 @@ options catalogued for one role, cells drafted for one opportunity) and a demo o | `prompt.md`, `run.sh`, `check.py` | the engagement unattended: a fresh project from `material/`, Claude Code with only the plugin, then the checks of its result | | [runs/](runs/) | unattended runs: each one's report and `check.py` output | +## As a site + + uv run morphogen site build --config demos/fernhill/site.toml --out _site + +builds the map (the firm's parts, the interfaces between them, owners), the catalog (four options for job +scheduling, none measured) and Optimise (the quote calculator as a cell). The judge's verdicts from the first run are +not on it: the evidence log lives in git's own directory and was not committed, so Optimise says that and shows no +verdict. To show them, rerun the judge and export its log with `morphogen evidence --limit 100000 > verdicts.json`, +then set `verdicts` in `site.toml`. + ## The first run (2026-11-24) - **Mapped:** the firm as a System, 5 teams, 6 process steps, its tools and 2 roles; 40 evidence quotes, all found diff --git a/demos/fernhill/site.toml b/demos/fernhill/site.toml new file mode 100644 index 0000000..422a4ff --- /dev/null +++ b/demos/fernhill/site.toml @@ -0,0 +1,26 @@ +# Fernhill's site: the made-up firm mapped from its documents to opportunities (site/README.md, "The config file"). +# Build it with `uv run morphogen site build --config demos/fernhill/site.toml --out _site`. Paths are relative to +# this file. Fernhill has no research claims, so the research pages are empty and leave the header; the map, the +# catalog (four options for job scheduling) and Optimise (one cell, the quote calculator) show. + +[site] +title = "Fernhill Kitchens" +description = "A made-up kitchen firm, mapped from its documents: teams, process, tools, the quote calculator as a cell, and options for job scheduling." +owner = "OpenReplicant" +repo = "OpenReplicant/Morphogen" +branch = "main" +system = "system:default/fernhill" + +[sources] +# The map: the System, its teams, the process steps, the tools and the cell. The Location in catalog-info.yaml names +# the files under catalog/, and they are read through it. +map = ["engagement/catalog-info.yaml"] +# The options catalogued for the job-scheduling role. +options = ["engagement/catalog/scheduling.yaml"] +# The judge's verdict log, exported with `morphogen evidence --limit 100000 > verdicts.json`: none is kept here, since +# the evidence log lives in git's own directory, not in the repository. Optimise says so rather than inventing one. +# verdicts = "engagement/verdicts.json" +claims = [] + +[nav] +pages = ["map", "catalog", "optimise", "search"] diff --git a/morphogen/site.py b/morphogen/site.py index f6f3710..2ab8475 100644 --- a/morphogen/site.py +++ b/morphogen/site.py @@ -104,6 +104,9 @@ def _q(s: str) -> str: 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 +# map = ["catalog/map.yaml"] # more entity files for the map (read with `catalog`) +# options = ["catalog/options.yaml"] # more entity files for the options catalogued for roles +# verdicts = "verdicts.json" # the judge's log: morphogen evidence --limit 100000 > verdicts.json # The labels on each steering link (the agent reads the `research-action:` line in the body first). [labels] @@ -114,8 +117,9 @@ def _q(s: str) -> str: # 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"] +# Any of: claims, queue, predictions, roles, map, catalog, optimise, notes, search. catalog and optimise leave the +# header when there is nothing to show. Pages with `nav: N` in front matter come after. +pages = ["claims", "queue", "predictions", "roles", "map", "catalog", "optimise", "notes"] """ ABOUT = """\ diff --git a/site/README.md b/site/README.md index 2062dc3..24d8672 100644 --- a/site/README.md +++ b/site/README.md @@ -1,9 +1,12 @@ -# The research site - -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 +# The Morphogen site + +A static site for any system running Morphogen, covering the kit's four verbs: **map** (the system's parts, the +interfaces they provide and consume, their owners and dependencies), **catalog** (the options for each role, side by +side), **research** (the claims the research agent has catalogued from papers, their status for that system, its +transfer predictions against outcomes: [docs/research-loop.md](../docs/research-loop.md)) and **optimise** (the cells +that may change, and the judge's verdict on each change). Every page is built from files; a page whose files are +absent leaves the header, so a research-only site is still a research-only site. There is a page for every claim, +paper, trial, model, option, role, component, interface and owner, 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. 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. @@ -48,6 +51,9 @@ system = "system:default/orchard" # the System each claim's status is shown f [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 +# map = ["catalog/map.yaml"] # entity files for the map and for the options: the same kind of file as +# options = ["catalog/options.yaml"] # `catalog`, read with it, named apart so a config says which is which +# verdicts = "verdicts.json" # the judge's log (below); optional 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 @@ -65,10 +71,10 @@ css = "brand/theme.css" # served as assets/user/theme.css, after style.css: 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 +# The header's pages, in order, from: claims, queue, predictions, roles, map, catalog (once a role or option exists), +# optimise (once there is a cell or a verdict), notes (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"] +pages = ["claims", "queue", "predictions", "roles", "map", "catalog", "optimise", "notes"] # Other links go in the same list as `{ text, href }`. An absolute http(s) URL or a path starting with `/` is written # as it is (a URL gets rel="noopener"); anything else is relative to the site and gets the base path from `--base`. # pages = ["claims", "queue", { text = "Lab", href = "https://example.org/lab" }, { text = "Home", href = "/" }] @@ -81,7 +87,40 @@ label = "Fund this" # the link's text (default "Fund th The funding figures themselves (a bar, price, share funded, a "ready" badge and the source) come from `queue.json` (`research/funding.yaml`, `morphogen.research rank`): a claim whose row has no `cost_money` shows none of it. -Morphogen's own demo builds from [config.toml](config.toml), which points at [demos/research-loop](../demos/research-loop). +### The entity files + +The map is Backstage `catalog-info.yaml` files (and the files a `Location` in them names, read relative to the file +that names them). The site reads `System`, `Component`, `API`, `Resource`, `Group` and `User`. A Component with +`spec.type: role` is a role, one with `spec.lifecycle: candidate` an option for the role in its +`spec.morphogen.fills`, any other a component; `providesApis`, `consumesApis`, `dependsOn`, `owner` and `subcomponentOf` +become references, each shown both ways. An owner with no `Group` or `User` file still gets a page. A **cell** is a +component (or the System) with `spec.morphogen.run` (or `tests`), read with the System's `defaults` under it; the +System's `spec.morphogen.autonomy` says whether a pass on its lifecycle may be merged by an agent (default: a person +reviews). An option's `spec.morphogen` fields `parameters` (a JSON Schema), `licence`, `docs.url` and `evaluation` +fill the catalog. + +### The verdict log + +`[sources] verdicts` names a file made from the judge's evidence log, which lives in git's own directory and is not +committed: + +```sh +morphogen evidence --limit 100000 > verdicts.json # a JSON array; JSON lines work too +``` + +The page shows each record with `kind: verdict`: the change proposed (commits, settings moved, files), passed or +refused, the measures (base, candidate, gain, interval, sign test) and the reasons rebuilt from the record's outcome +the way the judge words them, and the gate (who may merge). A verdict is listed under the cell it names (`cell`, +`cells` or `subject.system`), and one for a cell the map lacks is listed apart. The evidence chain checks each +record's `prev` and `hash` (SHA-256 of its canonical JSON, over the numbers as the file wrote them); an edited record +is named. The judge's own records carry no signature or transparency-log entry; if a record has a `signature`, +`attestation`, `transparency`, `rekor`, `log_index` or `inclusion_proof` field, it is shown as recorded and not +checked. A file that does not exist is skipped with a warning; one that is not JSON stops the build. + +Morphogen's own demo builds from [config.toml](config.toml), which points at [demos/research-loop](../demos/research-loop); +[demos/fernhill/site.toml](../demos/fernhill/site.toml) builds the made-up firm: its map, the options catalogued for +job scheduling, and its one cell. Fernhill has no verdict log (its evidence log was never committed), so Optimise +says so and shows none. ## Working on the templates @@ -148,6 +187,9 @@ used twice stops the build), and joins them into one graph: entities, typed refe | option | `options/.html` | a Component with `lifecycle: candidate` | | role | `roles/.html` | a Component with `type: role` | | system | `systems/.html` | the System | +| component | `components/.html` | any other Component | +| api | `apis/.html` | an API: who provides and consumes it, its tests | +| group | `owners/.html` | a Group or User, or a name given as an owner | | page | `.html` | a Markdown file in `content/` | References: a claim's `about` (option), `role`, `source` (paper or trial), `conditions.*.ref` (measured on), @@ -166,7 +208,9 @@ questions (`watch.yaml`), what has been tested and what is next in the queue. | `queue.html` | next to test: `queue.json`, best first, with plan, cost, score, funding (when there is a `funding.yaml`), steering, and buttons to prioritise or reject | | `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` | what the agent watches (`watch.yaml`, `seen.jsonl`), the roles, the options for each, and this system's conditions | -| `map.html` | the relations graph, laid out at build time (`src/lib/layout.mjs`); a static SVG of links, with highlighting and filters in Alpine | +| `map.html` | the system's graph (parts, interfaces, dependencies; only when the map has any), a table of every part with its owner, interfaces, dependencies and dependents, and the research's relations graph; static SVGs laid out at build time (`src/lib/layout.mjs`), with highlighting and filters in Alpine | +| `catalog.html` | per role: a table comparing its options (interfaces, parameters, licence, docs, measurements, claims), then each option's parameters, measurements and the trade-offs its claims report | +| `optimise.html` | the cells (what may change, the score, what the judge last measured, autonomy), the verdicts on each, and the evidence chain | | `search.html` | everything by kind; with JavaScript, a search over `data/search.json` (the header's box lands here) | | `notes.html` | notes and announcements from `content/` | | `data/claims.json`, `data/graph.json`, `data/search.json` | the records, the whole graph (with the calibration pairs and Brier score), the search index | diff --git a/site/public/assets/site.js b/site/public/assets/site.js index 5b4eab0..b830484 100644 --- a/site/public/assets/site.js +++ b/site/public/assets/site.js @@ -78,7 +78,7 @@ document.addEventListener("alpine:init", function () { // Search over data/search.json (fetched from this site only). ?q= from the header's search box fills it in. var KIND = { claim: "Claim", paper: "Paper", trial: "Trial", option: "Option", role: "Role", resource: "Resource", - component: "Component", system: "System", page: "Page" }; + component: "Component", api: "API", group: "Owner", system: "System", page: "Page" }; Alpine.data("search", function () { return { off: true, q: "", rows: [], results: [], countText: "", diff --git a/site/public/assets/style.css b/site/public/assets/style.css index cf70642..876adb6 100644 --- a/site/public/assets/style.css +++ b/site/public/assets/style.css @@ -351,3 +351,29 @@ details ul { margin-top: 8px; font-size: 0.88rem; } .funding { display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; font-size: 0.9rem; margin: 6px 0; } .fund-bar { width: 120px; } .tag-ready { background: var(--good-bg); color: var(--good); border-color: currentColor; font-weight: 650; } + +/* The system's map, the catalog and the Optimise page */ +.sec { font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.85rem; color: var(--accent-2); margin: 24px 0 6px; } +.tbl.wrap td, .tbl.wrap td:last-child { white-space: normal; } +.tbl.wrap th[scope=row] { text-align: left; font-weight: 500; text-transform: none; letter-spacing: 0; font-size: 0.92rem; color: var(--text); padding: 8px 8px 8px 0; border-bottom: 1px solid var(--border); vertical-align: top; } +.graph .t-api rect { stroke: var(--pred); stroke-dasharray: 4 2; } +.graph .t-group rect { stroke: var(--muted); } +.graph .t-component rect, .graph .t-option rect { stroke: var(--text); stroke-opacity: 0.5; } +.graph .node.cell rect { stroke: var(--good); stroke-width: 2; fill: var(--good-bg); } +.graph .edge.r-provides { stroke: var(--pred); stroke-opacity: 0.55; } +.graph .edge.r-consumes { stroke: var(--accent-2); stroke-opacity: 0.45; stroke-dasharray: 5 3; } +.graph .edge.r-depends-on { stroke: var(--warn); stroke-opacity: 0.5; } +.optdetail { display: grid; gap: 10px; } +.optdetail .opt { list-style: none; } +.optdetail code, .cell-card code, .verdict code { font-family: var(--mono); font-size: 0.88em; background: var(--panel-2); padding: 1px 4px; border-radius: 4px; overflow-wrap: anywhere; } +.res-sum { display: block; margin-top: 4px; } +.finding-better { color: var(--good); } .finding-worse { color: var(--bad); } +.verdicts { display: grid; gap: 12px; } +.verdict { border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; background: var(--bg); list-style: none; } +.verdict:target { outline: 2px solid var(--accent); outline-offset: 2px; } +.vhead { margin: 0 0 6px; } +.statement-small { margin: 0 0 8px; color: var(--muted); font-size: 0.92rem; } +.breaks { overflow-wrap: anywhere; word-break: break-all; } +.verbs { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); margin: 16px 0 0; padding: 0; list-style: none; } +.verbs .card { padding: 12px 14px; } +.verbs h3 { margin: 0 0 4px; } diff --git a/site/src/components/EntityList.astro b/site/src/components/EntityList.astro new file mode 100644 index 0000000..d3b00ac --- /dev/null +++ b/site/src/components/EntityList.astro @@ -0,0 +1,6 @@ +--- +// Entities as a comma-separated run of links, or the words `empty` when there are none. +import { link } from "../lib/text.mjs"; +const { items, empty = "none named" } = Astro.props; +--- +{items.length ? items.map((x, i) => <>{i > 0 && ", "}{x.title}) : {empty}} diff --git a/site/src/components/Interfaces.astro b/site/src/components/Interfaces.astro new file mode 100644 index 0000000..d9c342c --- /dev/null +++ b/site/src/components/Interfaces.astro @@ -0,0 +1,24 @@ +--- +// What an entity offers and needs, as the map says: the interfaces it provides and consumes, its owner, what it +// depends on and what depends on it. Shown only for what it has. An API shows who provides and who consumes it. +import { up } from "../lib/text.mjs"; +const { site, ent, depth = 0 } = Astro.props; +const u = up(depth); +const consumers = site.ins(ent, "consumes"); +const all = [ + ["Provides", site.outs(ent, "provides")], + ["Consumes", site.outs(ent, "consumes")], + ["Provided by", site.ins(ent, "provides")], + ["Consumed by", consumers], + ["Depends on", site.outs(ent, "depends-on")], + ["Dependents", site.ins(ent, "depends-on")], +].filter(([, l]) => l.length); +const owners = site.outs(ent, "owned-by"); +const owned = ent.type === "group" ? site.ins(ent, "owned-by") : []; +--- +{(all.length > 0 || owners.length > 0 || owned.length > 0) &&

Interfaces and ownership

+
+{owners.length > 0 && <>
Owner
{owners.map((o, i) => <>{i > 0 && ", "}{o.name})}
} +{all.map(([label, items]) => <>
{label}
{items.map((x, i) => <>{i > 0 && ", "}{x.title})}
)} +{owned.length > 0 && <>
Owns
{owned.map((x, i) => <>{i > 0 && ", "}{x.name})}
} +
} diff --git a/site/src/layouts/Base.astro b/site/src/layouts/Base.astro index 810143b..bde52ff 100644 --- a/site/src/layouts/Base.astro +++ b/site/src/layouts/Base.astro @@ -8,7 +8,8 @@ import { safeUrl, up } from "../lib/text.mjs"; const { site, title, description = "", depth = 0, current = "" } = Astro.props; const u = up(depth); const listed = site.pages.filter((p) => p.kind !== "page"); -const fixed = site.nav.filter((n) => n.id !== "notes" || listed.length).map((n) => [n.asIs ? n.href : `${u}${n.href}`, n.text, n.offsite, n.asIs ? null : n.href]); +const hidden = { notes: !listed.length, catalog: !site.hasCatalog, optimise: !site.hasOptimise }; +const fixed = site.nav.filter((n) => !hidden[n.id]).map((n) => [n.asIs ? n.href : `${u}${n.href}`, n.text, n.offsite, n.asIs ? null : n.href]); const extra = site.pages.filter((p) => typeof p.nav === "number").sort((a, b) => a.nav - b.nav).map((p) => [`${u}${p.slug}.html`, p.title, false, `${p.slug}.html`]); const nav = [...fixed, ...extra]; const fullTitle = title && title !== site.title ? `${title} · ${site.title}` : site.title; @@ -52,7 +53,7 @@ const iconType = { ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image
-

{site.owner}'s research, built by Morphogen from the claim, role and option files in {repoUrl ? {site.repo} : site.repo}. Static files only: no tracking, no cookies, nothing loaded from elsewhere. Steering happens in GitHub issues. Everything on the site · the graph as JSON

+

{site.owner}'s research, built by Morphogen from the map, catalog, claim and verdict files in {repoUrl ? {site.repo} : site.repo}. Static files only: no tracking, no cookies, nothing loaded from elsewhere. Steering happens in GitHub issues. Everything on the site · the graph as JSON

diff --git a/site/src/lib/catalog.mjs b/site/src/lib/catalog.mjs new file mode 100644 index 0000000..939297a --- /dev/null +++ b/site/src/lib/catalog.mjs @@ -0,0 +1,31 @@ +// What the catalog page says about an option: its adjustable parameters (a JSON Schema in spec.morphogen.parameters), +// and the figures the compare table sets side by side. Plain JavaScript, so `node --test` reads it too. + +const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v); + +/** The properties of a JSON Schema of settings, as rows: name, type, the range or the choices, the default. */ +export function parameterRows(schema) { + const props = isObj(schema) && isObj(schema.properties) ? schema.properties : isObj(schema) ? schema : {}; + const rows = []; + for (const [name, p] of Object.entries(props)) { + if (!isObj(p)) continue; + const lo = p.minimum ?? p.exclusiveMinimum, hi = p.maximum ?? p.exclusiveMaximum; + const range = lo != null || hi != null ? `${lo ?? "…"} to ${hi ?? "…"}` : ""; + const choices = Array.isArray(p.enum) ? p.enum.map(String).join(" | ") : ""; + rows.push({ + name, type: Array.isArray(p.type) ? p.type.join(" | ") : String(p.type ?? ""), bounds: choices || range, + default: p.default === undefined ? "" : typeof p.default === "string" ? p.default : JSON.stringify(p.default), + about: typeof p.description === "string" ? p.description : "", + }); + } + return rows; +} + +/** The claims about an option that say it is better, worse, or about the same as its baseline: the trade-offs the + * papers report, each with the metric. */ +export function tradeoffs(site, claims) { + return site.sorted(claims.filter((c) => !c.ours)).map((c) => { + const cl = c.spec.claim || {}; + return { claim: c, finding: cl.finding || "none-stated", metric: cl.metric || "", statement: cl.statement || c.title }; + }); +} diff --git a/site/src/lib/config.mjs b/site/src/lib/config.mjs index 3bc0aaf..a00b69c 100644 --- a/site/src/lib/config.mjs +++ b/site/src/lib/config.mjs @@ -23,10 +23,12 @@ export const NAV_PAGES = { predictions: ["predictions.html", "Predictions"], roles: ["roles.html", "Roles"], map: ["map.html", "Map"], + catalog: ["catalog.html", "Catalog"], + optimise: ["optimise.html", "Optimise"], notes: ["notes.html", "Notes"], search: ["search.html", "Search"], }; -const DEFAULT_NAV = ["claims", "queue", "predictions", "roles", "map", "notes"]; +const DEFAULT_NAV = ["claims", "queue", "predictions", "roles", "map", "catalog", "optimise", "notes"]; const ACTIONS = ["prioritise", "reject", "dispute", "question", "propose-role", "propose-option"]; /** One `[nav] pages` entry: a page id (or `{page, text}`), or `{text, href}` for any other link. A link is external @@ -114,7 +116,12 @@ export function loadConfig(file = process.env.MORPHOGEN_SITE_CONFIG || path.join labels, sources: { claims: list(src.claims).map(at), - catalog: list(src.catalog).map(at), + // `catalog` is every entity file; `map` and `options` name the map's and the catalogued options' files apart + // (the same kind of file, read together): see site/README.md + catalog: [...new Set([...list(src.catalog), ...list(src.map), ...list(src.options)].map(at))], + map: list(src.map).map(at), + options: list(src.options).map(at), + verdicts: at(src.verdicts), research: at(src.research), content: at(src.content), schema: at(src.schema) || path.resolve(SITE_DIR, "..", "schemas", "evidence-claim.v1.json"), diff --git a/site/src/lib/data.mjs b/site/src/lib/data.mjs index 6e2c7eb..a81e3ef 100644 --- a/site/src/lib/data.mjs +++ b/site/src/lib/data.mjs @@ -9,6 +9,8 @@ // component components/.html any other Component // resource resources/.html a Resource: a model, engine, GPU or dataset (spec.type) // system systems/.html a System +// api apis/.html an API: an interface that components provide and consume +// group owners/.html a Group or User, or an owner a spec names that has no file of its own // trial trials/.html derived: a claim's source when it is our trial or probe, and every outcome's trial // paper papers/.html derived: a claim's source when it is a paper (or any other outside source) // page .html a Markdown file in the content folder (attached by the Astro side, site.mjs) @@ -20,6 +22,7 @@ import addFormats from "ajv-formats"; import YAML from "yaml"; import { loadConfig } from "./config.mjs"; import { MIXED, OBSERVATION, refKind, refName, slugify, truncate } from "./text.mjs"; +import { cellsOf, loadVerdicts } from "./optimise.mjs"; export const TYPES = { @@ -31,6 +34,8 @@ export const TYPES = { resource: { dir: "resources", one: "Resource", many: "Resources" }, component: { dir: "components", one: "Component", many: "Components" }, system: { dir: "systems", one: "System", many: "Systems" }, + api: { dir: "apis", one: "API", many: "APIs" }, + group: { dir: "owners", one: "Owner", many: "Owners" }, page: { dir: "", one: "Page", many: "Pages" }, }; @@ -47,6 +52,10 @@ export const RELS = { fills: ["Fills the role", "Options for it"], "part-of": ["Part of", "Parts"], "in-system": ["System", "In this system"], + provides: ["Provides", "Provided by"], + consumes: ["Consumes", "Consumed by"], + "depends-on": ["Depends on", "Dependents"], + "owned-by": ["Owner", "Owns"], mentions: ["Mentions", "Notes and pages"], "uses-trial": ["Trial", "Claims from it"], }; @@ -156,6 +165,7 @@ export class Site { this.edges = []; this.unresolved = []; this.research = {}; + this.verdicts = { file: null, records: [], all: [], chain: null, problems: [] }; this.pages = []; } @@ -200,8 +210,8 @@ export class Site { if (!ref) return null; const kind = refKind(ref); const name = refName(ref); - const types = { component: ["role", "option", "component"], resource: ["resource"], system: ["system"] }[kind] - || (kind ? [] : ["role", "option", "component", "resource", "system"]); + const types = { component: ["role", "option", "component"], resource: ["resource"], system: ["system"], api: ["api"], + group: ["group"], user: ["group"] }[kind] || (kind ? [] : ["role", "option", "component", "resource", "system", "api", "group"]); for (const t of types) { const e = this.entities.get(`${t}:${name}`); if (e) return e; @@ -348,6 +358,25 @@ export class Site { return out; } + // ---- what the pages have to show: a page whose data is absent leaves the header + + /** The map has interfaces, dependencies or owners to draw as well as the research's links. */ + get hasSystemMap() { + return this.edges.some((e) => ["provides", "consumes", "depends-on"].includes(e.rel)); + } + + get hasCatalog() { + return this.of("role").length > 0 || this.of("option").length > 0; + } + + get cells() { + return (this._cells ||= cellsOf(this)); + } + + get hasOptimise() { + return this.cells.length > 0 || this.verdicts.records.length > 0; + } + fileUrl(p) { return `https://github.com/${this.repo}/blob/${this.branch}/${p}`; } @@ -367,6 +396,40 @@ function shortTitle(desc, name) { return head && head.length <= 50 ? head : name; } +const asList = (v) => (v == null ? [] : Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && x); + +/** An API named by a bare name in providesApis/consumesApis is `api:default/name`. */ +const apiRef = (r) => (refKind(r) ? r : `api:default/${r}`); + +/** Entity documents from the catalog sources: files, folders of files, and the targets of each `Location` (read + * relative to the file that names it, once each; a target that is missing is a warning, not a failure). */ +function loadCatalog(sources, config, warnings) { + const docs = [], seen = new Set(); + const here = path.dirname(config); + const file = (f, named) => { + const abs = path.resolve(f); + if (seen.has(abs)) return; + seen.add(abs); + if (!fs.existsSync(abs)) { + warnings.push(`${path.relative(here, abs)} does not exist; skipped`); + return; + } + if (fs.statSync(abs).isDirectory()) { + for (const g of walk(abs).sort()) file(g, true); + return; + } + for (const d of loadYamlDocs(abs)) { + docs.push(d); + if (d.kind === "Location") { + const targets = [...asList(d.spec?.targets), ...asList(d.spec?.target)]; + for (const t of targets) if (!/^[a-z][a-z0-9+.-]*:/i.test(t)) file(path.resolve(path.dirname(abs), t), false); + } + } + }; + for (const f of sources) file(f, false); + return docs; +} + function fills(option) { const f = option.spec?.morphogen?.fills || []; return Array.isArray(f) ? f : [f]; @@ -387,16 +450,15 @@ export function loadSite(cfg = loadConfig()) { const root = cfg.root; const schema = JSON.parse(fs.readFileSync(srcs.schema, "utf8")); const raw = loadClaims(srcs.claims, root, schema); - const docs = []; const warnings = []; - for (const f of srcs.catalog) { - if (fs.existsSync(f) && fs.statSync(f).isDirectory()) for (const g of walk(f).sort()) docs.push(...loadYamlDocs(g)); - else if (fs.existsSync(f)) docs.push(...loadYamlDocs(f)); - else warnings.push(`${path.relative(path.dirname(cfg.config), f)} does not exist; skipped`); - } + const docs = loadCatalog(srcs.catalog, cfg.config, warnings); const site = new Site(cfg); site.research = loadResearch(srcs.research); site.warnings = warnings; + if (srcs.verdicts) { + site.verdicts = loadVerdicts(srcs.verdicts); + if (!site.verdicts.file) warnings.push(`${path.relative(path.dirname(cfg.config), srcs.verdicts)} does not exist; no verdicts`); + } // catalog entities for (const d of docs) { @@ -405,6 +467,8 @@ export function loadSite(cfg = loadConfig()) { if (!md.name) continue; const base = { doc: d, name: md.name, title: md.name, summary: md.description || "", spec }; if (d.kind === "System") site.add("system", md.name, base); + else if (d.kind === "API") site.add("api", md.name, base); + else if (d.kind === "Group" || d.kind === "User") site.add("group", md.name, { ...base, kind: d.kind.toLowerCase(), title: md.title || md.name }); else if (d.kind === "Resource") { site.add("resource", md.name, { ...base, kind: spec.type || "resource", title: shortTitle(md.description, md.name) }); } else if (d.kind === "Component") { @@ -412,12 +476,26 @@ export function loadSite(cfg = loadConfig()) { site.add(type, md.name, base); } } + // an owner a spec names that has no Group or User file is still somebody: a page listing what it owns + for (const ent of [...site.entities.values()]) { + const owner = ent.spec?.owner; + if (typeof owner !== "string" || !owner || ent.type === "group") continue; + if (!site.catalogRef(owner)) { + const kind = refKind(owner) === "user" ? "user" : "group"; + site.add("group", refName(owner), { doc: null, name: refName(owner), title: refName(owner), summary: "", spec: {}, kind, implied: true }); + } + } // catalog references for (const ent of [...site.entities.values()]) { const spec = ent.spec || {}; if (ent.type === "option") for (const r of fills(ent)) refEdge(site, ent, r, "fills"); if (spec.subcomponentOf) refEdge(site, ent, spec.subcomponentOf, "part-of"); if (spec.system && ent.type !== "system") refEdge(site, ent, `system:${refName(spec.system)}`, "in-system"); + if (ent.type === "group") continue; + if (typeof spec.owner === "string" && spec.owner) refEdge(site, ent, spec.owner, "owned-by"); + for (const r of asList(spec.providesApis)) refEdge(site, ent, apiRef(r), "provides"); + for (const r of asList(spec.consumesApis)) refEdge(site, ent, apiRef(r), "consumes"); + for (const r of asList(spec.dependsOn)) refEdge(site, ent, r, "depends-on"); } // claims, and the papers and trials they come from diff --git a/site/src/lib/layout.mjs b/site/src/lib/layout.mjs index 4bf8dc8..5f4df02 100644 --- a/site/src/lib/layout.mjs +++ b/site/src/lib/layout.mjs @@ -23,9 +23,25 @@ export function mapEdges(site) { }); } -export function layout(site, { colWidth = 230, rowHeight = 22, top = 40, nodeWidth = 180 } = {}) { - const edges = mapEdges(site); - const cols = COLUMNS.map((c) => ({ ...c, nodes: [] })); +/** The system's own map: who owns what, the roles and systems, the components, the interfaces between them and what + * they depend on. */ +export const SYSTEM_COLUMNS = [ + { key: "owners", label: "Owners", types: ["group"] }, + { key: "systems", label: "Systems and roles", types: ["system", "role"] }, + { key: "components", label: "Components and options", types: ["component", "option"] }, + { key: "apis", label: "Interfaces", types: ["api"] }, + { key: "resources", label: "Resources", types: ["resource"] }, +]; + +/** The references the system's map draws: what provides and consumes an interface, what depends on what, how parts + * nest and which role an option fills. Ownership and membership are on each entity's page, not drawn. */ +export function systemEdges(site) { + return site.edges.filter((e) => ["provides", "consumes", "depends-on", "part-of", "fills"].includes(e.rel)); +} + +export function layout(site, { colWidth = 230, rowHeight = 22, top = 40, nodeWidth = 180, columns = COLUMNS, edgesOf = mapEdges, connectedOnly = false } = {}) { + const edges = edgesOf(site); + const cols = columns.map((c) => ({ ...c, nodes: [] })); const colOf = new Map(); for (const ent of site.entities.values()) { const i = cols.findIndex((c) => c.types.includes(ent.type)); @@ -41,12 +57,15 @@ export function layout(site, { colWidth = 230, rowHeight = 22, top = 40, nodeWid nbrs.get(a).add(b); } } - // start: claims by role then option, others by type then name + if (connectedOnly) for (const c of cols) c.nodes = c.nodes.filter((n) => nbrs.has(n.id)); + // start: claims by role then option, others by type then name (a system's map: by type then name) for (const c of cols) c.nodes.sort((a, b) => (a.type + (a.spec?.role || "") + (a.spec?.about || "") + a.key).localeCompare(b.type + (b.spec?.role || "") + (b.spec?.about || "") + b.key)); const pos = new Map(); const index = () => cols.forEach((c) => c.nodes.forEach((n, i) => pos.set(n.id, i / Math.max(1, c.nodes.length - 1)))); index(); - const order = [2, 1, 3, 0, 4, 2, 1, 3, 0, 4, 2]; + const n = cols.length; + const order = n === 5 && columns === COLUMNS ? [2, 1, 3, 0, 4, 2, 1, 3, 0, 4, 2] + : [...Array(n).keys(), ...[...Array(n).keys()].reverse(), ...Array(n).keys()]; for (const ci of order) { const c = cols[ci]; const bary = (n) => { @@ -58,7 +77,7 @@ export function layout(site, { colWidth = 230, rowHeight = 22, top = 40, nodeWid c.nodes = keyed.map((x) => x[1]); index(); } - const height = top + Math.max(...cols.map((c) => c.nodes.length)) * rowHeight + 20; + const height = top + Math.max(1, ...cols.map((c) => c.nodes.length)) * rowHeight + 20; const nodes = []; const at = new Map(); cols.forEach((c, ci) => { diff --git a/site/src/lib/optimise.mjs b/site/src/lib/optimise.mjs new file mode 100644 index 0000000..9a3ee35 --- /dev/null +++ b/site/src/lib/optimise.mjs @@ -0,0 +1,288 @@ +// The Optimise page's data: the cells in the map (what may change, how each is scored, who may merge a pass) and the +// judge's verdict log. Plain JavaScript with no Astro imports, so `node --test` reads it too. +// +// The verdict log is the judge's evidence log (morphogen/evidence.py), exported with +// morphogen evidence --limit 100000 > verdicts.json +// (a JSON array, newest first, as that command prints it) or as JSON lines. Each record is a JSON object chained to +// the one before it by `prev` and `hash`; a verdict has `kind: verdict`, `verdict: pass|fail`, `refs` (base and +// candidate commit), `parameters`, `gate`, and an `outcome` whose keys depend on the method (morphogen/judge.py; +// schemas/evidence-record.v1.json). The judge's own `reasons` are not stored, so the reasons shown are rebuilt from +// the outcome the same way the judge words them. +import crypto from "node:crypto"; +import fs from "node:fs"; +import { refName } from "./text.mjs"; + +/** A number as the file wrote it: Python writes 1.0 and 1e-05 where JavaScript would write 1 and 0.00001, and a + * hash is of the text. */ +class Raw { + constructor(source) { + this.source = source; + } +} + +const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v); +const list = (v) => (v == null ? [] : Array.isArray(v) ? v : [v]); +const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null); +const str = (v) => (typeof v === "string" ? v : v == null ? "" : String(v)); + +// ---------------------------------------------------------------- the log + +/** The same canonical JSON the log hashes (morphogen/evidence.py `canonical`): keys sorted, no spaces, UTF-8. */ +export function canonical(v) { + if (v instanceof Raw) return v.source; + if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`; + if (isObj(v)) return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`; + return JSON.stringify(v); +} + +export function recordHash(rec) { + const { hash, ...rest } = rec; + return crypto.createHash("sha256").update(canonical(rest)).digest("hex"); +} + +function parseBoth(t, what) { + try { + const plain = JSON.parse(t); + let raw = plain; + try { + raw = JSON.parse(t, (k, v, ctx) => (typeof v === "number" && ctx?.source ? new Raw(ctx.source) : v)); + } catch { + raw = plain; // no number sources in this runtime: hashes are checked on the numbers JavaScript writes + } + return { plain, raw }; + } catch (e) { + throw new Error(`build: ${what} is not valid JSON: ${e.message}`); + } +} + +/** Parse a log file's text: a JSON array, `{records: [...]}`, or JSON lines; each row twice, as plain values and with + * its numbers as written. Throws on text that is none of them. */ +export function parseLog(text, name = "the verdict log") { + const t = text.trim(); + let rows, raws; + if (!t) rows = raws = []; + else if (t.startsWith("[") || (t.startsWith("{") && !t.includes("\n{"))) { + const { plain, raw } = parseBoth(t, name); + const pick = (j) => (Array.isArray(j) ? j : Array.isArray(j?.records) ? j.records : [j]); + rows = pick(plain); + raws = pick(raw); + } else { + const parsed = t.split("\n").filter((l) => l.trim()).map((l, i) => parseBoth(l, `${name}, line ${i + 1}`)); + rows = parsed.map((x) => x.plain); + raws = parsed.map((x) => x.raw); + } + return rows.map((r, i) => ({ row: r, raw: raws[i] })); +} + +/** Whether the records form the log's chain: each one's `prev` is the one before's `hash`, `seq` counts up by one, and + * its hash recomputes from the record as written. `edited` lists the records whose hash does not recompute. */ +export function verifyChain(sorted, raws = new Map()) { + let links = true, brokenAt = null; + const edited = []; + sorted.forEach((r, i) => { + if (i > 0) { + const p = sorted[i - 1]; + if (r.prev !== p.hash || r.seq !== p.seq + 1) { + if (links) brokenAt = r.seq; + links = false; + } + } + if (typeof r.hash !== "string" || recordHash(raws.get(r) || r) !== r.hash) edited.push(r.seq); + }); + const first = sorted[0]; + return { + records: sorted.length, from: first?.seq ?? null, to: sorted.at(-1)?.seq ?? null, + complete: !!first && first.seq === 1 && /^0{64}$/.test(str(first.prev)), + links, brokenAt, edited, + }; +} + +const EVIDENCE_FIELDS = ["signature", "signatures", "attestation", "attestations", "transparency", "transparency_log", "tlog", + "rekor", "log_index", "inclusion_proof", "bundle", "sigstore"]; + +/** Any signature or transparency-log entry a record carries, as [field, text] (shortened). Nothing in the judge's own + * records has one yet; the log is open to fields a caller adds. */ +export function proofsOf(rec) { + const out = []; + for (const k of Object.keys(rec)) { + if (!EVIDENCE_FIELDS.includes(k.toLowerCase())) continue; + const v = rec[k]; + if (v == null || v === "" || (Array.isArray(v) && !v.length)) continue; + const text = typeof v === "string" ? v : canonical(v); + out.push([k, text.length > 240 ? `${text.slice(0, 240)}…` : text]); + } + return out; +} + +const short = (sha) => str(sha).slice(0, 12); + +function pct(x) { + const n = num(x); + return n == null ? "" : `${n >= 0 ? "+" : ""}${(n * 100).toFixed(1)}%`; +} + +/** The measures of a verdict: one row per metric the judge compared, from outcome.metrics. */ +function measuresOf(outcome) { + const m = isObj(outcome.metrics) ? outcome.metrics : {}; + return Object.entries(m).filter(([, c]) => isObj(c)).map(([name, c]) => ({ + name, base: num(c.base), candidate: num(c.candidate), gain: num(c.gain), ci95: Array.isArray(c.ci95) ? c.ci95.map(num) : null, + p: num(c.sign_test_p), ok: c.ok === true ? true : c.ok === false ? false : null, + })); +} + +/** Why, in the judge's own words, from what a verdict record keeps. */ +export function reasonsOf(rec) { + const o = isObj(rec.outcome) ? rec.outcome : {}; + const why = []; + const denied = list(o.denied).map(str).filter(Boolean); + if (denied.length) why.push(`changes what the cell may not change: ${denied.join("; ")}`); + const forbidden = list(o.forbidden).map(str).filter(Boolean); + if (forbidden.length) why.push(`changes files that shadow standard modules or customise Python: ${forbidden.join(", ")}`); + for (const v of list(o.parameter_violations)) why.push(str(v)); + if (o.check === false) why.push("the base's tests fail on the candidate"); + const system = isObj(o.system) ? o.system : null; + if (system && system.ok === false) why.push(`the enclosing system (${str(system.cell || system.target)}) gets worse`); + for (const x of list(o.interfaces)) if (isObj(x) && x.passed === false) why.push(`interface ${str(x.interface)}: its test fails on the candidate`); + for (const x of list(o.tests)) if (isObj(x) && x.passed === false) why.push(`${x.interface ? `interface ${str(x.interface)}` : `cell ${str(x.cell)}`}: its test fails on the candidate`); + const wrong = num(o.wrong) || 0, failed = num(o.failed) || 0; + if (wrong || failed) why.push(`${wrong} wrong and ${failed} failed outputs on ${num(o.generated_inputs) ?? "?"} generated inputs`); + if (num(o.timed_output_mismatches)) why.push(`${o.timed_output_mismatches} timed runs gave different output from the base`); + for (const m of measuresOf(o)) { + if (m.ok === false) { + const ci = m.ci95 && m.ci95.length === 2 ? ` (95% interval ${pct(m.ci95[0])} to ${pct(m.ci95[1])}${m.p != null ? `, sign test p=${m.p}` : ""})` : ""; + why.push(`${m.name}: gain ${pct(m.gain)}${ci} does not meet the bar`); + } + } + return why; +} + +/** The cells a record is about: `cell`, else `cells`, else the names in subject.system. */ +function cellsIn(rec) { + if (rec.cell) return [str(rec.cell)]; + if (Array.isArray(rec.cells) && rec.cells.length) return rec.cells.map(str); + const sys = str(rec.subject?.system); + return sys ? sys.split(",").map((x) => x.trim()).filter(Boolean) : []; +} + +/** One verdict record, as the page shows it. */ +export function shapeVerdict(rec) { + const o = isObj(rec.outcome) ? rec.outcome : {}; + const passed = rec.verdict === "pass"; + const params = isObj(rec.parameters) + ? Object.entries(rec.parameters).filter(([, p]) => isObj(p)).map(([name, p]) => ({ name, owner: str(p.owner), base: p.base, candidate: p.candidate })) + : []; + const files = isObj(o.files) ? Object.keys(o.files).sort() : []; + const reasons = reasonsOf(rec); + const measures = measuresOf(o); + return { + seq: rec.seq, at: str(rec.at), by: str(rec.by), trust: str(rec.trust), claim: str(rec.claim), method: str(rec.method), + verdict: passed ? "pass" : "fail", cells: cellsIn(rec), subject: str(rec.subject?.path), + base: str(rec.refs?.base), candidate: str(rec.refs?.candidate), baseShort: short(rec.refs?.base), candidateShort: short(rec.refs?.candidate), + gate: str(rec.gate?.decision), sandbox: str(rec.sandbox), request: isObj(rec.request) ? str(rec.request.digest) : "", + measures, changed: params.filter((p) => JSON.stringify(p.base) !== JSON.stringify(p.candidate)), params, files, + reasons: reasons.length ? reasons : passed ? (measures.length ? ["every measure met its bar"] : ["the checks passed"]) : ["the record gives no reason"], + proofs: proofsOf(rec), hash: str(rec.hash), prev: str(rec.prev), generated: num(o.generated_inputs) ?? (isObj(o.generated_inputs) ? num(o.generated_inputs.cases) : null), + }; +} + +/** Read a verdict log. `file` is null in the result when it does not exist; a file that is not a log stops the build. */ +export function loadVerdicts(file) { + const none = { file: null, records: [], all: [], chain: null, problems: [] }; + if (!file || !fs.existsSync(file)) return none; + const parsed = parseLog(fs.readFileSync(file, "utf8"), file); + const problems = []; + const raws = new Map(); + const all = parsed.filter((p, i) => (isObj(p.row) ? true : (problems.push(`record ${i + 1} is not an object`), false))) + .map((p, i) => { + const r = { ...p.row, seq: Number.isInteger(p.row.seq) ? p.row.seq : i + 1 }; + raws.set(r, { ...p.raw, seq: p.raw.seq instanceof Raw ? p.raw.seq : r.seq }); + return r; + }) + .sort((a, b) => a.seq - b.seq); + const verdicts = all.filter((r) => r.kind === "verdict" && (r.verdict === "pass" || r.verdict === "fail")).map(shapeVerdict); + return { file, records: verdicts, all, chain: all.length ? verifyChain(all, raws) : null, problems }; +} + +// ---------------------------------------------------------------- the cells + +/** The metric a cell's `better` names first, and its direction: "mape lower" or {mape: {lower: true}}. */ +export function primaryMetric(better) { + if (typeof better === "string") { + const first = better.split(",")[0].trim().split(/\s+/); + return first[0] ? { name: first[0], direction: first[1] || "" } : null; + } + if (isObj(better)) { + const [name, spec] = Object.entries(better)[0] || []; + if (!name) return null; + const dir = typeof spec === "string" ? spec : isObj(spec) ? (spec.lower || spec.direction === "lower" ? "lower" : spec.higher || spec.direction === "higher" ? "higher" : "") : ""; + return { name, direction: dir }; + } + return null; +} + +function metricsText(better) { + if (typeof better === "string") return better; + if (isObj(better)) return Object.entries(better).map(([k, v]) => `${k} ${primaryMetric({ [k]: v }).direction}`.trim()).join(", "); + return ""; +} + +/** Everything in `change` as {target, bounds}: `path#NAME in 0..100`, `path:key`, a path or a glob. */ +function changeOf(change) { + return list(change).map(str).map((c) => { + const m = /^(.*?)\s+in\s+(.+)$/.exec(c); + return { target: m ? m[1] : c, bounds: m ? m[2] : "" }; + }); +} + +/** The cells in the map: a component or system with a `run` (or `tests`) under `spec.morphogen`, with the System's + * `defaults` underneath. A role or an option is never a cell; an entity with neither is structure. */ +export function cellsOf(site) { + const system = site.of("system").find((s) => s.spec?.morphogen) || null; + const settings = system?.spec?.morphogen || {}; + const defaults = isObj(settings.defaults) ? settings.defaults : {}; + const out = []; + for (const ent of site.entities.values()) { + if (ent.type !== "component" && ent.type !== "system") continue; + const own = ent.spec?.morphogen; + if (!isObj(own) || !(own.run || own.tests)) continue; + const r = { ...defaults, ...Object.fromEntries(Object.entries(own).filter(([, v]) => v !== null)) }; + const lifecycle = str(ent.spec?.lifecycle); + const auto = isObj(settings.autonomy) ? settings.autonomy : {}; + const decision = auto[lifecycle] === "merge" ? "merge" : "review"; + const owner = ent.out.find((e) => e.rel === "owned-by")?.to || null; + out.push({ + ent, name: ent.name, lifecycle, owner, rules: r, + description: str(r.description), + change: changeOf(r.change), keep: list(r.keep).map(str), + judged: !!r.run, run: str(r.run), score: str(r.score), tests: list(r.tests).map(str), + better: metricsText(r.better), primary: primaryMetric(r.better), observe: isObj(r.observe) ? canonical(r.observe) : str(r.observe), + autonomy: decision, autonomyNote: decision === "merge" + ? `a pass on a ${lifecycle || "this"} cell may be merged by an agent` + : `a pass on a ${lifecycle || "this"} cell goes to a person: the judge never merges, and the project's autonomy does not name this lifecycle as merge`, + }); + } + return out.sort((a, b) => a.name.localeCompare(b.name)); +} + +/** Verdicts by cell name (a verdict on several cells is listed under each), and the ones whose cell is not in the map. */ +export function verdictsByCell(site, cells) { + const known = new Set(cells.map((c) => c.name)); + const by = new Map(); + const strays = new Map(); + for (const v of site.verdicts.records) { + const names = v.cells.length ? v.cells : [v.subject || "(unnamed)"]; + for (const n0 of names) { + const n = refName(n0); + const bucket = known.has(n) ? by : strays; + if (!bucket.has(n)) bucket.set(n, []); + bucket.get(n).push(v); + } + } + for (const m of [by, strays]) for (const l of m.values()) l.sort((a, b) => b.seq - a.seq); + return { by, strays }; +} + +/** What the judge last measured for a cell: the newest verdict's measures (what was observed, as the judge took it). */ +export function lastMeasured(verdicts) { + return (verdicts || []).find((v) => v.measures.length) || null; +} diff --git a/site/src/lib/site.mjs b/site/src/lib/site.mjs index a1a3210..88c9b7c 100644 --- a/site/src/lib/site.mjs +++ b/site/src/lib/site.mjs @@ -4,7 +4,7 @@ import { getCollection } from "astro:content"; import { attachPages, loadSite } from "./data.mjs"; -const RESERVED = new Set(["index", "queue", "predictions", "roles", "map", "search", "notes", "404"]); +const RESERVED = new Set(["index", "queue", "predictions", "roles", "map", "catalog", "optimise", "search", "notes", "404"]); let cached = null; let warned = false; diff --git a/site/src/pages/apis/[name].astro b/site/src/pages/apis/[name].astro new file mode 100644 index 0000000..e7ed91e --- /dev/null +++ b/site/src/pages/apis/[name].astro @@ -0,0 +1,35 @@ +--- +// One API: an interface that components provide and consume, who does each, its tests and where it is defined. +import Base from "../../layouts/Base.astro"; +import EntityHead from "../../components/EntityHead.astro"; +import Evidence from "../../components/Evidence.astro"; +import Interfaces from "../../components/Interfaces.astro"; +import Mentions from "../../components/Mentions.astro"; +import References from "../../components/References.astro"; +import { getSite } from "../../lib/site.mjs"; +import { truncate, up } from "../../lib/text.mjs"; + +export async function getStaticPaths() { + const site = await getSite(); + return site.of("api").map((x) => ({ params: { name: x.slug }, props: { id: x.id } })); +} +const site = await getSite(); +const a = site.entities.get(Astro.props.id); +const spec = a.spec || {}; +const m = spec.morphogen || {}; +const tests = [m.tests].flat().filter(Boolean); +const external = { consumes: "the system offers it to the world", provides: "the system relies on it and does not own it" }[m.external]; +--- + + + + +{(spec.definition || tests.length > 0 || external || spec.lifecycle) &&

The promise

+{spec.definition && <>
Defined in
{String(spec.definition)}
} +{spec.lifecycle && <>
Lifecycle
{spec.lifecycle}
} +{external && <>
Open to the world
{external}
} +{tests.length > 0 && <>
Its tests
{tests.map((t) => {String(t)})}
} +
} + + + diff --git a/site/src/pages/catalog.astro b/site/src/pages/catalog.astro new file mode 100644 index 0000000..4a4e0cb --- /dev/null +++ b/site/src/pages/catalog.astro @@ -0,0 +1,74 @@ +--- +// The catalog: for each role, the options catalogued for it (interfaces, adjustable parameters, licence, docs, +// measurements, trade-offs), the research claims about each, and a table to compare them. +import Base from "../layouts/Base.astro"; +import EvidenceQuotes from "../components/Evidence.astro"; +import EntityList from "../components/EntityList.astro"; +import ExtLink from "../components/ExtLink.astro"; +import StatusCounts from "../components/StatusCounts.astro"; +import { getSite } from "../lib/site.mjs"; +import { parameterRows, tradeoffs } from "../lib/catalog.mjs"; +import { proposeOptionUrl } from "../lib/steer.mjs"; +import { link, truncate } from "../lib/text.mjs"; +const site = await getSite(); +const roles = site.of("role"); +const orphans = site.of("option").filter((o) => !site.outs(o, "fills").length); +const view = (o) => { + const m = o.spec?.morphogen || {}; + const claims = site.ins(o, "about"); + return { o, m, claims, provides: site.outs(o, "provides"), consumes: site.outs(o, "consumes"), deps: site.outs(o, "depends-on"), + params: parameterRows(m.parameters), ev: m.evaluation || {}, trade: tradeoffs(site, claims), results: site.results(claims).filter((x) => x.a.outcome) }; +}; +const sections = [...roles.map((r) => ({ role: r, opts: site.ins(r, "fills").map(view) })), + ...(orphans.length ? [{ role: null, opts: orphans.map(view) }] : [])]; +--- + +
+

Options for each role

+

The catalog

+

For each role in the map, the parts that could play it: what each provides and consumes, the settings a tuner may move, its licence and documentation, what has been measured, and the claims from papers about it. Open a role's table to compare its options side by side. The map shows how the roles sit among the parts; Roles shows what the research agent watches for each.

+

{sections.map(({ role }, i) => <>{i > 0 && " · "}{role ? {role.name} : options with no role})}

+
+{sections.map(({ role, opts }) =>
+

{role ? "Role" : "No role named"}

+

{role ? {role.name} : "Options not yet tied to a role"}

+ {role &&

{role.summary}

} + {role && } + {role && (site.outs(role, "provides").length > 0 || site.outs(role, "consumes").length > 0) &&

The role's interfaces provides ; consumes . An option fits when it keeps these.

} + +

Compare options for this role ({opts.length})

+ {opts.length > 0 ?
+ + + {opts.map((v) => + + + + + + + + )}
{role ? role.name : "Options"}: one row per option, from its catalog entry and the claims about it
OptionProvidesConsumesParametersLicenceDocsMeasuredClaims
{v.o.name}{v.params.length ? v.params.map((p) => p.name).join(", ") : none declared}{v.m.licence || not stated}{v.m.docs?.url ? : none}{v.ev.result ? truncate(String(v.ev.result), 90) : not measured} !c.ours)} />
:

No option has been catalogued for this role yet.

} + +

The options ({opts.length})

+
    {opts.map((v) =>
  • +

    {v.o.name}

    +

    {v.o.summary}

    +
    +
    Provides
    +
    Consumes
    + {v.deps.length > 0 && <>
    Depends on
    } +
    Licence
    {v.m.licence || not stated}
    +
    Docs
    {v.m.docs?.url ? : none linked}
    +
    Measurements
    {v.ev.result ? <>{v.ev.result}{v.ev.method && How: {truncate(String(v.ev.method), 300)}} : not measured}{v.results.length > 0 && {v.results.length} paper claim{v.results.length === 1 ? "" : "s"} with an outcome on this system: see its page.}
    +
    + {v.params.length > 0 && <>

    Adjustable parameters

    + {v.params.map((p) => )}
    NameTypeRange or choicesDefaultWhat it does
    {p.name}{p.type}{p.bounds}{p.default}{p.about}
    } +

    Trade-offs the research reports ({v.trade.length})

    + {v.trade.length ? :

    No claim from a paper yet.

    } +

    Status of those claims here

    !c.ours)} />

    +
  • )}
+ {role &&

Suggest an option for this role The role's page: questions, tests, claims

} +
)} +{sections.length === 0 &&

No role or option in the map.

} + diff --git a/site/src/pages/components/[name].astro b/site/src/pages/components/[name].astro index 9703197..cb3f2eb 100644 --- a/site/src/pages/components/[name].astro +++ b/site/src/pages/components/[name].astro @@ -2,6 +2,7 @@ // A Component that is neither a role nor an option. import Base from "../../layouts/Base.astro"; import EntityHead from "../../components/EntityHead.astro"; +import Interfaces from "../../components/Interfaces.astro"; import Evidence from "../../components/Evidence.astro"; import Mentions from "../../components/Mentions.astro"; import References from "../../components/References.astro"; @@ -18,6 +19,7 @@ const x = site.entities.get(Astro.props.id); + diff --git a/site/src/pages/index.astro b/site/src/pages/index.astro index 8512029..98f6b73 100644 --- a/site/src/pages/index.astro +++ b/site/src/pages/index.astro @@ -26,8 +26,22 @@ function item(c) { ...(c.spec.conditions?.models || []).map((m) => m.name || ""), ...(c.spec.assessments || []).map((a) => site.configLabel(a))].join(" ").toLowerCase(); return { c, src, role, option, search, qs: src.quote_status || "none", from: c.out.find((e) => e.rel === "from")?.to }; } +const verbs = [ + { id: "map", name: "Map", href: "map.html", text: `${site.of("system").length + site.of("component").length + site.of("role").length} systems, components and roles, ${site.of("api").length} interfaces, ${site.of("resource").length} resources: what provides, consumes and depends on what.`, show: site.hasSystemMap || claims.length === 0 }, + { id: "catalog", name: "Catalog", href: "catalog.html", text: `${site.of("option").length} option${site.of("option").length === 1 ? "" : "s"} for ${site.of("role").length} role${site.of("role").length === 1 ? "" : "s"}: interfaces, parameters, licence, measurements and trade-offs, side by side.`, show: site.hasCatalog }, + { id: "research", name: "Research", href: claims.length ? "#claims" : "roles.html", text: `${paperN} claims from papers about the options, with the conditions they were measured under and whether they hold here.`, show: claims.length > 0 }, + { id: "optimise", name: "Optimise", href: "optimise.html", text: `${site.cells.length} cell${site.cells.length === 1 ? "" : "s"} that may change and ${site.verdicts.records.length} verdict${site.verdicts.records.length === 1 ? "" : "s"} from the judge.`, show: site.hasOptimise }, +].filter((v) => v.show); +const landing = site.hasSystemMap || site.hasCatalog || site.hasOptimise; --- +{landing &&
+

Map, catalog, research, optimise

+

{site.title}

+

{site.description}

+ +
} +{claims.length > 0 && <>

The research agent's catalog

Claims from papers, checked against this system

@@ -57,4 +71,5 @@ function item(c) { +} diff --git a/site/src/pages/map.astro b/site/src/pages/map.astro index dbfff4e..668450f 100644 --- a/site/src/pages/map.astro +++ b/site/src/pages/map.astro @@ -1,37 +1,62 @@ --- import { link } from "../lib/text.mjs"; -// The relations graph: every claim between the papers and trials it comes from (and the models it was tested on) -// and the options and roles it bears on. A static SVG of links, laid out at build time (src/lib/layout.mjs); +// The map: the system as its files describe it (its parts, the interfaces between them, who owns what, what each +// depends on), and the relations graph of the research (every claim between the papers and trials it comes from and +// the options and roles it bears on). Both are static SVGs of links, laid out at build time (src/lib/layout.mjs); // Alpine's `graph` component (assets/site.js) highlights a node's neighbours and filters by kind. import Base from "../layouts/Base.astro"; import { TYPES } from "../lib/data.mjs"; -import { layout } from "../lib/layout.mjs"; +import { SYSTEM_COLUMNS, layout, systemEdges } from "../lib/layout.mjs"; import { getSite } from "../lib/site.mjs"; const site = await getSite(); -const g = layout(site); -const types = [...new Set(g.nodes.map((n) => n.ent.type))]; -const cls = (n) => `node t-${n.ent.type}${n.ent.type === "claim" ? ` s-${site.status(n.ent)}` : ""}`; +const research = site.claims.length > 0; +const sys = site.hasSystemMap ? layout(site, { columns: SYSTEM_COLUMNS, edgesOf: systemEdges, connectedOnly: true }) : null; +const graphs = [ + sys && { id: "system", g: sys, title: "The system", heading: "Parts, interfaces and dependencies", + note: "Each part sits between the interfaces it consumes and those it provides, with what it depends on to the right. Point at a node to see its neighbours; open it for its page." }, + research && { id: "research", g: layout(site), title: "The research", heading: "How the research links", + note: "Each claim sits between where it came from (a paper or one of our trials, and the models it was tested on) and what it bears on (an option, and the role that option could fill). Models link only to claims with a result on them; every page lists the rest." }, +].filter(Boolean); +const cls = (n) => `node t-${n.ent.type}${n.ent.type === "claim" ? ` s-${site.status(n.ent)}` : ""}${n.ent.type === "component" && site.cells.some((c) => c.ent === n.ent) ? " cell" : ""}`; +const kinds = ["system", "role", "component", "option", "api", "resource"]; +const rows = kinds.flatMap((t) => site.of(t)).filter((e) => e.type !== "resource" || site.hasSystemMap); +const names = (ent, rel, end) => (end === "in" ? site.ins(ent, rel) : site.outs(ent, rel)); +const cellNames = new Set(site.cells.map((c) => c.ent.id)); --- - +
-

How it all links

+

What it is made of

The map

-

Each claim sits between where it came from (a paper or one of our trials, and the models it was tested on) and what it bears on (an option, and the role that option could fill). Point at a node to see its neighbours; open it for its page. Models link only to claims with a result on them; every page lists the rest.

+

{site.hasSystemMap + ? "The system's parts, the interfaces they provide and consume, who owns each and what it depends on, then the research that bears on them. Every entity has a page with its interfaces, owner, dependencies and dependents." + : "Each claim sits between where it came from and what it bears on. Point at a node to see its neighbours; open it for its page."}

+

{site.hasCatalog && <>The catalog: the options for each role. }{site.hasOptimise && <>Optimise: the cells and the judge's verdicts. }Research: the claims.

+{graphs.map((x) =>
+

{x.heading}

+

{x.note}

-
- -The map: {g.nodes.length} entities and {g.paths.length} links -{g.cols.map((c) => {c.label})} -{g.paths.map((p) => )} -{g.nodes.map((n) => {n.label}{TYPES[n.ent.type].one}: {n.ent.title})} + +{x.title}: {x.g.nodes.length} entities and {x.g.paths.length} links +{x.g.cols.map((c) => {c.label})} +{x.g.paths.map((p) => )} +{x.g.nodes.map((n) => {n.label}{TYPES[n.ent.type].one}: {n.ent.title})}
+
)} +{site.hasSystemMap &&

Every part, with its interfaces ({rows.length})

+
+ +{rows.map((e) => + +{[names(e, "owned-by"), names(e, "provides"), names(e, "consumes"), names(e, "depends-on"), names(e, "depends-on", "in")].map((l) => )} +)}
EntityOwnerProvidesConsumesDepends onDependents
{e.title} {TYPES[e.type].one}{cellNames.has(e.id) && <> cell}{l.length ? l.map((x, i) => <>{i > 0 && ", "}{x.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.

+

{research && <>Claims are coloured by their status in the research graph: green replicated, red did not transfer, amber mixed, blue predicted, grey untested, purple our own observation. }data/graph.json has every entity and reference, for other tools; search lists everything by kind.

diff --git a/site/src/pages/optimise.astro b/site/src/pages/optimise.astro new file mode 100644 index 0000000..0afa04d --- /dev/null +++ b/site/src/pages/optimise.astro @@ -0,0 +1,80 @@ +--- +// Optimise: the cells in the map (what may change, how each is scored, what the judge last observed, who may merge a +// pass), the judge's verdict log for each (every change proposed, kept or refused, with the measures and the reasons), +// and the log's evidence chain. Built from the map's `spec.morphogen` and the verdict log in [sources] verdicts +// (src/lib/optimise.mjs); a site with neither has nothing here and no link to it. +import Base from "../layouts/Base.astro"; +import { getSite } from "../lib/site.mjs"; +import { lastMeasured, verdictsByCell } from "../lib/optimise.mjs"; +import { link } from "../lib/text.mjs"; +const site = await getSite(); +const cells = site.cells; +const log = site.verdicts; +const { by, strays } = verdictsByCell(site, cells); +const empty = !site.hasOptimise; +const num = (x) => (x == null ? "" : Number.isInteger(x) ? String(x) : String(Math.round(x * 10000) / 10000)); +const pct = (x) => (x == null ? "" : `${x >= 0 ? "+" : ""}${(x * 100).toFixed(1)}%`); +const val = (v) => (typeof v === "string" ? v : JSON.stringify(v)); +const chain = log.chain; +const proofs = log.records.filter((v) => v.proofs.length); +--- + +
+

What may change, and what the judge said

+

Optimise

+ {empty ?

Nothing here: this site's map has no cell (a part with `spec.morphogen.run`) and no verdict log is set in `[sources] verdicts`.

+ :

A cell is a part that can be changed and judged on its own. The judge scores each proposed change against the base by rules written before the change, and refuses anything outside what the cell may change. It never merges: a pass says who may. The map shows where each cell sits; the catalog lists the options for the roles around it.

} +
+ +{cells.length > 0 &&

Cells ({cells.length})

+{cells.map((c) => { + const vs = by.get(c.name) || []; + const seen = lastMeasured(vs); + return
+

Cell{c.lifecycle && <> · {c.lifecycle}}{c.owner && <> · owned by {c.owner.name}}

+

{c.name}

+ {(c.description || c.ent.summary) &&

{c.description || c.ent.summary}

} +
+
May change
{c.change.length ?
    {c.change.map((x) =>
  • {x.target}{x.bounds && <> within {x.bounds}}
  • )}
: nothing is opened: no candidate can be accepted}{c.keep.length > 0 && Held fixed: {c.keep.map((k, i) => <>{i > 0 && ", "}{k})}}
+
Score
{c.better ? <>{c.better} : no metric named}{c.score && scored outside the candidate by {c.score}}{c.run ? workload {c.run} : no workload: it has tests, so it is structure, not a judged cell}
+
Observed
{seen ? <>{seen.measures.map((m) => {m.name} {num(m.base)} to {num(m.candidate)}{m.gain != null && <> ({pct(m.gain)})} in verdict #{seen.seq} ({seen.verdict === "pass" ? "passed" : "refused"}), {seen.at})} + : {log.file ? "the log holds no measured verdict on this cell" : "no verdict log: nothing measured is on record here"}}{c.observe && declared to be observed in operation by {c.observe}}
+
Autonomy
{c.autonomy === "merge" ? "an agent may merge" : "a person reviews"} {c.autonomyNote}
+ {c.tests.length > 0 && <>
Must still pass
{c.tests.map((t) => {t})}
} +
Verdicts
{vs.length ? {vs.length} in the log: {vs.filter((v) => v.verdict === "pass").length} passed, {vs.filter((v) => v.verdict === "fail").length} refused : none yet}
+
+
; +})}
} + +{cells.length > 0 && !log.records.length &&

No verdicts to show

+

{log.file ? "The verdict log has no record of a judged change." : "No verdict log is set for this site."} The judge writes each verdict to its evidence log, which lives in git's own directory and is not committed; export it with morphogen evidence --limit 100000 > verdicts.json and name the file in [sources] verdicts of the site's config.

} + +{[...cells.map((c) => [c.name, c.ent.slug, by.get(c.name)]), ...[...strays].map(([n, v]) => [n, null, v])].filter(([, , vs]) => vs?.length).map(([name, slug, vs]) =>
+

Verdicts on {name} ({vs.length}){!slug && · not a cell in this site's map}

+
    {vs.map((v) =>
  1. +

    {v.verdict === "pass" ? "Passed" : "Refused"} #{v.seq} {v.at}{v.trust && <> · trust {v.trust}}{v.by && <> · by {v.by}}

    + {v.claim &&

    {v.claim}

    } +
    +
    Proposed
    {v.baseShort || v.candidateShort ? <>commit {v.candidateShort || "?"} against base {v.baseShort || "?"} : no commits recorded} + {v.changed.length > 0 && Settings moved: {v.changed.map((p, i) => <>{i > 0 && "; "}{p.name} {val(p.base)} to {val(p.candidate)})}} + {v.files.length > 0 && Files: {v.files.map((f, i) => <>{i > 0 && ", "}{f})}}
    + {v.measures.length > 0 && <>
    Measures
    + {v.measures.map((m) => )}
    MeasureBaseCandidateGain95% intervalSign test pBar
    {m.name}{num(m.base)}{num(m.candidate)}{pct(m.gain)}{m.ci95 ? `${pct(m.ci95[0])} to ${pct(m.ci95[1])}` : ""}{num(m.p)}{m.ok === true ? "met" : m.ok === false ? "not met" : ""}
    {v.generated != null && checked on {v.generated} generated inputs}
    } +
    Why
      {v.reasons.map((r) =>
    • {r}
    • )}
    +
    Gate
    {v.gate === "merge" ? "an agent may merge" : v.gate === "review" ? "a person reviews" : v.gate === "none" ? "no pass, so nothing to merge" : not recorded}{v.sandbox && · run in {v.sandbox}}
    +
    +
  2. )}
+
)} + +{chain &&

The evidence chain

+

Each record in the log carries the hash of the one before it, so an edit shows. The records read here: {chain.records}, numbered {chain.from} to {chain.to}{chain.complete ? ", from the first record of the log" : ", not from the log's first record, so what came before cannot be checked"}.

+
+
Links
{chain.links ? intact : broken at #{chain.brokenAt}} each record's prev is the hash before it and the numbers count up by one
+
Hashes
{chain.edited.length === 0 ? all recomputed : {chain.edited.length} do not match: #{chain.edited.slice(0, 8).join(", #")}{chain.edited.length > 8 && ", …"}} SHA-256 of each record's canonical JSON without its hash{chain.edited.length > 0 && "; a record that does not match its hash was edited after it was written"}
+
Signatures
{proofs.length ? <>{proofs.length} verdict{proofs.length === 1 ? "" : "s"} carry a signature or a transparency-log entry, shown as recorded: the page does not check them. : none: the judge's records carry no signature or transparency-log entry, so the hash chain is the only link between them}
+
+ {proofs.length > 0 &&
{proofs.flatMap((v) => v.proofs.map(([k, t]) => ))}
VerdictFieldValue
#{v.seq}{k}{t}
} + {log.problems.length > 0 &&

{log.problems.join("; ")}

} +

The first and last hash, for comparing with another copy of the log: {log.all[0].hash} and {log.all.at(-1).hash}

+
} + diff --git a/site/src/pages/options/[name].astro b/site/src/pages/options/[name].astro index 37b79b6..22e4e37 100644 --- a/site/src/pages/options/[name].astro +++ b/site/src/pages/options/[name].astro @@ -4,6 +4,7 @@ import Base from "../../layouts/Base.astro"; import ClaimList from "../../components/ClaimList.astro"; import EntityHead from "../../components/EntityHead.astro"; +import Interfaces from "../../components/Interfaces.astro"; import Evidence from "../../components/Evidence.astro"; import ExtLink from "../../components/ExtLink.astro"; import Mentions from "../../components/Mentions.astro"; @@ -31,6 +32,7 @@ const tested = site.results(claims).filter((x) => x.a.outcome);

+ {(ev.need || ev.method || ev.result) &&

Evaluation

{ev.need && <>
What would count
{ev.need}
}{ev.method && <>
How it is measured
{ev.method}
}{ev.result && <>
Result so far
{ev.result}
}
}

Tested on

{tested.length ? :

No claim about this option has an outcome on this system yet.

} diff --git a/site/src/pages/owners/[name].astro b/site/src/pages/owners/[name].astro new file mode 100644 index 0000000..5f3ebea --- /dev/null +++ b/site/src/pages/owners/[name].astro @@ -0,0 +1,26 @@ +--- +// An owner: a Group or User, or a name a spec gives as its owner. What it owns, and what that provides and consumes. +import Base from "../../layouts/Base.astro"; +import EntityHead from "../../components/EntityHead.astro"; +import Interfaces from "../../components/Interfaces.astro"; +import Mentions from "../../components/Mentions.astro"; +import References from "../../components/References.astro"; +import { getSite } from "../../lib/site.mjs"; +import { TYPES } from "../../lib/data.mjs"; +import { up } from "../../lib/text.mjs"; + +export async function getStaticPaths() { + const site = await getSite(); + return site.of("group").map((x) => ({ params: { name: x.slug }, props: { id: x.id } })); +} +const site = await getSite(); +const g = site.entities.get(Astro.props.id); +--- + + + {g.implied &&

Named as an owner in the map; the map has no Group or User file for it.

} +
+ + + + diff --git a/site/src/pages/resources/[name].astro b/site/src/pages/resources/[name].astro index f8046fd..88e9eb4 100644 --- a/site/src/pages/resources/[name].astro +++ b/site/src/pages/resources/[name].astro @@ -4,6 +4,7 @@ import Base from "../../layouts/Base.astro"; import ClaimList from "../../components/ClaimList.astro"; import EntityHead from "../../components/EntityHead.astro"; +import Interfaces from "../../components/Interfaces.astro"; import Evidence from "../../components/Evidence.astro"; import Mentions from "../../components/Mentions.astro"; import References from "../../components/References.astro"; @@ -32,6 +33,7 @@ const kindText = { model: "Model", engine: "Engine", hardware: "Hardware", datas

{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.

}
diff --git a/site/src/pages/roles/[name].astro b/site/src/pages/roles/[name].astro index e384b0d..d036bf6 100644 --- a/site/src/pages/roles/[name].astro +++ b/site/src/pages/roles/[name].astro @@ -4,6 +4,7 @@ import Base from "../../layouts/Base.astro"; import ClaimList from "../../components/ClaimList.astro"; import EntityHead from "../../components/EntityHead.astro"; +import Interfaces from "../../components/Interfaces.astro"; import Evidence from "../../components/Evidence.astro"; import Meter from "../../components/Meter.astro"; import Mentions from "../../components/Mentions.astro"; @@ -35,6 +36,7 @@ const queue = site.queue().map((q, i) => ({ ...q, rank: i + 1 })).filter((q) =>

+

Open questions the agent watches

diff --git a/site/src/pages/search.astro b/site/src/pages/search.astro index 35d536b..9361684 100644 --- a/site/src/pages/search.astro +++ b/site/src/pages/search.astro @@ -6,7 +6,7 @@ import { TYPES } from "../lib/data.mjs"; import { getSite } from "../lib/site.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 order = ["claim", "paper", "trial", "resource", "option", "role", "component", "api", "group", "system", "page"]; const groups = order.map((t) => [t, [...site.of(t)].sort((a, b) => a.title.localeCompare(b.title))]).filter(([, l]) => l.length); --- diff --git a/site/src/pages/systems/[name].astro b/site/src/pages/systems/[name].astro index bb38361..6e75b8f 100644 --- a/site/src/pages/systems/[name].astro +++ b/site/src/pages/systems/[name].astro @@ -3,6 +3,7 @@ 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"; +import Interfaces from "../../components/Interfaces.astro"; import ExtLink from "../../components/ExtLink.astro"; import Mentions from "../../components/Mentions.astro"; import References from "../../components/References.astro"; @@ -25,6 +26,7 @@ const links = s.doc?.metadata?.links || [];

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/test/lib.test.mjs b/site/test/lib.test.mjs index b962bcb..3de1eff 100644 --- a/site/test/lib.test.mjs +++ b/site/test/lib.test.mjs @@ -30,3 +30,30 @@ test("refs, slugs and trial families", () => { assert.equal(slugify("../../etc/passwd"), "etc-passwd"); assert.equal(trialFamily("E-17b"), "E-17"); }); + +test("the verdict log: reasons, the chain, and an edit", async () => { + const { parseLog, reasonsOf, shapeVerdict, verifyChain, recordHash, primaryMetric } = await import("../src/lib/optimise.mjs"); + const a = { seq: 1, prev: "0".repeat(64), kind: "verdict", verdict: "fail", cell: "c", outcome: { denied: ["x.py: outside"], metrics: { m: { base: 1, candidate: 2, gain: -0.5, ci95: [-0.6, -0.4], sign_test_p: 0.3, ok: false } } } }; + a.hash = recordHash(a); + const b = { seq: 2, prev: a.hash, kind: "verdict", verdict: "pass", cell: "c", outcome: { metrics: {} } }; + b.hash = recordHash(b); + assert.deepEqual(reasonsOf(a), ["changes what the cell may not change: x.py: outside", "m: gain -50.0% (95% interval -60.0% to -40.0%, sign test p=0.3) does not meet the bar"]); + assert.deepEqual(shapeVerdict(b).reasons, ["the checks passed"]); + assert.equal(verifyChain([a, b]).links, true); + assert.deepEqual(verifyChain([a, b]).edited, []); + assert.deepEqual(verifyChain([a, { ...b, claim: "edited" }]).edited, [2]); + assert.equal(verifyChain([a, { ...b, prev: "f".repeat(64) }]).brokenAt, 2); + assert.equal(parseLog(`${JSON.stringify(a)}\n${JSON.stringify(b)}\n`).length, 2); // JSON lines + assert.equal(parseLog(JSON.stringify({ records: [a] })).length, 1); + assert.throws(() => parseLog("{not json"), /not valid JSON/); + assert.deepEqual(primaryMetric({ mape: { lower: true } }), { name: "mape", direction: "lower" }); + assert.deepEqual(primaryMetric("accuracy higher, wall_seconds lower"), { name: "accuracy", direction: "higher" }); +}); + +test("a number is hashed as the file wrote it", async () => { + const { parseLog, recordHash } = await import("../src/lib/optimise.mjs"); + const text = '[{"seq": 1, "x": 1.0, "prev": "p"}]'; + const [{ raw }] = parseLog(text); + const plainHash = recordHash(JSON.parse(text)); + assert.notEqual(recordHash(raw), plainHash, "1.0 and 1 hash differently, as in Python's canonical JSON"); +}); diff --git a/tests/test_site.py b/tests/test_site.py index 00ea77b..85d7625 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -484,7 +484,7 @@ def setUpClass(cls): 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"}]')): + ('pages = ["claims", "queue", "predictions", "roles", "map", "catalog", "optimise", "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") @@ -580,5 +580,297 @@ def test_init_refuses_to_overwrite_and_needs_a_system(self): site.init(tmp, repo="not a repo", system="mine", force=True) +def project_config(root: Path, extra_sources: str = "", pages: str = '["map", "catalog", "optimise", "search"]') -> Path: + cfg = root / "site.toml" + cfg.write_text('[site]\nrepo = "Owner/Repo"\nsystem = "system:default/shop"\n[sources]\n' + f'catalog = ["catalog-info.yaml"]\n{extra_sources}\n[nav]\npages = {pages}\n', encoding="utf-8") + return cfg + + +SHOP = [ + {"apiVersion": "backstage.io/v1alpha1", "kind": "System", "metadata": {"name": "shop", "description": "A shop " + HOSTILE}, + "spec": {"owner": "group:default/team", "morphogen": {"autonomy": {"experimental": "merge"}}}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Group", "metadata": {"name": "team", "title": "The team"}, "spec": {"type": "team"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "pricing", "description": "Prices " + HOSTILE}, + "spec": {"type": "library", "lifecycle": "production", "owner": "group:default/team", "system": "shop", + "providesApis": ["price-list"], "consumesApis": ["catalog-feed"], "dependsOn": ["resource:default/db"], + "morphogen": {"description": "Quote closer to cost " + HOSTILE, "dir": "pricing", "run": "python bench.py", + "change": ["pricing/p.py#MARKUP in 0.1..0.6", "prompts/"], "keep": ["pricing/p.py#RATE"], + "better": {"mape": {"lower": True}}, "score": "python score.py", "tests": "python -m unittest -q", + "observe": "otel"}}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "checkout", "description": "Takes the order"}, + "spec": {"type": "service", "lifecycle": "production", "owner": "user:default/ann", "system": "shop", + "consumesApis": ["price-list"], "dependsOn": ["resource:default/db"]}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "API", "metadata": {"name": "price-list", "description": "Price per item"}, + "spec": {"type": "openapi", "lifecycle": "production", "owner": "group:default/team", "definition": "contracts/prices.md", + "morphogen": {"tests": "python -m unittest -q contracts", "external": "consumes"}}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "API", "metadata": {"name": "catalog-feed"}, "spec": {"type": "grpc"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Resource", "metadata": {"name": "db", "description": "The orders database"}, + "spec": {"type": "database", "owner": "group:default/team"}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "payments", "description": "Take payment"}, + "spec": {"type": "role", "lifecycle": "production", "owner": "group:default/team", "system": "shop", "consumesApis": ["price-list"]}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "stripe", "description": "Stripe " + HOSTILE}, + "spec": {"type": "service", "lifecycle": "candidate", "owner": "group:default/team", "system": "shop", "providesApis": ["catalog-feed"], + "morphogen": {"fills": "component:default/payments", "licence": "proprietary " + HOSTILE, + "docs": {"url": "javascript:alert(1)"}, + "parameters": {"type": "object", "properties": {"retries": {"type": "integer", "minimum": 0, "maximum": 5, "default": 2, + "description": "Attempts " + HOSTILE}}}, + "evaluation": {"result": "p95 120 ms " + HOSTILE}}}}, + {"apiVersion": "backstage.io/v1alpha1", "kind": "Component", "metadata": {"name": "paypal", "description": "PayPal"}, + "spec": {"type": "service", "lifecycle": "candidate", "owner": "group:default/team", "system": "shop", + "morphogen": {"fills": "component:default/payments", "licence": "MIT", "docs": {"url": "https://example.org/paypal"}}}}, +] + + +def judge_log(path: Path, tamper: bool = False) -> None: + """A verdict log as `morphogen evidence` prints it: records through the real hash-chained log, in the shapes + morphogen/judge.py writes them (a pass with measures, a refusal with its reasons, a probe, a change check).""" + from morphogen.evidence import Evidence + ev = Evidence(path.with_suffix(".db")) + base, cand = "a" * 40, "b" * 40 + common = {"kind": "verdict", "trust": "measured", "by": "judge", "refs": {"base": base, "candidate": cand}, "sandbox": "podman"} + ev.append({**common, "claim": "pricing: bbbbbbbbbbbb is better than aaaaaaaaaaaa " + HOSTILE, "verdict": "pass", + "subject": {"system": "pricing", "path": "cell:pricing"}, "cell": "pricing", "gate": {"decision": "review"}, + "parameters": {"p.py#MARKUP": {"owner": "agent", "base": 0.2, "candidate": 0.35}}, + "outcome": {"check": True, "generated_inputs": 40, "wrong": 0, "failed": 0, "timed_output_mismatches": 0, + "metrics": {"mape": {"base": 0.124, "candidate": 0.034, "gain": 0.72, "ci95": [0.5, 0.8], + "sign_test_p": 0.008, "ok": True}}}}) + ev.append({**common, "claim": "pricing: cccc is not better", "verdict": "fail", "refs": {"base": base, "candidate": "c" * 40}, + "subject": {"system": "pricing", "path": "cell:pricing"}, "cell": "pricing", "gate": {"decision": "none"}, + "parameters": {"p.py#MARKUP": {"owner": "agent", "base": 0.35, "candidate": 0.9}}, + "outcome": {"check": True, "denied": ["tests/t.py: outside what the cell may change " + HOSTILE], + "parameter_violations": ["sets MARKUP to 0.9, outside its range [0.1, 0.6]"], + "metrics": {"mape": {"base": 0.034, "candidate": 0.05, "gain": -0.4, "ci95": [-0.6, -0.1], + "sign_test_p": 0.5, "ok": False}}}}) + ev.append({"kind": "probe", "claim": "probe of bbbb (practice; not a verdict)", "trust": "measured", "by": "judge", + "subject": {"system": "pricing"}, "outcome": {}}) + ev.append({**common, "claim": "change dddd keeps what checkout promises", "verdict": "pass", "cells": ["checkout"], + "subject": {"system": "checkout", "path": "change"}, "gate": {"decision": "merge"}, + "outcome": {"files": {"checkout/a.py": ["checkout"]}, "denied": [], "tests": [{"cell": "checkout", "test": "t", "passed": True}]}, + "signature": "sig:" + HOSTILE, "transparency": {"log_index": 7, "log": "rekor.example"}}) + ev.append({**common, "claim": "elsewhere: a verdict on a cell not in the map", "verdict": "fail", "cell": "ghost", + "subject": {"system": "ghost"}, "gate": {"decision": "none"}, "outcome": {"check": False}}) + rows = ev.query(limit=100) # newest first, as the command prints it + if tamper: + rows[1]["claim"] = "edited afterwards" + path.write_text(json.dumps(rows, indent=2), encoding="utf-8") + + +class Optimise(_Toolchain): + """The Optimise page: the cells, the judge's verdict log for each, and the evidence chain.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.tmp = tempfile.TemporaryDirectory() + cls.root = Path(cls.tmp.name) + (cls.root / "catalog-info.yaml").write_text(yaml.safe_dump_all(SHOP), encoding="utf-8") + judge_log(cls.root / "verdicts.json") + cfg = project_config(cls.root, 'verdicts = "verdicts.json"') + cls.out = cls.root / "out" + built(cls.out, config=cfg) + cls.page = read(cls.out, "optimise.html") + cls.text = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", cls.page.split("alert", re.sub(r'="[^"]*"', '=""', all_html(self.out))) + + def test_the_header_lists_optimise_and_the_map_marks_the_cell(self): + index = read(self.out, "index.html") + nav = re.search(r'', index).group(1) + self.assertEqual(re.findall(r">([^<]+)", nav), ["Map", "Catalog", "Optimise", "Search"]) + self.assertIn('class="tag tag-ready" href="optimise.html">cell', read(self.out, "map.html")) + + def test_a_log_edited_afterwards_shows_a_break(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "catalog-info.yaml").write_text(yaml.safe_dump_all(SHOP), encoding="utf-8") + judge_log(root / "verdicts.json", tamper=True) + built(root / "out", config=project_config(root, 'verdicts = "verdicts.json"')) + page = read(root / "out", "optimise.html") + self.assertRegex(page, r"1 do not match: #4") + self.assertNotIn("all recomputed", page) + + def test_cells_without_a_log_say_what_is_missing_and_show_no_verdict(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "catalog-info.yaml").write_text(yaml.safe_dump_all(SHOP), encoding="utf-8") + built(root / "out", config=project_config(root)) + page = read(root / "out", "optimise.html") + self.assertIn("No verdicts to show", page) + self.assertIn("morphogen evidence --limit 100000", page) + self.assertNotIn('class="verdict"', page) + self.assertNotIn("The evidence chain", page) + + +class SystemMap(_Toolchain): + """Entities with interfaces: the map's graph and table, each entity's page, the catalog's compare table.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.tmp = tempfile.TemporaryDirectory() + cls.root = Path(cls.tmp.name) + (cls.root / "catalog-info.yaml").write_text(yaml.safe_dump_all(SHOP), encoding="utf-8") + cls.out = cls.root / "out" + built(cls.out, config=project_config(cls.root), base="/ui") + cls.graph = json.loads(read(cls.out, "data/graph.json")) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_interfaces_owners_and_dependencies_become_references(self): + rels = {(e["from"], e["to"], e["rel"]) for e in self.graph["edges"]} + for edge in (("component:pricing", "api:price-list", "provides"), ("component:checkout", "api:price-list", "consumes"), + ("component:pricing", "resource:db", "depends-on"), ("component:pricing", "group:team", "owned-by"), + ("component:checkout", "group:ann", "owned-by")): # `ann` has no file: an owner all the same + self.assertIn(edge, rels) + self.assertEqual(self.graph["unresolved"], []) + + def test_the_map_page_has_the_system_graph_and_a_row_per_entity(self): + page = read(self.out, "map.html") + self.assertIn('id="graph-system"', page) + self.assertIn('href="/ui/apis/price-list.html"', page) + row = re.search(r'(.*?)', page, re.S).group(1) + for want in ("/ui/owners/team.html", "price-list", "catalog-feed", "/ui/resources/db.html", ">cell<"): + self.assertIn(want, row) + dependents = re.search(r'(.*?)', page, re.S).group(1) + self.assertIn("pricing", dependents) + self.assertIn("checkout", dependents) + + def test_an_entity_page_shows_provides_consumes_owner_dependencies_and_dependents(self): + page = read(self.out, "components/pricing.html") + text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", page)) + for want in ("Interfaces and ownership", "Owner team", "Provides price-list", "Consumes catalog-feed", "Depends on The orders database"): + self.assertIn(want, text) + api = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", read(self.out, "apis/price-list.html"))) + self.assertIn("Provided by pricing", api) + self.assertRegex(api, r"Consumed by .*checkout") + self.assertIn("contracts/prices.md", api) + self.assertIn("python -m unittest -q contracts", api) + owner = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", read(self.out, "owners/ann.html"))) + self.assertIn("no Group or User file", owner) + self.assertIn("checkout", owner) + res = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", read(self.out, "resources/db.html"))) + self.assertIn("Dependents", res) + + def test_catalog_compares_the_options_for_a_role(self): + page = read(self.out, "catalog.html") + table = re.search(r"", page, re.S).group(0) + for want in ("stripe", "paypal", "catalog-feed", "MIT", "proprietary", "retries", "https://example.org/paypal"): + self.assertIn(want, table) + self.assertNotRegex(page, r'href="\s*javascript:') # the docs link that was not http(s) is text + text = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", page))) + self.assertIn("Compare options for this role (2)", text) + self.assertIn("retries integer 0 to 5 2", text) + self.assertIn("The role's interfaces", text) + self.assertNotIn("