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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"name": "morphogen",
"source": "./",
"description": "Improve a system at any scope, from one cell to the whole, behind a judge the agent cannot edit.",
"version": "0.8.0"
"version": "0.9.0"
}
]
}
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
"name": "morphogen",
"version": "0.8.0",
"version": "0.9.0",
"description": "Improve a system at any scope, from one cell to the whole, behind a judge the agent cannot edit: structure, judge, evidence and optimizers over MCP.",
"author": {
"name": "OpenReplicant"
Expand Down
3 changes: 2 additions & 1 deletion demos/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ is a component that stands alone, or a larger system built from them.
| [entity-resolution](entity-resolution/BRIEF.md) | decide whether two records name the same entity, behind one interface with swappable backends | nothing |
| [catalog](catalog/BRIEF.md) | take in entities: resolve, classify under adopted schemes, attach claims with trust | entity-resolution |
| [cognitive-model](cognitive-model/BRIEF.md) | the Common Model of Cognition on Claude Code | catalog, and the rest of its spec |
| [fernhill](fernhill/README.md) | an engagement on a made-up kitchen firm: mapped from its documents and an interview, one opportunity judged, options for one role, a report of implementation projects | the kit alone (no code to build) |

Build them in that order: each one's cells become available to the next.
Build the first three in that order: each one's cells become available to the next. `fernhill` stands alone.

## Rules

Expand Down
53 changes: 53 additions & 0 deletions demos/fernhill/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Fernhill: an engagement on a made-up firm

The kit alone (the `map`, `catalog` and `morphogen` skills, Morphogen's CLI and judge; no database, no kernel) on a
small business that does not exist: from its documents and an interview to a report of optimisation opportunities,
each written up as an implementation project. It is the kit's done-when (a made-up firm mapped into entity files,
options catalogued for one role, cells drafted for one opportunity) and a demo of what an engagement delivers.

| Folder | What it is |
| --- | --- |
| [material/](material/) | the firm's material, as a client would hand it over: an overview, the office handbook, the systems list, the quote calculator, the job sheet export (`jobs.csv`, 121 jobs) and an interview with the director. All made up. |
| [making/](making/) | how `jobs.csv` was made (`make_jobs.py`, one seed). It holds the true costs the engagement has to find, so no engagement run sees it. |
| [engagement/](engagement/) | the first run's result, done in a Claude Code session following the skills: the map (`catalog-info.yaml`, `catalog/`), the baselines (`analysis/`), the quote calculator as a judged cell (`cells/quote/`), four options for job scheduling (`catalog/scheduling.yaml`) and [the report](engagement/report.md). |
| `prompt.md`, `run.sh`, `check.py` | the engagement unattended: a fresh project from `material/`, Claude Code with only the plugin, then the checks of its result |
| [runs/](runs/) | unattended runs: each one's report and `check.py` output |

## The first run (2026-11-24)

- **Mapped:** the firm as a System, 5 teams, 6 process steps, its tools and 2 roles; 40 evidence quotes, all found
on the lines they cite (`check.py`).
- **Judged:** the quote calculator, as code with its six cost constants free within bounds and the margin held
fixed. Held-out cost error 12.4% to 3.4% after `tune` (40 trials), **pass**, 7 runs, sign test p = 0.008, in
Podman.
- **Catalogued:** Fergus, Tradify, ServiceM8 and shared Google calendars for job scheduling, each fact quoted from
the vendor's own page; none measured (a trial needs accounts, the operator's call).
- **Report:** four projects: the calculator (about £53,000 a year of margin), quotes in three days, a schedule the
fitters can see, fewer remakes.

## The unattended run (2026-11-24, sonnet)

`run.sh`, no help: all eight checks pass ([check.txt](runs/2026-11-24-sonnet/check.txt)); 29 evidence quotes, all
found. It mapped the firm, drafted its own quote cell (hours per cabinet split by range), tuned it to held-out
error 15.0% to 4.5% (pass) by moving fixed hours per job from 16 to 50, catalogued Tradify, ServiceM8, Powered Now
and Jobber, and wrote [a report](runs/2026-11-24-sonnet/report.md) of five projects. It said itself that 50 is the
top of the range it allowed, standing in for under-counted hours per cabinet.

## What the runs found in the kit, for issues

1. **A plugin update did not happen.** #102 and #103 changed the plugin but not its version (0.8.0), so
`claude plugin update` reported "already at the latest version" and kept code from before them; the old code
read only `morphogen.yaml`. Fixed here: 0.9.0. A version bump belongs in every pull request that changes the
plugin.
2. **A cell that cannot pass.** With `max_repeats: 6` a deterministic score cannot reach the sign test's bar (the
best p is 0.0156), so a 9-point gain failed. `status` and `structure_check` could say so before a run.
3. **Org maps are noisy in `status`.** Every process step is listed as a cell, `ready: false`, though none has a
`run`; structure-only entities could be listed apart.
4. **A tuned value at its bound passes without a word.** The unattended run's pass rests on a setting at the
top of its range; `tune` could report it, since a value at the bound means the range, not the system, chose it.
5. **The CLI needs a file.** `morphogen structure check` takes the catalog's path, where `status` finds it itself.

Run it again (Python 3.11 or later, Podman, Claude Code signed in):

demos/fernhill/run.sh /path/to/empty/workdir
python3 making/make_jobs.py # only to rebuild material/jobs.csv
75 changes: 75 additions & 0 deletions demos/fernhill/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Check what an engagement left: the done-when of the demo, as checks a script can make.

python3 demos/fernhill/check.py PROJECT PLUGIN_DIR

PROJECT is the engagement's git repository; PLUGIN_DIR is Morphogen's plugin, whose CLI does the structure and
status checks. Standard library only. Prints one line per check and exits 1 if any fails. It checks the form of
the result, not its judgement: whether the opportunities are the right ones is for a person reading report.md.
"""

import json
import re
import subprocess
import sys
from pathlib import Path

proj, plugin = Path(sys.argv[1]).resolve(), sys.argv[2]
results = []


def check(name, ok, detail=""):
results.append(ok)
print(f"{'PASS' if ok else 'FAIL'} {name}" + (f": {detail}" if detail else ""))


def git(*args):
return subprocess.run(["git", *args], cwd=proj, capture_output=True, text=True).stdout


def morphogen(*args):
r = subprocess.run(["uv", "run", "--quiet", "--project", plugin, "morphogen", *args], cwd=proj,
capture_output=True, text=True)
try:
return json.loads(r.stdout)
except json.JSONDecodeError:
return {"error": (r.stdout + r.stderr).strip()[-300:]}


tracked = set(git("ls-files").split())
check("report.md committed on main", "report.md" in git("ls-tree", "--name-only", "main").split())
check("the client's material is not committed", not any(p.startswith("material/") for p in tracked))
catalog = [proj / p for p in tracked if p.endswith((".yaml", ".yml")) and (p == "catalog-info.yaml" or p.startswith("catalog/"))]
check("a catalog", (proj / "catalog-info.yaml") in catalog, f"{len(catalog)} files")

found = morphogen("structure", "check", "catalog-info.yaml")
errors = [f for f in found.get("findings", []) if f.get("severity") == "error"]
check("structure check: no errors", "error" not in found and not errors,
found.get("error") or "; ".join(f["message"] for f in errors[:3]))

status = morphogen("status")
judged = [c["cell"] for c in status.get("cells", []) if c.get("verdicts")]
check("a cell with a verdict", bool(judged), ", ".join(judged) or status.get("next", status.get("error", "")))

text = "\n".join(p.read_text() for p in catalog if p.exists())
candidates = len(re.findall(r"lifecycle:\s*candidate", text))
check("at least three options for a role", candidates >= 3, f"{candidates} candidates")

# Evidence lines: `trust | file:Lnn[-mm] | "quote"`. A quote must be on the lines it names; URLs are not fetched.
total, misses = 0, []
for m in re.finditer(r'^\s*(stated|inferred) \| ([^|\s]+?):L(\d+)(?:-(\d+))? \| "(.+)"\s*$', text, re.M):
_, path, a, b, quote = m.groups()
total += 1
src = proj / path
lines = src.read_text().splitlines() if src.is_file() else []
span = "\n".join(lines[int(a) - 1:int(b or a)])
if quote.strip('"') not in span:
misses.append(f"{path}:L{a}")
check("evidence quotes are where they say", total > 0 and not misses,
f"{total - len(misses)} of {total}" + (f"; first misses: {', '.join(misses[:3])}" if misses else ""))

report = (proj / "report.md").read_text() if (proj / "report.md").exists() else ""
words = ["target", "measure", "option", "cost", "risk"]
absent = [w for w in words if w not in report.lower()]
check("the report writes opportunities up as projects", not absent, "missing: " + ", ".join(absent) if absent else "")

sys.exit(0 if all(results) else 1)
4 changes: 4 additions & 0 deletions demos/fernhill/engagement/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
material/
morphogen.local.yaml
.morphogen/
__pycache__/
70 changes: 70 additions & 0 deletions demos/fernhill/engagement/analysis/baseline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""The engagement's baselines, from the job sheet export: one line per measure.

python analysis/baseline.py material/jobs.csv > analysis/baseline.txt

Each line: measure, value, and how it was computed. Standard library only.
"""

import csv
import statistics as st
import sys
from datetime import date

LABOUR_RATE = 32.0 # material/quote-calculator.md, B16
MARGIN = 0.35 # B18


def d(s):
return date.fromisoformat(s) if s else None


def main(path):
rows = list(csv.DictReader(open(path)))
decided = [r for r in rows if r["outcome"] in ("won", "lost")]
lag = lambda r: (d(r["quote_sent_date"]) - d(r["survey_date"])).days
out = []
say = lambda k, v, how: out.append(f"{k}\t{v}\t{how}")
say("jobs", len(rows), "rows in jobs.csv")
say("won/lost/pending", "/".join(str(sum(r["outcome"] == o for r in rows)) for o in ("won", "lost", "pending")), "outcome")
say("win_rate", f"{sum(r['outcome'] == 'won' for r in decided) / len(decided):.2f}", "won / (won + lost)")
lags = [lag(r) for r in rows]
say("quote_days_median", st.median(lags), "quote_sent_date - survey_date, calendar days, all jobs")
say("quote_days_within_5", f"{sum(x <= 5 for x in lags) / len(lags):.2f}", "share of quotes sent within 5 days of the survey")
for lo, hi in ((0, 5), (6, 9), (10, 14), (15, 999)):
s = [r for r in decided if lo <= lag(r) <= hi]
if s:
say(f"win_rate_quote_{lo}_{hi if hi < 999 else 'plus'}_days", f"{sum(r['outcome'] == 'won' for r in s) / len(s):.2f}", f"n={len(s)}")
lost = [r for r in rows if r["outcome"] == "lost"]
say("lost_to_quicker_quote", sum(r["lost_reason"] == "went with a quicker quote" for r in lost), "lost_reason, of lost jobs")
done = [r for r in rows if r["actual_materials"]]
say("completed_with_costs", len(done), "rows with actual_materials")
margins, cost_err, under = [], [], 0
for r in done:
cost = float(r["actual_materials"]) + LABOUR_RATE * float(r["actual_labour_hours"])
price = float(r["quoted_price"])
quoted_cost = price / (1 + MARGIN)
margins.append((price - cost) / cost)
cost_err.append((quoted_cost - cost) / cost)
under += cost > quoted_cost
say("markup_on_cost_median", f"{st.median(margins):.3f}", "(quoted_price - actual cost) / actual cost; intended 0.35")
say("jobs_at_a_loss", sum(m < 0 for m in margins), "actual cost above quoted_price")
say("quoted_cost_error_median", f"{st.median(cost_err):+.3f}", "(quoted_price/1.35 - actual cost) / actual cost")
say("jobs_cost_underestimated", f"{under}/{len(done)}", "actual cost above the calculator's cost")
shortfall = sum(float(r["quoted_price"]) / (1 + MARGIN) * MARGIN - (float(r["quoted_price"]) - float(r["actual_materials"]) - LABOUR_RATE * float(r["actual_labour_hours"])) for r in done)
say("margin_shortfall_gbp", f"{shortfall:.0f}", "intended margin minus realised margin, summed over completed jobs")
rem = [int(r["remade_cabinets"] or 0) for r in done]
say("jobs_with_remakes", f"{sum(x > 0 for x in rem)}/{len(done)}", "remade_cabinets > 0")
say("remakes_from_survey", sum(1 for r in done if r["remake_cause"] == "survey measurement"), "jobs, remake_cause")
slips = [(d(r["fit_start"]) - d(r["fit_planned_start"])).days for r in done]
say("fit_slipped_share", f"{sum(s > 0 for s in slips) / len(slips):.2f}", "fit_start after fit_planned_start")
say("fit_slip_days_median_when_slipped", st.median([s for s in slips if s > 0]), "days")
inv = [(d(r["final_invoice_date"]) - d(r["fit_end"])).days for r in done]
say("invoice_days_median", st.median(inv), "final_invoice_date - fit_end")
paid = [r for r in done if r["paid_date"]]
balance = sum(float(r["quoted_price"]) * 0.6 for r in done) / len(done)
say("balance_avg_gbp", f"{balance:.0f}", "60% of quoted_price, completed jobs")
print("\n".join(out))


