diff --git a/morphogen/ui.py b/morphogen/ui.py
index 6ff2a14..82e2bbb 100644
--- a/morphogen/ui.py
+++ b/morphogen/ui.py
@@ -84,7 +84,7 @@ def evidence(self, limit: int = 100, kind: str | None = None, by: str | None = N
return out
def targets(self) -> list[dict]:
- """Each cell with a `run`, from the working tree's morphogen.yaml, with its last results."""
+ """Each cell with a `run`, from the working tree's catalog, with its last results."""
recs = self._evidence().dump()
out = []
try:
diff --git a/schemas/evidence-record.v1.json b/schemas/evidence-record.v1.json
index 581c1fa..afe70c3 100644
--- a/schemas/evidence-record.v1.json
+++ b/schemas/evidence-record.v1.json
@@ -371,7 +371,7 @@
}
],
"default": null,
- "description": "per setting: base (the base commit's morphogen.yaml), morphogen.local.yaml, request, or default",
+ "description": "per setting: base (the base commit's catalog), morphogen.local.yaml, request, or default",
"title": "Settings From"
},
"subject": {
diff --git a/schemas/morphogen-spec.v0.json b/schemas/morphogen-spec.v1.json
similarity index 79%
rename from schemas/morphogen-spec.v0.json
rename to schemas/morphogen-spec.v1.json
index dc7ba4e..fd95b26 100644
--- a/schemas/morphogen-spec.v0.json
+++ b/schemas/morphogen-spec.v1.json
@@ -1,8 +1,8 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://github.com/OpenReplicant/Morphogen/schemas/morphogen-spec.v0.json",
- "title": "spec.morphogen (DRAFT, v0)",
- "description": "DRAFT. Morphogen's own fields on a Backstage catalog entity, under the one key `spec.morphogen`. Phase 1 of the kit publishes this schema; nothing reads these fields yet (phase 2 loads them). The cell fields are those a cell in morphogen.yaml accepts today (morphogen/project.py, CellDoc), so a cell moves unchanged. What Backstage already holds is not repeated: a cell's `in` is the entity's subcomponentOf or system, `provides` and `consumes` are providesApis and consumesApis, `owner` and `lifecycle` are the entity's own. Use the Option fields on a Component with spec.lifecycle: candidate, the Cell fields on the entity a cell judges, the ApiTests fields on an API entity and the SystemSettings fields on the System entity. The fields are flat under `spec.morphogen`: the schema is the four definitions together, so one entity may carry the fields of more than one (a candidate that is also judged, say), and a field none of them defines is refused.",
+ "$id": "https://github.com/OpenReplicant/Morphogen/schemas/morphogen-spec.v1.json",
+ "title": "spec.morphogen (v1)",
+ "description": "Morphogen's own fields on a Backstage catalog entity, under the one key `spec.morphogen`; the project's catalog (`catalog-info.yaml` at the repository root, and the files a `Location` in it names) is where the judge reads them, from the base commit only. The cell fields are those of CellRules in morphogen/project.py. What Backstage already holds is not repeated: a cell's `in` is the entity's subcomponentOf (a Component nested in a Component) or system, `provides` and `consumes` are providesApis and consumesApis (and dependsOn), `owner` and `lifecycle` are the entity's own. Use the Option fields on a Component with spec.lifecycle: candidate (never a cell; nor is an entity with spec.type: role), the Cell fields on the entity a cell judges (an entity with no `run` is structure), the ApiTests fields on an API entity and the SystemSettings fields on the System entity (at most one System carries them). The fields are flat under `spec.morphogen`: the schema is the four definitions together, so one entity may carry the fields of more than one (a System that is also a judged cell, say), and a field none of them defines is refused.",
"type": "object",
"$defs": {
"StringOrList": {
@@ -71,7 +71,7 @@
}
},
"Cell": {
- "description": "A cell's rules, on the entity it judges. The fields of CellDoc in morphogen/project.py, less those Backstage holds (in, provides, consumes, owner, lifecycle). Commands run in `dir`, relative to the project root.",
+ "description": "A cell's rules, on the entity it judges: the fields of CellRules in morphogen/project.py, less those Backstage holds (in, provides, consumes, owner, lifecycle). Commands run in `dir`, relative to the project root. In `SystemSettings.defaults`, a field a cell sets to null opts out of that default.",
"type": "object",
"properties": {
"description": {
@@ -214,7 +214,7 @@
}
},
"SystemSettings": {
- "description": "On the System entity: the judge's settings (Config in morphogen/documents.py, today the top level of morphogen.yaml) and defaults cells inherit, which replace YAML anchors.",
+ "description": "On the System entity: the judge's settings (SystemRules in morphogen/project.py), read from the base commit, and `defaults`: cell fields every cell with rules of its own in this System inherits unless it sets its own (the System too, when it has cell rules of its own). `autonomy`, `sandbox` and `budget` can be overridden by the operator's uncommitted morphogen.local.yaml where documents.py says so.",
"type": "object",
"properties": {
"trunk": {
@@ -258,7 +258,7 @@
},
"defaults": {
"$ref": "#/$defs/Cell",
- "description": "Fields a cell in this system inherits where it does not set them."
+ "description": "Fields a cell in this system inherits where it does not set them (a field set to null is set, so it opts out)."
}
}
}
diff --git a/skills/catalog/SKILL.md b/skills/catalog/SKILL.md
index 663087b..a9d24c3 100644
--- a/skills/catalog/SKILL.md
+++ b/skills/catalog/SKILL.md
@@ -7,7 +7,7 @@ description: Find alternatives for a role a part plays - search the catalogs (pa
Works on a role the `map` skill named, in files: no database, any harness. An option for a role is an ordinary
Backstage `Component` with `spec.lifecycle: candidate`; what Morphogen adds goes under the one key
-`spec.morphogen` (draft schema: `schemas/morphogen-spec.v0.json`). An option is *an alternative* when it
+`spec.morphogen` (draft schema: `schemas/morphogen-spec.v1.json`). An option is *an alternative* when it
provides every interface the role requires, which is why a loosely named interface makes everything look
interchangeable.
diff --git a/skills/map/SKILL.md b/skills/map/SKILL.md
index 82b2f56..23c5d6a 100644
--- a/skills/map/SKILL.md
+++ b/skills/map/SKILL.md
@@ -11,10 +11,9 @@ judge from the base commit. No database and no server are needed, and any Backst
A map counts for a verdict only once the operator has approved it and it is on main. Your job is a draft the
operator can approve: small, checked, every claim traceable to where you found it.
-**Coming, phase 2:** the cell rules will move from `morphogen.yaml` into the entity they judge, under
-`spec.morphogen` (draft schema: `schemas/morphogen-spec.v0.json`). Until phase 2 lands, the judge reads cells
-from `morphogen.yaml` and the catalog files as section 1 says; write the rest of the map as entities now, and
-the cell rules where the judge reads them today.
+The cell rules are part of the same files: `spec.morphogen` on the entity a cell judges (schema:
+`schemas/morphogen-spec.v1.json`; section 1 shows where each kind of rule goes). There is no other
+project file for the judge to read.
## 0. How you work
@@ -50,7 +49,7 @@ Backstage server.
| an option for a role | a `Component` with `spec.lifecycle: candidate` (the catalog skill) |
Morphogen's own fields go under **one key**, `spec.morphogen`, so they never clash with fields Backstage adds.
-Annotation values must be strings. Fields are described in `schemas/morphogen-spec.v0.json` (a draft).
+Annotation values must be strings. Fields are described in `schemas/morphogen-spec.v1.json` (a draft).
A role is interchangeable when its interfaces are named exactly enough to check: an API and its version, a file
format, a protocol, a socket size, a skill set. An interface named loosely ("an API") makes everything look
@@ -92,26 +91,50 @@ metadata: {name: labels}
spec: {type: openapi, lifecycle: production, owner: group:default/team, definition: "see contracts/labels.md"}
```
-Until phase 2, the cell's rules live in `morphogen.yaml`, naming the entity's ref where there is one:
+The cell's rules go on the entity it judges, under `spec.morphogen` (the project root's
+`catalog-info.yaml`, or a file a `Location` in it names):
```yaml
-# morphogen.yaml, at the project root
-cells:
- app: {}
- classify:
- in: app
+apiVersion: backstage.io/v1alpha1
+kind: System
+metadata: {name: app}
+spec:
+ owner: team
+ morphogen: # once per project: its settings, and defaults every cell inherits
+ sandbox: podman
+ defaults: {rounds: {warmup: 0, repeats: 4, max_repeats: 8}, timeout: 60}
+---
+apiVersion: backstage.io/v1alpha1
+kind: Component
+metadata: {name: classify}
+spec:
+ type: library
+ lifecycle: production
+ owner: team
+ system: app # a part below the grain of another is a Component with subcomponentOf
+ providesApis: [labels]
+ morphogen:
dir: targets/classify # where its commands run (default: the root)
change: targets/classify/classify.py#THRESHOLD in 0..100 # or a path or glob: src/**, prompts/
run: python bench.py
better: accuracy higher # plain names: wall_seconds, cpu_seconds, max_rss_kb, or scored
score: python score.py # scores each run's output, from the base
tests: python -m unittest -q test_classify
- provides: labels
- report: {in: app, consumes: labels}
-interfaces:
- labels: python -m unittest -q contracts.test_labels # run from the root
+---
+apiVersion: backstage.io/v1alpha1
+kind: API
+metadata: {name: labels}
+spec:
+ type: openapi
+ morphogen:
+ tests: python -m unittest -q contracts.test_labels # run from the root
```
+An entity with no `run` (and no tests) is structure, not a judged cell. An option for a role
+(`spec.lifecycle: candidate`) and a role (`spec.type: role`) are never cells. Every catalog file the judge
+reads (the root and each `Location` target) is a rule file: a candidate that changes one is refused, so
+write the cell's rules before the operator merges the map, never in the same branch as the improvement.
+
Settings: `path#NAME` is a module-level constant in a Python file, `path:dotted.key` a key in YAML,
JSON or TOML; `in lo..hi` or `in [a, b]` bounds it. Optional on a cell: `same_as_base: {gen, run}`
(outputs must match the base on generated inputs), `observe: otel`, `guard: false` or `guard:
@@ -122,8 +145,8 @@ cannot be committed goes there too, as `inputs: /path` (read from `MORPHOGEN_INP
## 2. Start with `status`, and smaller than you think
-Call `status` first (or `morphogen status`). It reports the sources (`morphogen.yaml`,
-`morphogen.local.yaml`, Backstage catalog files), each cell on the trunk and whether the judge can
+Call `status` first (or `morphogen status`). It reports the sources (the catalog,
+`morphogen.local.yaml`, catalog files nothing names), each cell on the trunk and whether the judge can
judge it, cells drafted but not yet on the trunk, what is missing, and the next step. Follow the
next step; call it again after each one.
@@ -131,9 +154,9 @@ Morphogen needs cells, not a complete map. Measure first; map what earns attenti
- **Not a git repository, or no commit on `main`:** the judge reads its rules from a commit. Ask the
operator before running `git init` or committing on their behalf.
-- **A Backstage catalog, no `morphogen.yaml`:** do not rewrite the catalog. Write
- `morphogen.yaml` with `backstage: [catalog-info.yaml]` and add only what the catalog lacks, for
- the one part to improve, under its ref (`component:classify` is enough).
+- **A Backstage catalog already:** do not rewrite it. Add `spec.morphogen` to the one entity to improve
+ (and the System's settings if the project needs any), and nothing else. A catalog file the root
+ `catalog-info.yaml` does not name is not read: name it as a `Location` target.
- **No catalog:** write the entities for the parts that matter (section 1), nothing more.
- **Nothing here yet:** ask the operator what to improve and how they would know it improved.
Draft one cell for that: `change` (as narrow as the job allows), `run`, `better` and `tests`.
diff --git a/skills/morphogen/SKILL.md b/skills/morphogen/SKILL.md
index 80cd7bc..774283a 100644
--- a/skills/morphogen/SKILL.md
+++ b/skills/morphogen/SKILL.md
@@ -19,9 +19,9 @@ use the `map` skill to draft one with the operator first.
interfaces have tests (intent coverage). Errors (gaps, cycles) come before anything else.
- `structure_scope(cell)`: what a change inside that cell touches, and the tests it must pass.
- A target is `cell:NAME` for a cell with a `run` (or the cell's name, or its `dir`). Read the
- cell in `morphogen.yaml`. **Its `change` is all you may change**: paths and globs you may edit,
+ cell's `spec.morphogen` in the catalog (`catalog-info.yaml`). **Its `change` is all you may change**: paths and globs you may edit,
and settings (`path#NAME in lo..hi`, `path:key in [a, b]`) you may set within their bounds, which
- in a file named only that way are the only thing you may touch. Everything else, `morphogen.yaml`
+ in a file named only that way are the only thing you may touch. Everything else, the catalog files
and every test included, belongs to the judge: a candidate that changes any of it is refused
before it runs. `keep` lists settings you may not change even in a file you may edit.
@@ -41,7 +41,7 @@ cost or errors go before choosing what to change.
Rules that keep trials honest:
- Never edit anything outside the cell's `change` to make a change pass: the bench, the scorer,
- the tests and `morphogen.yaml` are the judge's, and a candidate that touches them is refused.
+ the tests and the catalog files are the judge's, and a candidate that touches them is refused.
- Never try to read held-out answers or name the scorer's private directory; the candidate is
refused.
- A probe is practice, never a verdict. Only a `pass` verdict can be proposed for merging.
diff --git a/tests/catalog.py b/tests/catalog.py
new file mode 100644
index 0000000..c251e22
--- /dev/null
+++ b/tests/catalog.py
@@ -0,0 +1,82 @@
+"""The test projects' authoring form, `{cells, interfaces, }`, as the catalog a project commits.
+
+Fixtures keep a project as a plain dict so a test can change one field; `dump` turns it into the
+`catalog-info.yaml` the judge reads: a Component per cell (a System for the root cell that carries the
+settings), an API per interface, `spec.morphogen` holding the cell's rules and the settings.
+"""
+
+from __future__ import annotations
+
+import yaml
+
+from morphogen.backstage import SETTINGS
+
+FILE = "catalog-info.yaml"
+STRUCTURE_KEYS = ("in", "provides", "consumes", "owner", "lifecycle") # Backstage's own fields; the rest are rules
+
+
+def _listed(v):
+ return [] if v is None else list(v) if isinstance(v, (list, tuple)) else [v]
+
+
+def entities(doc: dict) -> list[dict]:
+ cells, ifaces = doc.get("cells") or {}, doc.get("interfaces") or {}
+ settings = {k: v for k, v in doc.items() if k in SETTINGS}
+ roots = [n for n, c in cells.items() if not (c or {}).get("in")]
+ holder = roots[0] if roots else None
+ out = []
+ for name, c in cells.items():
+ c = dict(c or {})
+ parent = c.get("in")
+ kind = "System" if name == holder and settings else "Component"
+ spec: dict = {"type": "service", "lifecycle": c.get("lifecycle", "experimental")}
+ if "lifecycle" not in c:
+ del spec["lifecycle"]
+ if c.get("owner"):
+ spec["owner"] = c["owner"]
+ if parent:
+ spec["subcomponentOf" if cells.get(parent) is not None and _kind(parent, cells, holder, settings) == "Component"
+ else "system"] = parent
+ apis = [i for i in _listed(c.get("consumes")) if i not in cells or i in ifaces]
+ deps = [i for i in _listed(c.get("consumes")) if i in cells and i not in ifaces]
+ if c.get("provides"):
+ spec["providesApis"] = _listed(c["provides"])
+ if apis:
+ spec["consumesApis"] = apis
+ if deps:
+ spec["dependsOn"] = [f"component:{d}" for d in deps]
+ rules = {k: v for k, v in c.items() if k not in STRUCTURE_KEYS}
+ if name == holder and settings:
+ rules.update(settings)
+ if rules:
+ spec["morphogen"] = rules
+ out.append({"apiVersion": "backstage.io/v1alpha1", "kind": kind, "metadata": {"name": name}, "spec": spec})
+ if settings and holder is None:
+ out.append({"apiVersion": "backstage.io/v1alpha1", "kind": "System", "metadata": {"name": "project"},
+ "spec": {"morphogen": dict(settings)}})
+ for name, i in ifaces.items():
+ i = {"tests": i} if isinstance(i, (str, list)) else dict(i or {})
+ e = {"apiVersion": "backstage.io/v1alpha1", "kind": "API", "metadata": {"name": name},
+ "spec": {"type": "openapi", **({"morphogen": i} if i else {})}}
+ out.append(e)
+ return out
+
+
+def _kind(name, cells, holder, settings):
+ return "System" if name == holder and settings else "Component"
+
+
+def dump(doc: dict) -> str:
+ """The catalog text (one file, one document per entity) for an authoring dict."""
+ return yaml.safe_dump_all(entities(doc), sort_keys=False)
+
+
+def project(doc: dict):
+ """The Project the catalog written from `doc` compiles to (read from a temporary directory)."""
+ import tempfile
+ from pathlib import Path
+
+ from morphogen.project import Project
+ d = Path(tempfile.mkdtemp())
+ (d / FILE).write_text(dump(doc))
+ return Project.load(d)
diff --git a/tests/fixture.py b/tests/fixture.py
index 7cd9281..abc3c6d 100644
--- a/tests/fixture.py
+++ b/tests/fixture.py
@@ -1,4 +1,4 @@
-"""Throwaway git projects in the cell format (one morphogen.yaml), committed on main.
+"""Throwaway git projects in the cell format (a catalog, catalog-info.yaml), committed on main.
Trials run with `sandbox: none` unless MORPHOGEN_TEST_SANDBOX names another runner (docker or
podman), so the same suites can run inside a container.
@@ -16,6 +16,7 @@
from morphogen import judge as judge_mod
from morphogen.documents import load_config
from morphogen.evidence import Evidence
+from tests.catalog import FILE, dump as catalog_dump
HERE = Path(__file__).resolve().parent
TARGET = "targets/slow-script"
@@ -43,7 +44,7 @@ def git(cwd, *args):
class Project:
- """A git repository with morphogen.yaml (`cells`, `interfaces`) and files, committed on main.
+ """A git repository with a catalog (written from `cells`, `interfaces` and settings) and files, committed on main.
`home` is the directory `path()` and `branch()` resolve against (the judged cell's `dir`); `cell`
is the cell judged by default. `local` is written to the uncommitted morphogen.local.yaml."""
@@ -73,7 +74,7 @@ def __init__(self, files: dict[str, str] | None = None, sample: str | None = "sl
"cells": cells}
if interfaces:
self.doc_["interfaces"] = interfaces
- self._write(self.repo / "morphogen.yaml", yaml.safe_dump(self.doc_, sort_keys=False))
+ self._write(self.repo / FILE, self.dump(self.doc_))
git(self.repo, "add", "-A")
git(self.repo, "commit", "-q", "-m", "base")
(self.repo / ".git" / "info" / "exclude").write_text("morphogen.local.yaml\n")
@@ -101,11 +102,11 @@ def path(self, rel):
return self.repo / self.home / rel
def doc(self) -> dict:
- """A copy of morphogen.yaml as committed on main."""
+ """A copy of the catalog's authoring form as committed on main."""
return copy.deepcopy(self.doc_)
def dump(self, doc: dict) -> str:
- return yaml.safe_dump(doc, sort_keys=False)
+ return catalog_dump(doc)
def branch(self, name, files=None, delete=(), root=False, links=None, base="main"):
"""Commit a candidate on `name`. `files` and `delete` are paths relative to `home`, or to the
@@ -133,16 +134,16 @@ def branch_files(self, name, files, **kw):
branch_root = branch_files
def on_main(self, files=None, doc=None, root=False):
- """Commit on main: files (relative to `home`, or the root), and a new morphogen.yaml."""
+ """Commit on main: files (relative to `home`, or the root), and a new catalog."""
git(self.repo, "checkout", "-q", "main")
at = self.repo if root else self.repo / self.home
for rel, text in (files or {}).items():
self._write(at / rel, text)
if doc is not None:
self.doc_ = copy.deepcopy(doc)
- self._write(self.repo / "morphogen.yaml", self.dump(doc))
+ self._write(self.repo / FILE, self.dump(doc))
git(self.repo, "add", "-A")
- git(self.repo, "commit", "-q", "-m", "base: " + ", ".join(sorted(files or {}) or ["morphogen.yaml"]))
+ git(self.repo, "commit", "-q", "-m", "base: " + ", ".join(sorted(files or {}) or [FILE]))
self.cfg = load_config(self.repo)
def judge(self, candidate, labels=None, target=None, base="main"):
@@ -205,7 +206,7 @@ def observed_project(collected, primary=True):
return Project({"observe.py": OBSERVER}, cells={"slow-script": observed_cell(collected, primary)})
-SETTINGS = "\n# Settings the judge reads (see morphogen.yaml).\nCHUNK = 64\nLIMIT = 1000\n"
+SETTINGS = "\n# Settings the judge reads (see the catalog).\nCHUNK = 64\nLIMIT = 1000\n"
def parameter_project() -> "Project":
diff --git a/tests/fixture_cells.py b/tests/fixture_cells.py
index 6d27c19..1f4f46d 100644
--- a/tests/fixture_cells.py
+++ b/tests/fixture_cells.py
@@ -1,4 +1,4 @@
-"""The classifier in the cell format: one morphogen.yaml with the cells, their `change`, `run`,
+"""The classifier in the cell format: one catalog with the cells, their `change`, `run`,
`better` and `tests`, and the interfaces; the held-out answers named in an uncommitted
morphogen.local.yaml."""
@@ -11,6 +11,7 @@
from morphogen.documents import load_config
from morphogen.evidence import Evidence
+from tests.catalog import FILE, dump
from tests.fixture import SANDBOX, git, judge_mod
from tests.fixture_scored import (CLASSIFY, CLASSIFY_BENCH, CLASSIFY_SCORE, CLASSIFY_TEST, CONTRACT_TEST,
GOLD, INPUTS)
@@ -43,7 +44,7 @@ def cells_doc(code: bool = False) -> dict:
class CellsProject:
- """A git repository on main with the classifier described in morphogen.yaml."""
+ """A git repository on main with the classifier described in its catalog."""
target = "cell:classify"
@@ -64,7 +65,7 @@ def __init__(self, code: bool = False, search: bool = False):
"classify/inputs.json": json.dumps(INPUTS),
"contracts/__init__.py": "",
"contracts/test_labels.py": CELLS_CONTRACT,
- "morphogen.yaml": yaml.safe_dump(cells_doc(code), sort_keys=False),
+ FILE: dump(cells_doc(code)),
}
for rel, text in files.items():
self.write(rel, text)
diff --git a/tests/test_backstage.py b/tests/test_backstage.py
index 422fa26..501db8d 100644
--- a/tests/test_backstage.py
+++ b/tests/test_backstage.py
@@ -1,5 +1,6 @@
-"""Backstage's catalog-info.yaml as a source of cells: refs, Location targets, the mapping to cells
-and interfaces, merging with morphogen.yaml, and the judge on a project described in both."""
+"""The project's catalog (catalog-info.yaml): refs, Location targets, the mapping to cells and interfaces, the
+settings and defaults on the System, options and roles, and the judge on a project whose catalog is split across
+files. Every catalog file the judge reads is a rule file: the integrity tests are here."""
import copy
import tempfile
@@ -10,46 +11,32 @@
from morphogen import backstage as bs
from morphogen import judge as judge_mod
+from morphogen.documents import DocumentError, load_config, rules_config
from morphogen.project import Project, ProjectError
-from tests.fixture import CLASSIFY, CLASSIFY_BENCH, CLASSIFY_CELL, CONTRACT_TEST, ScoredProject, StructuredProject
+from tests import catalog as catalog_mod
+from tests.fixture import CLASSIFY, CLASSIFY_BENCH, CLASSIFY_CELL, CONTRACT_TEST, ScoredProject, StructuredProject, git
HERE = Path(__file__).resolve().parent / "fixtures" / "backstage"
BETTER = CLASSIFY.replace("THRESHOLD = 10", "THRESHOLD = 50")
BREAKS_NEIGHBOUR = BETTER.replace('def label(x):\n', 'def label(x):\n if x < 0:\n raise ValueError("negative")\n')
+ROOT = "catalog-info.yaml"
-def entity(kind, name, spec=None, annotations=None):
- md = {"name": name, **({"annotations": annotations} if annotations else {})}
- return {"apiVersion": "backstage.io/v1alpha1", "kind": kind, "metadata": md, "spec": spec or {}}
+def entity(kind, name, spec=None, morphogen=None, **md):
+ spec = dict(spec or {})
+ if morphogen is not None:
+ spec["morphogen"] = morphogen
+ return {"apiVersion": "backstage.io/v1alpha1", "kind": kind, "metadata": {"name": name, **md}, "spec": spec}
-def catalog(provides=True, consumes=True, change=None, lifecycle="production"):
- """The classifier's system as the catalog sees it: `app` holds `classify`, which provides the
- labels API that `report` consumes; the API's contract test is an annotation."""
- classify = {"type": "service", "lifecycle": lifecycle, "owner": "team-a", "system": "app"}
- if provides:
- classify["providesApis"] = ["labels"]
- report = {"type": "service", "lifecycle": "production", "owner": "team-a", "system": "app"}
- if consumes:
- report["consumesApis"] = ["labels"]
- docs = [entity("System", "app", {"owner": "team-a"}),
- entity("Component", "classify", classify, {"morphogen.dev/change": change} if change else None),
- entity("Component", "report", report),
- entity("API", "labels", {"type": "openapi", "lifecycle": "production", "owner": "team-a",
- "definition": "openapi: 3.0.0"},
- {"morphogen.dev/tests": "python -m unittest -q contracts.test_labels"})]
- return yaml.safe_dump_all(docs, sort_keys=False)
-
-
-class CatalogProject(ScoredProject):
- """The structured classifier, half in catalog-info.yaml (the system, the components, the API and
- its test) and half in morphogen.yaml (how `classify` is changed and judged)."""
-
- def __init__(self, cell=None, catalog_text=None):
- cell = cell or copy.deepcopy(CLASSIFY_CELL)
- super().__init__(cells={"component:classify": cell}, settings={"backstage": "catalog-info.yaml"},
- root_files={"catalog-info.yaml": catalog_text or catalog(),
- "contracts/__init__.py": "", "contracts/test_labels.py": CONTRACT_TEST})
+def load(files: dict[str, list | dict | str]) -> Project:
+ """A project from catalog files written to a temporary directory (entities, or YAML text, per path)."""
+ d = Path(tempfile.mkdtemp())
+ for rel, docs in files.items():
+ (d / rel).parent.mkdir(parents=True, exist_ok=True)
+ (d / rel).write_text(docs if isinstance(docs, str) else
+ yaml.safe_dump_all(docs if isinstance(docs, list) else [docs], sort_keys=False))
+ return Project.load(d)
class Refs(unittest.TestCase):
@@ -62,87 +49,219 @@ def test_parse(self):
with self.assertRaises(bs.CatalogError, msg=bad):
bs.parse_ref(bad, "api")
+ def test_a_cell_is_named_by_its_name(self):
+ self.assertEqual(bs.ref_name("Component:Default/Web", "api"), "web")
+ self.assertEqual(bs.ref_name("labels", "api"), "labels")
+ self.assertEqual(bs.ref_name("ops/web", "component"), "ops/web")
+ self.assertEqual(bs.ref_name("resource:default/db", "component"), "resource:db")
+
class Examples(unittest.TestCase):
- """Backstage's own example entities (tests/fixtures/backstage, Apache-2.0)."""
+ """Backstage's own example entities (tests/fixtures/backstage, Apache-2.0): a root Location naming seven files."""
@classmethod
def setUpClass(cls):
- cls.p = Project.from_dict({"backstage": "catalog-info.yaml"}, root=HERE)
+ cls.p = Project.load(HERE)
cls.s = cls.p.structure()
def test_cells_and_nesting(self):
self.assertEqual(sorted(self.s.cells), sorted([
- "domain:default/audio", "domain:default/artists", "system:default/artist-engagement-portal",
- "component:default/artist-lookup", "component:default/www-artist", "component:default/wayback-archive",
- "component:default/wayback-archive-ingestion", "component:default/wayback-archive-storage"]))
- self.assertEqual(self.s.parent("domain:default/artists"), "domain:default/audio") # subdomainOf
- self.assertEqual(self.s.parent("system:default/artist-engagement-portal"), "domain:default/artists")
- self.assertEqual(self.s.parent("component:default/www-artist"), "system:default/artist-engagement-portal")
- self.assertEqual(self.s.parent("component:default/wayback-archive-storage"), "component:default/wayback-archive")
+ "audio", "artists", "artist-engagement-portal", "artist-lookup", "www-artist", "wayback-archive",
+ "wayback-archive-ingestion", "wayback-archive-storage"]))
+ self.assertEqual(self.s.parent("artists"), "audio") # subdomainOf
+ self.assertEqual(self.s.parent("artist-engagement-portal"), "artists")
+ self.assertEqual(self.s.parent("www-artist"), "artist-engagement-portal")
+ self.assertEqual(self.s.parent("wayback-archive-storage"), "wayback-archive") # subcomponentOf
def test_interfaces(self):
- self.assertEqual(self.s.providers("api:default/wayback-archive"), ["component:default/wayback-archive"])
- self.assertEqual(self.s.interfaces["resource:default/artists-db"].external, "provides") # dependsOn
- self.assertEqual(self.s.consumers("resource:default/artists-db"), ["component:default/artist-lookup"])
+ self.assertEqual(self.s.providers("wayback-archive"), ["wayback-archive"])
+ self.assertEqual(self.s.interfaces["resource:artists-db"].external, "provides") # dependsOn
+ self.assertEqual(self.s.consumers("resource:artists-db"), ["artist-lookup"])
# a component listed as an API is provided by that component
- self.assertEqual(self.s.providers("component:default/artist-lookup"), ["component:default/artist-lookup"])
- self.assertEqual(self.s.consumers("component:default/artist-lookup"), ["component:default/www-artist"])
+ self.assertEqual(self.s.providers("artist-lookup"), ["artist-lookup"])
+ self.assertEqual(self.s.consumers("artist-lookup"), ["www-artist"])
self.assertEqual(self.p.errors(), [])
def test_every_file_read_is_a_rule_file(self):
self.assertIn("components/wayback.yaml", self.p.rule_files) # two documents in one file
self.assertIn("catalog-info.yaml", self.p.rule_files)
- self.assertEqual(self.p.sources["component:default/wayback-archive"], "backstage (components/wayback.yaml)")
+ self.assertEqual(self.p.sources["wayback-archive-ingestion"], "components/wayback.yaml")
+ self.assertEqual(self.p.sources["api:wayback-archive"], "wayback-archive-api.yaml")
self.assertFalse(self.p.allows(list(self.s.cells), "components/wayback.yaml"))
def test_refused_inputs(self):
- with tempfile.TemporaryDirectory() as d:
- d = Path(d)
- for bad in ("../outside.yaml", "/etc/hosts", "https://example.com/catalog-info.yaml"):
- with self.assertRaises(ProjectError, msg=bad):
- Project.from_dict({"backstage": bad}, root=d)
- (d / "loc.yaml").write_text(yaml.safe_dump(entity("Location", "l", {"targets": ["../../x.yaml"]})))
- with self.assertRaises(ProjectError):
- Project.from_dict({"backstage": "loc.yaml"}, root=d)
- for annotations in ({"morphogen.dev/nope": "x"}, {"morphogen.dev/run": 3}):
- (d / "c.yaml").write_text(yaml.safe_dump(entity("Component", "c", {}, annotations)))
- with self.assertRaises(ProjectError, msg=str(annotations)):
- Project.from_dict({"backstage": "c.yaml"}, root=d)
- with self.assertRaises(ProjectError):
- Project.from_dict({"backstage": "c.yaml"}) # no directory to read from
-
-
-class Merge(unittest.TestCase):
- def test_both_sources_and_conflicts(self):
- with tempfile.TemporaryDirectory() as d:
- d = Path(d)
- (d / "catalog-info.yaml").write_text(catalog(change="classify.py"))
- p = Project.from_dict({"backstage": "catalog-info.yaml", "cells": {
- "component:classify": {"run": "python bench.py", "consumes": "extra"},
- "helper": {"in": "Component:Classify"}},
- "interfaces": {"extra": {"tests": "true", "external": "provides"}}}, root=d)
- c = p.doc.cells["component:default/classify"]
- self.assertEqual(c.change, ["classify.py"]) # from the annotation
- self.assertEqual(c.run, "python bench.py") # from morphogen.yaml
- self.assertEqual(c.provides, ["api:default/labels"])
- self.assertEqual(c.consumes, ["extra"])
- self.assertEqual(p.doc.cells["helper"].in_, "component:default/classify")
- self.assertIn("and morphogen.yaml", p.sources["component:default/classify"])
- self.assertEqual(p.sources["helper"], "morphogen.yaml")
- self.assertEqual(p.errors(), [])
- p = Project.from_dict({"backstage": "catalog-info.yaml", "cells": {
- "component:classify": {"change": "other.py"}}}, root=d)
- self.assertTrue(any("change" in x for x in p.errors()), p.errors())
+ for bad in ("../outside.yaml", "/etc/hosts", "https://example.com/catalog-info.yaml"):
+ with self.assertRaises(ProjectError, msg=bad):
+ load({ROOT: entity("Location", "l", {"targets": [bad]})})
+ with self.assertRaises(ProjectError):
+ load({ROOT: entity("Location", "l", {"targets": ["../../x.yaml"]})})
+ with self.assertRaises(ProjectError):
+ load({ROOT: entity("Location", "l", {"targets": ["missing.yaml"]})})
+ for rules in ({"nope": "x"}, {"run": 3}, "run: x", {"defaults": {"nope": 1}}):
+ with self.assertRaises(ProjectError, msg=str(rules)):
+ load({ROOT: entity("Component", "c", {}, rules)})
+ self.assertIsNone(Project.load(Path(tempfile.mkdtemp()))) # no catalog, no project
+
+ def test_the_old_annotations_are_not_read(self):
+ c = entity("Component", "c")
+ c["metadata"]["annotations"] = {"morphogen.dev/run": "python x.py"}
+ self.assertIsNone(load({ROOT: c}).doc.cells["c"].run)
+
+
+class Mapping(unittest.TestCase):
+ def test_a_sub_grain_cell_is_a_component_nested_with_subcomponent_of(self):
+ p = load({ROOT: [entity("System", "app"),
+ entity("Component", "classify", {"system": "app"}, {"run": "python bench.py"}),
+ entity("Component", "threshold", {"subcomponentOf": "classify"},
+ {"run": "python bench.py", "change": "classify.py#THRESHOLD in 0..100"})]})
+ self.assertEqual(p.doc.cells["classify"].in_, "app")
+ self.assertEqual(p.doc.cells["threshold"].in_, "classify")
+ self.assertEqual(p.doc.cells["threshold"].run, "python bench.py")
+
+ def test_an_api_carries_its_tests(self):
+ p = load({ROOT: [entity("Component", "a", {"providesApis": ["labels"]}),
+ entity("API", "labels", {"type": "openapi"}, {"tests": ["true", "false"]}),
+ entity("API", "upstream", {"type": "openapi"}, {"tests": "true", "external": "provides"})]})
+ self.assertEqual(p.doc.interfaces["labels"].tests, ["true", "false"])
+ self.assertEqual(p.doc.interfaces["upstream"].external, "provides")
+ with self.assertRaises(ProjectError): # cell rules do not belong on an API
+ load({ROOT: entity("API", "labels", {"type": "openapi"}, {"run": "x"})})
+
+ def test_an_entity_without_a_run_is_structure(self):
+ p = load({ROOT: [entity("System", "app"), entity("Component", "a", {"system": "app"}, {"tests": "true"}),
+ entity("Component", "b", {"system": "app"})]})
+ self.assertEqual({n for n, c in p.doc.cells.items() if c.run}, set())
+ with self.assertRaises(ProjectError):
+ p.spec("a")
+
+ def test_options_and_roles_are_never_cells(self):
+ """An option for a role (lifecycle: candidate) and the role itself (type: role) are the catalog's, not the judge's:
+ even one that carries a run is skipped, and one that names parts does not put them in the structure."""
+ p = load({ROOT: [
+ entity("System", "app"),
+ entity("Component", "matcher", {"system": "app", "providesApis": ["scoring"]},
+ {"run": "python bench.py", "change": "m.py"}),
+ entity("Component", "rapidfuzz", {"type": "library", "lifecycle": "candidate", "system": "app",
+ "providesApis": ["scoring"]},
+ {"run": "python bench.py", "fills": "matcher", "licence": "MIT",
+ "parameters": {"type": "object"}, "docs": {"url": "https://example.org/docs"},
+ "evaluation": {"need": "faster", "result": "2x"}}),
+ entity("Component", "fuzzy-matching", {"type": "role", "system": "app"}, {"run": "python bench.py"}),
+ entity("API", "scoring", {"type": "openapi"}, {"tests": "true"})]})
+ self.assertEqual(sorted(p.doc.cells), ["app", "matcher"])
+ self.assertEqual(p.doc.interfaces["scoring"].tests, "true")
+
+ def test_two_cells_may_not_share_a_name(self):
+ with self.assertRaises(ProjectError) as e:
+ load({ROOT: [entity("System", "x"), entity("Component", "x")]})
+ self.assertIn("rename", str(e.exception))
+ p = load({ROOT: [entity("Component", "x"), entity("Component", "x", namespace="other")]})
+ self.assertEqual(sorted(p.doc.cells), ["other/x", "x"])
+
+
+class Settings(unittest.TestCase):
+ def test_the_system_carries_the_settings(self):
+ p = load({ROOT: [entity("System", "app", {}, {"trunk": "trunk", "sandbox": "podman",
+ "sandbox_image": "python:3.13-slim",
+ "budget": {"trials_per_day": 3},
+ "autonomy": {"experimental": "merge"}}),
+ entity("Component", "a", {"system": "app", "lifecycle": "experimental"})]})
+ self.assertEqual(p.settings["trunk"], "trunk")
+ self.assertEqual(p.settings["budget"], {"trials_per_day": 3})
+ self.assertEqual(p.gate("a", True)["decision"], "merge")
+ self.assertEqual(p.gate("a", False)["decision"], "none")
+
+ def test_more_than_one_system_with_settings_is_refused(self):
+ with self.assertRaises(ProjectError) as e:
+ load({ROOT: [entity("System", "one", {}, {"sandbox": "none"}), entity("System", "two", {}, {"trunk": "x"})]})
+ self.assertIn("more than one System", str(e.exception))
+ p = load({ROOT: [entity("System", "one", {}, {"sandbox": "none"}), entity("System", "two", {}, {"tests": "true"})]})
+ self.assertEqual(p.settings, {"sandbox": "none"}) # a System with only cell rules carries no settings
+
+ def test_settings_on_anything_but_a_system_are_refused(self):
+ for kind in ("Component", "Domain", "API"):
+ with self.assertRaises(ProjectError, msg=kind):
+ load({ROOT: entity(kind, "x", {}, {"sandbox": "none"})})
+
+ def test_a_bad_setting_is_refused(self):
+ for rules in ({"sandbox": "chroot"}, {"autonomy": {"x": "always"}}, {"budget": 3}):
+ with self.assertRaises(ProjectError, msg=str(rules)):
+ load({ROOT: entity("System", "app", {}, rules)})
+
+ def test_defaults_are_inherited_unless_the_cell_sets_its_own(self):
+ p = load({ROOT: [
+ entity("System", "app", {}, {"defaults": {"tests": "python -m unittest -q", "timeout": 60,
+ "rounds": {"repeats": 4}}}),
+ entity("Component", "a", {"system": "app"}, {"run": "python a.py", "timeout": 5}),
+ entity("Component", "inner", {"subcomponentOf": "a"}, {"run": "python i.py"}),
+ entity("Component", "bare", {"system": "app"}),
+ entity("Component", "elsewhere", {}, {"run": "python e.py"})]})
+ a, inner = p.doc.cells["a"], p.doc.cells["inner"]
+ self.assertEqual((a.timeout, a.tests, a.rounds.repeats), (5, "python -m unittest -q", 4))
+ self.assertEqual((inner.timeout, inner.tests), (60, "python -m unittest -q")) # through its parent, up to the System
+ self.assertIsNone(p.doc.cells["bare"].timeout) # no rules of its own: structure
+ self.assertIsNone(p.doc.cells["elsewhere"].timeout) # not in that System
+ self.assertIsNone(p.doc.cells["app"].timeout)
+ self.assertEqual(p.settings, {}) # defaults are not settings
+
+ def test_a_system_with_cell_rules_of_its_own_inherits_too(self):
+ p = load({ROOT: [entity("System", "er", {}, {"tests": "true", "defaults": {"run": "python bench.py", "timeout": 9}}),
+ entity("Component", "off", {"system": "er"}, {"change": "x.py", "timeout": None})]})
+ self.assertEqual((p.doc.cells["er"].run, p.doc.cells["er"].tests, p.doc.cells["er"].timeout),
+ ("python bench.py", "true", 9))
+ self.assertEqual(p.doc.cells["off"].run, "python bench.py")
+ self.assertIsNone(p.doc.cells["off"].timeout) # null opts out of a default
+
+ def test_settings_come_from_the_catalog_for_the_config(self):
+ p = StructuredProject()
+ try:
+ self.assertEqual(p.cfg["sandbox"], p.doc()["sandbox"])
+ self.assertEqual(p.cfg["budget"], {"trials_per_day": 0})
+ finally:
+ p.close()
+
+
+class SplitProject(StructuredProject):
+ """The structured classifier with its catalog split over files, as a project would keep it: the root
+ holds a Location and the System (which carries the settings), `catalog/components.yaml` the components,
+ `catalog/apis.yaml` the API. `docs/catalog-info.yaml` is a catalog file nothing names."""
+
+ def __init__(self, cell_change=None):
+ super().__init__()
+ self.cell_change = cell_change
+ self.split()
+
+ def split(self, doc=None, loose=True):
+ doc = doc or self.doc()
+ if self.cell_change:
+ doc["cells"]["classify"]["change"] = self.cell_change
+ es = catalog_mod.entities(doc)
+ root = [e for e in es if e["kind"] == "System"]
+ comps = [e for e in es if e["kind"] == "Component"]
+ apis = [e for e in es if e["kind"] == "API"]
+ loc = entity("Location", "project", {"targets": ["catalog/components.yaml", "catalog/apis.yaml"]})
+ git(self.repo, "checkout", "-q", "main")
+ self.write_catalog({ROOT: [loc] + root, "catalog/components.yaml": comps, "catalog/apis.yaml": apis})
+ if loose:
+ self.write_catalog({"docs/catalog-info.yaml": [entity("Component", "notes")]})
+ git(self.repo, "add", "-A")
+ git(self.repo, "commit", "-q", "-m", "base: a split catalog")
+ self.cfg = load_config(self.repo)
+
+ def write_catalog(self, files):
+ for rel, docs in files.items():
+ self._write(self.repo / rel, yaml.safe_dump_all(docs, sort_keys=False))
+
+ def read_entities(self, rel):
+ return list(yaml.safe_load_all((self.repo / rel).read_text()))
class Judged(unittest.TestCase):
- """The judge on the classifier described half in the catalog: the same verdicts as the classifier
- described in morphogen.yaml alone."""
+ """The judge on the classifier whose catalog is split over files: the same verdicts as the one-file catalog."""
@classmethod
def setUpClass(cls):
- cls.p, cls.ref = CatalogProject(), StructuredProject()
+ cls.p, cls.ref = SplitProject(), StructuredProject()
@classmethod
def tearDownClass(cls):
@@ -154,7 +273,7 @@ def both(self, name, classify):
b = self.ref.judge(self.ref.branch(name, {"classify.py": classify}))
return a, b
- def test_same_verdicts_as_the_cell_file_alone(self):
+ def test_same_verdicts_as_the_one_file_catalog(self):
first = None
for name, text, word in (("t50", BETTER, None), ("breaks", BREAKS_NEIGHBOUR, "interface"),
("t500", CLASSIFY.replace("THRESHOLD = 10", "THRESHOLD = 500"), "range")):
@@ -164,75 +283,181 @@ def test_same_verdicts_as_the_cell_file_alone(self):
if word:
self.assertTrue(any(word in x for x in a["reasons"]), (name, a["reasons"]))
self.assertEqual(first["verdict"], "pass", first)
- self.assertEqual(first["cell"], "component:default/classify")
- self.assertEqual([x["interface"] for x in first["interfaces"]], ["api:default/labels"])
+ self.assertEqual(first["cell"], "classify")
+ self.assertEqual([x["interface"] for x in first["interfaces"]], ["labels"])
def test_names(self):
proj = judge_mod.structure_of(self.p.repo)
for name in ("classify", "component:classify", "component:default/classify", "Component:Default/Classify"):
- self.assertEqual(proj.resolve(name), "component:default/classify", name)
+ self.assertEqual(proj.resolve(name), "classify", name)
+
+ def test_the_rule_files_are_the_catalog_files_the_root_names(self):
+ proj = judge_mod.structure_of(self.p.repo)
+ self.assertEqual(sorted(proj.rule_files), ["catalog-info.yaml", "catalog/apis.yaml", "catalog/components.yaml"])
class CatalogCheats(unittest.TestCase):
- """The rules read from the catalog are the judge's, like morphogen.yaml."""
+ """Every catalog file the judge reads (the root and each Location target) is a rule file: a candidate that
+ changes, adds or removes one is refused, whatever it says, and the rules are the base's."""
@classmethod
def setUpClass(cls):
- cls.p = CatalogProject()
+ cls.p = SplitProject()
@classmethod
def tearDownClass(cls):
cls.p.close()
- def assertRefused(self, p, name, files, word="outside"):
- r = p.judge(p.branch(name, files, root=True), target="cell:classify")
+ def assertRefused(self, name, files, word="outside", p=None, delete=()):
+ p = p or self.p
+ r = p.judge(p.branch(name, files, root=True, delete=delete), target="cell:classify")
self.assertEqual(r["verdict"], "fail", f"cheat {name!r} passed the judge: {r}")
self.assertTrue(any(word in x for x in r["reasons"]), r["reasons"])
return r
- def test_drop_the_interface_from_the_catalog(self):
- self.assertRefused(self.p, "drop-api", {"catalog-info.yaml": catalog(provides=False, consumes=False),
- "targets/classify/classify.py": BREAKS_NEIGHBOUR})
+ def edited(self, rel, edit):
+ docs = self.p.read_entities(rel)
+ edit(docs)
+ return yaml.safe_dump_all(docs, sort_keys=False)
- def test_widen_change_with_an_annotation(self):
+ def test_widen_a_cells_rules_in_any_catalog_file(self):
rigged = CLASSIFY_BENCH.replace("print(label(x))", 'print("high" if x >= 50 else "low")')
- self.assertRefused(self.p, "annotate", {"catalog-info.yaml": catalog(change="targets/**"),
- "targets/classify/bench.py": rigged})
-
- def test_weaken_the_catalog_for_next_time(self):
- # The operator opened everything (change: "**"). The candidate's gain is honest, and this
- # verdict uses the base's catalog anyway; but it also drops the API from the catalog, so once
- # merged, every later judgment would skip the contract. The catalog is the judge's: refused.
- cell = copy.deepcopy(CLASSIFY_CELL)
- cell["change"] = "**"
- q = CatalogProject(cell=cell)
+
+ def widen(docs):
+ for d in docs:
+ if d["metadata"]["name"] == "classify":
+ d["spec"]["morphogen"]["change"] = "targets/**"
+ r = self.assertRefused("widen", {"catalog/components.yaml": self.edited("catalog/components.yaml", widen),
+ "targets/classify/bench.py": rigged})
+ self.assertTrue(any("catalog/components.yaml" in x for x in r["reasons"]), r["reasons"])
+
+ def test_edit_the_rules_in_the_root(self):
+ def drop(docs):
+ for d in docs:
+ if d["kind"] == "System":
+ d["spec"]["morphogen"]["budget"] = {"trials_per_day": 1000}
+ r = self.assertRefused("root", {ROOT: self.edited(ROOT, drop), "targets/classify/classify.py": BETTER})
+ self.assertTrue(any(ROOT in x for x in r["reasons"]), r["reasons"])
+
+ def test_drop_the_interface_from_the_catalog(self):
+ def drop(docs):
+ for d in docs:
+ d["spec"].pop("providesApis", None)
+ d["spec"].pop("consumesApis", None)
+ self.assertRefused("drop-api", {"catalog/components.yaml": self.edited("catalog/components.yaml", drop),
+ "targets/classify/classify.py": BREAKS_NEIGHBOUR})
+
+ def test_remove_the_tests_from_an_api(self):
+ def drop(docs):
+ for d in docs:
+ d["spec"].pop("morphogen", None)
+ self.assertRefused("untested", {"catalog/apis.yaml": self.edited("catalog/apis.yaml", drop),
+ "targets/classify/classify.py": BREAKS_NEIGHBOUR}, word="catalog/apis.yaml")
+
+ def test_add_a_location_target(self):
+ def add(docs):
+ docs[0]["spec"]["targets"].append("catalog/more.yaml")
+ r = self.assertRefused("new-target", {ROOT: self.edited(ROOT, add),
+ "catalog/more.yaml": yaml.safe_dump(entity("Component", "more")),
+ "targets/classify/classify.py": BETTER})
+ self.assertTrue(any(ROOT in x for x in r["reasons"]), r["reasons"])
+
+ def test_add_a_catalog_file_the_root_does_not_name_but_point_at_it(self):
+ """The new file only matters if the root names it, and the root is a rule file."""
+ r = self.assertRefused("extra-file", {"catalog/extra.yaml": yaml.safe_dump(entity("Component", "x", {}, {"run": "true"})),
+ "targets/classify/classify.py": BETTER})
+ self.assertTrue(any("catalog/extra.yaml" in x for x in r["reasons"]), r["reasons"])
+
+ def test_remove_a_location_target(self):
+ r = self.assertRefused("remove-target", {"targets/classify/classify.py": BETTER}, delete=["catalog/apis.yaml"])
+ self.assertTrue(any("catalog/apis.yaml" in x for x in r["reasons"]), r["reasons"])
+
+ def test_rename_a_location_target_away(self):
+ self.assertRefused("rename-target", {"catalog/apis-moved.yaml": (self.p.repo / "catalog/apis.yaml").read_text(),
+ "targets/classify/classify.py": BETTER}, delete=["catalog/apis.yaml"])
+
+ def test_the_settings_are_the_bases(self):
+ """A candidate's System may say anything; checked out, loaded from the working copy, the judge still uses
+ the base's settings and refuses the change to the file."""
+ def edit(docs):
+ for d in docs:
+ if d["kind"] == "System":
+ d["spec"]["morphogen"].update(sandbox="none", sandbox_image="attacker/python:latest",
+ budget={"trials_per_day": 1000})
+ p = self.p
+ cand = p.branch("settings", {ROOT: self.edited(ROOT, edit), "targets/classify/classify.py": BETTER}, root=True)
+ base_sha = judge_mod.resolve(p.repo, "main")
+ git(p.repo, "checkout", "-q", cand)
try:
- r = self.assertRefused(q, "weaken", {"catalog-info.yaml": catalog(provides=False, consumes=False),
- "targets/classify/classify.py": BETTER})
- self.assertTrue(any("catalog-info.yaml" in x for x in r["reasons"]), r["reasons"])
+ cfg = load_config(p.repo)
+ self.assertEqual(cfg["budget"], {"trials_per_day": 1000}) # the working copy says so
+ got = rules_config(p.repo, base_sha, cfg)
+ self.assertEqual(got["budget"], {"trials_per_day": 0})
+ self.assertEqual(got["sandbox_image"], "python:3.12-slim")
+ self.assertEqual(got["settings_from"]["budget"], "base")
+ r = judge_mod.judge(p.repo, cfg, "cell:classify", "main", cand, p.evidence)
+ finally:
+ git(p.repo, "checkout", "-q", "main")
+ self.assertEqual(r["verdict"], "fail", r)
+ self.assertTrue(any(ROOT in x for x in r["reasons"]), r["reasons"])
+
+ def test_a_file_the_root_does_not_name_is_judged_normally(self):
+ """`docs/catalog-info.yaml` is nothing's rules: where a cell may change it, editing it is no cheat."""
+ q = SplitProject(cell_change=["targets/classify/classify.py", "targets/classify/classify.py#THRESHOLD in 0..100",
+ "docs/catalog-info.yaml"])
+ try:
+ self.assertNotIn("docs/catalog-info.yaml", judge_mod.structure_of(q.repo).rule_files)
+ r = q.judge(q.branch("loose", {"docs/catalog-info.yaml": yaml.safe_dump(entity("Component", "notes2", {}, {"run": "x"})),
+ "targets/classify/classify.py": BETTER}, root=True), target="cell:classify")
+ self.assertEqual(r["verdict"], "pass", r)
+ self.assertFalse(any("docs/catalog-info.yaml" in x for x in r.get("reasons", [])))
+ finally:
+ q.close()
+
+ def test_a_file_nothing_may_change_is_still_default_denied(self):
+ self.assertRefused("loose-denied", {"docs/catalog-info.yaml": yaml.safe_dump(entity("Component", "notes2")),
+ "targets/classify/classify.py": BETTER}, word="docs/catalog-info.yaml")
+
+ def test_a_cell_may_not_be_allowed_to_change_the_rules_it_is_judged_by(self):
+ """Even when the operator wrote `change: **`, the catalog files stay the judge's."""
+ q = SplitProject(cell_change="**")
+ try:
+ def drop(docs):
+ for d in docs:
+ d["spec"].pop("providesApis", None)
+ d["spec"].pop("consumesApis", None)
+ docs = q.read_entities("catalog/components.yaml")
+ drop(docs)
+ r = self.assertRefused("weaken", {"catalog/components.yaml": yaml.safe_dump_all(docs, sort_keys=False),
+ "targets/classify/classify.py": BETTER}, p=q)
+ self.assertTrue(any("catalog/components.yaml" in x for x in r["reasons"]), r["reasons"])
finally:
q.close()
- def test_a_conflict_between_the_sources_is_refused(self):
- q = CatalogProject(catalog_text=catalog(change="targets/classify/bench.py"))
+ def test_a_broken_catalog_on_the_base_is_refused_by_name(self):
+ q = SplitProject()
try:
- with self.assertRaises(judge_mod.JudgeError) as e:
+ q.write_catalog({"catalog/apis.yaml": [entity("API", "labels", {}, {"run": "x"})]})
+ git(q.repo, "commit", "-qam", "base: a bad API")
+ with self.assertRaises((judge_mod.JudgeError, DocumentError)) as e:
q.judge(q.branch("any", {"classify.py": BETTER}), target="cell:classify")
- self.assertIn("change", str(e.exception))
+ self.assertIn("catalog/apis.yaml", str(e.exception))
finally:
q.close()
class Autonomy(unittest.TestCase):
- """`autonomy` in morphogen.yaml maps a cell's lifecycle to what a pass allows: `merge` (an agent may
- merge it) or `review` (a person decides; the default). The gate is the base's: owner and lifecycle
- come from the base's catalog, the policy from the base's morphogen.yaml."""
+ """`autonomy` on the System maps a cell's lifecycle to what a pass allows: `merge` (an agent may merge it) or
+ `review` (a person decides; the default). The gate is the base's: owner and lifecycle come from the base's
+ catalog, the policy from the base's System."""
def project(self, lifecycle):
- q = CatalogProject(catalog_text=catalog(lifecycle=lifecycle))
+ q = StructuredProject()
doc = q.doc()
+ doc["cells"]["classify"]["lifecycle"] = lifecycle
+ doc["cells"]["classify"]["owner"] = "team-a"
doc["autonomy"] = {"experimental": "merge"}
- q.on_main(doc=doc)
+ q.on_main(doc=doc, root=True)
self.addCleanup(q.close)
return q
@@ -254,17 +479,19 @@ def test_relabel_the_cell_experimental_to_be_merged(self):
# An honest gain, and the candidate also marks its cell experimental in the catalog so that
# its pass would be merged without review. The catalog is the judge's: refused.
q = self.project("production")
- r = q.judge(q.branch("relabel", {"catalog-info.yaml": catalog(lifecycle="experimental"),
- "targets/classify/classify.py": BETTER}, root=True), target="cell:classify")
+ doc = q.doc()
+ doc["cells"]["classify"]["lifecycle"] = "experimental"
+ r = q.judge(q.branch("relabel", {ROOT: q.dump(doc), "targets/classify/classify.py": BETTER}, root=True),
+ target="cell:classify")
self.assertEqual(r["verdict"], "fail", r)
self.assertNotEqual(r["gate"]["decision"], "merge")
- def test_grant_autonomy_in_the_candidates_own_file(self):
+ def test_grant_autonomy_in_the_candidates_own_catalog(self):
q = self.project("production")
doc = q.doc()
doc["autonomy"] = {"production": "merge"}
- r = q.judge(q.branch("grant", {"morphogen.yaml": q.dump(doc),
- "targets/classify/classify.py": BETTER}, root=True), target="cell:classify")
+ r = q.judge(q.branch("grant", {ROOT: q.dump(doc), "targets/classify/classify.py": BETTER}, root=True),
+ target="cell:classify")
self.assertEqual(r["verdict"], "fail", r)
self.assertNotEqual(r["gate"]["decision"], "merge")
@@ -277,28 +504,38 @@ def test_a_skill_is_a_cell(self):
docs = [entity("System", "agents", {"owner": "ai-team"}),
entity("AiResource", "map", {"type": "skill", "lifecycle": "experimental", "owner": "ai-team",
"system": "agents", "dependsOn": ["airesource:default/house-style"]},
- {"morphogen.dev/change": "skills/map/SKILL.md", "backstage.io/source-location":
- "url:https://example.org/skills/map/SKILL.md"}),
+ {"change": "skills/map/SKILL.md"}),
entity("AiResource", "house-style", {"type": "rule", "lifecycle": "production", "owner": "ai-team",
"category": "quality", "rationale": "one voice"})]
- cells, ifaces, _ = bs.to_cells([{**d, "_file": "catalog-info.yaml"} for d in docs])
- m = cells["airesource:default/map"]
+ cells, ifaces, _, _ = bs.to_cells([{**d, "_file": "catalog-info.yaml"} for d in docs])
+ m = cells["map"]
self.assertEqual((m["in"], m["change"], m["lifecycle"], m["owner"]),
- ("system:default/agents", ["skills/map/SKILL.md"], "experimental", "group:default/ai-team"))
- self.assertEqual(m["consumes"], ["airesource:default/house-style"])
- self.assertIn("airesource:default/house-style", cells)
+ ("agents", "skills/map/SKILL.md", "experimental", "group:default/ai-team"))
+ self.assertEqual(m["consumes"], ["house-style"])
+ self.assertIn("house-style", cells)
-class DemoSplit(unittest.TestCase):
- """demos/entity-resolution: the structure in catalog-info.yaml, what may change in morphogen.yaml,
- and together the same cells, nesting, interfaces and settings as the demo had in one file."""
+class StatusOfARootLocation(unittest.TestCase):
+ def test_status_lists_catalog_files_the_root_does_not_name(self):
+ from morphogen.status import status
+ q = SplitProject()
+ try:
+ s = status(q.repo, q.cfg)
+ self.assertEqual(sorted(s["sources"]["catalog"]["read"]),
+ ["catalog-info.yaml", "catalog/apis.yaml", "catalog/components.yaml"])
+ self.assertTrue(any("docs/catalog-info.yaml" in m for m in s["missing"]), s["missing"])
+ finally:
+ q.close()
- def test_the_demo_reads_both(self):
+
+class Demos(unittest.TestCase):
+ """demos/entity-resolution: one catalog, the structure and what may change, as the demo had in one file."""
+
+ def test_the_demo_reads(self):
from morphogen.structure import Structure
- s = Structure.load(Path(__file__).resolve().parents[1] / "demos" / "entity-resolution" / "morphogen.yaml")
- short = (lambda x: x.split("/")[-1] if x else x)
- shape = {short(c): (short(s.parent(c)), sorted(map(short, s.cells[c].provides)),
- sorted(map(short, s.cells[c].consumes)), sorted(s.cells[c].parameters)) for c in s.cells}
+ s = Structure.load(Path(__file__).resolve().parents[1] / "demos" / "entity-resolution" / ROOT)
+ shape = {c: (s.parent(c), sorted(s.cells[c].provides), sorted(s.cells[c].consumes),
+ sorted(s.cells[c].parameters)) for c in s.cells}
self.assertEqual(shape, {
"er": (None, ["resolver"], ["candidates", "pair-score"], []),
"blocking": ("er", ["candidates"], [], ["BLOCK_LIMIT", "BLOCK_MAX_DF"]),
@@ -307,10 +544,25 @@ def test_the_demo_reads_both(self):
"backend": ("er", ["similarity"], [], ["BACKEND"]),
"clustering": ("er", [], ["pair-score"], []),
"speed": ("matcher", [], [], [])})
- r = s.interfaces["api:default/resolver"]
+ r = s.interfaces["resolver"]
self.assertEqual((r.tests, r.external), (["python -m unittest discover -s tests -t ."], "consumes"))
self.assertEqual(s.coverage()["tested"], 4)
+ def test_the_f1_workload_is_the_systems_defaults(self):
+ p = Project.load(Path(__file__).resolve().parents[1] / "demos" / "entity-resolution")
+ for name in ("er", "blocking", "matcher", "backend"):
+ c = p.doc.cells[name]
+ self.assertEqual((c.run, c.score, c.timeout), ("python bench.py", "python score.py", 300), name)
+ self.assertEqual(sorted(p.spec(name)["measure"]["metrics"]), ["scored.f1", "scored.precision"], name)
+ self.assertEqual(p.doc.cells["er"].tests, "python -m unittest discover -s tests -t .")
+ self.assertIsNone(p.doc.cells["clustering"].run)
+ speed = p.spec("speed") # its own measure: wall time, the same output
+ self.assertEqual(sorted(speed["measure"]["metrics"]), ["max_rss_kb", "wall_seconds"])
+ self.assertTrue(speed["measure"]["same_output"])
+ self.assertNotIn("score", speed["measure"])
+ self.assertEqual([e["path"] for e in p.changes["matcher"]], ["er/settings.py"] * 4)
+ self.assertEqual(p.errors(), [])
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_cells.py b/tests/test_cells.py
index 8e86af0..57e7741 100644
--- a/tests/test_cells.py
+++ b/tests/test_cells.py
@@ -1,4 +1,4 @@
-"""The cell format (morphogen.yaml): parsing, compiling, and default deny. A candidate may change only
+"""The cell format (`spec.morphogen` in the catalog): parsing, compiling, and default deny. A candidate may change only
what the judged cell's scope names in `change`; everything else is the judge's."""
from pathlib import Path
@@ -10,6 +10,7 @@
from morphogen import optimize as O
from morphogen import project as P
from morphogen.structure import Structure
+from tests.catalog import dump, project as catalog_project
from tests.fixture_cells import CELLS_CONTRACT, CellsProject, cells_doc
from tests.fixture_scored import CLASSIFY, CLASSIFY_BENCH
@@ -43,7 +44,7 @@ def test_better_forms(self):
P.parse_better("accuracy sideways")
def test_compile_structure_and_spec(self):
- proj = P.Project.from_dict(cells_doc())
+ proj = catalog_project(cells_doc())
s = proj.structure()
self.assertEqual(s.cells["classify"].parent, "app")
self.assertEqual(s.providers("labels"), ["classify"])
@@ -62,13 +63,13 @@ def test_unknown_fields_are_refused(self):
d = cells_doc()
d["cells"]["classify"]["chnage"] = "x.py"
with self.assertRaises(P.ProjectError):
- P.Project.from_dict(d)
+ catalog_project(d)
- def test_tests_only_from_the_base_and_the_project_file_is_never_changeable(self):
+ def test_tests_only_from_the_base_and_the_catalog_is_never_changeable(self):
d = cells_doc()
d["cells"]["classify"]["change"] = "**"
- proj = P.Project.from_dict(d)
- self.assertFalse(proj.allows(["classify"], "morphogen.yaml"))
+ proj = catalog_project(d)
+ self.assertFalse(proj.allows(["classify"], "catalog-info.yaml"))
self.assertTrue(proj.allows(["classify"], "classify/bench.py"))
@@ -138,7 +139,7 @@ def test_widen_change_in_the_candidates_own_project_file(self):
d["cells"]["classify"]["change"] = "classify/**"
rigged = CLASSIFY_BENCH.replace("print(label(x))", 'print("high" if x >= 50 else "low")')
self.assertRefused(self.p, "widen", "outside",
- files={"morphogen.yaml": yaml.safe_dump(d), "classify/bench.py": rigged})
+ files={"catalog-info.yaml": dump(d), "classify/bench.py": rigged})
def test_change_more_than_the_setting(self):
rigged = BETTER.replace('def label(x):\n', 'def label(x):\n x = x + 0\n')
@@ -187,7 +188,7 @@ def test_names(self):
self.p.judge("by-name", target="cell:report") # no run
def test_structure_tools_read_the_project_file(self):
- s = Structure.load(self.p.repo / "morphogen.yaml")
+ s = Structure.load(self.p.repo / "catalog-info.yaml")
self.assertEqual(sorted(s.cells), ["app", "classify", "report"])
self.assertEqual(s.coverage()["tested"], 1)
diff --git a/tests/test_gateway.py b/tests/test_gateway.py
index e7b54f3..55f3c27 100644
--- a/tests/test_gateway.py
+++ b/tests/test_gateway.py
@@ -9,6 +9,7 @@
from morphogen.documents import load_config
from morphogen.schema import Verdict
+from tests.catalog import dump
from tests.fixture import CLASSIFY, git
from tests.fixture_cells import CellsProject, cells_doc
@@ -35,7 +36,7 @@ def setUp(self):
(self.p.repo / "morphogen.local.yaml").write_text(yaml.safe_dump(doc))
doc = cells_doc(code=True)
doc["cells"]["classify"]["better"] = "metered.calls lower, metered.tokens lower"
- self.p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False))
+ self.p.write("catalog-info.yaml", dump(doc))
self.p.write("classify/classify.py", self.calls(3))
git(self.p.repo, "commit", "-qam", "base: three calls a run")
self.p.cfg = load_config(self.p.repo)
diff --git a/tests/test_judge.py b/tests/test_judge.py
index 936f23d..51179b4 100644
--- a/tests/test_judge.py
+++ b/tests/test_judge.py
@@ -10,6 +10,7 @@
from morphogen import documents
from morphogen import judge as judge_mod
from morphogen.evidence import Evidence
+from tests.catalog import dump
from tests.fixture import (CLASSIFY, COMPUTE, FAST, SETTINGS, TARGET, WRONG, GuardedProject, InputsProject,
SampleProject, ScoredProject, StructuredProject, git, parameter_project)
@@ -54,7 +55,7 @@ def test_probe_gives_feedback_not_a_verdict(self):
def test_the_judge_refuses_a_malformed_cell(self):
doc = self.p.doc()
doc["cells"]["slow-script"]["better"] = {"wall_seconds": {"lower": True, "gain": "huge"}}
- cand = self.p.branch("malformed-base", {"morphogen.yaml": self.p.dump(doc)}, root=True)
+ cand = self.p.branch("malformed-base", {"catalog-info.yaml": self.p.dump(doc)}, root=True)
with self.assertRaises(judge_mod.JudgeError):
self.p.judge("main", base=cand)
@@ -197,7 +198,7 @@ def test_settings_are_recorded_searched_and_counted_once(self):
doc = self.p.doc()
doc["cells"]["classify"]["change"] += ["targets/classify/classify.py#MARGIN in [0, 1, 2]",
"targets/classify/classify.py#THRESHOLD in 0..100"] # twice
- base = self.p.branch_files("cell-params", {"morphogen.yaml": self.p.dump(doc),
+ base = self.p.branch_files("cell-params", {"catalog-info.yaml": self.p.dump(doc),
"targets/classify/classify.py": CLASSIFY + "MARGIN = 0\n"})
git(self.p.repo, "checkout", "-q", base)
try:
@@ -246,7 +247,7 @@ def test_a_cell_speedup_that_helps_the_system_passes(self):
def test_no_guard_when_turned_off(self):
doc = self.p.doc()
doc["cells"]["fast"]["guard"] = False
- base = self.p.branch_root("no-guard-base", {"morphogen.yaml": self.p.dump(doc)})
+ base = self.p.branch_root("no-guard-base", {"catalog-info.yaml": self.p.dump(doc)})
cand = self.p.branch_root("faster-3", {"targets/system/compute.py": self.FASTER}, base=base)
self.assertIsNone(self.p.judge(cand, base=base)["system"])
diff --git a/tests/test_redteam.py b/tests/test_redteam.py
index 4545197..54dcbff 100644
--- a/tests/test_redteam.py
+++ b/tests/test_redteam.py
@@ -18,6 +18,7 @@
from morphogen import judge as judge_mod
from morphogen.documents import load_config
+from tests.catalog import dump
from tests.fixture_cells import CellsProject, cells_doc
from tests.fixture import (AGENT, git, CLASSIFY, CLASSIFY_CELL, COMPUTE, CONTRACT_TEST, FAST, SETTINGS, AgentProject,
GuardedProject, InputsProject,
@@ -123,9 +124,9 @@ def tearDownClass(cls):
def assertFails(self, name, files=None, delete=()):
files = dict(files or {})
- doc = files.pop("morphogen.yaml", None)
+ doc = files.pop("catalog-info.yaml", None)
if doc is not None:
- name = self.p.branch(name, {"morphogen.yaml": doc}, root=True)
+ name = self.p.branch(name, {"catalog-info.yaml": doc}, root=True)
r = self.p.judge(self.p.branch(name, files, delete, base=name))
self.assertEqual(r["verdict"], "fail", f"cheat {name!r} passed the judge: {r}")
return r
@@ -146,8 +147,8 @@ def test_rig_the_benchmark(self):
def test_lower_the_bar_in_the_project_file(self):
doc = self.p.doc()
doc["cells"]["slow-script"].update(run="true", better={"wall_seconds": {"lower": True, "min": -1}})
- r = self.assertFails("lower-bar", {"morphogen.yaml": self.p.dump(doc), "topwords.py": self.slow + "# x\n"})
- self.assertTrue(any("morphogen.yaml" in x for x in r["reasons"]), r["reasons"])
+ r = self.assertFails("lower-bar", {"catalog-info.yaml": self.p.dump(doc), "topwords.py": self.slow + "# x\n"})
+ self.assertTrue(any("catalog-info.yaml" in x for x in r["reasons"]), r["reasons"])
def test_delete_the_tests(self):
self.assertFails("delete-tests", delete=["test_topwords.py"])
@@ -247,10 +248,10 @@ def test_promote_self_reported_telemetry(self):
doc["cells"]["slow-script"]["better"] = {"observed.latency_ms": {"lower": True, "min": 0.10},
"wall_seconds": "lower"}
cand = p.branch("promote-self", {"observe.py": QUIET_OBSERVER})
- cand = p.branch("promote-self-2", {"morphogen.yaml": p.dump(doc)}, root=True, base=cand)
+ cand = p.branch("promote-self-2", {"catalog-info.yaml": p.dump(doc)}, root=True, base=cand)
r = p.judge(cand)
self.assertEqual(r["verdict"], "fail", r)
- self.assertTrue(any("morphogen.yaml" in x for x in r["reasons"]), r["reasons"])
+ self.assertTrue(any("catalog-info.yaml" in x for x in r["reasons"]), r["reasons"])
finally:
p.close()
@@ -371,7 +372,7 @@ def tearDownClass(cls):
def assertFails(self, name, files):
files = dict(files)
- root = {"morphogen.yaml": files.pop("morphogen.yaml")} if "morphogen.yaml" in files else {}
+ root = {"catalog-info.yaml": files.pop("catalog-info.yaml")} if "catalog-info.yaml" in files else {}
root.update({f"{self.p.home}/{k}": v for k, v in files.items()})
r = self.p.judge(self.p.branch(name, root, root=True))
self.assertEqual(r["verdict"], "fail", f"cheat {name!r} passed the judge: {r}")
@@ -408,8 +409,8 @@ def test_read_the_held_out_answers_by_an_obfuscated_path(self):
def test_edit_the_bar_in_the_project_file(self):
doc = self.p.doc()
doc["cells"]["classify"]["better"]["accuracy"]["min"] = -1
- r = self.assertFails("lower-bar", {"morphogen.yaml": self.p.dump(doc), "classify.py": CLASSIFY + "# touched\n"})
- self.assertTrue(any("morphogen.yaml" in x for x in r["reasons"]), r["reasons"])
+ r = self.assertFails("lower-bar", {"catalog-info.yaml": self.p.dump(doc), "classify.py": CLASSIFY + "# touched\n"})
+ self.assertTrue(any("catalog-info.yaml" in x for x in r["reasons"]), r["reasons"])
# --- cheats with the inputs: data kept outside the repository (its licence keeps it out of git) and
@@ -540,8 +541,8 @@ def test_drop_the_interface_from_the_structure(self):
doc["cells"]["classify"]["provides"] = []
doc["cells"]["report"]["consumes"] = []
r = self.assertFails("drop-interface", {"targets/classify/classify.py": BETTER_BUT_BREAKS_NEIGHBOUR,
- "morphogen.yaml": self.p.dump(doc)})
- self.assertTrue(any("morphogen.yaml" in x for x in r["reasons"]), r["reasons"])
+ "catalog-info.yaml": self.p.dump(doc)})
+ self.assertTrue(any("catalog-info.yaml" in x for x in r["reasons"]), r["reasons"])
def test_break_a_neighbours_interface_naming_the_target_by_path(self):
"""The target is the cell's measure, named by its directory (spelled oddly) and not as a cell."""
@@ -699,8 +700,8 @@ def test_weaken_the_interface_test_too(self):
def test_drop_the_interface_tests_from_the_rules(self):
doc = cells_doc(code=True)
doc["interfaces"]["labels"] = []
- self.assertRefused("no-tests", {"classify/classify.py": BROKEN_LABEL, "morphogen.yaml": yaml.safe_dump(doc)},
- why="morphogen.yaml")
+ self.assertRefused("no-tests", {"classify/classify.py": BROKEN_LABEL, "catalog-info.yaml": dump(doc)},
+ why="catalog-info.yaml")
def test_shadow_unittest_at_the_root(self):
self.assertRefused("fake-unittest", {"classify/classify.py": BROKEN_LABEL, "unittest.py": FAKE_UNITTEST},
@@ -717,9 +718,9 @@ def test_a_file_no_cell_owns(self):
class SettingsCheats(unittest.TestCase):
- """The judge's settings (sandbox, sandbox_image, budget) are rules too: they come from the base commit's
- morphogen.yaml, with only the operator's uncommitted morphogen.local.yaml laid over them. An agent that
- edits the working copy of morphogen.yaml without committing, then calls the judge from that checkout
+ """The judge's settings (sandbox, sandbox_image, budget) are rules too: they come from the System's
+ `spec.morphogen` in the base commit's catalog, with only the operator's uncommitted morphogen.local.yaml laid over them. An agent that
+ edits the working copy of the catalog without committing, then calls the judge from that checkout
(the CLI and the MCP server read the project root), must change nothing."""
def setUp(self):
@@ -729,15 +730,15 @@ def tearDown(self):
self.p.close()
def edit_working_copy(self, **settings):
- doc = yaml.safe_load((self.p.repo / "morphogen.yaml").read_text())
+ doc = cells_doc(code=True)
doc.update(settings)
- self.p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False)) # not committed
+ self.p.write("catalog-info.yaml", dump(doc)) # not committed
self.p.cfg = load_config(self.p.repo) # as the CLI and MCP read it
def test_raise_the_trial_budget_in_the_working_copy(self):
doc = cells_doc(code=True)
doc["budget"] = {"trials_per_day": 1}
- self.p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False))
+ self.p.write("catalog-info.yaml", dump(doc))
git(self.p.repo, "commit", "-qam", "base: one trial a day")
self.p.evidence.append({"kind": "verdict", "by": "judge", "verdict": "fail", "claim": "today's trial", "trust": "measured"})
self.edit_working_copy(budget={"trials_per_day": 100})
@@ -947,7 +948,7 @@ def test_report_its_own_counts(self):
from tests.fixture_gateway import CALL
doc = cells_doc(code=True)
doc["cells"]["classify"]["better"] = "metered.calls lower"
- self.p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False))
+ self.p.write("catalog-info.yaml", dump(doc))
self.p.write("classify/classify.py", CLASSIFY + "LIMIT = 100\n" + CALL + "for _ in range(3):\n call()\n")
git(self.p.repo, "commit", "-qam", "base: three calls a run, calls metered")
self.p.cfg = load_config(self.p.repo)
@@ -963,7 +964,7 @@ def test_report_its_own_counts_into_the_record(self):
from tests.fixture_gateway import CALL
doc = cells_doc(code=True)
doc["cells"]["classify"]["better"] = "metered.calls lower"
- self.p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False))
+ self.p.write("catalog-info.yaml", dump(doc))
self.p.write("classify/classify.py", CLASSIFY + "LIMIT = 100\n" + CALL + "for _ in range(3):\n call()\n")
git(self.p.repo, "commit", "-qam", "base: three calls a run, calls metered")
self.p.cfg = load_config(self.p.repo)
@@ -1034,7 +1035,7 @@ def test_a_metered_metric_needs_a_gateway(self):
try:
doc = cells_doc(code=True)
doc["cells"]["classify"]["better"] = "metered.calls lower"
- p.write("morphogen.yaml", yaml.safe_dump(doc, sort_keys=False))
+ p.write("catalog-info.yaml", dump(doc))
git(p.repo, "commit", "-qam", "calls metered")
p.cfg = load_config(p.repo)
with self.assertRaises(judge_mod.JudgeError) as e:
diff --git a/tests/test_request.py b/tests/test_request.py
index e1f3e69..2758dbd 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -12,7 +12,7 @@
from morphogen import request as request_mod
from morphogen.documents import DocumentError
from tests.fixture import CLASSIFY
-from tests.fixture_cells import CellsProject
+from tests.fixture_cells import CellsProject, cells_doc
HONEST = CLASSIFY + "LIMIT = 100\n# same\n"
@@ -71,7 +71,7 @@ def test_write_the_request_inside_the_repository(self):
self.assertRefused(self.write(self.change_request(), where=self.p.repo), "inside the repository")
def test_carry_rules_in_the_request(self):
- doc = yaml.safe_load((self.p.repo / "morphogen.yaml").read_text())
+ doc = cells_doc(code=True)
doc["interfaces"]["labels"] = []
self.assertRefused(self.write(self.change_request(cells=doc["cells"], interfaces=doc["interfaces"])),
"the rules come from the base commit")
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 3f526c1..83a09d6 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -36,11 +36,50 @@ def test_verdicts_the_judge_writes_validate(self):
class SpecSchema(unittest.TestCase):
- """schemas/morphogen-spec.v0.json (a draft) carries the fields a cell accepts today, so phase 2 can load them."""
+ """schemas/morphogen-spec.v1.json carries exactly the fields the code accepts under `spec.morphogen`: the cell's,
+ the API's, the System's settings and the option's."""
- def test_the_cell_fields_are_those_morphogen_yaml_accepts(self):
- from morphogen.project import CellDoc
- spec = json.loads((HERE / "schemas/morphogen-spec.v0.json").read_text())
+ def schema(self):
+ return json.loads((HERE / "schemas/morphogen-spec.v1.json").read_text())
+
+ def fields(self, name):
+ return set(self.schema()["$defs"][name]["properties"])
+
+ def test_the_cell_fields_are_those_the_catalog_accepts(self):
+ from morphogen.project import CellDoc, CellRules
held_by_backstage = {"in", "provides", "consumes", "owner", "lifecycle"}
accepted = {(f.alias or n) for n, f in CellDoc.model_fields.items()} - held_by_backstage
- self.assertEqual(set(spec["$defs"]["Cell"]["properties"]), accepted)
+ self.assertEqual(self.fields("Cell"), accepted)
+ self.assertEqual(self.fields("Cell"), set(CellRules.model_fields))
+
+ def test_the_api_fields(self):
+ from morphogen.project import InterfaceDoc
+ self.assertEqual(self.fields("ApiTests"), set(InterfaceDoc.model_fields))
+
+ def test_the_system_settings(self):
+ from morphogen.project import SystemRules
+ self.assertEqual(self.fields("SystemSettings"), set(SystemRules.model_fields))
+ defaults = self.schema()["$defs"]["SystemSettings"]["properties"]["defaults"]
+ self.assertEqual(defaults["$ref"], "#/$defs/Cell")
+
+ def test_the_option_fields(self):
+ from morphogen.project import OptionRules
+ self.assertEqual(self.fields("Option"), set(OptionRules.model_fields))
+
+ def test_the_whole_is_what_spec_morphogen_accepts(self):
+ from morphogen.project import MorphogenSpec
+ s = self.schema()
+ union = set().union(*(self.fields(r["$ref"].rsplit("/", 1)[1]) for r in s["allOf"]))
+ self.assertEqual(union, set(MorphogenSpec.model_fields))
+ self.assertIs(s["unevaluatedProperties"], False)
+
+ def test_the_settings_the_catalog_reads_are_the_systems(self):
+ from morphogen.backstage import SETTINGS
+ self.assertEqual(set(SETTINGS), self.fields("SystemSettings"))
+
+ def test_the_defaults_for_the_settings_match(self):
+ from morphogen.documents import Config
+ props = self.schema()["$defs"]["SystemSettings"]["properties"]
+ for name, f in Config.model_fields.items():
+ if name in props and "default" in props[name]:
+ self.assertEqual(props[name]["default"], f.default, name)
diff --git a/tests/test_status.py b/tests/test_status.py
index f515fe2..e46680f 100644
--- a/tests/test_status.py
+++ b/tests/test_status.py
@@ -12,6 +12,7 @@
from morphogen.documents import load_config
from morphogen.evidence import Evidence
from morphogen.status import status
+from tests.catalog import dump
from tests.fixture import SANDBOX, git
WORK = "import time\n\nDELAY = 0.4\n\n\ndef main():\n time.sleep(DELAY)\n print('done')\n\n\nif __name__ == '__main__':\n main()\n"
@@ -36,7 +37,7 @@ def write(self, rel, text):
(self.repo / rel).write_text(text)
def doc(self, cells, **extra):
- self.write("morphogen.yaml", yaml.safe_dump({"sandbox": SANDBOX, **extra, "cells": cells}, sort_keys=False))
+ self.write("catalog-info.yaml", dump({"sandbox": SANDBOX, **extra, "cells": cells}))
def commit(self, msg="c"):
git(self.repo, "add", "-A")
@@ -57,8 +58,8 @@ def test_from_nothing_to_a_verdict(self):
self.write("test_work.py", TEST)
self.commit("the system")
s = self.now()
- self.assertFalse(s["sources"]["morphogen.yaml"])
- self.assertIn("no map yet", s["next"])
+ self.assertFalse(s["sources"]["catalog-info.yaml"])
+ self.assertIn("no catalog yet", s["next"])
# the map skill's first draft, not yet on main
self.doc({"work": CELL})
@@ -97,25 +98,27 @@ def test_problems_and_sources(self):
git(self.repo, "config", "user.email", "t@example.com")
git(self.repo, "config", "user.name", "test")
self.write("work.py", WORK)
- self.write("catalog-info.yaml", yaml.safe_dump({
+ (self.repo / "sub").mkdir()
+ self.write("sub/catalog-info.yaml", yaml.safe_dump({
"apiVersion": "backstage.io/v1alpha1", "kind": "Component",
"metadata": {"name": "work"}, "spec": {"type": "service", "lifecycle": "experimental", "owner": "me"}}))
self.commit()
s = self.now()
- self.assertEqual(s["sources"]["backstage"]["found"], ["catalog-info.yaml"])
- self.assertIn("backstage: [catalog-info.yaml]", s["next"])
+ self.assertEqual(s["sources"]["catalog"]["found"], ["sub/catalog-info.yaml"])
+ self.assertIn("not the project's catalog root", s["next"])
# a cell with a run but nothing it may change; a committed local file
- self.doc({"work": {"run": "python work.py"}}, backstage="catalog-info.yaml")
+ self.doc({"work": {"run": "python work.py"}})
self.write("morphogen.local.yaml", "sandbox: none\n")
self.commit()
s = self.now()
names = {c["cell"]: c for c in s["cells"]}
- self.assertIn("component:default/work", names)
+ self.assertIn("work", names)
self.assertFalse(names["work"]["ready"])
self.assertIn("no `change`", names["work"]["problems"][0])
self.assertIn("no `better`", " ".join(names["work"]["notes"]))
self.assertTrue(any("morphogen.local.yaml is committed" in m for m in s["missing"]))
+ self.assertTrue(any("sub/catalog-info.yaml" in m for m in s["missing"]), s["missing"])
self.assertIn("not ready to judge", s["next"])
def test_structure_errors_on_the_trunk(self):
diff --git a/tests/test_structure.py b/tests/test_structure.py
index 5870269..4454dd8 100644
--- a/tests/test_structure.py
+++ b/tests/test_structure.py
@@ -10,7 +10,7 @@
import unittest
from pathlib import Path
-import yaml
+from tests.catalog import dump
from morphogen import Structure, StructureError, compare
from morphogen.render import mermaid
@@ -38,7 +38,7 @@
}
-# The same structure as the operator writes it (morphogen.yaml's cell format).
+# The same structure as the operator writes it (the catalog's cell format).
AGENT_FILE = {
"cells": {
"agent": {"provides": "answer"},
@@ -194,8 +194,8 @@ def run_cli(self, *args):
def test_the_file_compiles_to_the_same_structure(self):
with tempfile.TemporaryDirectory() as d:
- f = Path(d) / "morphogen.yaml"
- f.write_text(yaml.safe_dump(AGENT_FILE))
+ f = Path(d) / "catalog-info.yaml"
+ f.write_text(dump(AGENT_FILE))
s, ref = Structure.load(f), structure()
for c in ref.cells:
self.assertEqual((s.parent(c), s.cells[c].provides, s.cells[c].consumes),
@@ -205,8 +205,8 @@ def test_the_file_compiles_to_the_same_structure(self):
def test_check_scope_render(self):
with tempfile.TemporaryDirectory() as d:
- f = Path(d) / "morphogen.yaml"
- f.write_text(yaml.safe_dump(AGENT_FILE))
+ f = Path(d) / "catalog-info.yaml"
+ f.write_text(dump(AGENT_FILE))
r = self.run_cli("structure", "check", str(f))
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads(r.stdout)["coverage"]["tested"], 4)
@@ -217,8 +217,8 @@ def test_check_scope_render(self):
def test_check_fails_on_errors(self):
with tempfile.TemporaryDirectory() as d:
- f = Path(d) / "morphogen.yaml"
- f.write_text(yaml.safe_dump({"cells": {"a": {"consumes": "x"}}, "interfaces": {"x": []}}))
+ f = Path(d) / "catalog-info.yaml"
+ f.write_text(dump({"cells": {"a": {"consumes": "x"}}, "interfaces": {"x": []}}))
self.assertEqual(self.run_cli("structure", "check", str(f)).returncode, 1)
f.write_text("cells: [")
self.assertEqual(self.run_cli("structure", "check", str(f)).returncode, 2)