diff --git a/BRIEF.md b/BRIEF.md index a9e0a90..abbf1d2 100644 --- a/BRIEF.md +++ b/BRIEF.md @@ -10,12 +10,12 @@ what it taught. Issue numbers (#43, #45) refer to this repository's history. **What it is now: the kit, with the judge at its core.** Morphogen maps a system, researches and catalogues the options for each role, and optimises behind its judge, on files only, on any harness. The map, the options and -(in phase 2) the cells are all Backstage catalog entities, with Morphogen's own fields under one namespaced key, +the cells are all Backstage catalog entities, with Morphogen's own fields under one namespaced key, `spec.morphogen`; documentation is fetched into markdown files. The judge stays the core and stays independent: the skills that write the map and the catalog write what the judge reads from the base commit, and no candidate -may touch it. Everything below about the judge, the cell and the optimizers is unchanged. **Coming, phase 2:** the -cell format moves from `morphogen.yaml` onto the entities (draft: `schemas/morphogen-spec.v0.json`); until then -`morphogen.yaml` is what the judge reads. +may touch it. Everything below about the judge, the cell and the optimizers is unchanged. The cell format +is `spec.morphogen` on the entity a cell judges (`schemas/morphogen-spec.v1.json`), read from the project's +`catalog-info.yaml`: there is no other project file. **Where it sits.** The Knowledge Kernel is an optional layer above the kit: it ingests the same Backstage files when someone wants indexing, search or graph traversal, and the kit never requires it. Substrate is the default @@ -173,8 +173,8 @@ Morphogen needs cells, not a system structure. A mapper helps when there are man changes cross interfaces, or when intent is missing from the code. Without one, start by measuring: -1. **One cell by hand.** Name what may change, its existing tests and a measure: one cell in - `morphogen.yaml` and nothing else (rebuild 6 ran this way, with a `target.yaml`). +1. **One cell by hand.** Name what may change, its existing tests and a measure: one cell + (`spec.morphogen` on one catalog entity) and nothing else (rebuild 6 ran this way, with a `target.yaml`). 2. **Or profile first.** Run the system under its tests or workload with outside observation (a profiler offline, OBI live). The hot spots, by time, cost or errors, become candidate cells. An agent drafts each cell from what is already there (location, modality, tests it finds); @@ -307,7 +307,7 @@ secondary reports; read the paper before quoting them). Strategy: 1. **Allowed alternatives are a setting's choices.** No new concept: a `change` entry whose - choices are set in `morphogen.yaml` at the base commit, where no candidate can change them. + choices are set in the catalog at the base commit, where no candidate can change them. Adding a choice is an operator change, with its evidence attached: ```yaml diff --git a/CLAUDE.md b/CLAUDE.md index 98413dd..26f5843 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,14 +7,14 @@ docs/restart/LESSONS.md. - `morphogen/`: the core. `structure.py` (cells, interfaces, parameters; checks, scopes, boundaries, intended against observed), `render.py` (Mermaid), `judge.py` and `runner.py` (the judge), `serve.py` (the env values, services and model gateway a run is given; the meter), `errors.py`, `evidence.py`, `optimize.py` (the optimizer catalog, the selector and `tune`), `observers.py` (`command`, - `otel`), `project.py` (the cell format: morphogen.yaml's cells and interfaces, default deny), - `backstage.py` (catalog-info.yaml files as a source of cells), + `otel`), `project.py` (the cell format: `spec.morphogen` on the catalog's entities, default deny), + `backstage.py` (the catalog: `catalog-info.yaml` and its Location targets, read into cells, interfaces and settings), `status.py` (where a project stands and the next step), - `documents.py` (morphogen.yaml's settings, and the target spec a cell compiles to), `request.py` (one document in, one verdict out), `intake.py` (the judge held by another user: a candidate arrives as a git bundle), `cli.py`, `mcp_server.py`, `ui.py` and `ui.html` (the read-only web UI). + `documents.py` (the project's settings, from the System's `spec.morphogen`, and the target spec a cell compiles to), `request.py` (one document in, one verdict out), `intake.py` (the judge held by another user: a candidate arrives as a git bundle), `cli.py`, `mcp_server.py`, `ui.py` and `ui.html` (the read-only web UI). - `.claude-plugin/`, `skills/`, `agents/`: the Claude Code plugin around the MCP server. Skills (the kit): `morphogen` (improve a cell), `map` (take a system apart into Backstage entity files and draft cells), - `catalog` and `research` (options for a role, as `lifecycle: candidate` Components). `schemas/morphogen-spec.v0.json` - is the draft of the `spec.morphogen` fields; phase 2 loads them, morphogen.yaml still works until then. + `catalog` and `research` (options for a role, as `lifecycle: candidate` Components). `schemas/morphogen-spec.v1.json` + is the schema of the `spec.morphogen` fields the code loads (a test keeps them equal). - `tests/`: the core's tests and red team; fixture projects in `tests/fixture*.py`, the timed sample's files in `tests/fixtures`. - `demos/`: projects Morphogen can build and drive. The core never imports from them. @@ -64,7 +64,7 @@ judge callable by any system and tests the value claims before it is published; into it. 1. Design simplifications left: probe as a mode of the judge. Done: one structure document - (morphogen.yaml, phases 1-2), one kind of "still works" test (`tests`, `same_as_base`). + (the catalog, phases 1-2), one kind of "still works" test (`tests`, `same_as_base`). 2. Optimizers that escape local optima: done (hill-climb restarts, `anneal`, the selector's stagnation signal). Later: a stepping-stone archive and multi-step candidates. 3. The entity-resolution demo as the first real run: move its F1 into a scorer outside the diff --git a/PLAN.md b/PLAN.md index ef092cc..48b2076 100644 --- a/PLAN.md +++ b/PLAN.md @@ -7,19 +7,21 @@ ## The kit: the way there Everything committed becomes a Backstage catalog entity; Morphogen's own fields go under one key, -`spec.morphogen` ([schemas/morphogen-spec.v0.json](schemas/morphogen-spec.v0.json), a draft). An option for a role +`spec.morphogen` ([schemas/morphogen-spec.v1.json](schemas/morphogen-spec.v1.json), a draft). An option for a role is a `Component` with `spec.lifecycle: candidate`; a cell's rules go on the entity it judges; sub-grain cells are `Component`s nested with `subcomponentOf`; an interface's tests go on its `API`; settings and shared defaults go on the `System`. `morphogen.local.yaml` stays as it is. - **K1, skills and schema (this pull request, #102).** README, BRIEF and the skills say what Morphogen is now; the `map` skill is merged with Substrate's and writes entity files; new `catalog` and `research` skills; the draft - schema. No code behaviour changes; `morphogen.yaml` still works. Open check before K2: that Backstage's `API` and + schema. No code behaviour changes. Open check before K2: that Backstage's `API` and `System` kinds leave `spec` open the way `Component` does. -- **K2, cells into entities.** Load `spec.morphogen` from the catalog files; check a cell's settings against its - option's parameter schema; default deny covers every catalog file the judge reads (a red-team test across files - first); `morphogen.yaml` is removed with **no back-compatibility**, since only our own projects use it (Substrate, - the demos), and they are moved by hand. Decide whether `lifecycle: candidate` entities are skipped as cells. +- **K2, cells into entities (the pull request stacked on #102).** Done: `spec.morphogen` is loaded from the project's + catalog (`catalog-info.yaml` at the root and the `Location` targets it names); every catalog file the judge reads + is a rule file (a candidate that changes, adds or removes one is refused; red-team tests across files); settings and + `defaults` are the System's, read from the base; options (`lifecycle: candidate`) and roles (`type: role`) are + never cells; `morphogen.yaml` is removed with **no back-compatibility**, and the demos are moved by hand. Not done: + checking a cell's settings against its option's `parameters` schema (nothing in the judge reads options yet). - **K3, documentation as files.** A documentation MCP server that turns web documentation into markdown files, chosen with the `research` skill (a local one first: a hosted one sends what is looked up off the machine). Its output is a folder of markdown beside the catalog, named in each option's `docs.path`. @@ -145,7 +147,7 @@ cell file, and judges the same as before. Done: the demo is split that way and compiles to the same structure as before (a test). It cannot be judged until phase 6 makes its data reachable, so "judges the same" is shown on the structured -classifier instead: described half in a catalog, it reaches the same verdicts as in morphogen.yaml +classifier instead: described in a catalog split over files, it reaches the same verdicts as in one file alone. Red team: a candidate that weakens the catalog (drops an API) for later judgments is refused, even when `change` is `**`; it passed the judge before catalog files were made the judge's. @@ -217,7 +219,7 @@ Each item is one pull request; the ones that change the judge start with their c and end with the suite passing locally and in Podman, and an A/A check. - **7a. One request in, one verdict out.** The judge's input, written down as one document: the base - and candidate commits, the cells and interfaces (from `morphogen.yaml`, `catalog-info.yaml`, or a + and candidate commits, the cells and interfaces (from the project's `catalog-info.yaml`, or a request file a caller writes from its own store), `inputs`, and the local settings. Its output: the verdict record, with a published, versioned schema (the evidence log's canonical JSON and hash chain included), so a caller verifies a log without copying Morphogen's code. @@ -282,7 +284,7 @@ extras or leave it (7d); where the two demos go (7f); and what 7e's result means - Domain modules around a shared knowledge base, joined by the resolver. ## Decisions (operator, 2026-11-05) -1. **One file:** the cell format and project settings live in `morphogen.yaml` at the root; +1. **One file:** the cell format and project settings live in the catalog (`catalog-info.yaml` at the root); held-out paths, budget overrides and the sandbox in an uncommitted `morphogen.local.yaml`. 2. **The old format** (`target.yaml` plus `cells.yaml`) is removed after phase 2. 3. **The field is `change`.** diff --git a/README.md b/README.md index d790840..439220b 100644 --- a/README.md +++ b/README.md @@ -93,35 +93,99 @@ hole it closes. ## The cell format -> **Coming, phase 2.** The cell format below is today's. The kit moves every committed artifact into Backstage -> catalog entities: a cell's rules go on the entity it judges under one namespaced key, `spec.morphogen`; an -> option for a role is a `Component` with `spec.lifecycle: candidate`; sub-grain cells are `Component`s nested -> with `subcomponentOf`; an interface's tests go on its `API` entity; the project's settings and shared defaults go -> on the `System` entity. The fields are drafted in [`schemas/morphogen-spec.v0.json`](schemas/morphogen-spec.v0.json) -> and carried over unchanged from what a cell accepts below. `morphogen.local.yaml` stays as it is. Until phase 2 -> lands, `morphogen.yaml` is what the judge reads, and this reference is current. +Everything committed is a Backstage catalog. The project's catalog root is `catalog-info.yaml` at the +repository root; it may be a `Location` whose `targets` name more files inside the project. Morphogen's own +fields go under one key, `spec.morphogen`, on the entity they are about (the fields are in +[`schemas/morphogen-spec.v1.json`](schemas/morphogen-spec.v1.json)): -One `morphogen.yaml` at the project's root: +| On | `spec.morphogen` holds | +|---|---| +| the entity a cell judges (Component, System, Domain, AiResource) | the cell's rules: `change`, `keep`, `run`, `better`, `tests`, `score`, ... (below). An entity with no `run` (and no tests) is structure, not a judged cell | +| a sub-grain cell | the same, on a `Component` of its own nested with `spec.subcomponentOf` | +| an `API` | the interface's `tests`, and `external: consumes` or `provides` when the code needs it | +| the `System` | 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 (a field set to `null` opts out). At most one System carries settings; two is an error | +| an option for a role (`spec.lifecycle: candidate`) | `fills`, `parameters`, `licence`, `docs`, `evaluation` (the `catalog` skill). An option, and a role (`spec.type: role`), is never a cell | + +What Backstage already says is not repeated: `in` is `subcomponentOf` (or `system`, `domain`, `subdomainOf`), +`provides` and `consumes` are `providesApis` and `consumesApis` (and `dependsOn`), `owner` and `lifecycle` are the +entity's own. A cell is named by its `metadata.name` (`namespace/name` outside the `default` namespace), so two +cell entities may not share a name; a ref in any spelling (`classify`, `component:classify`, +`component:default/classify`) names it. + +A complete project, `catalog-info.yaml`: ```yaml -cells: - app: {} - classify: - in: app # the cell this one belongs to +apiVersion: backstage.io/v1alpha1 +kind: System +metadata: {name: app} +spec: + owner: team-a + morphogen: + sandbox: podman # settings: from the base commit, like every rule + budget: {trials_per_day: 20} + autonomy: {experimental: merge} # lifecycle -> may an agent merge a pass (default: review) + defaults: # inherited by every cell below that sets none of its own + rounds: {warmup: 0, repeats: 4, max_repeats: 8} + timeout: 60 +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: {name: classify} +spec: + type: service + lifecycle: experimental # what `autonomy` keys on + owner: team-a # who approves its candidates + system: app # `in` + providesApis: [labels] + morphogen: dir: classify # where its commands run (default: the root) 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 score: python score.py # scores each run's output, from the base tests: python -m unittest -q test_classify # must pass; a failure refuses - provides: labels - report: {in: app, consumes: labels} -interfaces: - labels: python -m unittest -q contracts.test_labels # run from the root +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: {name: threshold} # below the grain of the part: its own cell, nested +spec: + type: library + subcomponentOf: classify # `in` + morphogen: + change: classify/classify.py#THRESHOLD in 0..100 + run: python bench.py + better: wall_seconds lower +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: {name: report} +spec: {type: service, system: app, consumesApis: [labels]} # structure: no morphogen, no run +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: {name: labels} +spec: + type: openapi + definition: labels.yaml + morphogen: + tests: python -m unittest -q contracts.test_labels # run from the root +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: {name: rapidfuzz} # an option for a role: never a cell +spec: + type: library + lifecycle: candidate + morphogen: {fills: matcher, licence: MIT} ``` +Every catalog file the judge reads (the root and each `Location` target) is a rule file, read from the base +commit only: a candidate that changes, adds or removes one is refused, whatever `change` says, so a candidate +cannot edit the rules it is judged by. A catalog file the root does not reference is not read and is not +a rule file. + - **Default deny.** A candidate may change only what the judged cell's scope names in `change`. - Anything else changed, the project file, the bench, the scorer and every test included, refuses + Anything else changed, the catalog files, the bench, the scorer and every test included, refuses the candidate before anything runs. Candidates may not add symbolic links. - **`change`**: a path or glob (`src/**`, `prompts/`), or a setting: `path#NAME` (a Python constant) or `path:dotted.key` (YAML, JSON, TOML), bounded with `in lo..hi` or `in [a, b]`. A setting entry @@ -176,35 +240,28 @@ or their enclosing systems' boundaries cross, must pass on the candidate. That i computed from the structure rather than declared. The result is recorded as a verdict on the change, with the same `gate` (who may merge it) as any other. -### Backstage above it - -A project that already keeps Backstage's `catalog-info.yaml` files need not restate its structure. -`backstage: catalog-info.yaml` (or a list) in `morphogen.yaml` reads them directly, with no -Backstage server, following `Location` targets inside the project: +### How the catalog maps to cells | Backstage | Becomes | |---|---| -| `Component`, `System`, `Domain` | a cell, named by its ref: `component:default/classify` | +| `Component`, `System`, `Domain` | a cell, named by its name (`namespace/name` outside `default`) | | `AiResource` (Backstage 1.51: skills and rules) | a cell, `in` its `system`; a skill named in `change` is a text cell | | `owner`, `lifecycle` | the cell's `owner` (who approves its candidates) and `lifecycle` (what `autonomy` keys on) | | `subcomponentOf`, `system`, `domain`, `subdomainOf` | `in` | -| `API` | an interface, named by its ref; its tests from the annotation `morphogen.dev/tests` | +| `API` | an interface; its tests are `spec.morphogen.tests` | | `providesApis`, `consumesApis` | `provides`, `consumes` | | `dependsOn` | consumes it: provided by that cell, or external (a `Resource`) | -| annotations `morphogen.dev/change`, `keep`, `run`, `better`, `tests`, `score`, `dir`, `observe` | the cell's fields (one entry per line for lists) | +| `Location` targets | more catalog files to read, and so more rule files | + +The catalog is read directly, with no Backstage server. `structure check` reports which file each cell and +interface came from. **Who may merge a pass.** The judge never merges. Each verdict carries a `gate`: the cell's owner -and lifecycle, and the decision, `review` (a person decides) unless the operator's `autonomy` in -`morphogen.yaml` lets an agent merge a pass for that lifecycle (`autonomy: {experimental: merge}`). +and lifecycle, and the decision, `review` (a person decides) unless the System's `autonomy` +lets an agent merge a pass for that lifecycle (`autonomy: {experimental: merge}`). The gate is read from the base, so a candidate that relabels its cell `experimental`, or grants -itself autonomy, is refused like any other edit to the rules. - -`morphogen.yaml` then adds what the catalog does not hold, under the same names (`component:classify` -is enough), and may add cells below Backstage's grain with `in: component:classify`. Where the two -disagree on a field, the structure has an error and the judge refuses it; `structure check` reports -where each cell and interface came from. The catalog files are the judge's, like `morphogen.yaml`: -a candidate that changes one is refused, whatever `change` says. `demos/entity-resolution` is -described this way. +itself autonomy, is refused like any other edit to the rules. `demos/entity-resolution` is +described this way: one `catalog-info.yaml`, its `er` System carrying the F1 workload as `defaults`. ## In Claude Code @@ -224,7 +281,7 @@ evidence and draft its cells; `catalog`: find options for a role; `research`: ch **Starting fresh.** In a git repository, ask Claude to start Morphogen here. The map skill calls `status`, which says where the project stands and the next step: no commit yet, no map, a map drafted but not on `main`, a cell the judge cannot judge yet (and why), a cell to measure, a cell -to improve. It reads a Backstage `catalog-info.yaml` if there is one. The first map is one cell, +to improve. It reads the project's `catalog-info.yaml`; where one exists without Morphogen's fields, it adds `spec.morphogen` and leaves the rest. The first map is one cell, the part you want improved, with what may change, how to run it, what "better" means and the tests it must keep passing; it reaches `main` by your pull request, and only then does a verdict rest on it. @@ -234,7 +291,7 @@ it. ``` uv sync uv run morphogen status # where the project stands; the next step -uv run morphogen structure check morphogen.yaml +uv run morphogen structure check catalog-info.yaml uv run morphogen measure cell:classify uv run morphogen judge cell:classify my-branch uv run morphogen change my-branch # a change that claims no improvement: its cells' tests @@ -265,7 +322,7 @@ local: # optional: replaces morphogen.local.yaml gateway: {container: my-gateway, port: 8080, meter: /outside/meter} ``` -The rules (cells, interfaces, tests, and the settings in `morphogen.yaml`) still come from the base commit: +The rules (cells, interfaces, tests, and the System's settings in the catalog) still come from the base commit: a request that carries any, or sits inside the repository, is refused. The verdict records the request's digest. Each record in the evidence log follows a published schema, [`schemas/evidence-record.v1.json`](schemas/evidence-record.v1.json) (generated from `morphogen/schema.py`, @@ -296,7 +353,7 @@ directory, so it can only answer. The cell's `description` is its objective. | Part | Module | Does | |---|---|---| -| Cell format | `project.py`, `backstage.py` | parses `morphogen.yaml` and any Backstage catalog files it names; compiles them to a structure and, per cell, the spec the judge runs; default deny | +| Cell format | `project.py`, `backstage.py` | reads the catalog (`catalog-info.yaml` and the Location targets it names); compiles it to a structure and, per cell, the spec the judge runs; default deny | | Structure | `structure.py`, `render.py` | cells in a containment tree, interfaces as hyperedges with their tests; checks, scopes, computed boundaries, intent coverage, intended against observed, a Mermaid diagram | | Judge | `judge.py`, `runner.py` | scores a candidate commit against a base by the base's rules; `judge_change` holds a change with no measure to the tests of what it touches; `probe` gives practice feedback; `measure` records a baseline | | Evidence | `evidence.py` | an append-only, hash-chained log of measured and stated claims, in git's own directory | @@ -374,7 +431,7 @@ service images and its own model gateway in its own store. ## What the judge guarantees -- **The rules are the base's.** `morphogen.yaml` and everything a cell's `change` does not name come +- **The rules are the base's.** The catalog files and everything a cell's `change` does not name come from the base commit; a candidate that changes any of it is refused before anything runs. - **Measurement is outside the code.** Time and memory are measured by a wrapper process; inputs come from a fresh seed every round; each timed run must print what the base prints (unless the @@ -394,7 +451,7 @@ service images and its own model gateway in its own store. the gateway's to refuse. Each run's calls, tokens and cost come from the operator's meter reading the gateway's record; the key the meter gives a run is scanned for in its output like any secret. - **The judge's own settings are the base's too.** The sandbox, its image and the budget come from - `morphogen.yaml` as committed on the base, with only the operator's `morphogen.local.yaml` (or a + the catalog's settings as committed on the base, with only the operator's `morphogen.local.yaml` (or a request's `local`) over them, never from the working copy; each verdict records them and where each came from. - **Settings stay in bounds.** A setting moved outside its range or choices, a kept setting @@ -411,7 +468,7 @@ service images and its own model gateway in its own store. The red team holds the known ways to cheat: 61 of them (`tests/test_redteam.py` and the default-deny cheats in `tests/test_cells.py`), from patching the timer to reading the held-out answers, rigging -the bench, widening `change` in the candidate's own `morphogen.yaml`, breaking a neighbour's +the bench, widening `change` in the candidate's own catalog, breaking a neighbour's contract, winning locally while the system gets slower, switching telemetry off to look free, raising the budget in an uncommitted working copy, or carrying rules in a request. Every one must fail; a new one goes there first. The whole suite also runs with every trial in diff --git a/agents/reviewer.md b/agents/reviewer.md index adac5a9..9f115ce 100644 --- a/agents/reviewer.md +++ b/agents/reviewer.md @@ -10,7 +10,7 @@ tools: --- You review a change you did not write. You are given only the target, the -base and candidate commits, and the cell in `morphogen.yaml`. Do not ask for +base and candidate commits, and the cell's `spec.morphogen` in the catalog. Do not ask for or rely on the author's explanation. Use `git diff ` and read the changed code. Look for: diff --git a/agents/worker.md b/agents/worker.md index 971b28f..9d4fdd3 100644 --- a/agents/worker.md +++ b/agents/worker.md @@ -16,10 +16,10 @@ to try, and a branch name. 1. Create a git worktree for your branch from the trunk: `git worktree add ../ -b `, and work only there. 2. Make the smallest change that implements the approach. -3. Change only what the cell's `change` in `morphogen.yaml` names (and, for a +3. Change only what the cell's `change` (`spec.morphogen` in the catalog) names (and, for a setting, only that setting, within its bounds). The judge refuses a candidate that changes anything else, the bench, the tests and - `morphogen.yaml` included, so doing so only wastes the trial. + the catalog files included, so doing so only wastes the trial. 4. Run the target's own tests if they are quick, and the tests of the interfaces your change touches (`structure_scope` lists them). Do not tune against the benchmark's input or try to read held-out answers: the judge diff --git a/demos/README.md b/demos/README.md index 489296d..7d0b44c 100644 --- a/demos/README.md +++ b/demos/README.md @@ -1,6 +1,6 @@ # Demos -> These projects describe themselves in `morphogen.yaml` and `catalog-info.yaml` today. In phase K2 of the kit ([PLAN.md](../PLAN.md)) their cells move onto Backstage entities under `spec.morphogen` and `morphogen.yaml` is removed, with no back-compatibility; the demos are moved by hand. +> These projects describe themselves in a Backstage `catalog-info.yaml`, with Morphogen's fields under `spec.morphogen` (the kit's phase K2, [PLAN.md](../PLAN.md)). Projects a fresh Morphogen instance can start building, and that Morphogen can then drive. Each is a component that stands alone, or a larger system built from them. diff --git a/demos/cognitive-model/catalog-info.yaml b/demos/cognitive-model/catalog-info.yaml new file mode 100644 index 0000000..44ad60d --- /dev/null +++ b/demos/cognitive-model/catalog-info.yaml @@ -0,0 +1,790 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: 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' +spec: + type: service +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: cycle + description: 'The cognitive cycle: one model step between tool batches' +spec: + type: service + subcomponentOf: cmc/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: dm + description: 'Declarative memory: semantic and episodic chunks; one best chunk per cue, by activation' +spec: + type: service + subcomponentOf: cmc/declarative-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: learn + description: 'Learning: online and gated' +spec: + type: service + subcomponentOf: cmc/learning +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: motor + description: 'Motor: write-side tools are the only way to change the world' +spec: + type: service + subcomponentOf: cmc/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: percept + description: 'Perception: senses feed the percept buffer, compressed' +spec: + type: service + subcomponentOf: cmc/perception +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: pm + description: 'Procedural memory: skills as explicit productions over the model''s implicit procedures' +spec: + type: service + subcomponentOf: cmc/procedural-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: wm + description: 'Working memory: named buffers, each holding at most one chunk (imaginal up to 5)' +spec: + type: service + subcomponentOf: cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: central-selector + namespace: cmc + description: reads the WM snapshot, matches productions, selects one act per cycle +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - wm/buffer-goal + - wm/buffer-imaginal +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: cycle + namespace: cmc + description: One model step between tool batches; hooks run each phase +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: declarative-memory + namespace: cmc + description: Semantic and episodic chunks, retrieved one at a time by activation +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: evaluation + namespace: cmc + description: '20 recurring tasks over 2 weeks, with and without cmc: success rate, tokens per task, how often + the same mistake repeats' +spec: + type: service + subcomponentOf: default/cmc +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: harness + namespace: cmc + description: hooks, skills, subagents, MCP client, permissions +spec: + type: service + subcomponentOf: default/cmc +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: learning + namespace: cmc + description: Reinforcement, encoding, chunking and consolidation as side effects of work +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: motor + namespace: cmc + description: Write-side tools, gated on a stated goal +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: operator + namespace: cmc + description: promotes proposed skills; gives explicit feedback that outweighs the judge +spec: + type: service + subcomponentOf: default/cmc +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: perception + namespace: cmc + description: Read-side tools and watchers, compressed into the percept buffer +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: procedural-memory + namespace: cmc + description: Productions (skills, subagents, the model's weights) with utilities +spec: + type: service + subcomponentOf: default/cmc + consumesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: working-memory + namespace: cmc + description: A small, slot-based workspace re-injected into context every cycle; the only hub +spec: + type: service + subcomponentOf: default/cmc + providesApis: + - cmc/working-memory +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: act + namespace: cycle + description: gate motor tools; log the selection +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: boot + namespace: cycle + description: restore the goal stack from dm; inject WM and the active skills +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: close + namespace: cycle + description: decay and evict; tick the cycle; re-inject WM +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: encode + namespace: cycle + description: encode the turn as an episodic chunk +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: input + namespace: cycle + description: prompt as percept; set goal; inject WM and top-3 candidates +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: perceive + namespace: cycle + description: compress results; motor outcome; log fired skill +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: pre-compact + namespace: cycle + description: flush WM and the goal stack to dm +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: select + namespace: cycle + description: Claude matches skills against WM and chooses one act +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: session-end + namespace: cycle + description: queue consolidation and chunking +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: turn-end + namespace: cycle + description: judge the goal; record reward; continue if a subgoal is open +spec: + type: service + subcomponentOf: default/cycle +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: activation + namespace: dm + description: A_i = ln(sum t_j^-d) + sum W_k S_ki + beta sim(cue,i) + noise; below threshold returns failure +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: core-facts + namespace: dm + description: high-activation facts always loaded; promoted and demoted by the consolidator +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: embeddings + namespace: dm + description: embed chunks and cues +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: encode + namespace: dm + description: dm_encode(chunk) +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: retrieve + namespace: dm + description: dm_retrieve(cue, kind?) -> one chunk into the retrieval buffer; appends the time to access_times + (rehearsal) +spec: + type: service + subcomponentOf: default/dm + consumesApis: + - wm/buffer-retrieval +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: search + namespace: dm + description: 'dm_search(query, k): debugging only; denied to Claude in settings' +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: store + namespace: dm + description: 'chunk: id, kind, slots (JSON), text, embedding, created, access_times[], source' +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: vector-index + namespace: dm + description: nearest chunks to a cue +spec: + type: service + subcomponentOf: default/dm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: chunking + namespace: learn + description: draft a skill from a tool sequence that recurred >= 3 times with high reward, into _proposed/ with + an evidence note +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: consolidation + namespace: learn + description: merge duplicate chunks; promote and demote CLAUDE.md facts; prune skills +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: critic + namespace: learn + description: after low reward twice in a row; writes the retrieval buffer +spec: + type: service + subcomponentOf: default/learn + consumesApis: + - wm/buffer-retrieval +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: episodic-encoding + namespace: learn + description: goal, skills fired, key percepts, outcome, reward; also evicted WM chunks +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: failure-credit + namespace: learn + description: small negative reward to the active skill on PostToolUseFailure +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: review-gate + namespace: learn + description: a person moves drafts from _proposed/ to skills/ +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: reward + namespace: learn + description: R in [0,1] from goal outcome, tests passing and explicit feedback; at most 2 continuations per turn +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: utility-update + namespace: learn + description: U_i <- U_i + alpha (R - U_i) for every skill fired this turn +spec: + type: service + subcomponentOf: default/learn +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: effectors + namespace: motor + description: Edit, Write, Bash, actuator MCP tools +spec: + type: service + subcomponentOf: default/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: gate + namespace: motor + description: deny a motor tool when the goal buffer is empty +spec: + type: service + subcomponentOf: default/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: outcome + namespace: motor + description: write the action and outcome to the motor buffer +spec: + type: service + subcomponentOf: default/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: permissions + namespace: motor + description: which effectors run without asking +spec: + type: service + subcomponentOf: default/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: serial-bottleneck + namespace: motor + description: one intention per batch; optionally deny a second motor tool in a batch +spec: + type: service + subcomponentOf: default/motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: compress + namespace: percept + description: compress large results into a percept chunk; may replace the result with updatedToolOutput +spec: + type: service + subcomponentOf: default/percept +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: extra-senses + namespace: percept + description: log tail, CI status poller, screenshot description +spec: + type: service + subcomponentOf: default/percept +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: senses + namespace: percept + description: Read, Grep, Glob, WebFetch, WebSearch, read-only MCP servers +spec: + type: service + subcomponentOf: default/percept +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: watch + namespace: percept + description: bottom-up percepts when watched files change +spec: + type: service + subcomponentOf: default/percept +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: candidate-ranking + namespace: pm + description: top 3 skills by similarity(description, goal) x utility, added to the WM snapshot +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: compiled-routines + namespace: pm + description: long self-contained procedures; return one chunk to the retrieval or imaginal buffer +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: implicit + namespace: pm + description: 'the model''s weights: most procedural knowledge' +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: productions + namespace: pm + description: condition names WM buffers; every action step ends by changing WM +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: pruning + namespace: pm + description: move skills with utility < 0.2 after >= 10 fires to _inactive/, then reloadSkills +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: skill-log + namespace: pm + description: log which skill fired this cycle +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: utility-table + namespace: pm + description: 'per skill: utility (0..1, starts 0.5), fires, successes, last_fired' +spec: + type: service + subcomponentOf: default/pm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: buffer-goal + namespace: wm + description: holds current goal and subgoal stack +spec: + type: service + subcomponentOf: default/wm + providesApis: + - wm/buffer-goal +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: buffer-imaginal + namespace: wm + description: holds scratch problem state (plan, partial answer) +spec: + type: service + subcomponentOf: default/wm + providesApis: + - wm/buffer-imaginal +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: buffer-motor + namespace: wm + description: holds last action and its outcome +spec: + type: service + subcomponentOf: default/wm + providesApis: + - wm/buffer-motor +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: buffer-percept + namespace: wm + description: holds latest compressed perception +spec: + type: service + subcomponentOf: default/wm + providesApis: + - wm/buffer-percept +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: buffer-retrieval + namespace: wm + description: holds last chunk returned from declarative memory +spec: + type: service + subcomponentOf: default/wm + providesApis: + - wm/buffer-retrieval +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: compaction-guard + namespace: wm + description: flush WM and the goal stack to dm before compaction; re-inject after +spec: + type: service + subcomponentOf: default/wm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: decay + namespace: wm + description: evict chunks untouched for N cycles and hand them to the encoder +spec: + type: service + subcomponentOf: default/wm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: injection + namespace: wm + description: snapshot as additionalContext at the start of every cycle, ~2,000 characters +spec: + type: service + subcomponentOf: default/wm + consumesApis: + - wm/buffer-goal + - wm/buffer-imaginal + - wm/buffer-motor + - wm/buffer-percept + - wm/buffer-retrieval +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: store + namespace: wm + description: buffers, goal stack and the procedures table in .cmc/cmc.sqlite +spec: + type: service + subcomponentOf: default/wm +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: tools + namespace: wm + description: wm_get, wm_put(buffer, chunk), wm_set_goal, wm_push_subgoal, wm_pop_subgoal, wm_clear(buffer) +spec: + type: service + subcomponentOf: default/wm +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: working-memory + namespace: cmc +spec: + type: slot +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: buffer-goal + namespace: wm +spec: + type: slot +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: buffer-imaginal + namespace: wm +spec: + type: slot +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: buffer-motor + namespace: wm +spec: + type: slot +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: buffer-percept + namespace: wm +spec: + type: slot +--- +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: buffer-retrieval + namespace: wm +spec: + type: slot 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/cognitive-model/rebuild-6-map/README.md b/demos/cognitive-model/rebuild-6-map/README.md index 2f38bf9..856c964 100644 --- a/demos/cognitive-model/rebuild-6-map/README.md +++ b/demos/cognitive-model/rebuild-6-map/README.md @@ -3,7 +3,7 @@ `build_map.py` writes `lists/` (systems, slots, types, sources, components, parameters) in the list format of the `rebuild-6` branch, where it was mounted into a scratch Morphogen project as `cmc`: 160 entries, 63 slots, 24 parameters. Kept as the record of what mapping the spec found; -Morphogen now reads the cell format: `python rebuild-6-map/to_cells.py > morphogen.yaml` converts -these lists to the demo's `morphogen.yaml` (what does not carry over is listed in the script). +Morphogen now reads the project's Backstage catalog: `python rebuild-6-map/to_cells.py > catalog-info.yaml` converts +these lists to the demo's `catalog-info.yaml` (what does not carry over is listed in the script). mkdir -p lists && python build_map.py lists diff --git a/demos/cognitive-model/rebuild-6-map/to_cells.py b/demos/cognitive-model/rebuild-6-map/to_cells.py index 5e78d97..9e49fbc 100644 --- a/demos/cognitive-model/rebuild-6-map/to_cells.py +++ b/demos/cognitive-model/rebuild-6-map/to_cells.py @@ -1,9 +1,11 @@ -"""Convert the rebuild 6 map (lists/) to the cell format, printing a morphogen.yaml. +"""Convert the rebuild 6 map (lists/) to a Backstage catalog, printing the demo's catalog-info.yaml. - python rebuild-6-map/to_cells.py > morphogen.yaml + python rebuild-6-map/to_cells.py > catalog-info.yaml -Systems and slots become cells: each slot sits `in` its system, and each subsystem `in` the slot of -`cmc` it fills. Links become interfaces, one per slot others use: `talks_through` and `read_by` +Systems and slots become Components (an API for each interface), nested with `subcomponentOf`: each slot +sits in its system, and each subsystem in the slot of `cmc` it fills. A name with a slash (`wm/buffer-goal`) +is the entity `buffer-goal` in the namespace `wm`, which is how Backstage writes it; Morphogen names the cell +the same way. Links become interfaces, one per slot others use: `talks_through` and `read_by` consume it, `written_by` (slots only) consume it too. What does not carry over: - `next` links (the cycle's order of phases): sequence, not an interface; @@ -53,4 +55,26 @@ def use(interface, user): for c in cells.values(): if c.get("in") is None: c.pop("in", None) -yaml.safe_dump({"cells": cells, "interfaces": interfaces}, sys.stdout, sort_keys=False, width=110) + + +def ref(name): + """A reference with its namespace written out: Backstage reads a bare name in the referrer's own namespace.""" + return name if "/" in name else f"default/{name}" + + +def entity(kind, name, spec=None, description=None): + ns, _, short = name.rpartition("/") + md = {"name": short, **({"namespace": ns} if ns else {}), **({"description": description} if description else {})} + return {"apiVersion": "backstage.io/v1alpha1", "kind": kind, "metadata": md, "spec": spec or {}} + + +docs = [] +for name, c in cells.items(): + spec = {"type": "service", **({"subcomponentOf": ref(c["in"])} if c.get("in") else {})} + if c.get("provides"): + spec["providesApis"] = [ref(c["provides"])] + if c.get("consumes"): + spec["consumesApis"] = [ref(x) for x in c["consumes"]] + docs.append(entity("Component", name, spec, c.get("description"))) +docs += [entity("API", name, {"type": "slot"}) for name in interfaces] +yaml.safe_dump_all(docs, sys.stdout, sort_keys=False, width=110) diff --git a/demos/entity-resolution/README.md b/demos/entity-resolution/README.md index 80a922b..75e097a 100644 --- a/demos/entity-resolution/README.md +++ b/demos/entity-resolution/README.md @@ -7,7 +7,7 @@ Plan and build are done for a baseline; optimizing waits for Morphogen's base. S |---|---| | Plan: interface tests | `tests/test_interface.py` (the resolver), `tests/test_contracts.py` (candidates, pair-score, similarity) | | Build: two backends | `overlap` (overlap coefficient) and `tfidf` (TF-IDF cosine); both pass the interface test | -| Cells | `catalog-info.yaml` (the structure) and `morphogen.yaml` (what may change, how each is judged): backend, blocking, matcher on F1; `speed` (er/text.py) on wall time with the same output | +| Cells | `catalog-info.yaml` (the structure, and under `spec.morphogen` what may change and how each is judged; the `er` System's `defaults` carry the F1 workload): backend, blocking, matcher on F1; `speed` (er/text.py) on wall time with the same output | | Measure | `bench.py` prints the pairs it finds; `score.py`, from the base, computes F1 against answers outside the repository | | Judged | `speed`: passed, 69% faster; `matcher` tuned: passed, held-out F1 0.422 to 0.428 (below) | | Optimize | next: `blocking`, then `backend` | @@ -19,7 +19,7 @@ Run it (Python 3.11 or later, standard library only): python data/split.py ~/er-split # records and answers outside the repository MORPHOGEN_INPUTS=~/er-split/inputs python bench.py | MORPHOGEN_PRIVATE=~/er-split/search python score.py -To judge it, the demo must be the root of its own git repository (the judge reads `morphogen.yaml` +To judge it, the demo must be the root of its own git repository (the judge reads `catalog-info.yaml` at the root), with the lines `data/split.py` prints in `morphogen.local.yaml`. ## First verdicts (2026-11-06, Abt-Buy, in Podman) diff --git a/demos/entity-resolution/catalog-info.yaml b/demos/entity-resolution/catalog-info.yaml index b591483..d08347a 100644 --- a/demos/entity-resolution/catalog-info.yaml +++ b/demos/entity-resolution/catalog-info.yaml @@ -1,16 +1,32 @@ -# The resolver as Backstage sees it: the components and the APIs between them. What Morphogen adds -# (what each cell may change, and how it is judged) is in morphogen.yaml, which reads this file. +# The resolver as a Backstage catalog: the components and the APIs between them (the structure), and under +# `spec.morphogen` what each cell may change and how it is judged. `er` is the System: its `defaults` are what +# every cell in it inherits (the F1 workload and its scorer), and it is itself the whole system the guard measures. +# +# 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. apiVersion: backstage.io/v1alpha1 -kind: Component +kind: System metadata: name: er description: Entity resolution, the resolver as a whole spec: - type: library - lifecycle: experimental owner: operator + lifecycle: experimental providesApis: [resolver] consumesApis: [candidates, pair-score] # Base.resolve and Base.add use both + morphogen: + tests: python -m unittest discover -s tests -t . + defaults: + 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 --- apiVersion: backstage.io/v1alpha1 kind: Component @@ -21,8 +37,12 @@ spec: type: library lifecycle: experimental owner: operator - subcomponentOf: er + system: er providesApis: [candidates] + morphogen: + change: + - er/settings.py#BLOCK_MAX_DF in 0.01..0.5 + - er/settings.py#BLOCK_LIMIT in 5..200 --- apiVersion: backstage.io/v1alpha1 kind: Component @@ -33,9 +53,16 @@ spec: type: library lifecycle: experimental owner: operator - subcomponentOf: er + system: er providesApis: [pair-score] consumesApis: [similarity] + morphogen: + 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] --- apiVersion: backstage.io/v1alpha1 kind: Component @@ -46,8 +73,10 @@ spec: type: library lifecycle: experimental owner: operator - subcomponentOf: er + system: er providesApis: [similarity] + morphogen: + change: er/settings.py#BACKEND in [overlap, tfidf] --- apiVersion: backstage.io/v1alpha1 kind: Component @@ -58,42 +87,66 @@ spec: type: library lifecycle: experimental owner: operator - subcomponentOf: er + system: er consumesApis: [pair-score] --- +# 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. It sets its own everything the System +# defaults, and opts out of the scorer with `score: null`. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: speed + description: Tokenising and comparing names (er/text.py). Most of the run is spent here, in difflib. +spec: + type: library + lifecycle: experimental + owner: operator + subcomponentOf: matcher + morphogen: + change: er/text.py + run: python bench.py + score: null + 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 +--- apiVersion: backstage.io/v1alpha1 kind: API metadata: name: resolver description: The Resolver protocol (er/base.py) - annotations: - morphogen.dev/tests: python -m unittest discover -s tests -t . spec: type: python lifecycle: experimental owner: operator definition: see er/base.py + morphogen: + tests: python -m unittest discover -s tests -t . + external: consumes # used by whatever needs resolution --- apiVersion: backstage.io/v1alpha1 kind: API metadata: name: candidates - annotations: - morphogen.dev/tests: python -m unittest -q tests.test_contracts.Candidates -spec: {type: python, lifecycle: experimental, owner: operator, definition: Base.candidates} +spec: + {type: python, lifecycle: experimental, owner: operator, definition: Base.candidates, + morphogen: {tests: python -m unittest -q tests.test_contracts.Candidates}} --- apiVersion: backstage.io/v1alpha1 kind: API metadata: name: pair-score - annotations: - morphogen.dev/tests: python -m unittest -q tests.test_contracts.PairScore -spec: {type: python, lifecycle: experimental, owner: operator, definition: Base.pair} +spec: + {type: python, lifecycle: experimental, owner: operator, definition: Base.pair, + morphogen: {tests: python -m unittest -q tests.test_contracts.PairScore}} --- apiVersion: backstage.io/v1alpha1 kind: API metadata: name: similarity - annotations: - morphogen.dev/tests: python -m unittest -q tests.test_contracts.Similarity -spec: {type: python, lifecycle: experimental, owner: operator, definition: er.backends} +spec: + {type: python, lifecycle: experimental, owner: operator, definition: er.backends, + morphogen: {tests: python -m unittest -q tests.test_contracts.Similarity}} diff --git a/demos/entity-resolution/er/settings.py b/demos/entity-resolution/er/settings.py index ed289ac..287654b 100644 --- a/demos/entity-resolution/er/settings.py +++ b/demos/entity-resolution/er/settings.py @@ -1,4 +1,4 @@ -"""Settings Morphogen may tune. Each is named in morphogen.yaml (`change: er/settings.py#NAME in ...` +"""Settings Morphogen may tune. Each is named in catalog-info.yaml (`spec.morphogen.change: er/settings.py#NAME in ...` for the tunable ones, `keep:` for the operator's), so the judge can read it in base and candidate and refuse a change it may not make. Plain constants only: a value computed by an expression cannot be read by the judge.""" 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/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/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/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/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/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/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/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/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.