if __name__ == "__main__":
main(sys.argv[1])
22 changes: 22 additions & 0 deletions demos/fernhill/engagement/analysis/baseline.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
jobs 121 rows in jobs.csv
won/lost/pending 52/62/7 outcome
win_rate 0.46 won / (won + lost)
quote_days_median 9 quote_sent_date - survey_date, calendar days, all jobs
quote_days_within_5 0.17 share of quotes sent within 5 days of the survey
win_rate_quote_0_5_days 0.80 n=20
win_rate_quote_6_9_days 0.57 n=44
win_rate_quote_10_14_days 0.32 n=34
win_rate_quote_15_plus_days 0.00 n=16
lost_to_quicker_quote 15 lost_reason, of lost jobs
completed_with_costs 50 rows with actual_materials
markup_on_cost_median 0.163 (quoted_price - actual cost) / actual cost; intended 0.35
jobs_at_a_loss 2 actual cost above quoted_price
quoted_cost_error_median -0.138 (quoted_price/1.35 - actual cost) / actual cost
jobs_cost_underestimated 50/50 actual cost above the calculator's cost
margin_shortfall_gbp 83576 intended margin minus realised margin, summed over completed jobs
jobs_with_remakes 6/50 remade_cabinets > 0
remakes_from_survey 5 jobs, remake_cause
fit_slipped_share 0.48 fit_start after fit_planned_start
fit_slip_days_median_when_slipped 5.5 days
invoice_days_median 12.5 final_invoice_date - fit_end
balance_avg_gbp 7512 60% of quoted_price, completed jobs
23 changes: 23 additions & 0 deletions demos/fernhill/engagement/analysis/map.mmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
flowchart LR
subgraph c_fernhill["fernhill"]
c_design["design"]
c_final_invoice["final-invoice"]
c_fit["fit"]
c_orders["orders"]
c_quote["quote"]
c_quote_calculator["quote-calculator"]
c_survey["survey"]
c_whiteboard["whiteboard"]
end
outside(["outside"])
c_whiteboard -->|"fitting-schedule"| c_fit
i_job_spec(("job-spec"))
c_design --> i_job_spec
c_quote_calculator --> i_job_spec
i_job_spec --> c_orders
i_job_spec --> c_quote
outside -->|"resource:sketchup"| c_design
outside -->|"resource:xero"| c_final_invoice
c_survey -->|"room-survey"| c_design
classDef absence stroke-dasharray: 5 5,opacity:0.6
classDef divergence stroke:#d33,stroke-width:2px
40 changes: 40 additions & 0 deletions demos/fernhill/engagement/analysis/split.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Write the quote cell's data outside the repository: the jobs' inputs and two answer sets.

