Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

excalidraw: cover scene.py, verdict.py, build.py and the shell scripts; fix two bugs

deef727ae3210d6
diff --git a/store/agents/excalidraw/toolchain/scene.py b/store/agents/excalidraw/toolchain/scene.py
index bbcdc1e05..274ff2bd0 100644
--- a/store/agents/excalidraw/toolchain/scene.py
+++ b/store/agents/excalidraw/toolchain/scene.py
@@ -93,7 +93,7 @@ class Scene:
return self.text(x, y, text, size=size)
def note(self, x: float, y: float, text: str, color: str = "yellow", w: float = 220) -> dict:
- """A sticky note: a filled box with left-aligned small text."""
+ """A sticky note: a filled box, 220 px wide by default, with its text small and centred."""
return self.box(x, y, text, color=color, w=w, size=16)
# ---- edges ----
@@ -160,8 +160,10 @@ def _edge(el: dict, tx: float, ty: float) -> tuple[float, float]:
return cx, cy
hw, hh = el["width"] / 2, el["height"] / 2
if el["type"] == "ellipse":
- ang = math.atan2(dy, dx)
- return cx + hw * math.cos(ang), cy + hh * math.sin(ang)
+ # Along the line itself: (dx·s/hw)² + (dy·s/hh)² = 1. The ellipse's parametric angle is not the
+ # line's angle unless it is a circle, and an arrow started there pointed off-centre.
+ s = 1 / math.hypot(dx / hw, dy / hh)
+ return cx + dx * s, cy + dy * s
sx = hw / abs(dx) if dx else math.inf
sy = hh / abs(dy) if dy else math.inf
s = min(sx, sy)
diff --git a/store/agents/excalidraw/toolchain/test_scene.py b/store/agents/excalidraw/toolchain/test_scene.py
index 5d3e25ea2..099746407 100644
--- a/store/agents/excalidraw/toolchain/test_scene.py
+++ b/store/agents/excalidraw/toolchain/test_scene.py
@@ -1,9 +1,11 @@
-import json, sys, unittest
+import contextlib, io, json, math, os, runpy, sys, tempfile, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
-from scene import Scene
+from scene import PALETTE, FONT_MONO, Scene, _edge
from verdict import judge
+PACKAGE = Path(__file__).resolve().parent.parent
+
class SceneAndVerdict(unittest.TestCase):
def test_a_scene_is_valid_and_bound(self):
s = Scene()
@@ -27,4 +29,122 @@ class SceneAndVerdict(unittest.TestCase):
def test_not_a_scene(self):
v = judge({"hello": 1}, "d.excalidraw"); self.assertFalse(v["ready"]); self.assertIsNone(v["artifact"])
+
+class Nodes(unittest.TestCase):
+ def test_an_unlabelled_box_is_one_element_at_the_default_size(self):
+ s = Scene()
+ node = s.box(10, 20, color="no-such-colour")
+ self.assertEqual(s.elements, [node])
+ self.assertEqual((node["width"], node["height"], node["boundElements"]), (160, 72, []))
+ self.assertEqual((node["backgroundColor"], node["strokeColor"]), PALETTE["blue"], "an unknown colour is blue")
+ self.assertEqual(node["roundness"], {"type": 3})
+
+ def test_a_label_centres_in_its_box_and_grows_it(self):
+ s = Scene()
+ node = s.box(0, 0, "A rather long label", shape="diamond", color="red")
+ label = s.elements[1]
+ self.assertEqual(node["width"], len("A rather long label") * 20 * 0.6 + 4 + 48)
+ self.assertEqual((label["containerId"], label["verticalAlign"], label["textAlign"]), (node["id"], "middle", "center"))
+ self.assertAlmostEqual(label["x"] + label["width"] / 2, node["width"] / 2)
+ self.assertIsNone(node["roundness"], "only rectangles are rounded")
+
+ def test_free_text_title_and_note(self):
+ s = Scene()
+ t = s.text(5, 6, "line one\nline two", font=FONT_MONO, align="right")
+ self.assertEqual((t["fontFamily"], t["textAlign"], t["verticalAlign"], t["containerId"]), (FONT_MONO, "right", "top", None))
+ self.assertEqual((t["strokeColor"], t["height"]), ("#1e1e1e", 2 * 20 * 1.25))
+ self.assertEqual(s.text(0, 0, "red", color="#e03131")["strokeColor"], "#e03131")
+ self.assertEqual(s.title("Big", 0, -100)["fontSize"], 32)
+ note = s.note(0, 0, "Retries: 3")
+ self.assertEqual((note["width"], note["backgroundColor"], s.elements[-1]["fontSize"]), (220, PALETTE["yellow"][0], 16))
+
+ def test_a_dark_scene_inks_light_and_says_so(self):
+ s = Scene(dark=True)
+ self.assertEqual(s.text(0, 0, "x")["strokeColor"], "#e9ecef")
+ self.assertEqual(s.to_dict()["appState"]["theme"], "dark")
+
+
+class Edges(unittest.TestCase):
+ def test_dashed_two_headed_and_unlabelled(self):
+ s = Scene(); a = s.box(0, 0, "A"); b = s.box(0, 300, "B")
+ arrow = s.arrow(a, b, dashed=True, both=True)
+ self.assertEqual((arrow["strokeStyle"], arrow["startArrowhead"], arrow["endArrowhead"]), ("dashed", "arrow", "arrow"))
+ self.assertEqual(arrow["boundElements"], [], "no label, no bound text")
+ self.assertEqual((arrow["x"], arrow["y"], arrow["points"][1]), (80, 72, [0, 300 - 72]), "straight down, edge to edge")
+
+ def test_where_a_line_leaves_each_shape(self):
+ rect = {"type": "rectangle", "x": 0, "y": 0, "width": 100, "height": 50}
+ self.assertEqual(_edge(rect, 50, 25), (50, 25), "toward its own centre: the centre")
+ x, y = _edge(rect, 50, 500)
+ self.assertEqual(x, 50); self.assertAlmostEqual(y, 50, msg="straight down leaves through the bottom")
+ ellipse = {**rect, "type": "ellipse"}
+ x, y = _edge(ellipse, 50 + 300, 25 + 300)
+ self.assertAlmostEqual(((x - 50) / 50) ** 2 + ((y - 25) / 25) ** 2, 1)
+ self.assertAlmostEqual(math.atan2(y - 25, x - 50), math.pi / 4)
+ diamond = {**rect, "type": "diamond"}
+ x, y = _edge(diamond, 150, 75)
+ self.assertAlmostEqual(abs(x - 50) / 50 + abs(y - 25) / 25, 1, msg="on the diamond's outline, not its box")
+
+
+class Output(unittest.TestCase):
+ def test_save_writes_what_to_dict_says(self):
+ s = Scene(); s.box(0, 0, "A")
+ with tempfile.TemporaryDirectory() as d:
+ path = s.save(Path(d) / "x.excalidraw")
+ self.assertEqual(json.loads(path.read_text()), s.to_dict())
+ cwd = os.getcwd()
+ os.chdir(d)
+ try:
+ self.assertEqual(s.save(), Path("diagram.excalidraw"))
+ self.assertTrue((Path(d) / "diagram.excalidraw").is_file())
+ finally:
+ os.chdir(cwd)
+
+
+def rounded(value):
+ if isinstance(value, float):
+ return round(value, 6) + 0.0
+ if isinstance(value, list):
+ return [rounded(v) for v in value]
+ return value
+
+
+def shape_of(data: dict) -> list:
+ """A scene without what is random per run (ids, seeds, timestamps): references become indexes,
+ coordinates are compared to a millionth of a pixel."""
+ index = {e["id"]: i for i, e in enumerate(data["elements"])}
+ ref = lambda v: index.get(v, v)
+ out = []
+ for e in data["elements"]:
+ e = {k: rounded(v) for k, v in e.items() if k not in ("id", "seed", "versionNonce", "updated")}
+ e["boundElements"] = [{**b, "id": ref(b["id"])} for b in e["boundElements"]]
+ for key in ("containerId", "frameId"):
+ if e.get(key):
+ e[key] = ref(e[key])
+ for key in ("startBinding", "endBinding"):
+ if e.get(key):
+ e[key] = {**e[key], "elementId": ref(e[key]["elementId"])}
+ out.append(e)
+ return out
+
+
+class Template(unittest.TestCase):
+ def test_build_py_makes_the_starter_diagram_the_template_ships(self):
+ with tempfile.TemporaryDirectory() as d:
+ cwd = os.getcwd()
+ os.chdir(d)
+ try:
+ with contextlib.redirect_stdout(io.StringIO()) as printed:
+ runpy.run_path(str(PACKAGE / "template" / "build.py"), run_name="__main__")
+ finally:
+ os.chdir(cwd)
+ self.assertEqual(printed.getvalue(), "diagram.excalidraw\n")
+ built = json.loads((Path(d) / "diagram.excalidraw").read_text())
+ v = judge(built, "diagram.excalidraw")
+ self.assertTrue(v["ready"], v["findings"])
+ self.assertEqual(v["summary"], "diagram.excalidraw · 5 shapes · 5 arrows · valid")
+ shipped = json.loads((PACKAGE / "template" / "diagram.excalidraw").read_text())
+ self.assertEqual(shape_of(built), shape_of(shipped), "template/diagram.excalidraw is what build.py draws")
+
+
if __name__ == "__main__": unittest.main()
diff --git a/store/agents/excalidraw/toolchain/test_scripts.py b/store/agents/excalidraw/toolchain/test_scripts.py
new file mode 100644
index 000000000..93c5e35a3
--- /dev/null
+++ b/store/agents/excalidraw/toolchain/test_scripts.py
@@ -0,0 +1,159 @@
+"""setup.sh, doctor.sh, init-workspace.sh and viewer.sh, run for real against a scratch install whose
+PATH holds only stub commands (and the few coreutils the scripts use), so every ok / miss line and
+exit path is reached without npm, a network or the installed node_modules:
+
+ python3 -m unittest toolchain/test_scripts.py
+"""
+import shutil, subprocess, tempfile, unittest
+from pathlib import Path
+
+PACKAGE = Path(__file__).resolve().parent.parent
+BASH = "/bin/bash"
+COREUTILS = ("dirname", "mkdir")
+BUNDLE = "node_modules/@excalidraw/excalidraw/dist/excalidraw.production.min.js"
+# `node -p "require(...)"`: the versions the scripts print.
+NODE = 'case "$2" in *react/package.json*) echo 18.3.1 ;; *) echo 0.17.6 ;; esac'
+
+
+class Sandbox:
+ """An install dir with the package's scripts, a bin/ of stubs as the whole PATH, and a log of
+ every stub call."""
+
+ def __init__(self, test: unittest.TestCase):
+ tmp = tempfile.TemporaryDirectory()
+ test.addCleanup(tmp.cleanup)
+ self.root = Path(tmp.name)
+ self.install = self.root / "install"
+ (self.install / "toolchain").mkdir(parents=True)
+ for script in PACKAGE.glob("toolchain/*.sh"):
+ shutil.copy(script, self.install / "toolchain" / script.name)
+ shutil.copy(PACKAGE / "viewer.sh", self.install / "viewer.sh")
+ self.bin = self.root / "bin"
+ self.bin.mkdir()
+ self.calls = self.root / "calls.log"
+ self.calls.touch()
+ for name in COREUTILS:
+ real = next(p for p in (Path("/bin") / name, Path("/usr/bin") / name) if p.exists())
+ (self.bin / name).symlink_to(real)
+
+ def stub(self, name: str, body: str = "") -> Path:
+ path = self.bin / name
+ path.write_text(f'#!/bin/bash\necho "{name} $*" >> "$CALLS"\n{body}\n')
+ path.chmod(0o755)
+ return path
+
+ def file(self, rel: str) -> None:
+ path = self.install / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("")
+
+ def run(self, script: str, cwd: Path | None = None, **env: str) -> subprocess.CompletedProcess:
+ return subprocess.run([BASH, str(self.install / script)], cwd=cwd or self.install,
+ env={"PATH": str(self.bin), "CALLS": str(self.calls), **env},
+ capture_output=True, text=True, timeout=60)
+
+ def logged(self) -> list[str]:
+ return self.calls.read_text().splitlines()
+
+
+class Doctor(unittest.TestCase):
+ def test_ready(self):
+ box = Sandbox(self)
+ box.stub("node", NODE)
+ box.stub("python3", 'echo "Python 3.12.1"')
+ for rel in (BUNDLE, "viewer.mjs", "viewer/index.html", "viewer/app.js"):
+ box.file(rel)
+ r = box.run("toolchain/doctor.sh")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(r.stdout.splitlines(), ["ok excalidraw 0.17.6", "ok pane (viewer.mjs, viewer/)", "ok Python 3.12.1"])
+
+ def test_every_miss_is_reported_not_just_the_first(self):
+ box = Sandbox(self)
+ r = box.run("toolchain/doctor.sh")
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines(), ["miss node_modules — run toolchain/setup.sh",
+ "miss viewer.mjs or viewer/ — the checkout is incomplete",
+ "miss python3"])
+
+ def test_a_pane_missing_one_file_is_incomplete(self):
+ box = Sandbox(self)
+ box.stub("node", NODE)
+ box.stub("python3", 'echo "Python 3.12.1"')
+ for rel in (BUNDLE, "viewer.mjs", "viewer/index.html"):
+ box.file(rel)
+ r = box.run("toolchain/doctor.sh")
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines()[1], "miss viewer.mjs or viewer/ — the checkout is incomplete")
+
+
+class Setup(unittest.TestCase):
+ def sandbox(self, *missing: str, npm: str = f"mkdir -p node_modules/@excalidraw/excalidraw/dist && : > {BUNDLE}") -> Sandbox:
+ box = Sandbox(self)
+ for name, body in (("node", NODE), ("npm", npm), ("python3", "")):
+ if name not in missing:
+ box.stub(name, body)
+ return box
+
+ def test_installs_from_the_lockfile(self):
+ box = self.sandbox()
+ r = box.run("toolchain/setup.sh")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(r.stdout.splitlines(), [" npm ci (Excalidraw 0.17.6)", "ok excalidraw 0.17.6 · react 18.3.1"])
+ self.assertIn("npm ci --silent --no-audit --no-fund", box.logged())
+
+ def test_each_missing_tool_is_a_miss(self):
+ for tool, line in (("node", "miss node >= 18 on PATH"), ("npm", "miss npm on PATH"),
+ ("python3", "miss python3 (the scene helper and the verdict)")):
+ with self.subTest(tool=tool):
+ r = self.sandbox(tool).run("toolchain/setup.sh")
+ self.assertEqual((r.returncode, r.stdout.strip()), (1, line))
+
+ def test_a_failed_npm_ci_fails_setup(self):
+ r = self.sandbox(npm="exit 1").run("toolchain/setup.sh")
+ self.assertEqual(r.returncode, 1)
+ self.assertNotIn("ok", r.stdout)
+
+ def test_no_bundle_after_npm_ci_is_a_miss(self):
+ r = self.sandbox(npm="true").run("toolchain/setup.sh")
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(r.stdout.splitlines()[-1], "miss the Excalidraw bundle after npm ci")
+
+
+class InitWorkspace(unittest.TestCase):
+ def test_seeds_the_verdict_and_survives_a_failing_one(self):
+ box = Sandbox(self)
+ ws = box.root / "ws"
+ ws.mkdir()
+ box.stub("python3", "exit 1")
+ r = box.run("toolchain/init-workspace.sh", cwd=ws, HARNESS_DSH_DIR=str(box.install))
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertTrue((ws / ".harness").is_dir())
+ self.assertEqual(box.logged(), [f"python3 {box.install}/toolchain/verdict.py"])
+
+ def test_needs_the_install_dir(self):
+ r = Sandbox(self).run("toolchain/init-workspace.sh")
+ self.assertNotEqual(r.returncode, 0)
+ self.assertIn("HARNESS_DSH_DIR", r.stderr)
+
+
+class Viewer(unittest.TestCase):
+ def test_runs_the_server_beside_it(self):
+ box = Sandbox(self)
+ box.stub("node", 'echo "port $HARNESS_VIEWER_PORT"')
+ r = box.run("viewer.sh", cwd=box.root, HARNESS_VIEWER_PORT="4123", HARNESS_WORKSPACE=str(box.root))
+ self.assertEqual((r.returncode, r.stdout), (0, "port 4123\n"), r.stderr)
+ self.assertEqual(box.logged(), [f"node {box.install}/viewer.mjs"])
+
+ def test_needs_a_port_and_a_workspace(self):
+ box = Sandbox(self)
+ box.stub("node")
+ for env, missing in (({"HARNESS_WORKSPACE": "/tmp"}, "HARNESS_VIEWER_PORT"), ({"HARNESS_VIEWER_PORT": "4123"}, "HARNESS_WORKSPACE")):
+ with self.subTest(missing=missing):
+ r = box.run("viewer.sh", **env)
+ self.assertNotEqual(r.returncode, 0)
+ self.assertIn(missing, r.stderr)
+ self.assertEqual(box.logged(), [], "node never starts")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/store/agents/excalidraw/toolchain/test_verdict.py b/store/agents/excalidraw/toolchain/test_verdict.py
new file mode 100644
index 000000000..a39cc9d01
--- /dev/null
+++ b/store/agents/excalidraw/toolchain/test_verdict.py
@@ -0,0 +1,115 @@
+"""verdict.py: every finding it can make, and main() on a real workspace: python3 -m unittest toolchain/test_verdict.py"""
+import contextlib, io, json, os, runpy, sys, tempfile, unittest
+from pathlib import Path
+from unittest import mock
+sys.path.insert(0, str(Path(__file__).parent))
+import verdict
+from verdict import judge
+
+HERE = Path(__file__).resolve().parent
+
+
+def scene(*elements) -> dict:
+ return {"type": "excalidraw", "version": 2, "elements": list(elements)}
+
+
+BOX = {"id": "box", "type": "rectangle"}
+LABEL = {"id": "label", "type": "text", "text": "API", "containerId": "box"}
+
+
+class Findings(unittest.TestCase):
+ def kinds(self, v):
+ return [(f["severity"], f["kind"]) for f in v["findings"]]
+
+ def test_an_element_without_an_id_or_with_an_unknown_type(self):
+ v = judge(scene(BOX, {"type": "rectangle"}, {"id": "s", "type": "star"}), "d.excalidraw")
+ self.assertEqual(self.kinds(v), [("error", "schema"), ("error", "schema")])
+ self.assertEqual(v["findings"][1]["message"], "element 's' has no id or an unknown type 'star'")
+ self.assertEqual(v["summary"], "d.excalidraw · 2 shapes · 0 arrows · 2 errors")
+ self.assertEqual([p["state"] for p in v["phases"]], ["done", "failed", "pending"])
+
+ def test_json_that_is_not_a_string_where_an_id_or_type_belongs_is_a_finding_not_a_crash(self):
+ # A hand edit can leave a list or an object there; the verdict used to raise TypeError
+ # (unhashable) and write nothing.
+ v = judge(scene({"id": ["a"], "type": "rectangle"}, {"id": "b", "type": {"shape": "box"}},
+ {"id": "c", "type": "arrow", "startBinding": {"elementId": ["a"]}, "endBinding": {"elementId": "b"}},
+ {"id": "t", "type": "text", "text": "x", "containerId": {"id": "b"}}), "d.excalidraw")
+ self.assertFalse(v["ready"])
+ self.assertEqual(self.kinds(v), [("error", "schema"), ("error", "schema"), ("error", "binding"), ("error", "binding")])
+
+ def test_a_label_whose_container_is_gone(self):
+ v = judge(scene(LABEL), "d.excalidraw")
+ self.assertEqual(v["findings"][0]["message"], "text label belongs to a missing container box")
+
+ def test_review_warnings_leave_it_ready_with_review_open(self):
+ loose = {"id": "a", "type": "arrow", "startBinding": {"elementId": "box"}, "endBinding": None}
+ v = judge(scene(BOX, LABEL, loose, {"id": "e", "type": "text", "text": " "}), "d.excalidraw")
+ self.assertTrue(v["ready"])
+ self.assertEqual(self.kinds(v), [("warning", "review"), ("warning", "review")])
+ self.assertEqual([f["message"] for f in v["findings"]], ["arrow a is not attached at both ends", "text e is empty"])
+ self.assertEqual(v["phases"][2]["state"], "active")
+ self.assertEqual(v["summary"], "d.excalidraw · 1 shape · 1 arrow · valid")
+
+ def test_deleted_elements_do_not_count_and_cannot_be_bound_to(self):
+ v = judge(scene({**BOX, "isDeleted": True}, LABEL, "not an element"), "d.excalidraw")
+ self.assertEqual(self.kinds(v), [("error", "binding")])
+ self.assertEqual(v["summary"], "d.excalidraw · 0 shapes · 0 arrows · 1 error")
+
+ def test_an_empty_scene_is_not_ready(self):
+ v = judge(scene(), "d.excalidraw")
+ self.assertFalse(v["ready"])
+ self.assertEqual((v["summary"], v["artifact"]), ("d.excalidraw · empty", "d.excalidraw"))
+ self.assertEqual([p["state"] for p in v["phases"]], ["active", "pending", "pending"])
+
+
+class Main(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.ws = Path(tmp.name)
+ patcher = mock.patch.object(verdict, "WS", self.ws)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def main(self, *argv):
+ with contextlib.redirect_stdout(io.StringIO()) as out:
+ code = verdict.main(["verdict.py", *argv])
+ return code, out.getvalue(), json.loads((self.ws / ".harness" / "verdict.json").read_text())
+
+ def test_the_default_diagram(self):
+ (self.ws / "diagram.excalidraw").write_text(json.dumps(scene(BOX, LABEL)))
+ code, printed, v = self.main()
+ self.assertEqual((code, printed), (0, "ready · diagram.excalidraw · 1 shape · 0 arrows · valid\n"))
+ self.assertEqual(v["artifact"], "diagram.excalidraw")
+
+ def test_a_named_diagram_relative_or_absolute_prints_its_findings(self):
+ (self.ws / "flows").mkdir()
+ (self.ws / "flows" / "x.excalidraw").write_text(json.dumps(scene({"id": "s", "type": "star"})))
+ for arg in ("flows/x.excalidraw", str(self.ws / "flows" / "x.excalidraw")):
+ code, printed, v = self.main(arg)
+ self.assertEqual(code, 1)
+ self.assertEqual(v["artifact"], "flows/x.excalidraw")
+ self.assertEqual(printed.splitlines()[1], " error element 's' has no id or an unknown type 'star'")
+
+ def test_a_missing_or_unparseable_file_is_unreadable(self):
+ code, printed, v = self.main()
+ self.assertEqual(code, 1)
+ self.assertEqual(v["summary"], "diagram.excalidraw · unreadable")
+ self.assertEqual(v["findings"][0]["kind"], "file")
+ self.assertIsNone(v["artifact"])
+ (self.ws / "diagram.excalidraw").write_text("{ not json")
+ code, printed, v = self.main()
+ self.assertEqual((code, v["summary"]), (1, "diagram.excalidraw · unreadable"))
+ self.assertTrue(v["findings"][0]["message"].startswith("diagram.excalidraw: Expecting property name"), v["findings"])
+
+ def test_run_as_a_script(self):
+ (self.ws / "diagram.excalidraw").write_text(json.dumps(scene(BOX)))
+ with mock.patch.dict(os.environ, {"HARNESS_WORKSPACE": str(self.ws)}), mock.patch.object(sys, "argv", ["verdict.py"]), contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaises(SystemExit) as exit_:
+ runpy.run_path(str(HERE / "verdict.py"), run_name="__main__")
+ self.assertEqual(exit_.exception.code, 0)
+ self.assertTrue(json.loads((self.ws / ".harness" / "verdict.json").read_text())["ready"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/store/agents/excalidraw/toolchain/verdict.py b/store/agents/excalidraw/toolchain/verdict.py
index 235b23de2..6a30fc55e 100755
--- a/store/agents/excalidraw/toolchain/verdict.py
+++ b/store/agents/excalidraw/toolchain/verdict.py
@@ -24,15 +24,18 @@ def judge(data: object, rel: str) -> dict:
findings.append({"severity": "error", "kind": "schema", "message": f"{rel} is not an Excalidraw scene (type 'excalidraw' with an elements list)"})
else:
elements = [e for e in data["elements"] if isinstance(e, dict) and not e.get("isDeleted")]
- ids = {e.get("id") for e in elements}
+ # A hand-edited file can hold any JSON where an id or a type belongs: only strings are ids,
+ # so a list or an object there is a finding, not a TypeError that leaves no verdict at all.
+ ids = {e["id"] for e in elements if isinstance(e.get("id"), str)}
+ known = lambda ref: isinstance(ref, str) and ref in ids
for e in elements:
- if not isinstance(e.get("id"), str) or e.get("type") not in SHAPES:
+ if not isinstance(e.get("id"), str) or not isinstance(e.get("type"), str) or e["type"] not in SHAPES:
findings.append({"severity": "error", "kind": "schema", "message": f"element {e.get('id')!r} has no id or an unknown type {e.get('type')!r}"})
for key in ("startBinding", "endBinding"):
b = e.get(key)
- if isinstance(b, dict) and b.get("elementId") not in ids:
+ if isinstance(b, dict) and not known(b.get("elementId")):
findings.append({"severity": "error", "kind": "binding", "message": f"arrow {e.get('id')} is bound to a missing element {b.get('elementId')}"})
- if e.get("type") == "text" and e.get("containerId") and e["containerId"] not in ids:
+ if e.get("type") == "text" and e.get("containerId") and not known(e["containerId"]):
findings.append({"severity": "error", "kind": "binding", "message": f"text {e.get('id')} belongs to a missing container {e['containerId']}"})
for e in elements:
if e.get("type") == "arrow" and not (e.get("startBinding") and e.get("endBinding")):
@@ -44,7 +47,8 @@ def judge(data: object, rel: str) -> dict:
ok = valid and not errors and drawn
counts: dict[str, int] = {}
for e in elements:
- counts[e.get("type", "?")] = counts.get(e.get("type", "?"), 0) + 1
+ kind = e.get("type") if isinstance(e.get("type"), str) else "?"
+ counts[kind] = counts.get(kind, 0) + 1
shapes = sum(counts.get(k, 0) for k in ("rectangle", "ellipse", "diamond"))
bits = [Path(rel).name]
if drawn: