From b7250c51d2a22d9cbc8897ead88fa42802ee3fea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:09:01 -0800 Subject: [PATCH 1/5] Load the cell format from the project's catalog: spec.morphogen on Backstage entities, morphogen.yaml removed (K2) The root is catalog-info.yaml; Location targets are followed. A cell's rules are spec.morphogen on its entity, an API's tests on the API, the project's settings and shared defaults on the one System that carries them. Options (lifecycle: candidate) and roles (type: role) are never cells. Cells are named by metadata.name (namespace/name outside default). The settings the judge uses are read from the base commit's catalog through git. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Khsqyv3JB21BJ91MipHNhp --- demos/cognitive-model/morphogen.yaml | 257 ------------------ demos/entity-resolution/morphogen.yaml | 58 ---- morphogen/backstage.py | 200 +++++++++----- morphogen/documents.py | 48 ++-- morphogen/project.py | 224 ++++++++------- morphogen/structure.py | 23 +- ...en-spec.v0.json => morphogen-spec.v1.json} | 0 7 files changed, 295 insertions(+), 515 deletions(-) delete mode 100644 demos/cognitive-model/morphogen.yaml delete mode 100644 demos/entity-resolution/morphogen.yaml rename schemas/{morphogen-spec.v0.json => morphogen-spec.v1.json} (100%) diff --git a/demos/cognitive-model/morphogen.yaml b/demos/cognitive-model/morphogen.yaml deleted file mode 100644 index a0ef9db..0000000 --- a/demos/cognitive-model/morphogen.yaml +++ /dev/null @@ -1,257 +0,0 @@ -cells: - cmc: - description: 'Common Model of Cognition on Claude Code: Claude is the central pattern matcher and action selector; - the plugin supplies a small working memory, separate procedural and declarative stores, quantitative metadata, - and learning as a side effect of work' - cycle: - in: cmc/cycle - description: 'The cognitive cycle: one model step between tool batches' - dm: - in: cmc/declarative-memory - description: 'Declarative memory: semantic and episodic chunks; one best chunk per cue, by activation' - learn: - in: cmc/learning - description: 'Learning: online and gated' - motor: - in: cmc/motor - description: 'Motor: write-side tools are the only way to change the world' - percept: - in: cmc/perception - description: 'Perception: senses feed the percept buffer, compressed' - pm: - in: cmc/procedural-memory - description: 'Procedural memory: skills as explicit productions over the model''s implicit procedures' - wm: - in: cmc/working-memory - description: 'Working memory: named buffers, each holding at most one chunk (imaginal up to 5)' - cmc/central-selector: - in: cmc - description: reads the WM snapshot, matches productions, selects one act per cycle - consumes: - - wm/buffer-goal - - wm/buffer-imaginal - cmc/cycle: - in: cmc - description: One model step between tool batches; hooks run each phase - consumes: - - cmc/working-memory - cmc/declarative-memory: - in: cmc - description: Semantic and episodic chunks, retrieved one at a time by activation - consumes: - - cmc/working-memory - cmc/evaluation: - in: cmc - description: '20 recurring tasks over 2 weeks, with and without cmc: success rate, tokens per task, how often - the same mistake repeats' - cmc/harness: - in: cmc - description: hooks, skills, subagents, MCP client, permissions - cmc/learning: - in: cmc - description: Reinforcement, encoding, chunking and consolidation as side effects of work - consumes: - - cmc/working-memory - cmc/motor: - in: cmc - description: Write-side tools, gated on a stated goal - consumes: - - cmc/working-memory - cmc/operator: - in: cmc - description: promotes proposed skills; gives explicit feedback that outweighs the judge - cmc/perception: - in: cmc - description: Read-side tools and watchers, compressed into the percept buffer - consumes: - - cmc/working-memory - cmc/procedural-memory: - in: cmc - description: Productions (skills, subagents, the model's weights) with utilities - consumes: - - cmc/working-memory - cmc/working-memory: - in: cmc - description: A small, slot-based workspace re-injected into context every cycle; the only hub - provides: cmc/working-memory - cycle/act: - in: cycle - description: gate motor tools; log the selection - cycle/boot: - in: cycle - description: restore the goal stack from dm; inject WM and the active skills - cycle/close: - in: cycle - description: decay and evict; tick the cycle; re-inject WM - cycle/encode: - in: cycle - description: encode the turn as an episodic chunk - cycle/input: - in: cycle - description: prompt as percept; set goal; inject WM and top-3 candidates - cycle/perceive: - in: cycle - description: compress results; motor outcome; log fired skill - cycle/pre-compact: - in: cycle - description: flush WM and the goal stack to dm - cycle/select: - in: cycle - description: Claude matches skills against WM and chooses one act - cycle/session-end: - in: cycle - description: queue consolidation and chunking - cycle/turn-end: - in: cycle - description: judge the goal; record reward; continue if a subgoal is open - dm/activation: - in: dm - description: A_i = ln(sum t_j^-d) + sum W_k S_ki + beta sim(cue,i) + noise; below threshold returns failure - dm/core-facts: - in: dm - description: high-activation facts always loaded; promoted and demoted by the consolidator - dm/embeddings: - in: dm - description: embed chunks and cues - dm/encode: - in: dm - description: dm_encode(chunk) - dm/retrieve: - in: dm - description: dm_retrieve(cue, kind?) -> one chunk into the retrieval buffer; appends the time to access_times - (rehearsal) - consumes: - - wm/buffer-retrieval - dm/search: - in: dm - description: 'dm_search(query, k): debugging only; denied to Claude in settings' - dm/store: - in: dm - description: 'chunk: id, kind, slots (JSON), text, embedding, created, access_times[], source' - dm/vector-index: - in: dm - description: nearest chunks to a cue - learn/chunking: - in: learn - description: draft a skill from a tool sequence that recurred >= 3 times with high reward, into _proposed/ with - an evidence note - learn/consolidation: - in: learn - description: merge duplicate chunks; promote and demote CLAUDE.md facts; prune skills - learn/critic: - in: learn - description: after low reward twice in a row; writes the retrieval buffer - consumes: - - wm/buffer-retrieval - learn/episodic-encoding: - in: learn - description: goal, skills fired, key percepts, outcome, reward; also evicted WM chunks - learn/failure-credit: - in: learn - description: small negative reward to the active skill on PostToolUseFailure - learn/review-gate: - in: learn - description: a person moves drafts from _proposed/ to skills/ - learn/reward: - in: learn - description: R in [0,1] from goal outcome, tests passing and explicit feedback; at most 2 continuations per - turn - learn/utility-update: - in: learn - description: U_i <- U_i + alpha (R - U_i) for every skill fired this turn - motor/effectors: - in: motor - description: Edit, Write, Bash, actuator MCP tools - motor/gate: - in: motor - description: deny a motor tool when the goal buffer is empty - motor/outcome: - in: motor - description: write the action and outcome to the motor buffer - motor/permissions: - in: motor - description: which effectors run without asking - motor/serial-bottleneck: - in: motor - description: one intention per batch; optionally deny a second motor tool in a batch - percept/compress: - in: percept - description: compress large results into a percept chunk; may replace the result with updatedToolOutput - percept/extra-senses: - in: percept - description: log tail, CI status poller, screenshot description - percept/senses: - in: percept - description: Read, Grep, Glob, WebFetch, WebSearch, read-only MCP servers - percept/watch: - in: percept - description: bottom-up percepts when watched files change - pm/candidate-ranking: - in: pm - description: top 3 skills by similarity(description, goal) x utility, added to the WM snapshot - pm/compiled-routines: - in: pm - description: long self-contained procedures; return one chunk to the retrieval or imaginal buffer - pm/implicit: - in: pm - description: 'the model''s weights: most procedural knowledge' - pm/productions: - in: pm - description: condition names WM buffers; every action step ends by changing WM - pm/pruning: - in: pm - description: move skills with utility < 0.2 after >= 10 fires to _inactive/, then reloadSkills - pm/skill-log: - in: pm - description: log which skill fired this cycle - pm/utility-table: - in: pm - description: 'per skill: utility (0..1, starts 0.5), fires, successes, last_fired' - wm/buffer-goal: - in: wm - description: holds current goal and subgoal stack - provides: wm/buffer-goal - wm/buffer-imaginal: - in: wm - description: holds scratch problem state (plan, partial answer) - provides: wm/buffer-imaginal - wm/buffer-motor: - in: wm - description: holds last action and its outcome - provides: wm/buffer-motor - wm/buffer-percept: - in: wm - description: holds latest compressed perception - provides: wm/buffer-percept - wm/buffer-retrieval: - in: wm - description: holds last chunk returned from declarative memory - provides: wm/buffer-retrieval - wm/compaction-guard: - in: wm - description: flush WM and the goal stack to dm before compaction; re-inject after - wm/decay: - in: wm - description: evict chunks untouched for N cycles and hand them to the encoder - wm/injection: - in: wm - description: snapshot as additionalContext at the start of every cycle, ~2,000 characters - consumes: - - wm/buffer-goal - - wm/buffer-imaginal - - wm/buffer-motor - - wm/buffer-percept - - wm/buffer-retrieval - wm/store: - in: wm - description: buffers, goal stack and the procedures table in .cmc/cmc.sqlite - wm/tools: - in: wm - description: wm_get, wm_put(buffer, chunk), wm_set_goal, wm_push_subgoal, wm_pop_subgoal, wm_clear(buffer) -interfaces: - cmc/working-memory: [] - wm/buffer-goal: [] - wm/buffer-imaginal: [] - wm/buffer-motor: [] - wm/buffer-percept: [] - wm/buffer-retrieval: [] diff --git a/demos/entity-resolution/morphogen.yaml b/demos/entity-resolution/morphogen.yaml deleted file mode 100644 index a10150b..0000000 --- a/demos/entity-resolution/morphogen.yaml +++ /dev/null @@ -1,58 +0,0 @@ -# The demo's cells: the structure (components, APIs, nesting) comes from catalog-info.yaml; this file -# adds what each cell may change and how it is judged. -# -# The benchmark data is not committed (its licence names no version). data/fetch.py downloads it and -# data/split.py writes the records and the two answer sets outside the repository; the uncommitted -# morphogen.local.yaml names them per cell: `inputs` (the records, read-only to every run), -# `search` (answers for probes and optimizers) and `private` (held-out answers, for verdicts). -# bench.py prints the pairs it finds; score.py, from the base, computes F1 against the answers. -backstage: catalog-info.yaml - -judged: &f1 - run: python bench.py - score: python score.py - better: - f1: {higher: true, min: 0.005, gain: absolute, aggregate: mean} - precision: {higher: true, max_regression: 0.10} - rounds: {warmup: 0, repeats: 4, max_repeats: 8} # the score is deterministic; 8 rounds decide it - timeout: 300 - -cells: - component:er: - <<: *f1 - tests: python -m unittest discover -s tests -t . - - component:blocking: - <<: *f1 - change: - - er/settings.py#BLOCK_MAX_DF in 0.01..0.5 - - er/settings.py#BLOCK_LIMIT in 5..200 - - component:matcher: - <<: *f1 - change: - - er/settings.py#THRESHOLD in 0.5..0.99 - - er/settings.py#MODEL_MISMATCH in 0..1 - - er/settings.py#WORD_MISMATCH in 0..1 - - er/settings.py#TYPO_RATIO in 0.6..1 - keep: [er/settings.py#ALIASES, er/settings.py#STOPWORDS] - - component:backend: - <<: *f1 - change: er/settings.py#BACKEND in [overlap, tfidf] - - # Below Backstage's grain: the text functions the matcher uses, judged on speed. The pairs found - # must be exactly the base's (same_output), so F1 cannot move. - speed: - in: component:matcher - description: Tokenising and comparing names (er/text.py). Most of the run is spent here, in difflib. - change: er/text.py - run: python bench.py - tests: python -m unittest discover -s tests -t . - better: {wall_seconds: {lower: true, min: 0.10}, max_rss_kb: {lower: true, max_regression: 0.5}} - same_output: true - rounds: {warmup: 1, repeats: 5, max_repeats: 12} - timeout: 300 - -interfaces: - api:resolver: {external: consumes} # used by whatever needs resolution; its test is in the catalog diff --git a/morphogen/backstage.py b/morphogen/backstage.py index 98246e8..8507a3d 100644 --- a/morphogen/backstage.py +++ b/morphogen/backstage.py @@ -1,45 +1,49 @@ -"""Backstage's catalog as a source of cells: `catalog-info.yaml` files read directly, with no Backstage -server. +"""The project's catalog: Backstage `catalog-info.yaml` files read directly, with no Backstage server. - morphogen.yaml: backstage: catalog-info.yaml # or a list; paths inside the project +The root is `catalog-info.yaml` at the repository root (Backstage's convention). It may be a +`Location` whose targets name more files inside the project; every file read this way is a rule file +(project.py: the judge reads it from the base commit, and a candidate may not change it). | Backstage | Becomes | |-------------------------------------------------|-------------------------------------------------| -| Component, System, Domain | a cell, named by its ref (component:default/x) | +| Component, System, Domain | a cell, named by its name (`ns/name` outside `default`) | | subcomponentOf, system, domain, subdomainOf | `in` | -| API | an interface, named by its ref | +| API | an interface, named the same way | | providesApis, consumesApis | provides, consumes | | dependsOn X | consumes X: provided by X if X is a cell, else external (a Resource) | | Location targets | more files to read (relative paths inside the project) | -| annotations morphogen.dev/change, keep, run, better, tests, score, dir, observe | the cell's fields; on an API, morphogen.dev/tests are its tests | +| owner, lifecycle | the cell's owner and lifecycle (what `autonomy` keys on) | +| `spec.morphogen` on a Component/System/Domain | the cell's rules (project.CellRules) | +| `spec.morphogen` on an API | the interface's `tests` and `external` | +| `spec.morphogen` on the System | the project's settings and `defaults` (at most one System carries them) | Refs follow Backstage: `[kind:][namespace/]name`, lowercased; an omitted namespace is the entity's own, and an omitted kind is the field's default (Component for subcomponentOf and dependsOn, System, -Domain, API for the API lists). An annotation that lists several entries (`change`, `keep`, -`tests`) puts one per line. Fields Backstage defines that Morphogen does not use (owner, lifecycle, -type, definition, links, tags) are ignored, as are kinds without a structural meaning here (Group, -User, Template). +Domain, API for the API lists). A cell is named by its `metadata.name` in the `default` namespace +and `namespace/name` elsewhere, whatever its kind, so two cell entities may not share a name. +Options (`spec.lifecycle: candidate`) and roles (`spec.type: role`) are never cells. Fields Backstage +defines that Morphogen does not use (type, definition, links, tags) are ignored, as are kinds without a +structural meaning here (Group, User, Template). """ from __future__ import annotations +from collections.abc import Callable from pathlib import Path, PurePosixPath from typing import Any import yaml CELL_KINDS = ("component", "system", "domain", "airesource") -ANNOTATION = "morphogen.dev/" -CELL_FIELDS = ("change", "keep", "run", "better", "tests", "score", "dir", "observe") -LISTED = ("change", "keep", "tests") +ROOT = "catalog-info.yaml" +SETTINGS = ("trunk", "sandbox", "sandbox_image", "budget", "autonomy", "defaults") # on the System only class CatalogError(ValueError): pass -def parse_ref(ref: str, default_kind: str, namespace: str = "default") -> str: - """`[kind:][namespace/]name` -> `kind:namespace/name`, lowercased.""" +def _parts(ref: str, default_kind: str, namespace: str = "default") -> tuple[str, str, str]: if not isinstance(ref, str) or not ref.strip(): raise CatalogError(f"an empty entity reference ({ref!r})") ref = ref.strip() @@ -51,37 +55,49 @@ def parse_ref(ref: str, default_kind: str, namespace: str = "default") -> str: ns, name = namespace, rest if not kind or not ns or not name: raise CatalogError(f"entity reference {ref!r}: write [kind:][namespace/]name") - return f"{kind}:{ns}/{name}".lower() + return kind.lower(), ns.lower(), name.lower() + + +def parse_ref(ref: str, default_kind: str, namespace: str = "default") -> str: + """`[kind:][namespace/]name` -> `kind:namespace/name`, lowercased (Backstage's full form).""" + kind, ns, name = _parts(ref, default_kind, namespace) + return f"{kind}:{ns}/{name}" -def is_ref(text: str) -> bool: - kind, sep, rest = text.partition(":") - return bool(sep) and kind.lower() in CELL_KINDS + ("api", "resource") +def ref_name(ref: str, default_kind: str, namespace: str = "default") -> str: + """The name a reference has in a project: `name` in the default namespace, `ns/name` elsewhere; a kind + that is neither a cell's nor an API's (a Resource) stays in front (`resource:db`), as it is outside the catalog.""" + kind, ns, name = _parts(ref, default_kind, namespace) + own = name if ns == "default" else f"{ns}/{name}" + return own if kind in CELL_KINDS + ("api",) else f"{kind}:{own}" -def _inside(root: Path, rel: str, what: str) -> Path: +def _inside(rel: str, what: str) -> PurePosixPath: p = PurePosixPath(rel) if p.is_absolute() or ".." in p.parts or "://" in rel: raise CatalogError(f"{what} {rel!r}: give a relative path inside the project") - return root / p + return p -def read(root: Path, files: list[str]) -> tuple[list[dict], list[str]]: - """Every entity in `files` and the Location targets they name (each file read once), with the - project-relative paths read.""" +def fs_reader(root: Path) -> Callable[[str], str]: root = Path(root) - entities, seen, queue = [], [], [(f, "backstage") for f in files] + return lambda rel: (root / rel).read_text() + + +def read(files: list[str], read_text: Callable[[str], str]) -> tuple[list[dict], list[str]]: + """Every entity in `files` and the Location targets they name (each file read once through + `read_text`, which takes a project-relative path), with the project-relative paths read: the rule files.""" + entities, seen, queue = [], [], [(f, "catalog") for f in files] while queue: rel, what = queue.pop(0) - path = _inside(root, rel, what) - key = str(PurePosixPath(rel)) + key = str(_inside(rel, what)) if key in seen: continue seen.append(key) try: - docs = [d for d in yaml.safe_load_all(path.read_text()) if d is not None] + docs = [d for d in yaml.safe_load_all(read_text(key)) if d is not None] except OSError as e: - raise CatalogError(f"{rel}: cannot read ({e.strerror or e})") from None + raise CatalogError(f"{rel}: cannot read ({getattr(e, 'strerror', None) or e})") from None except yaml.YAMLError as e: raise CatalogError(f"{rel}: not valid YAML ({e})") from None for d in docs: @@ -92,13 +108,12 @@ def read(root: Path, files: list[str]) -> tuple[list[dict], list[str]]: if str(d["kind"]).lower() == "location": spec = d.get("spec") or {} targets = list(spec.get("targets") or []) + ([spec["target"]] if spec.get("target") else []) - base = PurePosixPath(rel).parent + base = PurePosixPath(key).parent for t in targets: if not isinstance(t, str): raise CatalogError(f"{rel}: Location targets are strings") - joined = PurePosixPath(*(base / t).parts) parts: list[str] = [] - for part in joined.parts: # normalise ./ and a/../ within the project + for part in (base / t).parts: # normalise ./ and a/../ within the project if part == "..": if not parts: raise CatalogError(f"{rel}: Location target {t!r} leaves the project") @@ -109,42 +124,80 @@ def read(root: Path, files: list[str]) -> tuple[list[dict], list[str]]: return entities, seen -def _lines(v: Any) -> list[str]: - if not isinstance(v, str): - raise CatalogError(f"annotation values are strings, not {type(v).__name__}") - return [x.strip() for x in v.splitlines() if x.strip()] +def _is_option(spec: dict) -> bool: + return str(spec.get("lifecycle") or "").lower() == "candidate" -def to_cells(entities: list[dict]) -> tuple[dict, dict, dict[str, str]]: - """(cells, interfaces, the file each came from), in the cell format's dict form.""" +def _is_role(spec: dict) -> bool: + return str(spec.get("type") or "").lower() == "role" + + +def _rules(e: dict, me: str) -> dict: + """The entity's `spec.morphogen`, checked: a mapping of known fields (project.MorphogenSpec).""" + from pydantic import ValidationError + from .project import MorphogenSpec + raw = (e.get("spec") or {}).get("morphogen") + if raw is None: + return {} + if not isinstance(raw, dict): + raise CatalogError(f"{e['_file']}: {me}: spec.morphogen is a mapping") + try: + MorphogenSpec.model_validate(raw) + except ValidationError as err: + raise CatalogError(f"{e['_file']}: {me}: spec.morphogen: " + "; ".join( + f"{'.'.join(map(str, x['loc']))}: {x['msg']}" for x in err.errors())) from None + return dict(raw) + + +def to_cells(entities: list[dict]) -> tuple[dict, dict, dict[str, str], dict]: + """(cells, interfaces, the file each came from, the project's settings), in the cell format's dict form. + The file of a cell is under its name, of an interface under `api:` and its name. + The settings are what the one System that carries them says under `spec.morphogen`.""" + from .project import CELL_FIELDS cells: dict[str, dict] = {} interfaces: dict[str, dict] = {} origin: dict[str, str] = {} - provides: dict[str, set] = {} + kinds: dict[str, str] = {} + blocks: dict[str, dict] = {} # a cell's own spec.morphogen, before the System's defaults + settings: dict = {} + settings_from: list[str] = [] + defaults: dict = {} for e in entities: kind = str(e["kind"]).lower() md, spec = e.get("metadata") or {}, e.get("spec") or {} ns = str(md.get("namespace") or "default").lower() - me = parse_ref(md["name"], kind, ns) - notes = {k[len(ANNOTATION):]: v for k, v in (md.get("annotations") or {}).items() - if k.startswith(ANNOTATION)} + me = ref_name(md["name"], kind, ns) if kind == "api": - entry: dict = {} - if "tests" in notes: - entry["tests"] = _lines(notes.pop("tests")) - if notes: - raise CatalogError(f"{me}: on an API, only {ANNOTATION}tests is read (not {', '.join(notes)})") - interfaces[me] = entry - origin[me] = e["_file"] + rules = _rules(e, me) + extra = set(rules) - {"tests", "external"} + if extra: + raise CatalogError(f"{e['_file']}: {me}: on an API, spec.morphogen takes tests and external " + f"(not {', '.join(sorted(extra))})") + if me in interfaces: + raise CatalogError(f"{me} is defined twice ({origin[f'api:{me}']}, {e['_file']})") + interfaces[me] = {k: v for k, v in rules.items()} + origin[f"api:{me}"] = e["_file"] continue if kind not in CELL_KINDS: continue + if _is_option(spec) or _is_role(spec): # an option for a role, or the role: never a cell + continue + rules = _rules(e, me) + mine = {k: rules.pop(k) for k in SETTINGS if k in rules} + carries = bool(mine) + if mine: + if kind != "system": + raise CatalogError(f"{e['_file']}: {me}: {', '.join(mine)} are the project's settings: put them " + "on the System entity") + settings_from.append(f"{me} ({e['_file']})") + defaults = mine.pop("defaults", {}) + settings = mine cell: dict = {} - parent = {"component": spec.get("subcomponentOf") and parse_ref(spec["subcomponentOf"], "component", ns) - or spec.get("system") and parse_ref(spec["system"], "system", ns), - "system": spec.get("domain") and parse_ref(spec["domain"], "domain", ns), - "domain": spec.get("subdomainOf") and parse_ref(spec["subdomainOf"], "domain", ns), - "airesource": spec.get("system") and parse_ref(spec["system"], "system", ns)}[kind] + parent = {"component": spec.get("subcomponentOf") and ref_name(spec["subcomponentOf"], "component", ns) + or spec.get("system") and ref_name(spec["system"], "system", ns), + "system": spec.get("domain") and ref_name(spec["domain"], "domain", ns), + "domain": spec.get("subdomainOf") and ref_name(spec["subdomainOf"], "domain", ns), + "airesource": spec.get("system") and ref_name(spec["system"], "system", ns)}[kind] if parent: cell["in"] = parent if md.get("description"): @@ -153,23 +206,38 @@ def to_cells(entities: list[dict]) -> tuple[dict, dict, dict[str, str]]: cell["owner"] = parse_ref(str(spec["owner"]), "group", ns) if spec.get("lifecycle"): cell["lifecycle"] = str(spec["lifecycle"]) - prov = [parse_ref(r, "api", ns) for r in spec.get("providesApis") or []] - cons = [parse_ref(r, "api", ns) for r in spec.get("consumesApis") or []] - cons += [parse_ref(r, "airesource" if kind == "airesource" else "component", ns) for r in spec.get("dependsOn") or []] + prov = [ref_name(r, "api", ns) for r in spec.get("providesApis") or []] + cons = [ref_name(r, "api", ns) for r in spec.get("consumesApis") or []] + cons += [ref_name(r, "airesource" if kind == "airesource" else "component", ns) for r in spec.get("dependsOn") or []] if prov: cell["provides"] = prov if cons: cell["consumes"] = cons - for k, v in notes.items(): - if k not in CELL_FIELDS: - raise CatalogError(f"{me}: unknown annotation {ANNOTATION}{k} ({', '.join(CELL_FIELDS)})") - cell[k] = _lines(v) if k in LISTED else v + cell.update({k: v for k, v in rules.items() if k in CELL_FIELDS}) if me in cells: - raise CatalogError(f"{me} is defined twice ({origin[me]}, {e['_file']})") + raise CatalogError(f"{me} is defined twice, as a {kinds[me]} in {origin[me]} and as a {kind} in " + f"{e['_file']}: a cell is named by its name alone, so rename one") cells[me] = cell + kinds[me] = kind origin[me] = e["_file"] - provides[me] = set(prov) - # An interface named by a cell's ref (a dependsOn, or a component listed as an API) is that cell; + if rules or ("morphogen" in spec and not carries): # the System that only carries settings is no cell with rules + blocks[me] = rules + if len(settings_from) > 1: + raise CatalogError("more than one System carries the project's settings: " + "; ".join(settings_from) + + ". Put trunk, sandbox, budget, autonomy and defaults on one System") + # The System's defaults: cell fields every cell with rules of its own in that System inherits unless it sets its + # own (a field set to null is its own: it opts out), the System itself too when it has rules of its own. + holder = settings_from[0].split(" ")[0] if settings_from else None + if defaults and holder: + for name in blocks: + at, seen = name, set() + while at in cells and at not in seen: # up the `in` chain to the enclosing System + seen.add(at) + if at == holder: + cells[name] = {**{k: v for k, v in defaults.items() if k not in blocks[name]}, **cells[name]} + break + at = cells[at].get("in") + # An interface named by a cell's name (a dependsOn, or a component listed as an API) is that cell; # one that names neither a cell nor an API is outside the catalog (a Resource, say). for name, cell in cells.items(): for i in cell.get("consumes", []): @@ -182,5 +250,5 @@ def to_cells(entities: list[dict]) -> tuple[dict, dict, dict[str, str]]: interfaces[i] = {} else: interfaces[i] = {"external": "provides"} - origin.setdefault(i, origin[name]) - return cells, interfaces, origin + origin.setdefault(f"api:{i}", origin[name]) + return cells, interfaces, origin, settings diff --git a/morphogen/documents.py b/morphogen/documents.py index 75fb66e..21591f8 100644 --- a/morphogen/documents.py +++ b/morphogen/documents.py @@ -1,6 +1,6 @@ """The documents people write and git versions, and the one way they are read. -`morphogen.yaml`'s settings (trunk, sandbox, budget), and the target spec a cell compiles to (how +The project's settings (trunk, sandbox, budget: `spec.morphogen` on its System, see project.py), and the target spec a cell compiles to (how the judge scores it; see project.py for the cell format the operator writes). Each has a schema; `load` reads a file, checks it and returns plain data, or raises DocumentError naming the file and every problem. Schemas check structure and types; what a value means is checked where it is used, @@ -27,7 +27,7 @@ class _Doc(BaseModel): model_config = ConfigDict(extra="allow") -# morphogen.yaml +# the project's settings class Budget(_Doc): trials_per_day: int | None = None @@ -133,17 +133,23 @@ def load(kind: str, path: Path) -> dict: def load_config(root: Path) -> dict: - """morphogen.yaml at the project root, or the defaults, with the operator's morphogen.local.yaml - (uncommitted) laid over it: `sandbox`, `sandbox_image` and `budget` override, and `cells` (held-out - answer paths per cell: `private`, `search`), `env`, `services` and `gateway` (serve.py) are kept under `local`.""" - from .project import local_config - f = Path(root) / "morphogen.yaml" - cfg = load("config", f) if f.exists() else validate("config", {}) + """The project's settings from the System's `spec.morphogen` in the working copy's catalog (or the + defaults), with the operator's morphogen.local.yaml (uncommitted) laid over them: `sandbox`, + `sandbox_image` and `budget` override, and `cells` (held-out answer paths per cell: `private`, + `search`), `env`, `services` and `gateway` (serve.py) are kept under `local`. A catalog that does not + read gives the defaults here; `status` reports why.""" + from .backstage import fs_reader + from .project import FILE, ProjectError, local_config, settings_at + try: + base = settings_at(fs_reader(root)) + except ProjectError: + base = {} local = local_config(root) + cfg = validate("config", {k: v for k, v in base.items() if k in JUDGE_SETTINGS}, FILE) for k in LOCAL_SETTINGS: if k in local: cfg[k] = local[k] - cfg = validate("config", cfg, f) + cfg = validate("config", cfg, FILE) cfg["local"] = {"cells": local.get("cells") or {}, "settings": {k: local[k] for k in LOCAL_SETTINGS if k in local}, **{k: local[k] for k in LOCAL_SERVED if local.get(k)}} return cfg @@ -155,22 +161,22 @@ def load_config(root: Path) -> dict: def rules_config(repo: Path, sha: str, cfg: dict) -> dict: - """The settings a judged run uses: morphogen.yaml as committed at `sha` (the base), with the operator's - morphogen.local.yaml laid over it, never the working copy. `cfg` is load_config's result; what it read - from the local file is kept (cfg["local"]), what it read from the working copy is dropped. The result - says where each setting came from (`settings_from`).""" - import subprocess - r = subprocess.run(["git", "show", f"{sha}:morphogen.yaml"], cwd=repo, capture_output=True, text=True) + """The settings a judged run uses: the System's settings in the catalog as committed at `sha` (the + base), with the operator's morphogen.local.yaml laid over them, never the working copy. `cfg` is + load_config's result; what it read from the local file is kept (cfg["local"]), what it read from the + working copy is dropped. The result says where each setting came from (`settings_from`).""" + from .project import FILE, ProjectError, git_reader, settings_at + where_base = f"{sha[:12]}:{FILE}" try: - data = yaml.safe_load(r.stdout) if r.returncode == 0 else {} - except yaml.YAMLError as e: - raise DocumentError(f"{sha[:12]}:morphogen.yaml", [f"not valid YAML: {e}"]) from None - base = validate("config", {k: v for k, v in (data or {}).items() if k in JUDGE_SETTINGS}, f"{sha[:12]}:morphogen.yaml") + data = settings_at(git_reader(repo, sha)) + except ProjectError as e: + raise DocumentError(where_base, [str(e)]) from None + base = validate("config", {k: v for k, v in data.items() if k in JUDGE_SETTINGS}, where_base) local = (cfg.get("local") or {}).get("settings") or {} - out = validate("config", {**base, **local}, f"{sha[:12]}:morphogen.yaml + morphogen.local.yaml") + out = validate("config", {**base, **local}, f"{where_base} + morphogen.local.yaml") out["local"] = cfg.get("local") or {"cells": {}, "settings": {}} where = (cfg.get("local") or {}).get("from") or "morphogen.local.yaml" - out["settings_from"] = {k: (where if k in local else "base" if k in (data or {}) else "default") + out["settings_from"] = {k: (where if k in local else "base" if k in data else "default") for k in JUDGE_SETTINGS} return out diff --git a/morphogen/project.py b/morphogen/project.py index 9bc1035..2ab1128 100644 --- a/morphogen/project.py +++ b/morphogen/project.py @@ -1,21 +1,36 @@ -"""The cell format: one morphogen.yaml with the project's cells and interfaces. - - cells: - classify: - in: app # the cell this one belongs to +"""The cell format: the project's cells and interfaces, read from its Backstage catalog. + +The root is `catalog-info.yaml` at the repository root (a `Location` may name more files inside the +project). A cell's rules are `spec.morphogen` on the entity it judges: + + kind: Component + metadata: {name: classify} + spec: + type: service + lifecycle: experimental + system: app # the cell this one is in (`subcomponentOf` for a sub-grain cell) + providesApis: [labels] + morphogen: change: classify/classify.py#THRESHOLD in 0..100 # what may change; nothing else may - run: python bench.py # the workload - better: accuracy higher # the primary metric, and its direction - tests: python -m unittest -q test_classify # must pass on the candidate - score: python score.py # optional: scores each run's output - interfaces: - labels: python -m unittest -q contracts.test_labels + run: python bench.py # the workload + better: accuracy higher # the primary metric, and its direction + tests: python -m unittest -q test_classify # must pass on the candidate + score: python score.py # optional: scores each run's output + --- + kind: API + metadata: {name: labels} + spec: {morphogen: {tests: python -m unittest -q contracts.test_labels}} + +An entity with no `run` is structure, not a judged cell. The project's settings (trunk, sandbox, +sandbox_image, budget, autonomy) and `defaults` (cell fields every cell with rules in that System inherits +unless it sets its own) are `spec.morphogen` on the System; at most one System carries them. Options +(`spec.lifecycle: candidate`) and roles (`spec.type: role`) are never cells. See backstage.py. **Default deny.** A candidate may change only the paths the judged cell's scope names in `change`. -Everything else, the project file included, is the judge's: a candidate that changes it is refused -before anything runs. A `change` entry that names a setting (`path#NAME`, `path:dotted.key`) lets -only that setting change in its file, within its range or choices. `keep` names settings that must -not change even in a file `change` opens. +Everything else is the judge's, every catalog file it reads included (the root and each Location +target): a candidate that changes, adds or removes one is refused before anything runs. A `change` +entry that names a setting (`path#NAME`, `path:dotted.key`) lets only that setting change in its file, +within its range or choices. `keep` names settings that must not change even in a file `change` opens. Paths are relative to the project root; commands run in the cell's `dir` (default the root), and interface tests from the root. The compiled form is what the judge already reads: a Structure, and @@ -37,7 +52,7 @@ from . import documents from .structure import Structure, StructureError -FILE = "morphogen.yaml" +FILE = "catalog-info.yaml" # the project's catalog root, at the repository root LOCAL = "morphogen.local.yaml" JUDGE_METRICS = ("wall_seconds", "cpu_seconds", "max_rss_kb") METRIC_OPTIONS = {"min": "min_improvement", "max_regression": "max_regression", "gain": "gain", @@ -68,8 +83,8 @@ class SameAsBase(_Strict): cases: int | None = None -class CellDoc(_Strict): - in_: str | None = Field(None, alias="in") +class CellRules(_Strict): + """A cell's rules: the fields of `spec.morphogen` on the entity it judges.""" description: str | None = None dir: str = "." change: str | list[str] = [] @@ -81,28 +96,64 @@ class CellDoc(_Strict): observe: str | dict[str, Any] | None = None same_as_base: SameAsBase | None = None same_output: bool | None = None - provides: str | list[str] = [] - consumes: str | list[str] = [] guard: bool | dict[str, float] | None = None rounds: Rounds | None = None timeout: int | None = None simulates: str | None = None requires: list[str] = [] + + +CELL_FIELDS = tuple(CellRules.model_fields) + + +class CellDoc(CellRules): + """A cell as compiled: its rules, and what the catalog says around it.""" + in_: str | None = Field(None, alias="in") + provides: str | list[str] = [] + consumes: str | list[str] = [] owner: str | None = None # who approves its candidates (a Backstage group or user ref) lifecycle: str | None = None # experimental, production, ...: what `autonomy` keys on class InterfaceDoc(_Strict): + """An interface's tests: `spec.morphogen` on its API entity.""" tests: str | list[str] = [] external: Literal["consumes", "provides"] | None = None +class Budget(_Strict): + model_config = ConfigDict(extra="allow") + trials_per_day: int | None = None + probes_per_day: int | None = None + + +class SystemRules(_Strict): + """The project's settings and shared defaults: `spec.morphogen` on the System.""" + trunk: str | None = None + sandbox: Literal["auto", "podman", "docker", "none"] | None = None + sandbox_image: str | None = None + budget: Budget | None = None + autonomy: dict[str, Literal["merge", "review"]] | None = None # lifecycle -> what a pass allows (default review) + defaults: CellRules | None = None + + +class OptionRules(_Strict): + """An option for a role: `spec.morphogen` on a Component with `spec.lifecycle: candidate`.""" + fills: str | list[str] | None = None + parameters: dict[str, Any] | None = None + licence: str | None = None + docs: dict[str, Any] | None = None + evaluation: dict[str, Any] | None = None + + +class MorphogenSpec(CellRules, InterfaceDoc, SystemRules, OptionRules): + """Everything `spec.morphogen` may hold, flat: one entity may carry the fields of more than one.""" + + class ProjectDoc(BaseModel): - model_config = ConfigDict(extra="allow") # trunk, sandbox, budget: morphogen.yaml's settings - backstage: str | list[str] = [] - autonomy: dict[str, Literal["merge", "review"]] = {} # lifecycle -> what a pass allows (default review) cells: dict[str, CellDoc] = {} - interfaces: dict[str, str | list[str] | InterfaceDoc] = {} + interfaces: dict[str, InterfaceDoc] = {} + autonomy: dict[str, Literal["merge", "review"]] = {} # --- the small grammars @@ -253,55 +304,48 @@ def only_settings_differ(base: Path, cand: Path, names: set[str], keys: set[str] # --- the project -def _merge(bcells: dict, bifaces: dict, origin: dict, cells: dict, ifaces: dict) -> tuple[dict, dict, dict, list]: - """The catalog's cells and interfaces with morphogen.yaml's laid over them: (cells, interfaces, - where each came from, conflicts). A name that is a Backstage ref (component:x, api:ns/y) is - normalised; provides and consumes are joined; any other field both give must agree.""" +def read_catalog(read_text, files: list[str] = (FILE,)) -> tuple[dict, dict, dict, dict, list[str]]: + """The catalog at `files` (the root, and the Location targets it names) read through `read_text`: + (cells, interfaces, where each came from, the project's settings, the files read).""" from . import backstage as bs - norm = (lambda k, kind="component": bs.parse_ref(k, kind) if bs.is_ref(k) else k) - sources = {n: f"backstage ({origin[n]})" for n in list(bcells) + list(bifaces)} - conflicts: list[str] = [] - out = {n: dict(c) for n, c in bcells.items()} - for raw, c in cells.items(): - name = norm(raw) - c = dict(c or {}) - if isinstance(c.get("in"), str): - c["in"] = norm(c["in"]) - mine = out.setdefault(name, {}) - sources[name] = f"{sources[name]} and {FILE}" if name in sources else FILE - for k, v in c.items(): - if k in ("provides", "consumes"): - v = [norm(x, "api") for x in _listed(v)] - mine[k] = list(dict.fromkeys(_listed(mine.get(k)) + v)) - elif k in mine and mine[k] != v: - conflicts.append(f"cell {name}: {k} is {mine[k]!r} in the catalog and {v!r} in {FILE}") - else: - mine[k] = v - for k in ("provides", "consumes"): - if k in mine: - mine[k] = [norm(x, "api") for x in _listed(mine[k])] - outi = {n: dict(i) for n, i in bifaces.items()} - for raw, i in ifaces.items(): - name = norm(raw, "api") - i = {"tests": i} if isinstance(i, (str, list)) else dict(i or {}) - mine = outi.setdefault(name, {}) - sources[name] = f"{sources[name]} and {FILE}" if name in sources else FILE - for k, v in i.items(): - if k in mine and _listed(mine[k]) != _listed(v): - conflicts.append(f"interface {name}: {k} is {mine[k]!r} in the catalog and {v!r} in {FILE}") - else: - mine[k] = v - return out, outi, sources, conflicts + try: + entities, read = bs.read(list(files), read_text) + cells, ifaces, origin, settings = bs.to_cells(entities) + except bs.CatalogError as e: + raise ProjectError(str(e)) from None + return cells, ifaces, origin, settings, read + + +def git_reader(repo: Path, sha: str): + """Reads project files as committed at `sha`, never the working copy.""" + import subprocess + + def read_text(rel: str) -> str: + r = subprocess.run(["git", "show", f"{sha}:{rel}"], cwd=repo, capture_output=True, text=True) + if r.returncode != 0: + raise FileNotFoundError(2, "not in the commit", rel) + return r.stdout + return read_text + + +def settings_at(read_text) -> dict: + """The project's settings (what the System's `spec.morphogen` says) through `read_text`, or {} when + there is no catalog root.""" + try: + read_text(FILE) + except OSError: + return {} + return read_catalog(read_text)[3] class Project: def __init__(self, doc: ProjectDoc, source: str = FILE, rule_files: list[str] = (), - sources: dict | None = None, conflicts: list[str] = ()): + sources: dict | None = None, settings: dict | None = None): self.doc, self.source = doc, source - # Files the rules are read from besides morphogen.yaml (catalog files): never changeable. + # Every catalog file the rules were read from (the root and each Location target): never changeable. self.rule_files = list(rule_files) self.sources = sources or {} - self.conflicts = list(conflicts) + self.settings = settings or {} self.changes = {n: [parse_change(x) for x in _listed(c.change)] for n, c in doc.cells.items()} self.keeps = {n: [parse_change(x) for x in _listed(c.keep)] for n, c in doc.cells.items()} for n, ks in self.keeps.items(): @@ -313,40 +357,26 @@ def __init__(self, doc: ProjectDoc, source: str = FILE, rule_files: list[str] = self._structure = self._compile_structure() @classmethod - def from_dict(cls, data: Any, source: str = FILE, root: Path | None = None) -> Project: - """`root` is the project's directory, where `backstage` files are read from.""" - extra: dict = {} - if isinstance(data, dict) and data.get("backstage"): - from . import backstage as bs - if root is None: - raise ProjectError(f"{source}: reading `backstage` needs the project's directory") - try: - entities, files = bs.read(Path(root), _listed(data["backstage"])) - bcells, bifaces, origin = bs.to_cells(entities) - except bs.CatalogError as e: - raise ProjectError(f"{source}: backstage: {e}") from None - cells, ifaces, sources, conflicts = _merge(bcells, bifaces, origin, data.get("cells") or {}, - data.get("interfaces") or {}) - data = {**data, "cells": cells, "interfaces": ifaces} - extra = {"rule_files": files, "sources": sources, "conflicts": conflicts} - elif isinstance(data, dict): - extra = {"sources": {n: FILE for n in list(data.get("cells") or {}) + list(data.get("interfaces") or {})}} + def from_parts(cls, cells: dict, interfaces: dict, origin: dict, settings: dict, files: list[str], + source: str = FILE) -> Project: try: - return cls(ProjectDoc.model_validate(data), source, **extra) + doc = ProjectDoc.model_validate({"cells": cells, "interfaces": interfaces, + "autonomy": settings.get("autonomy") or {}}) + return cls(doc, source, rule_files=files, sources=origin, settings=settings) except ValidationError as e: raise ProjectError(f"{source}: " + "; ".join( f"{'.'.join(map(str, err['loc']))}: {err['msg']}" for err in e.errors())) from None @classmethod - def load(cls, tree: Path) -> Project | None: - """The project in `tree` (a checkout), or None when its morphogen.yaml has no cells.""" - f = Path(tree) / FILE - if not f.exists(): - return None - data = yaml.safe_load(f.read_text()) or {} - if not isinstance(data, dict) or not ("cells" in data or data.get("backstage")): + def load(cls, tree: Path, file: str = FILE) -> Project | None: + """The project in `tree` (a checkout): its catalog read from `catalog-info.yaml` at the root (and + the Location targets it names), or None when there is none.""" + tree = Path(tree) + if not (tree / file).exists(): return None - return cls.from_dict(data, str(f), root=Path(tree)) + from . import backstage as bs + cells, ifaces, origin, settings, files = read_catalog(bs.fs_reader(tree), [file]) + return cls.from_parts(cells, ifaces, origin, settings, files, str(tree / file)) # what the judge reads @@ -373,7 +403,7 @@ def _compile_structure(self) -> Structure: interfaces[n] = {"tests": _listed(i)} try: s = Structure.from_dict({"cells": cells, "interfaces": interfaces}, self.source) - s.origins, s.conflicts = dict(self.sources), list(self.conflicts) + s.origins = dict(self.sources) except StructureError as e: raise ProjectError(str(e)) from None return s # structural errors (gaps, cycles) are findings: `structure check` reports them @@ -389,7 +419,7 @@ def resolve(self, name: str) -> str: return name from . import backstage as bs try: - ref = bs.parse_ref(name, "component") + ref = bs.ref_name(name, "component") except bs.CatalogError: return name return ref if ref in self.doc.cells else name @@ -408,7 +438,7 @@ def structure(self) -> Structure: def cell(self, name: str) -> CellDoc: name = self.resolve(name) if name not in self.doc.cells: - raise ProjectError(f"no cell {name!r} in {FILE}") + raise ProjectError(f"no cell {name!r} in the catalog ({FILE})") return self.doc.cells[name] def dir(self, name: str) -> Path: @@ -463,7 +493,7 @@ def _entries(self, cells) -> list[dict]: return [e for c in cells for e in self.changes.get(c, [])] def allows(self, cells, path: str) -> bool: - if path in (FILE, LOCAL) or path in self.rule_files: # the rules themselves never change + if path in (FILE, LOCAL) or path in self.rule_files: # the rules themselves never change: the catalog root and every file it names return False return any(_glob_re(e["path"]).match(path) for e in self._entries(cells)) @@ -491,7 +521,7 @@ def check_changes(self, cells, changed: list[str], btree: Path, ctree: Path) -> def structure_file(root: Path, cfg: dict) -> str: - """The file the structure is read from.""" + """The file the structure is read from: the catalog root.""" return FILE diff --git a/morphogen/structure.py b/morphogen/structure.py index 0f85571..b2c368c 100644 --- a/morphogen/structure.py +++ b/morphogen/structure.py @@ -14,7 +14,6 @@ from pathlib import Path from typing import Any, Iterable, Literal -import yaml from pydantic import BaseModel, ConfigDict, ValidationError, model_validator # --- the document @@ -86,7 +85,7 @@ def __init__(self, source: str, problems: list[str]): @dataclass(frozen=True) class Finding: severity: Literal["error", "warning"] - kind: str # cycle | unknown-parent | unknown-interface | gap | conflict | unused | unattached | untested + kind: str # cycle | unknown-parent | unknown-interface | gap | unused | unattached | untested subject: str message: str @@ -99,10 +98,8 @@ class Structure: doc: Document source: str = "" _children: dict[str, list[str]] = field(default_factory=dict, repr=False) - # Where each cell and interface came from (morphogen.yaml, a Backstage catalog file, or both), and - # where those sources disagree: set when the structure is compiled from the cell format. + # Where each cell and interface came from (its catalog file): set when compiled from the catalog. origins: dict[str, str] = field(default_factory=dict) - conflicts: list[str] = field(default_factory=list) def __post_init__(self): self._children = {c: [] for c in self.doc.cells} @@ -126,17 +123,11 @@ def from_dict(cls, data: Any, source: str = "") -> Structure: @classmethod def load(cls, path: str | Path) -> Structure: path = Path(path) + from .project import Project, ProjectError # a structure file is a catalog; the cell format compiles to this + if not path.exists(): + raise StructureError(str(path), ["cannot read: no such file"]) try: - data = yaml.safe_load(path.read_text()) - except OSError as e: - raise StructureError(str(path), [f"cannot read: {e.strerror or e}"]) from None - except yaml.YAMLError as e: - raise StructureError(str(path), [f"not valid YAML: {e}"]) from None - from .project import Project, ProjectError # files are in the cell format; it compiles to this - if not isinstance(data, dict) or not ("cells" in data or data.get("backstage")): - raise StructureError(str(path), ["no cells: a structure file is in the cell format (morphogen.yaml)"]) - try: - return Project.from_dict(data, str(path), root=path.parent).structure() + return Project.load(path.parent, path.name).structure() except ProjectError as e: raise StructureError(str(path), [str(e)]) from None @@ -246,7 +237,7 @@ def neighbours(self, cell: str) -> list[str]: # checks def check(self) -> list[Finding]: - f: list[Finding] = [Finding("error", "conflict", c.split(":", 1)[0], c) for c in self.conflicts] + f: list[Finding] = [] for cid, cell in self.cells.items(): if cell.parent is not None and cell.parent not in self.cells: f.append(Finding("error", "unknown-parent", cid, f"parent {cell.parent!r} is not a cell")) diff --git a/schemas/morphogen-spec.v0.json b/schemas/morphogen-spec.v1.json similarity index 100% rename from schemas/morphogen-spec.v0.json rename to schemas/morphogen-spec.v1.json From 13f3a133b4da36b1cbb291efc3c70a5b30960302 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:09:01 -0800 Subject: [PATCH 2/5] Default deny covers every catalog file the judge reads; fixtures move to catalog form The root and each Location target are rule files. Tests (red team first): a candidate editing a cell's spec.morphogen in any catalog file, adding a Location target or a catalog file the root will read, or removing a target is refused; a catalog file the root does not name is judged normally; settings come from the base's System. Fixtures keep a dict authoring form (tests/catalog.py) and commit it as a catalog. The spec-schema parity test now covers the System settings, the API and the option fields. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Khsqyv3JB21BJ91MipHNhp --- morphogen/judge.py | 24 +- tests/catalog.py | 82 ++++++ tests/fixture.py | 19 +- tests/fixture_cells.py | 7 +- tests/test_backstage.py | 538 +++++++++++++++++++++++++++++----------- tests/test_cells.py | 17 +- tests/test_gateway.py | 3 +- tests/test_judge.py | 7 +- tests/test_redteam.py | 45 ++-- tests/test_request.py | 4 +- tests/test_schema.py | 49 +++- tests/test_status.py | 19 +- tests/test_structure.py | 16 +- 13 files changed, 606 insertions(+), 224 deletions(-) create mode 100644 tests/catalog.py diff --git a/morphogen/judge.py b/morphogen/judge.py index bce6bae..0de80b1 100644 --- a/morphogen/judge.py +++ b/morphogen/judge.py @@ -2,9 +2,9 @@ What makes it hard to fool: -- The rules come from the base commit: morphogen.yaml (the cells, their - workloads, scorers and tests), and every file a cell's `change` does not - name. Default deny: a candidate that changes anything else is refused +- The rules come from the base commit: the project's catalog (`catalog-info.yaml` and every file it + names; each cell's workload, scorer and tests are `spec.morphogen` on its entity), and every file a + cell's `change` does not name. Default deny: a candidate that changes anything else is refused before anything runs, so it cannot change how it is scored. - Time and memory are measured from outside the measured process, by a wrapper that waits for it and reads the operating system's resource usage. @@ -397,7 +397,7 @@ def _names_private(spec: dict, ctree: Path, changed: list[str]) -> list[str]: def project_of(tree: Path) -> Project | None: - """The cell-format project (morphogen.yaml with `cells`) on `tree`, or None.""" + """The project (its catalog, `catalog-info.yaml`) on `tree`, or None when there is none.""" try: return Project.load(tree) except ProjectError as e: @@ -405,10 +405,10 @@ def project_of(tree: Path) -> Project | None: def structure_of(tree: Path) -> Project: - """The project (morphogen.yaml with `cells`) on `tree`, the base's checkout.""" + """The project (its catalog) on `tree`, the base's checkout.""" proj = project_of(tree) if proj is None: - raise JudgeError(f"no {PROJECT_FILE} with cells on the base commit") + raise JudgeError(f"no {PROJECT_FILE} (the project's catalog) on the base commit") if proj.errors(): raise JudgeError(f"the structure on the base commit has errors: {'; '.join(proj.errors())}") return proj @@ -709,7 +709,7 @@ def _check_runner(spec: dict, cfg: dict) -> None: gaps = missing(cfg, spec.get("requires") or []) if gaps: raise JudgeError(f"this target requires {', '.join(gaps)}, which the {sandbox_mode(cfg)} runner does not " - "provide; set sandbox: podman (or auto, with Podman installed) in morphogen.yaml") + "provide; set sandbox: podman (or auto, with Podman installed) under spec.morphogen on the System in the catalog") def _check_spec(spec: dict) -> dict: @@ -768,7 +768,7 @@ def probe(root: Path, cfg: dict, target: str, candidate: str, evidence, base: st cases: int = 5, rounds: int = 3, cell: str | None = None, request: dict | None = None) -> dict: """A practice run: feedback on a candidate, never a verdict. It is the optimizers' inner evaluator. - Same rules as the judge (the base's morphogen.yaml, default deny, the forbidden-file and + Same rules as the judge (the base's catalog, default deny, the forbidden-file and setting checks, the cell's interface tests, fresh random inputs; scored against `search` answers, not the held-out ones), but it reports what an optimizer or an agent needs to learn from: the check's output, each generated case with the base's output and the candidate's where @@ -784,7 +784,7 @@ def probe(root: Path, cfg: dict, target: str, candidate: str, evidence, base: st limit = int((cfg.get("budget") or {}).get("probes_per_day", 0) or 0) if limit and _trials_today(evidence, "probe") >= limit: raise JudgeError(f"the probe budget for today ({limit}) is spent; the operator can raise " - "budget.probes_per_day in morphogen.yaml") + "budget.probes_per_day on the System's spec.morphogen") with worktrees(repo, [base_sha, cand_sha]) as (btree, ctree): a = _admit(root, repo, cfg, target, cell, base_sha, cand_sha, btree, ctree, "probe") spec, rel, gate, metrics_spec, bdir, cdir = (a[k] for k in ("spec", "rel", "gate", "metrics_spec", @@ -961,7 +961,7 @@ def judge_change(root: Path, cfg: dict, base: str, candidate: str, evidence, tim "kind": "verdict", "verdict": verdict, "subject": {"system": ", ".join(cells), "path": "change"}, - "method": "base's morphogen.yaml; cells from the changed files; default deny; forbidden-file check; " + "method": "base's catalog; cells from the changed files; default deny; forbidden-file check; " "declared settings; each cell's tests and the tests of every interface its scope touches " "or its enclosing systems' boundaries cross, from the base, run on the candidate", "outcome": {"files": files, "denied": denied, "forbidden": forbidden, "parameter_violations": violations, @@ -996,7 +996,7 @@ def judge(root: Path, cfg: dict, target: str, base: str, candidate: str, evidenc limit = int((cfg.get("budget") or {}).get("trials_per_day", 0) or 0) if limit and _trials_today(evidence) >= limit: raise JudgeError(f"the trial budget for today ({limit}) is spent; the operator can raise " - "budget.trials_per_day in morphogen.yaml") + "budget.trials_per_day on the System's spec.morphogen") with worktrees(repo, [base_sha, cand_sha]) as (btree, ctree): a = _admit(root, repo, cfg, target, cell, base_sha, cand_sha, btree, ctree) spec, rel, cell, gate, metrics_spec, bdir, cdir = (a[k] for k in ("spec", "rel", "cell", "gate", @@ -1098,7 +1098,7 @@ def judge(root: Path, cfg: dict, target: str, base: str, candidate: str, evidenc "kind": "verdict", "verdict": verdict, "subject": {"system": name, "path": subject}, - "method": "base's morphogen.yaml; default deny; forbidden-file check; declared settings; base's tests; " + "method": "base's catalog; default deny; forbidden-file check; declared settings; base's tests; " "output equivalence on fresh " "random inputs; paired ABBA runs timed outside the process, each checked for the base's " "output; sign test", 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) From 47281a5864c6bfe1bd713f67ae1910b1838e90a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:09:01 -0800 Subject: [PATCH 3/5] CLI, MCP, status and UI speak of the catalog; status makes sense for a project with no catalog Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Khsqyv3JB21BJ91MipHNhp --- morphogen/cli.py | 2 +- morphogen/mcp_server.py | 10 ++++---- morphogen/runner.py | 2 +- morphogen/schema.py | 2 +- morphogen/status.py | 44 +++++++++++++-------------------- morphogen/ui.html | 4 +-- morphogen/ui.py | 2 +- schemas/evidence-record.v1.json | 2 +- 8 files changed, 29 insertions(+), 39 deletions(-) diff --git a/morphogen/cli.py b/morphogen/cli.py index 5c6df0a..e22f489 100644 --- a/morphogen/cli.py +++ b/morphogen/cli.py @@ -10,7 +10,7 @@ morphogen evidence [--verify] [--limit N] [--by judge] morphogen ui [--host 127.0.0.1] [--port 8765] -TARGET is `cell:NAME` for a cell with a `run` in morphogen.yaml (or the cell's name, or its `dir`). +TARGET is `cell:NAME` for a cell with a `run` in the catalog (`spec.morphogen.run` on its entity) (or the cell's name, or its `dir`). """ from __future__ import annotations diff --git a/morphogen/mcp_server.py b/morphogen/mcp_server.py index 70ff3d5..a275d68 100644 --- a/morphogen/mcp_server.py +++ b/morphogen/mcp_server.py @@ -25,8 +25,8 @@ name="morphogen", instructions=( "Morphogen improves a system at any scope behind a judge the agent cannot edit. Start with status: " - "where the project stands and the next step. morphogen.yaml " - "says what the cells are, which interfaces join them, which tests guard each, and what each cell " + "where the project stands and the next step. The catalog (catalog-info.yaml, Backstage entities; " + "a cell's rules are `spec.morphogen` on its entity) says what the cells are, which interfaces join them, which tests guard each, and what each cell " "may change (`change`); nothing else may change, and a candidate that touches anything else is " "refused. To improve a cell: measure it (target cell:NAME), change it on a branch, commit, then " "call judge(target, candidate); or call tune(target) to search its bounded settings. probe gives " @@ -70,7 +70,7 @@ def _target(target: str) -> tuple[str, str | None]: @server.tool() @_safe def status() -> dict: - """Where the project stands: its sources (morphogen.yaml, morphogen.local.yaml, Backstage catalog + """Where the project stands: its sources (the catalog, morphogen.local.yaml, other catalog files), each cell on the trunk and whether the judge can judge it, cells drafted but not yet on the trunk, what is missing, its measurements and verdicts, and the next step. Call it first.""" from .status import status as status_of @@ -85,7 +85,7 @@ def status() -> dict: @server.tool() @_safe def structure_check(file: str | None = None) -> dict: - """Check the system structure (default: morphogen.yaml): cycles, unknown + """Check the system structure (default: the catalog, catalog-info.yaml): cycles, unknown parents or interfaces, gaps, unused or untested interfaces; and intent coverage.""" s = _structure(file) return {"findings": [f.__dict__ for f in s.check()], "coverage": s.coverage(), "roots": s.roots(), @@ -131,7 +131,7 @@ def probe(target: str, candidate: str, base: str | None = None, cases: int = 5, @server.tool() @_safe def judge(target: str, candidate: str, base: str = "main", labels: dict | None = None) -> dict: - """Score a candidate commit against the base by the base's rules (its morphogen.yaml; default deny). + """Score a candidate commit against the base by the base's rules (its catalog; default deny). With target `cell:NAME`, the candidate must also pass the tests of every interface the cell's scope touches, from the base's structure. The verdict is measured evidence. `labels` (optimizer, approach) are recorded, never decide.""" diff --git a/morphogen/runner.py b/morphogen/runner.py index 0279e7f..7b361af 100644 --- a/morphogen/runner.py +++ b/morphogen/runner.py @@ -1,7 +1,7 @@ """Runners: where the judge's commands run, and which guarantees hold there. Each runner declares the guarantees it provides; a cell may require some (`requires:` in -morphogen.yaml), and the judge refuses to score it on a runner that lacks them rather than quietly +the catalog), and the judge refuses to score it on a runner that lacks them rather than quietly giving weaker evidence. Every verdict records the guarantees that held. network_isolated the command cannot reach the network diff --git a/morphogen/schema.py b/morphogen/schema.py index 664571a..dc054e0 100644 --- a/morphogen/schema.py +++ b/morphogen/schema.py @@ -87,7 +87,7 @@ class Verdict(Record): sandbox: str = Field(description="the runner the judge used: none, podman or docker") runner: dict[str, Any] = Field(description="the guarantees that runner gives") settings: dict[str, Any] | None = Field(None, description="the judge's settings for this run (trunk, sandbox, sandbox_image, budget)") - settings_from: dict[str, str] | None = Field(None, description="per setting: base (the base commit's morphogen.yaml), morphogen.local.yaml, request, or default") + settings_from: dict[str, str] | None = Field(None, description="per setting: base (the base commit's catalog), morphogen.local.yaml, request, or default") request: RequestRef | None = None served: Served | None = Field(None, description="what the runs were given beyond their tree (morphogen.local.yaml's env and services); names, a digest and image ids, never a value") parameters: dict[str, Any] | list[Any] | None = None diff --git a/morphogen/status.py b/morphogen/status.py index edf506f..ef55a11 100644 --- a/morphogen/status.py +++ b/morphogen/status.py @@ -12,8 +12,6 @@ import subprocess from pathlib import Path -import yaml - from . import judge as judge_mod from .project import FILE, LOCAL, Project, ProjectError @@ -25,27 +23,17 @@ def _git(cwd: Path, *args: str) -> subprocess.CompletedProcess: def _catalogs(repo: Path) -> list[str]: - """Backstage catalog files in the checkout, tracked or not (ignored files excluded).""" + """Catalog files (`catalog-info.yaml`) in the checkout, tracked or not (ignored files excluded).""" p = _git(repo, "ls-files", "--cached", "--others", "--exclude-standard") files = p.stdout.splitlines() if p.returncode == 0 else [] return sorted(f for f in files if Path(f).name in CATALOG_NAMES) -def _named_catalogs(tree: Path) -> list[str]: - f = tree / FILE - try: - data = yaml.safe_load(f.read_text()) if f.exists() else None - except yaml.YAMLError: - return [] - b = (data or {}).get("backstage") if isinstance(data, dict) else None - return [b] if isinstance(b, str) else list(b or []) - - def _load(tree: Path) -> tuple[Project | None, str | None]: """The project on `tree`, or None; and a problem that stops it loading.""" try: return Project.load(tree), None - except (ProjectError, yaml.YAMLError) as e: + except ProjectError as e: return None, str(e) @@ -137,7 +125,7 @@ def status(start: Path, cfg: dict | None = None, evidence=None) -> dict: sources = { FILE: (repo / FILE).exists(), LOCAL: (repo / LOCAL).exists(), - "backstage": {"named": _named_catalogs(repo), "found": catalogs}, + "catalog": {"read": list(work.rule_files) if work else [], "found": catalogs}, } out["sources"] = sources missing: list[str] = [] @@ -145,10 +133,10 @@ def status(start: Path, cfg: dict | None = None, evidence=None) -> dict: missing.append(f"{LOCAL} is committed: it holds held-out paths and the sandbox; remove it from git") elif sources[LOCAL] and _git(repo, "check-ignore", "-q", LOCAL).returncode != 0: missing.append(f"{LOCAL} is not in .gitignore: add it, so it is never committed") - unread = [f for f in catalogs if f not in sources["backstage"]["named"]] - if unread: - missing.append(f"Backstage catalog files Morphogen does not read: {', '.join(unread)} " - f"(name them under `backstage:` in {FILE})") + unread = [f for f in catalogs if f not in sources["catalog"]["read"]] + if unread and work is not None: + missing.append(f"catalog files Morphogen does not read: {', '.join(unread)} " + f"(name them as targets of a Location in {FILE})") base_sha = None if _git(repo, "rev-parse", "--verify", f"{trunk}^{{commit}}").returncode == 0: @@ -178,9 +166,9 @@ def status(start: Path, cfg: dict | None = None, evidence=None) -> dict: if drafted: out["drafted"] = drafted if work_problem: - missing.append(f"{FILE} in the working tree does not load: {work_problem}") + missing.append(f"the catalog in the working tree does not load: {work_problem}") elif work and work.errors(): - missing.append(f"{FILE} in the working tree has errors: {'; '.join(work.errors())}") + missing.append(f"the catalog in the working tree has errors: {'; '.join(work.errors())}") if base: untested = [i for i, spec in base.structure().interfaces.items() if not spec.tests] if untested: @@ -198,13 +186,15 @@ def _next(out: dict, work: Project | None, base: Project | None, catalogs: list[ return f"fix the structure on `{trunk}` (the judge refuses it until then): " + "; ".join(out["errors"]) if base is None: if work is not None: - return (f"{FILE} is drafted but not on `{trunk}`: commit it on a branch and open a pull request; " - "the operator merges it. Until then `probe` can practise against it; no verdict rests on it") + return (f"the catalog ({FILE}) is drafted but not on `{trunk}`: commit it on a branch and open a pull " + "request; the operator merges it. Until then `probe` can practise against it; no verdict rests on it") if catalogs: - return (f"write {FILE} with `backstage: [{', '.join(catalogs)}]` and add, for the one part to improve, " - "`change`, `run`, `better` and `tests` (the map skill, step 2)") - return ("no map yet: ask the operator what to improve and how they would know it improved, then draft " - f"one cell in {FILE} with `change`, `run`, `better` and `tests` (the map skill)") + return (f"{', '.join(catalogs)} is not the project's catalog root: the root is {FILE} at the repository " + "root (a Location may name this file as a target). Add `spec.morphogen` with `change`, `run`, " + "`better` and `tests` to the one part to improve (the map skill, step 2)") + return ("no catalog yet: ask the operator what to improve and how they would know it improved, then write " + f"{FILE} with one Component whose `spec.morphogen` has `change`, `run`, `better` and `tests` " + "(the map skill)") ready = [c for c in out["cells"] if c.get("ready")] if not ready: broken = [c for c in out["cells"] if c.get("problems")] diff --git a/morphogen/ui.html b/morphogen/ui.html index 9c449c5..51dffce 100644 --- a/morphogen/ui.html +++ b/morphogen/ui.html @@ -99,7 +99,7 @@

Morphogen

@@ -231,7 +231,7 @@

Parameters

-

No cell with a run in morphogen.yaml.

+

No cell with a run in the catalog.