python analysis/split.py material/jobs.csv OUT

OUT/inputs/jobs.jsonl every completed job's four inputs and survey date (no costs): `inputs`
OUT/search/actuals.json actual costs of the search split, for probes and tuning: `search`
OUT/holdout/actuals.json actual costs of the held-out split, for verdicts only: `private`

A job is held out when the first byte of sha256(SALT + job_id) is in the top 40% of its range. Prints the lines
for morphogen.local.yaml.
"""

import csv
import hashlib
import json
import sys
from pathlib import Path

SALT = "fernhill-quote-v1:"
LABOUR_RATE = 32.0

src, out = sys.argv[1], Path(sys.argv[2]).expanduser().resolve()
if out.is_relative_to(Path(__file__).resolve().parents[1]):
sys.exit("OUT must be outside the repository")
jobs, actuals = [], {"search": {}, "holdout": {}}
for r in csv.DictReader(open(src)):
if not r["actual_materials"]:
continue
jobs.append({"job_id": r["job_id"], "cabinets": int(r["cabinets"]), "range": r["range"],
"worktop_material": r["worktop_material"], "worktop_m": float(r["worktop_m"]),
"survey_date": r["survey_date"]})
split = "holdout" if hashlib.sha256((SALT + r["job_id"]).encode()).digest()[0] / 256 >= 0.6 else "search"
actuals[split][r["job_id"]] = round(float(r["actual_materials"]) + LABOUR_RATE * float(r["actual_labour_hours"]), 2)
for d in ("inputs", "search", "holdout"):
(out / d).mkdir(parents=True, exist_ok=True)
(out / "inputs" / "jobs.jsonl").write_text("".join(json.dumps(j) + "\n" for j in jobs))
for s in ("search", "holdout"):
(out / s / "actuals.json").write_text(json.dumps(actuals[s], indent=0))
print(f"# {len(jobs)} jobs: {len(actuals['search'])} search, {len(actuals['holdout'])} held out")
print(f"cells:\n quote-calculator:\n inputs: {out / 'inputs'}\n search: {out / 'search'}\n private: {out / 'holdout'}")
25 changes: 25 additions & 0 deletions demos/fernhill/engagement/catalog-info.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Fernhill Kitchens (made up), mapped for an engagement: the firm as a System, its teams, the steps a job goes
# through, the tools behind them and the roles they play. Claims cite the firm's material (material/, kept out of
# the repository) or the baselines computed from it (analysis/baseline.txt).
apiVersion: backstage.io/v1alpha1
kind: System
metadata:
name: fernhill
description: Fernhill Kitchens, an 11-person kitchen design, build and fit firm. Made up for Morphogen's demo engagement.
annotations:
morphogen.dev/evidence: |
stated | material/overview.md:L6 | "founded in 2009 by Sian Hollis, a joiner, and we have grown to 11 people"
stated | material/overview.md:L30 | "Turnover about £400,000; about 30 kitchens fitted."
stated | material/interview.md:L8 | "We're busier than we've ever been and the bank balance doesn't"
spec:
owner: group:default/directors
lifecycle: production
morphogen:
defaults: {rounds: {warmup: 0, repeats: 4, max_repeats: 8}, timeout: 60}
---
apiVersion: backstage.io/v1alpha1
kind: Location
metadata:
name: fernhill-map
spec:
targets: [./catalog/teams.yaml, ./catalog/process.yaml, ./catalog/tools.yaml, ./catalog/quote.yaml, ./catalog/scheduling.yaml]
Loading